text:
ADMINS = (
    # ('Your Name', 'your_email@domain.com'),
)

MANAGERS = ADMINS

DEBUG = False
TEMPLATE_DEBUG = DEBUG
LOGIN_URL = '/accounts/login/' #this presumes that apache is pointing at /mousedb and may need to be changed if a different root is being used

MEDIA_URL = '/mousedb-media/'
STATIC_URL = '/mousedb-static/'

import os.path
PROJECT_DIR = os.path.dirname(__file__)
#these locations can be absolue paths or relative to the installation (as is shown here)
MEDIA_ROOT = os.path.join(PROJECT_DIR, "served-media") #set to where pictures and files will be stored.  Default is media folder and this is where MEDIA_URL on your webserver should point
STATIC_ROOT = os.path.join(PROJECT_DIR, "served-static") #this folder is populated by the collectstatic command and is where STATIC_URL on your webserver should point
MEDIA_URL = '/mousedb-media/'
STATIC_URL = '/mousedb-static/'

# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'America/Detroit'

DATABASES = {
    'default': {
        'NAME': '', # Or path to database file if using sqlite3.
        'ENGINE': '', #  Choose one of 'django.db.backends.postgresql_psycopg2','django.db.backends.postgresql', 'django.db.backends.mysql', 'django.db.backends.sqlite3', 'django.db.backends.oracle'
        'USER': '',  # Not used with sqlite3.
        'PASSWORD': '', # Not used with sqlite3
	'HOST':'', # Set to empty string for localhost. Not used with sqlite3.
	'PORT':'', # Set to empty string for default. Not used with sqlite3.
    }
}

WEAN_AGE = 21 #this is the earliers age at which pups can be weaned from their parents.
GENOTYPE_AGE = 14 #this is the earliest age at which pups can be genotyped or ear tagged.

redpajama_set_name: RedPajamaGithub


text:
		<?php if($questions != Null) for($i=0; $i<sizeof($questions); $i++){
				echo '

 '. $questions[$i]['question'] .'

';
			} ?>

	<button class="btn btn-default form-control" id="more" >Add more question</button>

		<form class="form-horizontal" action="<?php echo site_url('teacher/update/addassignques/add'); ?>" method="get">

			      		<textarea type="text" class="form-control" id="question" name="question" placeholder="Enter question"></textarea>

		  	<input type="hidden" name="assign_id" value="<?php echo $id; ?>">

		      		<button type="submit" class="btn btn-danger">Save</button>

		</form>


text:
Before do
  @driver = Selenium::WebDriver.for :firefox
end

After do
  @driver.quit
end

Given(/^I have (\d+) (.*)$/) do |amount, in_currency|
  @driver.get "http://localhost:8888"
  in_currency_selector = Selenium::WebDriver::Support::Select.new(@driver.find_element :id => "in_currency")
  in_currency_selector.select_by :value, in_currency
  in_amount = @driver.find_element :id => "in_amount"
  in_amount.clear
  in_amount.send_keys amount
end

When(/^I check conversion rate to (.*)$/) do |out_currency|
  out_currency_selector = Selenium::WebDriver::Support::Select.new(@driver.find_element :id => "out_currency")
  out_currency_selector.select_by :value, out_currency
  convert_button = @driver.find_element :id => "convert"
  convert_button.click
end

Then(/^the result should be greater than (\d+)$/) do |amount|
  wait = Selenium::WebDriver::Wait.new(:timeout => 3) # seconds
  wait.until { @driver.find_element(:id => "out_amount").attribute("value").to_f > 0 }
  @driver.find_element(:id => "out_amount").attribute("value").to_f.should > amount.to_f
end


text:
/* MACHINE GENERATED FILE, DO NOT EDIT */

package org.lwjgl.opengl;

import org.lwjgl.*;
import java.nio.*;

public final class ARBClearBufferObject {

	private ARBClearBufferObject() {}

	public static void glClearBufferData(int target, int internalformat, int format, int type, ByteBuffer data) {
		GL43.glClearBufferData(target, internalformat, format, type, data);
	}

	public static void glClearBufferSubData(int target, int internalformat, long offset, int format, int type, ByteBuffer data) {
		GL43.glClearBufferSubData(target, internalformat, offset, format, type, data);
	}

	public static void glClearNamedBufferDataEXT(int buffer, int internalformat, int format, int type, ByteBuffer data) {
		ContextCapabilities caps = GLContext.getCapabilities();
		long function_pointer = caps.glClearNamedBufferDataEXT;
		BufferChecks.checkFunctionAddress(function_pointer);
		BufferChecks.checkBuffer(data, 1);
		nglClearNamedBufferDataEXT(buffer, internalformat, format, type, MemoryUtil.getAddress(data), function_pointer);
	}
	static native void nglClearNamedBufferDataEXT(int buffer, int internalformat, int format, int type, long data, long function_pointer);

	public static void glClearNamedBufferSubDataEXT(int buffer, int internalformat, long offset, int format, int type, ByteBuffer data) {
		ContextCapabilities caps = GLContext.getCapabilities();
		long function_pointer = caps.glClearNamedBufferSubDataEXT;
		BufferChecks.checkFunctionAddress(function_pointer);
		BufferChecks.checkDirect(data);
		nglClearNamedBufferSubDataEXT(buffer, internalformat, offset, data.remaining(), format, type, MemoryUtil.getAddress(data), function_pointer);
	}
	static native void nglClearNamedBufferSubDataEXT(int buffer, int internalformat, long offset, long data_size, int format, int type, long data, long function_pointer);
}


text:
namespace boost {
namespace archive {

// explicitly instantiate for this type of text stream
template class basic_text_iprimitive<std::istream> ;

} // namespace archive
} // namespace boost


text:
using System;
using Zirpl.AppEngine.Model;

namespace Zirpl.Examples.CodeGeneration.VS2013.Commerce.Model.Membership
{
    public class User : EntityBase<Guid>
    {
        public virtual String UserName { get; set; }
        public virtual String LoweredUserName { get; set; }

        //public Guid ApplicationId { get; set; }
        //public bool IsAnonymous { get; set; }
        //public DateTime LastActivityDate { get; set; }
    }

}


text:
package org.literacyapp.contentprovider.model.content.multimedia;

import org.greenrobot.greendao.annotation.Entity;
import org.greenrobot.greendao.annotation.Generated;
import org.greenrobot.greendao.annotation.Id;

@Entity
public class JoinAudiosWithWords {

    @Id
    private Long id;

    private long audioId;

    private long wordId;

    @Generated(hash = 131625956)
    public JoinAudiosWithWords(Long id, long audioId, long wordId) {
        this.id = id;
        this.audioId = audioId;
        this.wordId = wordId;
    }

    @Generated(hash = 1453641339)
    public JoinAudiosWithWords() {
    }

    public Long getId() {
        return this.id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public long getAudioId() {
        return this.audioId;
    }

    public void setAudioId(long audioId) {
        this.audioId = audioId;
    }

    public long getWordId() {
        return this.wordId;
    }

    public void setWordId(long wordId) {
        this.wordId = wordId;
    }
}


text:
import valueItems from './helpers/valueItems'

export function unlocksValue (accountData, values) {
  if (!accountData.account || !accountData.shared || !accountData.bank || !accountData.characters || !accountData.materials) {
    return null
  }

  const unlockItems = unlocksItems(accountData)

  let summary = valueItems(unlockItems, values)
  delete summary['liquidBuy']
  delete summary['liquidSell']

  return summary
}

export function unlocksItems (accountData) {
  const items = [
    commanderStatus(accountData),
    bankSlots(accountData),
    characterSlots(accountData),
    sharedInventorySlots(accountData),
    storageExpanders(accountData),
    craftingLicences(accountData),
    characterBagSlots(accountData),
    buildTemplates(accountData),
    equipmentTemplates(accountData),
    buildStorage(accountData)
  ]

  return items.reduce((arr, elem) => arr.concat(elem), [])
    .filter(x => x.count > 0)
    .map(x => ({...x, binding: 'AccountUnlock'}))
}

function commanderStatus (accountData) {
  if (!accountData.account) {
    return []
  }

  return accountData.account.commander ? [{id: 67335, count: 1}] : []
}

function bankSlots (accountData) {
  if (!accountData.bank) {
    return []
  }

  const count = (accountData.bank.length / 30) - 1
  return [{id: 19995, count: count}]
}

function characterSlots (accountData) {
  if (!accountData.characters) {
    return []
  }

  const count = Math.max(5, accountData.characters.length) - 5
  return [{id: 19994, count: count}]
}

function sharedInventorySlots (accountData) {
  if (!accountData.shared) {
    return []
  }

  const count = accountData.shared.length
  return [{id: 67071, count: count}]
}

function storageExpanders (accountData) {
  if (!accountData.materials) {
    return []
  }

  const stacks = accountData.materials.map(x => x.count)
  const maxStack = Math.max.apply(null, stacks)
  const slots = Math.max(1, Math.ceil(maxStack / 250)) - 1

  return [{id: 42932, count: slots}]
}

function craftingLicences (accountData) {
  if (!accountData.characters) {
    return []
  }

  const activeCrafts = accountData.characters.map(x => {
    return x.crafting.filter(y => y.active).length
  })
  const licenses = Math.max(2, Math.max.apply(null, activeCrafts)) - 2

  return [{id: 42970, count: licenses}]
}

function characterBagSlots (accountData) {
  if (!accountData.characters) {
    return []
  }

  let sum = 0

  accountData.characters.map(character => {
    if (!character.bags) {
      return
    }

    sum += Math.max(character.bags.length - 5, 0)
  })

  return [{id: 19993, count: sum}]
}

function buildTemplates (accountData) {
  if (!accountData.characters) {
    return []
  }

  let sum = 0

  // A character has 3 tabs available by default and can be expanded up to 6 by purchasing
  // a Build Template Expansion (one item for one tab). These templates are character specific.
  accountData.characters.map(character => {
    if (!character.build_tabs_unlocked) {
      return
    }

    sum += Math.max(character.build_tabs_unlocked - 3, 0)
  })

  return [{id: 92209, count: sum}]
}

function equipmentTemplates (accountData) {
  if (!accountData.characters) {
    return []
  }

  let sum = 0

  // A character has 2 tabs available by default and can be expanded up to 6 by purchasing
  // a Equipment Template Expansion (one item for one tab). These templates are character specific.
  accountData.characters.map(character => {
    if (!character.equipment_tabs_unlocked) {
      return
    }

    sum += Math.max(character.equipment_tabs_unlocked - 2, 0)
  })

  return [{id: 92203, count: sum}]
}

function buildStorage (accountData) {
  if (!accountData.account) {
    return []
  }

  // An account has 3 tabs available by default and can be expanded up to 24 by purchasing
  // a Build Storage Expansion (one item for 3 tabs).
  const sum = accountData.account.build_storage_slots - 3

  return [{id: 92206, count: Math.floor(sum / 3)}]
}


text:
// Tests cloning and appending small and medium DOM trees.
function CloneNodes(size, style) {
    var me = this;
    this.size = size;
    this.style = style;

    this.name = me.size + ', ' + me.style;

    var nClones = 0;

    this.Setup = function() {
        // getDOMTree will initialize the global tree if necessary.
        me.domTree = me.getDOMTree();
        if (me.style == 'append')
            me.domTree = me.domTree.cloneNode(true);
    };

    this.Test = function() {
        var kIterations = 10;
        if (me.style == 'clone') {
            for (var iterations = 0; iterations < kIterations; iterations++)
                me.domTree.cloneNode(true);
        } else {
            for (var iterations = 0; iterations < kIterations; iterations++)
                this.suite.benchmarkContent.appendChild(me.domTree);
        }
    };

    // Returns a tree of size me.size from the pool in the prototype, creating
    // one if needed.
    this.getDOMTree = function() {
        var domTree = me.Trees[me.size];
        if (!domTree) {
            switch (this.size) {
            case 'small':
                domTree = BenchmarkSuite.prototype.generateSmallTree();
                break;
            case 'medium':
                domTree = BenchmarkSuite.prototype.generateMediumTree();
                break;
            case 'large':
                domTree = BenchmarkSuite.prototype.generateLargeTree();
                break;
            }
            me.Trees[me.size] = domTree;
        }
        return domTree;
    };

    this.GetBenchmark = function() {
        return new Benchmark(this.name, this.Test, this.Setup);
    };
};

CloneNodes.prototype = {
    Sizes: ['small', 'medium'],
    Styles: ['clone', 'append'],
    Trees: {}
};

// Generate a test for each size/style combination.
var benchmarks = [];
CloneNodes.prototype.Sizes.forEach(function(size) {
    CloneNodes.prototype.Styles.forEach(function(style) {
        benchmarks.push(new CloneNodes(size, style).GetBenchmark());
    });
});

var CloneNodesTest = new BenchmarkSuite('CloneNodes', benchmarks);


text:
package net.diabetech.lang;

import net.diabetech.util.*;

public class ThreadHelper {

    private ThreadHelper() {
    }

    public static void sleep(long milliseconds) {
        try {
            Thread.sleep(milliseconds);
        } catch (InterruptedException ie) {
            // ok, continue
            Logger.log("TimerManager.sleep() interrupted", milliseconds);
        }
    }
}


text:
<?php

class Google_Service_SystemsManagement_WindowsUpdateSettings extends Google_Collection
{
  protected $collection_key = 'exclusivePatches';
  public $classifications;
  public $excludes;
  public $exclusivePatches;

  public function setClassifications($classifications)
  {
    $this->classifications = $classifications;
  }
  public function getClassifications()
  {
    return $this->classifications;
  }
  public function setExcludes($excludes)
  {
    $this->excludes = $excludes;
  }
  public function getExcludes()
  {
    return $this->excludes;
  }
  public function setExclusivePatches($exclusivePatches)
  {
    $this->exclusivePatches = $exclusivePatches;
  }
  public function getExclusivePatches()
  {
    return $this->exclusivePatches;
  }
}


text:
package org.geometerplus.android.util;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;

public abstract class PackageUtil {
	private static Uri marketUri(String pkg) {
		return Uri.parse("market://details?id=" + pkg);
	}

	public static boolean installFromMarket(Activity activity, String pkg) {
		try {
			activity.startActivity(new Intent(
				Intent.ACTION_VIEW, marketUri(pkg)
			));
			return true;
		} catch (ActivityNotFoundException e) {
			return false;
		}
	}
	public static boolean canBeStarted(Context context, Intent intent, boolean checkSignature) {
		final PackageManager manager = context.getApplicationContext().getPackageManager();
		final ResolveInfo info =
			manager.resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY);
		if (info == null) {
			return false;
		}
		final ActivityInfo activityInfo = info.activityInfo;
		if (activityInfo == null) {
			return false;
		}
		if (!checkSignature) {
			return true;
		}
		return
			PackageManager.SIGNATURE_MATCH ==
			manager.checkSignatures(context.getPackageName(), activityInfo.packageName);
	}
}


text:
from dockyard.var import GLOBAL

routes = []

def init():
    GLOBAL.routes.extend(routes)


text:
<?php

namespace Illuminate\Foundation\Console;

use Closure;
use Illuminate\Console\Command;
use Illuminate\Contracts\Routing\UrlGenerator;
use Illuminate\Routing\Route;
use Illuminate\Routing\Router;
use Illuminate\Routing\ViewController;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
use ReflectionClass;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Terminal;

class RouteListCommand extends Command
{
    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'route:list';

    /**
     * The name of the console command.
     *
     * This name is used to identify the command during lazy loading.
     *
     * @var string|null
     */
    protected static $defaultName = 'route:list';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'List all registered routes';

    /**
     * The router instance.
     *
     * @var \Illuminate\Routing\Router
     */
    protected $router;

    /**
     * The table headers for the command.
     *
     * @var string[]
     */
    protected $headers = ['Domain', 'Method', 'URI', 'Name', 'Action', 'Middleware'];

    /**
     * The terminal width resolver callback.
     *
     * @var \Closure|null
     */
    protected static $terminalWidthResolver;

    /**
     * The verb colors for the command.
     *
     * @var array
     */
    protected $verbColors = [
        'ANY' => 'red',
        'GET' => 'blue',
        'HEAD' => '#6C7280',
        'OPTIONS' => '#6C7280',
        'POST' => 'yellow',
        'PUT' => 'yellow',
        'PATCH' => 'yellow',
        'DELETE' => 'red',
    ];

    /**
     * Create a new route command instance.
     *
     * @param  \Illuminate\Routing\Router  $router
     * @return void
     */
    public function __construct(Router $router)
    {
        parent::__construct();

        $this->router = $router;
    }

    /**
     * Execute the console command.
     *
     * @return void
     */
    public function handle()
    {
        $this->router->flushMiddlewareGroups();

        if (! $this->router->getRoutes()->count()) {
            return $this->error("Your application doesn't have any routes.");
        }

        if (empty($routes = $this->getRoutes())) {
            return $this->error("Your application doesn't have any routes matching the given criteria.");
        }

        $this->displayRoutes($routes);
    }

    /**
     * Compile the routes into a displayable format.
     *
     * @return array
     */
    protected function getRoutes()
    {
        $routes = collect($this->router->getRoutes())->map(function ($route) {
            return $this->getRouteInformation($route);
        })->filter()->all();

        if (($sort = $this->option('sort')) !== null) {
            $routes = $this->sortRoutes($sort, $routes);
        } else {
            $routes = $this->sortRoutes('uri', $routes);
        }

        if ($this->option('reverse')) {
            $routes = array_reverse($routes);
        }

        return $this->pluckColumns($routes);
    }

    /**
     * Get the route information for a given route.
     *
     * @param  \Illuminate\Routing\Route  $route
     * @return array
     */
    protected function getRouteInformation(Route $route)
    {
        return $this->filterRoute([
            'domain' => $route->domain(),
            'method' => implode('|', $route->methods()),
            'uri' => $route->uri(),
            'name' => $route->getName(),
            'action' => ltrim($route->getActionName(), '\\'),
            'middleware' => $this->getMiddleware($route),
        ]);
    }

    /**
     * Sort the routes by a given element.
     *
     * @param  string  $sort
     * @param  array  $routes
     * @return array
     */
    protected function sortRoutes($sort, array $routes)
    {
        return Arr::sort($routes, function ($route) use ($sort) {
            return $route[$sort];
        });
    }

    /**
     * Remove unnecessary columns from the routes.
     *
     * @param  array  $routes
     * @return array
     */
    protected function pluckColumns(array $routes)
    {
        return array_map(function ($route) {
            return Arr::only($route, $this->getColumns());
        }, $routes);
    }

    /**
     * Display the route information on the console.
     *
     * @param  array  $routes
     * @return void
     */
    protected function displayRoutes(array $routes)
    {
        $routes = collect($routes);

        $this->output->writeln(
            $this->option('json') ? $this->asJson($routes) : $this->forCli($routes)
        );
    }

    /**
     * Get the middleware for the route.
     *
     * @param  \Illuminate\Routing\Route  $route
     * @return string
     */
    protected function getMiddleware($route)
    {
        return collect($this->router->gatherRouteMiddleware($route))->map(function ($middleware) {
            return $middleware instanceof Closure ? 'Closure' : $middleware;
        })->implode("\n");
    }

    /**
     * Filter the route by URI and / or name.
     *
     * @param  array  $route
     * @return array|null
     */
    protected function filterRoute(array $route)
    {
        if (($this->option('name') && ! Str::contains($route['name'], $this->option('name'))) ||
            ($this->option('path') && ! Str::contains($route['uri'], $this->option('path'))) ||
            ($this->option('method') && ! Str::contains($route['method'], strtoupper($this->option('method')))) ||
            ($this->option('domain') && ! Str::contains($route['domain'], $this->option('domain')))) {
            return;
        }

        if ($this->option('except-path')) {
            foreach (explode(',', $this->option('except-path')) as $path) {
                if (str_contains($route['uri'], $path)) {
                    return;
                }
            }
        }

        return $route;
    }

    /**
     * Get the table headers for the visible columns.
     *
     * @return array
     */
    protected function getHeaders()
    {
        return Arr::only($this->headers, array_keys($this->getColumns()));
    }

    /**
     * Get the column names to show (lowercase table headers).
     *
     * @return array
     */
    protected function getColumns()
    {
        return array_map('strtolower', $this->headers);
    }

    /**
     * Parse the column list.
     *
     * @param  array  $columns
     * @return array
     */
    protected function parseColumns(array $columns)
    {
        $results = [];

        foreach ($columns as $column) {
            if (str_contains($column, ',')) {
                $results = array_merge($results, explode(',', $column));
            } else {
                $results[] = $column;
            }
        }

        return array_map('strtolower', $results);
    }

    /**
     * Convert the given routes to JSON.
     *
     * @param  \Illuminate\Support\Collection  $routes
     * @return string
     */
    protected function asJson($routes)
    {
        return $routes
            ->map(function ($route) {
                $route['middleware'] = empty($route['middleware']) ? [] : explode("\n", $route['middleware']);

                return $route;
            })
            ->values()
            ->toJson();
    }

    /**
     * Convert the given routes to regular CLI output.
     *
     * @param  \Illuminate\Support\Collection  $routes
     * @return array
     */
    protected function forCli($routes)
    {
        $routes = $routes->map(
            fn ($route) => array_merge($route, [
                'action' => $this->formatActionForCli($route),
                'method' => $route['method'] == 'GET|HEAD|POST|PUT|PATCH|DELETE|OPTIONS' ? 'ANY' : $route['method'],
                'uri' => $route['domain'] ? ($route['domain'].'/'.ltrim($route['uri'], '/')) : $route['uri'],
            ]),
        );

        $maxMethod = mb_strlen($routes->max('method'));

        $terminalWidth = $this->getTerminalWidth();

        return $routes->map(function ($route) use ($maxMethod, $terminalWidth) {
            [
                'action' => $action,
                'domain' => $domain,
                'method' => $method,
                'middleware' => $middleware,
                'uri' => $uri,
            ] = $route;

            $middleware = Str::of($middleware)->explode("\n")->filter()->whenNotEmpty(
                fn ($collection) => $collection->map(
                    fn ($middleware) => sprintf('         %s⇂ %s', str_repeat(' ', $maxMethod), $middleware)
                )
            )->implode("\n");

            $spaces = str_repeat(' ', max($maxMethod + 6 - mb_strlen($method), 0));

            $dots = str_repeat('.', max(
                $terminalWidth - mb_strlen($method.$spaces.$uri.$action) - 6 - ($action ? 1 : 0), 0
            ));

            $dots = empty($dots) ? $dots : " $dots";

            if ($action && ! $this->output->isVerbose() && mb_strlen($method.$spaces.$uri.$action.$dots) > ($terminalWidth - 6)) {
                $action = substr($action, 0, $terminalWidth - 7 - mb_strlen($method.$spaces.$uri.$dots)).'…';
            }

            $method = Str::of($method)->explode('|')->map(
                fn ($method) => sprintf('<fg=%s>%s</>', $this->verbColors[$method] ?? 'default', $method),
            )->implode('<fg=#6C7280>|</>');

            return [sprintf(
                '  <fg=white;options=bold>%s</> %s<fg=white>%s</><fg=#6C7280>%s %s</>',
                $method,
                $spaces,
                preg_replace('#({[^}]+})#', '<fg=yellow>$1</>', $uri),
                $dots,
                str_replace('   ', ' › ', $action),
            ), $this->output->isVerbose() && ! empty($middleware) ? "<fg=#6C7280>$middleware</>" : null];
        })->flatten()->filter()->prepend('')->push('')->toArray();
    }

    /**
     * Get the formatted action for display on the CLI.
     *
     * @param  array  $route
     * @return string
     */
    protected function formatActionForCli($route)
    {
        ['action' => $action, 'name' => $name] = $route;

        if ($action === 'Closure' || $action === ViewController::class) {
            return $name;
        }

        $name = $name ? "$name   " : null;

        $rootControllerNamespace = $this->laravel[UrlGenerator::class]->getRootControllerNamespace()
            ?? ($this->laravel->getNamespace().'Http\\Controllers');

        if (str_starts_with($action, $rootControllerNamespace)) {
            return $name.substr($action, mb_strlen($rootControllerNamespace) + 1);
        }

        $actionClass = explode('@', $action)[0];

        if (class_exists($actionClass) && str_starts_with((new ReflectionClass($actionClass))->getFilename(), base_path('vendor'))) {
            $actionCollection = collect(explode('\\', $action));

            return $name.$actionCollection->take(2)->implode('\\').'   '.$actionCollection->last();
        }

        return $name.$action;
    }

    /**
     * Get the terminal width.
     *
     * @return int
     */
    public static function getTerminalWidth()
    {
        return is_null(static::$terminalWidthResolver)
            ? (new Terminal)->getWidth()
            : call_user_func(static::$terminalWidthResolver);
    }

    /**
     * Set a callback that should be used when resolving the terminal width.
     *
     * @param  \Closure|null  $resolver
     * @return void
     */
    public static function resolveTerminalWidthUsing($resolver)
    {
        static::$terminalWidthResolver = $resolver;
    }

    /**
     * Get the console command options.
     *
     * @return array
     */
    protected function getOptions()
    {
        return [
            ['json', null, InputOption::VALUE_NONE, 'Output the route list as JSON'],
            ['method', null, InputOption::VALUE_OPTIONAL, 'Filter the routes by method'],
            ['name', null, InputOption::VALUE_OPTIONAL, 'Filter the routes by name'],
            ['domain', null, InputOption::VALUE_OPTIONAL, 'Filter the routes by domain'],
            ['path', null, InputOption::VALUE_OPTIONAL, 'Only show routes matching the given path pattern'],
            ['except-path', null, InputOption::VALUE_OPTIONAL, 'Do not display the routes matching the given path pattern'],
            ['reverse', 'r', InputOption::VALUE_NONE, 'Reverse the ordering of the routes'],
            ['sort', null, InputOption::VALUE_OPTIONAL, 'The column (precedence, domain, method, uri, name, action, middleware) to sort by', 'uri'],
        ];
    }
}


text:
<!DOCTYPE html>
<html>
<head>
  <title></title>
</head>
<body>

<script src="../taskrepo.js" type="text/javascript" charset="utf-8"></script>
</body>
</html>


text:
layout: post
date: 2010-12-02
time: "13:00:00"
authors: ["Greg Wilson"]
title: Programmer Competency Matrix
tags: ["Noticed"]
---

There's no scientific research behind this tabulation of what programmers ought to know, and some of the categorizations are unactionably vague, but it's still a useful guide. Most of Software Carpentry is Level 1, with some Level 0 and Level 2 stuff blended in.


text:
package com.base2services.b2cdi.config.resolvers;

import com.base2services.b2cdi.config.ConfigProperties;
import com.base2services.b2cdi.config.ConfigResolver;

import javax.enterprise.inject.Any;
import javax.enterprise.inject.Instance;
import javax.inject.Inject;
import java.util.Properties;

/**
 * Resolves Properties from a Properties file
 *
 * @author aaronwalker
 */
public class PropertiesFileConfigResolver implements ConfigResolver {

    @Inject
    @Any
    @ConfigProperties
    private Instance<Properties> propertyInstance;

    @Override
    public String resolve(String name) {
        for(Properties properties : propertyInstance) {
            if(properties.containsKey(name)) {
                return properties.getProperty(name);
            }
        }
        return null;
    }

    @Override
    public Integer salience() {
        return 20;
    }

}


text:
package org.headlessintrace.client.test.level1.request;

import static org.junit.Assert.*;

import java.io.PrintStream;
import java.util.Enumeration;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

import org.headlessintrace.client.DefaultFactory;
import org.headlessintrace.client.IntraceException;
import org.headlessintrace.client.filter.IncludeThisEventFilterExt;
import org.headlessintrace.client.filter.IncludeThisMethodFilterExt;
import org.headlessintrace.client.model.ITraceEvent;
import org.headlessintrace.client.request.ICompletedRequestCallback;
import org.headlessintrace.client.request.IRequest;
import org.headlessintrace.client.request.IRequestSeparator;
import org.headlessintrace.client.test.TestUtil;
import org.junit.Before;
import org.junit.Test;

public class TestMultiThreadedRequestSeparator {
	public static AtomicInteger atomicRequestCount = new AtomicInteger();
	public static AtomicInteger atomicEventCount = new AtomicInteger();
	/**
	 * Would like to use a closure instead of this, but closures don't exist yet.
	 */
	List<IRequest> m_completedRequests = new CopyOnWriteArrayList<IRequest>();
	private static final String THREAD_COMPLETION_EVENT = "[08:36:43.885]:[412]:java.lang.Thread:run: }:682";
	private static final String THREAD_START_EVENT = "[08:36:43.885]:[412]:java.lang.Thread:run: {:682";

	private ITraceEvent m_requestCompletionEvent = null;
	private ITraceEvent m_requestStartEvent = null;

	@Before
	public void setup() throws IntraceException {
		m_requestCompletionEvent = DefaultFactory.getFactory().getEventParser().createEvent(THREAD_COMPLETION_EVENT, 0);
		m_requestStartEvent = DefaultFactory.getFactory().getEventParser().createEvent(THREAD_START_EVENT, 0);
		atomicRequestCount.set(0);
	}

	@Test
	public void canSeparteMultipleMultiThreadedRequests_threeEach() throws IntraceException {
		IRequestSeparator requestSeparator = DefaultFactory.getFactory().getRequestSeparator();
		IncludeThisEventFilterExt eventFilter = new IncludeThisEventFilterExt();
		eventFilter.setFilterCriteria(m_requestCompletionEvent);
		IncludeThisEventFilterExt eventFilter2 = new IncludeThisEventFilterExt();
		eventFilter2.setFilterCriteria(m_requestStartEvent);

		requestSeparator.setRequestCompletionFilter(eventFilter);
		requestSeparator.setRequestStartFilter(eventFilter2);

		//requestSeparator.setRequestCompletionEvent(m_requestCompletionEvent);//Whenever this particular event first, that marks the end of a thread/request.

		m_completedRequests.clear();
		ICompletedRequestCallback requestCallback = new ICompletedRequestCallback() {
			@Override
			public void requestCompleted(IRequest events) {
				m_completedRequests.add(events);
			}
		};
		requestSeparator.setCompletedRequestCallback(requestCallback);

		//Try some larger and arbitrary numbers
		int numThreads = 51;
		int iterations = 1013;
	     CountDownLatch startSignal = new CountDownLatch(1);
	     CountDownLatch doneSignal = new CountDownLatch(numThreads);
		for (int i = 0; i < numThreads; i++) {
		       new Thread(new EventAndThreadIdGenerator(startSignal, doneSignal, requestSeparator,iterations, System.out)).start();
		}
	     startSignal.countDown();      // let all threads proceed
	     try {
	    	 //System.out.println("Waiting to finish");
			doneSignal.await();
			//System.out.println("Finished.");
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}           // wait for all to finish

		assertEquals("Whoops, the test infrastructure didn't produce the right # of requests", numThreads*iterations, atomicRequestCount.get());
		assertEquals("Whoops, the test infrastructure didn't produce the right number of events.", numThreads*iterations*EventAndThreadIdGenerator.getEventCount(), atomicEventCount.get());

		assertEquals("Added a fixed number of java.lang.Thread.run EXIT events using multiple threads.", numThreads*iterations, m_completedRequests.size());
		assertEquals("Whoops.  The RequestSeparator should have evicted all the requests, but some were left",0,requestSeparator.size());
		//System.out.println("collected events [" + atomicEventCount.get() + "] ");
		ConcurrentHashMap<String, IRequest> mapInFlight = requestSeparator.getInFlightRequests();
		for(IRequest request : m_completedRequests) {
			if (request==null) {
				fail("Shouldn't have any nulls here.");
			} else {
				//System.out.println("#%#% Found non-null item in hash map");
				List<ITraceEvent> endEvents = request.getEvents();
//				for(ITraceEvent x : endEvents) {
//					System.out.println("parent thread [" + request.getThreadId() + "] simulated thread id [" + x.getThreadId() + "] Event [" + x.getValue() + "]");
//				}
				assertEquals("Expected 2 events for each request", 3, endEvents.size());
			}
		}

		assertEquals("All in-flight requests should have been complted",0, mapInFlight.size());
		//System.out.println("InFlight stuff###################################");
		Enumeration<IRequest> inFlightEnum =  mapInFlight.elements();
		while(inFlightEnum.hasMoreElements()) {
			IRequest req = inFlightEnum.nextElement();
			for(ITraceEvent e : req.getEvents()) {
				System.out.println("Parent [" + req.getThreadId() + "] child [" + e.getThreadId() + "][" + e.getAgentTimeMillis() + "]");
			}
		}
	}

}

class EventAndThreadIdGenerator implements Runnable {
	public static int getEventCount() {
		return 5;
	}
	/**
	 * These events represent the same two events getting fired repeatedly, but synchronously, where one thread doesn't start until the previous one ends.
	 */
	static final String EVENTS_FROM_MULTIPLE_REQUESTS_PRISTINE =
			  "[08:36:43.884]:[91]:java.lang.Thread:run: {:682\n"
		    + "[08:36:43.881]:[89]:org.hsqldb.jdbc.jdbcConnection:prepareStatement: Arg: INSERT INTO Event (name, description, date, location) VALUES(?, ?, ?, ?)\n"
		    + "[08:36:43.882]:[90]:org.hsqldb.jdbc.jdbcConnection:prepareStatement: Arg: INSERT INTO Event (name, description, date, location) VALUES(?, ?, ?, ?)\n"
		    + "[08:36:43.883]:[90]:org.hsqldb.jdbc.jdbcConnection:prepareStatement: Arg: INSERT INTO Event (name, description, date, location) VALUES(?, ?, ?, ?)\n"
			+ "[08:36:43.884]:[91]:java.lang.Thread:run: }:682\n";
	List<ITraceEvent> events = null;
   private final CountDownLatch m_startSignal;
   private final CountDownLatch m_doneSignal;
	private int m_iterations = -1;
	private IRequestSeparator m_requestSeparator = null;
	PrintStream m_out = null;
	public EventAndThreadIdGenerator(CountDownLatch startSignal, CountDownLatch doneSignal, IRequestSeparator irs, int iterations, PrintStream out) throws IntraceException {

		events =  TestUtil.createEvents(EVENTS_FROM_MULTIPLE_REQUESTS_PRISTINE);
		m_iterations = iterations;
		m_requestSeparator = irs;
		this.m_startSignal = startSignal;
		this.m_doneSignal = doneSignal;
		this.m_out = out;
	}
    public void run() {
        try {
        	//m_out.println("Waiting to start [" + Thread.currentThread().getName() + "]");
			m_startSignal.await();
        	//m_out.println("starting [" + Thread.currentThread().getName() + "]");

			for(int i = 0; i < m_iterations; i++) {
				//Simulate events from the InTrace server agent
				int simulatedRequestId = TestMultiThreadedRequestSeparator.atomicRequestCount.incrementAndGet();
				List<ITraceEvent> events = TestUtil.createEvents(EVENTS_FROM_MULTIPLE_REQUESTS_PRISTINE);
				for(ITraceEvent e : events) {
					//Debug info
					int eventSeq = 	TestMultiThreadedRequestSeparator.atomicEventCount.incrementAndGet();
					e.setThreadId(""+simulatedRequestId);
					String strSimulatedThreadId = Thread.currentThread().getName()+"~"+simulatedRequestId+"!"+eventSeq;
					e.setValue(strSimulatedThreadId);
					e.setSourceLineNumber(eventSeq);
					m_requestSeparator.add(e);
				}
			}
	        m_doneSignal.countDown();
		} catch (InterruptedException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IntraceException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

    }

}


text:
//
//  BaseCell.h
//  DynamicTableGenerator
//
//  Created by tpb on 11/14/14.
//  Copyright (c) 2014 Theodore Brown. All rights reserved.
// These cells are for controlling the view, the paired Input is the controller/model access

#import <UIKit/UIKit.h>
#import "PureLayout.h"

#import "DynamicTableViewConstants.h"

#import "TableCellEditableProtocol.h"
#import "TableViewNavigationDelegate.h"

/**
 *  BaseCell is the root implemntation of `UITableViewCell` all DynamicCells are based off of.
 *  This cell has a title and subtitle but performs no actions
 */
@interface BaseCell : UITableViewCell {
    id <TableCellEditable> _delegate;
    id <TableViewNavigationDelegate> tableViewDelegate;
}

#define kLabelHorizontalInsets      15.0f
#define kLabelVerticalInsets        10.0f
#define kLabelHorizontalSpace       5.0f

@property (nonatomic, retain) NSIndexPath * indexPath;
@property (nonatomic, strong) IBOutlet UILabel *title;
@property (nonatomic, strong) IBOutlet UILabel *subTitle;
@property (nonatomic, assign) BOOL didSetupConstraints;
@property (nonatomic, assign) BOOL didSetupAcessoryConstraints;
//delegates
@property (nonatomic, strong) id delegate;
@property (nonatomic, strong) id tableViewDelegate;
//content selector / action
@property (nonatomic) SEL contentSelector;
//cell content config
@property (strong, nonatomic) NSDictionary *cellContentFormatDict;
@property (strong, nonatomic) NSString *cellContentTitle;//default string used in content: e.g. text box prompt string
@property (nonatomic,strong) NSNumber* cellContentFormatType; //stores a value for the content of the cell IE date vs datetime or Numpad vs text //static value used to define format of data
@property (strong, nonatomic) NSString *cellContentFormatString; //string used to format data for display
@property (nonatomic,strong) NSNumber* cellFormatType; //the global value of the cell type

- (id)initWithStyle:(UITableViewCellStyle)style atIndex:(NSIndexPath*)indexPath withReuseIdentifier:(NSString *)reuseIdentifier;

-(void) showContentFromSelector;
-(void) defineContentSelector:(SEL) contentSelector;
- (void) contentWasSelected:(id) sender;

-(void) defineCellFormatType:(NSNumber*)cellFormatEnumType; //defines cellFormatType
-(void) setCellFormatDict:(NSDictionary *)cellFormatDict;
- (void) cellFormatWasUpdated;

@end


text:
#!/usr/bin/env python3
# Copyright 2021 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Finds unused assets in Chromium code base.

This script is experimental. While it tries to discover known usages, the assets
identified should still be manually verified. It currently only looks for PNG
files.

The script also ignores several directory trees, such as third_party, docs, and
testing directories.

Usage:
  Either execute the script from the chromium/src directory or specify a
  chromium/src directory via the --src_dir flag.

  Example:
    $ tools/resources/find_unused_assets.py

  To output the list of unused assets to a file, use the --output_unused_files
  flag.

  Example:
    $ tools/resources/find_unused_assets.py \
      --output_unused_files=/tmp/unused_files.txt
"""

import argparse
from concurrent import futures
import functools
from html import parser as html_parser
import itertools
import json
import logging
import os
import pprint
import re
import subprocess
import sys
import threading
from typing import Iterable, List, Optional, Sequence, Set, Text, Tuple
from xml.etree import ElementTree as ET

IGNORED_PATHSPECS = [
    ':!**/docs/**',
    ':!**/pdfium/**',
    ':!**/test/**',
    ':!**/testdata/**',
    ':!**/testing/**',
    ':!**/vectorcanvastest/**',
    ':!**/*unittest/**',
    ':!docs/**',
    ':!native_client_sdk/**',
    ':!testing/**',
    ':!third_party/**',
    ':!tools/perf/page_sets/**',
    ':!tools/stats_viewer/**',
]

logger = logging.getLogger(__name__)

def init_logger():
  logger.setLevel(logging.DEBUG)
  ch = logging.StreamHandler()
  ch.setLevel(logging.INFO)
  formatter = logging.Formatter(
      '%(levelname)s %(asctime)s %(filename)s:%(lineno)d] %(message)s')
  ch.setFormatter(formatter)
  logger.addHandler(ch)

def parse_args():
  parser = argparse.ArgumentParser()
  parser.add_argument(
      '--src_dir',
      help='Optional chromium/src directory to analyze. If not specified, '
      'defaults to current working directory.')
  parser.add_argument('--output_unused_files',
                      help='Filepath to output the list of unused files.')
  parser.add_argument('--output_all_png_files',
                      help='Filepath to output the list of all PNG files.')
  return parser.parse_args()

def list_files(pathspecs: Sequence[str]) -> List[str]:
  cmd = ['git', 'ls-files'] + list(pathspecs) + IGNORED_PATHSPECS
  return subprocess.check_output(cmd).decode('utf-8').strip().split('\n')

def get_all_ext_files(extension: str) -> List[str]:
  return list_files([f'**/*.{extension}'])

def find_filepath_usage(fpath: str, segs: int = 1):
  """Finds file usage based on filepath.

  Args:
    fpath: The relative filepath.
    segs: The number of filepath segments to use for checking.

  Returns:
    True if usage found, False otherwise.
  """
  pattern = r'[\\/]'.join(fpath.split(os.sep)[-segs:])
  pattern = pattern.replace('\\', '\\\\')
  pattern = pattern.replace('.', '\\.')
  found = grep_pattern(pattern, pathspecs=tuple(IGNORED_PATHSPECS))
  if not found:
    logger.info('Found unused file: %s', fpath)
  return found

@functools.lru_cache()
def grep_pattern(pattern: Text,
                 pathspecs: Optional[Sequence[Text]] = None,
                 fixed: bool = False) -> List[Text]:
  """Greps for the specified pattern.

  Args:
    pattern: Regex pattern to find.
    pathspecs: Optional sequence of pathspecs to limit the search.
    fixed: Whether the pattern should be treated as a fixed string instead of a
      regex pattern.

  Returns:
    A list of matching filepaths.
  """
  pathspecs = pathspecs or []
  cmd = ['git', 'grep', '-I', '-w', '-l', '-e', pattern]
  if fixed:
    cmd.append('-F')
  cmd.append('--')
  cmd.extend(pathspecs)
  try:
    return subprocess.check_output(cmd).decode('utf-8').strip().split('\n')
  except subprocess.CalledProcessError as ex:
    if ex.returncode == 1:
      return []
    else:
      logger.exception('Got error when grepping: %s', pattern)
      raise

def find_usage_of_java_res(fpath: Text,
                           pathspecs: Optional[Iterable[Text]] = None
                           ) -> List[Text]:
  """Finds usage of a Java image resource.

  Args:
    fpath: The filepath to find.
    pathspecs: Optional pathspecs to look for usages.

  Returns:
    A list of filepaths that use |fpath|.
  """
  pathspecs = pathspecs or []
  common_pathspecs = list(pathspecs) + [':!**/*.gni', ':!**/*.gn'
                                        ] + IGNORED_PATHSPECS
  basename = os.path.basename(fpath).rsplit('.')[0]
  dirname = os.path.dirname(fpath)
  if 'drawable' in dirname:
    res_type = 'drawable'
  elif 'mipmap' in dirname:
    res_type = 'mipmap'
  else:
    raise ValueError(f'Could not parse resource type from filepath: {fpath}')

  pathspec_prefixes = [
      'android_webview',
      'chrome/android',
      'chrome/browser',
      'components',
      'content/public/android',
      'content/shell/android',
      'remoting/android',
      'tools/android',
      'ui/android',
      'weblayer/browser',
      'weblayer/shell',
  ]

  xml_pattern = f'@{res_type}/{basename}'
  found = grep_pattern(
      xml_pattern,
      pathspecs=tuple([p + '/**/*.xml'
                       for p in pathspec_prefixes] + common_pathspecs),
      fixed=True)

  java_pattern = f'R.{res_type}.{basename}'
  found = found or grep_pattern(
      java_pattern,
      pathspecs=tuple([p + '/**/*.java' for p in pathspec_prefixes] + [
          'chrome/browser/android/resource_id.h',
          'components/resources/android/*.h'
      ] + common_pathspecs),
      fixed=True)

  if not found:
    logger.info('Found unused file: %s', fpath)
  return found

def filter_usages_of_java_res(png_files: Iterable[Text], path_pattern: Text
                              ) -> Tuple[Set[Text], Set[Text]]:
  """Filters and finds used and unused Java image resources.

  Args:
    png_files: The paths of image files to filter through and find usages of.
    path_pattern: The regex pattern to filter filepaths.

  Returns:
    A tuple of (used, unused) filepaths.
  """
  used_png_files = set()
  unused_png_files = set()
  containing_files = set()
  matcher = re.compile(path_pattern)
  for png_file in sorted(png_files):
    matches = matcher.search(png_file)
    if not matches:
      continue
    found = find_usage_of_java_res(png_file)
    if found:
      used_png_files.add(png_file)
      containing_files |= set(found)
    else:
      unused_png_files.add(png_file)
  logger.info('Found %d PNG files used under %s dirs.', len(used_png_files),
              path_pattern)
  logger.info('Found %d unused PNG files under %s dirs.', len(unused_png_files),
              path_pattern)
  logger.debug('Containing files:\n%s',
               pprint.pformat(sorted(containing_files)))
  return used_png_files, unused_png_files

def find_images_by_filepath_string(filepaths: Iterable[Text],
                                   all_png_files: Set[Text]
                                   ) -> Tuple[Set[Text], Set[Text]]:
  """Finds images used and maybe unused by looking at filepath strings.

  The maybe unused files are determined by the fact that they're not referenced
  by any of the files in |filepaths| that are in their ancestor directories.

  Args:
    filepaths: The paths of the files that contain filepath strings.
    all_png_files: The set of all PNG files, used to filter results and
      find unused files.

  Returns:
    A tuple of (used_files, maybe_unused_files).
  """
  used_files = set()
  maybe_unused_files = set()
  ignored_files = set()
  png_filepath_matcher = re.compile(r'"([^/][^"]+\.png)"')
  for filepath in filepaths:
    rel_dir = os.path.dirname(filepath)
    used_by_current_file = set()
    with open(filepath, 'rb') as f:
      content = f.read().decode('utf-8')
      for match in png_filepath_matcher.finditer(content):
        img_relpath = match.group(1)
        rooted_img_path = os.path.join(rel_dir, img_relpath)
        if 'test' in os.path.dirname(img_relpath) or '$' in img_relpath:
          logger.debug('Ignoring %s', rooted_img_path)
          ignored_files.add(img_relpath)
          continue
        if rooted_img_path in all_png_files:
          used_by_current_file.add(rooted_img_path)
        else:
          logger.warning('PNG file %s does not exist, reffed in %s as %s',
                         rooted_img_path, filepath, img_relpath)
    used_files |= used_by_current_file
    # Consider any images in subdirectories that were not used by this file as
    # unused. Nested BUILD.gn files will be handled outside the loop.
    maybe_unused_files |= set(
        f for f in all_png_files
        if f.startswith(rel_dir) and f not in used_by_current_file)
  # Handles nested BUILD.gn files.
  maybe_unused_files -= used_files
  maybe_unused_files -= ignored_files
  return used_files, maybe_unused_files

def find_images_used_by_grd(all_png_files: Set[Text]) -> Set[Text]:
  """Finds image files referenced by grd/grdp.

  Args:
    all_png_files: The set of all PNG files, used to filter results.

  Returns:
    A set of image filepaths that are referenced by grd/grdp.
  """
  used_files = set()
  grd_files = set(get_all_ext_files('grd') + get_all_ext_files('grdp'))
  for grd_file in grd_files:
    grd_dir = os.path.dirname(grd_file)
    cur_relpaths = set()
    grd_root = ET.parse(grd_file).getroot()
    for elem in itertools.chain(grd_root.iter('include'),
                                grd_root.iter('structure')):
      relpath = elem.get('file')
      if relpath and relpath.endswith('.png'):
        relpath = relpath.replace('\\', '/')
        relpath = relpath.replace(
            '${input_tools_root_dir}',
            'third_party/google_input_tools/src/chrome/os')
        if relpath.startswith('${root_src_dir}'):
          relpath = relpath[len('${root_src_dir}') + 1]
        if relpath.startswith('/') or '$' in relpath:
          logger.error('When processing %s got weird relpath: %s', grd_file,
                       relpath)
          raise ValueError('Unexpected relpath!')
        rooted_filepath = os.path.normpath(os.path.join(grd_dir, relpath))
        if rooted_filepath in all_png_files:
          used_files.add(rooted_filepath)
        cur_relpaths.add(relpath)
    for relpath in cur_relpaths:
      pattern = re.compile(grd_dir + r'/(default_\d+_percent/)?' + relpath)
      for png_file in all_png_files:
        if pattern.match(png_file):
          used_files.add(png_file)
  return used_files

def find_images_used_by_html(all_png_files: Set[Text]) -> Set[Text]:
  """Finds images used by HTML img tags.

  Args:
    all_png_files: The set of all PNG files, used to filter results.

  Returns:
    A set of image filepaths referenced by HTML img tags.
  """
  current_relpaths = []

  class ImgHTMLParser(html_parser.HTMLParser):
    def handle_starttag(self, tag, attrs):
      if tag != 'img':
        return
      for name, value in attrs:
        if name != 'src' or not value.endswith('.png'):
          continue
        current_relpaths.append(value)

  used_files = set()
  ignored_src_pattern = re.compile(r'^(https?://)')
  html_files = set(get_all_ext_files('html'))
  for html_file in html_files:
    current_relpaths.clear()
    parser = ImgHTMLParser()
    with open(html_file, 'rb') as f:
      try:
        parser.feed(f.read().decode('utf-8'))
      except UnicodeDecodeError:
        logger.error('Failed to decode html file: %s', html_file)
        continue
    html_dir = os.path.dirname(html_file)
    for src_relpath in current_relpaths:
      if ignored_src_pattern.match(src_relpath):
        continue
      rooted_src_path = normalize_resource_url_path(html_dir, src_relpath)
      if '{{static}}' in src_relpath:
        # I don't know how to handle this yet.
        continue
      if rooted_src_path not in all_png_files:
        logger.debug('PNG file %s does not exist, reffed in %s as %s',
                     rooted_src_path, html_file, src_relpath)
        continue
      used_files.add(rooted_src_path)
  return used_files

def find_images_used_by_css(all_png_files: Set[Text]) -> Set[Text]:
  """Finds images used by css.

  Args:
    all_png_files: The set of all PNG files, used to filter results.

  Returns:
    A set of image filepaths referenced by css.
  """
  used_files = set()
  css_url_pattern = re.compile(r'\burl\(([^\)]+\.png)\)')
  # Both .css and .html files can contain css.
  files_with_css = set(get_all_ext_files('css') + get_all_ext_files('html'))
  for css_file in files_with_css:
    css_dir = os.path.dirname(css_file)
    with open(css_file, 'rb') as f:
      for match in css_url_pattern.finditer(f.read().decode('utf-8')):
        url_relpath = match.group(1)
        # TODO(aluh): Figure out if url references in css is relative to the
        # css file (current assumption) or the including html file.
        rooted_url_path = normalize_resource_url_path(css_dir, url_relpath)
        if rooted_url_path not in all_png_files:
          logger.debug('PNG file %s does not exist, reffed in %s as %s',
                       rooted_url_path, css_file, url_relpath)
          continue
        used_files.add(rooted_url_path)
  return used_files

def normalize_resource_url_path(rel_dir: Text, url: Text) -> Text:
  """Joins the relative root directory with the URL path and normalizes it.

  It handles the special case of the 'chrome://' web resource URL.

  Args:
    rel_dir: The relative directory from the source root.
    url: The URL path of the asset.

  Returns:
    The joined and normalized filepath.
  """
  if url.startswith('chrome://'):
    rooted_path = os.path.join('ui/webui', url[len('chrome://'):])
  else:
    rooted_path = os.path.join(rel_dir, url)
  return os.path.normpath(rooted_path)

def find_images_used_by_markdown(all_png_files: Set[Text]) -> Set[Text]:
  """Finds images used by markdown files.

  Args:
    all_png_files: The set of all PNG files, used to filter results.

  Returns:
    A set of image filepaths used by markdown files.
  """
  md_url_pattern = re.compile(r'\(([^\s\)]+\.png)[\s\)]')
  md_files = list_files(['**/README', '**/*.md'])
  used_files = set()
  for md_file in md_files:
    file_dir = os.path.dirname(md_file)
    with open(md_file, 'rb') as f:
      for match in md_url_pattern.finditer(f.read().decode('utf-8')):
        url_relpath = match.group(1)
        if url_relpath.startswith('http'):
          continue
        if url_relpath.startswith('/'):
          rooted_filepath = url_relpath.lstrip('/')
        else:
          rooted_filepath = os.path.join(file_dir, url_relpath)
        rooted_filepath = os.path.normpath(rooted_filepath)
        if rooted_filepath in all_png_files:
          used_files.add(rooted_filepath)
        else:
          logger.warning('PNG file %s does not exist, reffed in %s as %s',
                         rooted_filepath, md_file, url_relpath)
  return used_files

def find_images_used_by_ios_imageset(all_png_files: Set[Text]
                                     ) -> Tuple[Set[Text], Set[Text]]:
  """Finds images used and unused by ios imagesets and friends.

  Args:
    all_png_files: The set of all PNG files, used to filter results.

  Returns:
    A tuple of (used, unused) image filepaths from ios imagesets.
  """
  used_files = set()
  unused_files = set()
  json_files = set(
      get_all_ext_files('imageset/Contents.json') +
      get_all_ext_files('appiconset/Contents.json'))
  for json_file in json_files:
    rel_dir = os.path.dirname(json_file)
    with open(json_file, 'rb') as f:
      j = json.load(f)
      for elem in j.get('images', []):
        img_relpath = elem.get('filename', '')
        if not img_relpath.endswith('.png'):
          continue
        rooted_img_path = os.path.join(rel_dir, img_relpath)
        if rooted_img_path not in all_png_files:
          logger.warning('PNG file %s does not exist, reffed in %s as %s',
                         rooted_img_path, json_file, img_relpath)
          continue
        else:
          used_files.add(rooted_img_path)

  imageset_dirs = set(os.path.dirname(f) for f in json_files)
  imageset_png_files = set()
  for imageset_dir in imageset_dirs:
    imageset_png_files |= set(
        list_files([imageset_dir + '/*.png', imageset_dir + '/**/*.png']))
  unused_files = (imageset_png_files & all_png_files) - used_files

  return used_files, unused_files

def main() -> None:
  init_logger()
  args = parse_args()

  src_dir = os.getcwd()
  if args.src_dir and os.path.isdir(args.src_dir):
    src_dir = os.path.realpath(args.src_dir)
    os.chdir(src_dir)
  logger.info('Searching directory: %s', src_dir)

  # Set of all PNG files. Should not be modified.
  all_png_files = set(get_all_ext_files('png'))
  logger.info('Found %d PNG files total.', len(all_png_files))
  if args.output_all_png_files:
    with open(args.output_all_png_files, 'w') as fout:
      for fp in sorted(all_png_files):
        fout.write(fp)
        fout.write('\n')

  # Working set of files that still need to be examined.
  png_files = set(all_png_files)
  # Files that are used.
  used_png_files = set()
  # Files that are likely to be unused.
  likely_unused_png_files = set()

  # Exclude files used by grd files.
  logger.info('Looking for usages by grd files...')
  used_by_grd = find_images_used_by_grd(all_png_files)
  logger.info('Found %d PNG files used by grd files.', len(used_by_grd))
  used_png_files |= used_by_grd
  png_files -= used_png_files

  # Exclude files used by HTML files.
  logger.info('Looking for usages by html files...')
  used_by_html = find_images_used_by_html(all_png_files)
  logger.info('Found %d PNG files used by html img tags.', len(used_by_html))
  used_png_files |= used_by_html
  png_files -= used_png_files

  # Exclude files used in CSS.
  logger.info('Looking for usages by css files...')
  used_by_css = find_images_used_by_css(all_png_files)
  logger.info('Found %d PNG files used in css.', len(used_by_css))
  used_png_files |= used_by_css
  png_files -= used_png_files

  # Find files used by markdown.
  logger.info('Looking for usages by markdown files...')
  used_by_markdown = find_images_used_by_markdown(all_png_files)
  logger.info('Found %d PNG files used by markdown.', len(used_by_markdown))
  used_png_files |= used_by_markdown
  png_files -= used_png_files

  # Find images used by ios imagesets.
  logger.info('Looking for usages by ios imagesets...')
  used_by_imageset, unused_by_imageset = find_images_used_by_ios_imageset(
      all_png_files)
  logger.info('Found %d PNG files used in json.', len(used_by_imageset))
  used_png_files |= used_by_imageset
  png_files -= used_png_files
  logger.info('Found %d likely unused imageset PNG files.',
              len(unused_by_imageset))
  likely_unused_png_files |= unused_by_imageset
  png_files -= likely_unused_png_files

  # Check for usages by filepath string.
  manifest_pathspecs = ['**/manifest.json', '**/*.gni', '**/BUILD.gn']
  for pathspec in manifest_pathspecs:
    logger.info('Looking for usages with pathspec: %s', pathspec)
    used_by_pathspec, unused_by_pathspec = find_images_by_filepath_string(
        list_files([pathspec]), all_png_files)
    used_png_files |= used_by_pathspec
    png_files -= used_png_files
    likely_unused_png_files |= unused_by_pathspec
    png_files -= likely_unused_png_files
    logger.info('Found %d used PNG files from pathspec: %s',
                len(used_by_pathspec), pathspec)
    logger.info('Found %d likely unused PNG files from pathspec: %s',
                len(unused_by_pathspec), pathspec)

  # Check java resources image files.
  logger.info('Looking for usages by java or android resources...')
  path_patterns = [r'/res\w*/(drawable|mipmap)']
  for path_pattern in path_patterns:
    used_java_res_png_files, unused_java_res_png_files = (
        filter_usages_of_java_res(all_png_files, path_pattern=path_pattern))
    used_png_files |= used_java_res_png_files
    png_files -= used_png_files
    likely_unused_png_files |= unused_java_res_png_files
    png_files -= likely_unused_png_files

  logger.info('Still have %d remaining files:', len(png_files))
  pprint.pprint(sorted(png_files))

  # Check remaining files.
  lock = threading.Lock()
  remaining_used_files = set()
  remaining_unused_files = set()
  logger.info('Searching for remaining files...')

  def find_filepath_usage_wrapper(fpath: Text):
    found = find_filepath_usage(fpath)
    with lock:
      if found:
        remaining_used_files.add(fpath)
      else:
        remaining_unused_files.add(fpath)

  with futures.ThreadPoolExecutor(max_workers=32) as executor:
    num_processed = 0
    for future in futures.as_completed(
        executor.submit(find_filepath_usage_wrapper, fpath)
        for fpath in png_files):
      num_processed += 1
      if num_processed % 20 == 0:
        logger.info('Checked %d files so far.', num_processed)
      if future.exception():
        logger.error('Got exception when finding usage: %s', future.exception())

  logger.info('Found %d used misc PNG files.', len(remaining_used_files))
  logger.info('Found %d unused misc PNG files.', len(remaining_unused_files))
  used_png_files |= remaining_used_files
  likely_unused_png_files |= remaining_unused_files
  png_files -= used_png_files

  # Prune likely unused files.
  logger.info('Pruning likely unused files...')
  likely_unused_png_files -= used_png_files

  # Summarize findings.
  likely_unused_png_files = sorted(likely_unused_png_files)
  logger.info('Summary:')
  logger.info('  Found %d used files out of %d.', len(used_png_files),
              len(all_png_files))
  logger.info('  Found %d likely unused files.', len(likely_unused_png_files))
  pprint.pprint(likely_unused_png_files)

  if args.output_unused_files:
    with open(os.path.realpath(args.output_unused_files), 'w') as fout:
      for fp in likely_unused_png_files:
        fout.write(fp)
        fout.write('\n')
    logger.info('Saved list of likely unused files to: %s',
                args.output_unused_files)

if __name__ == '__main__':
  sys.exit(main())


text:
package net.daergoth.serviceapi.changelistener;

import net.daergoth.serviceapi.sensors.datatypes.SensorDataVO;

/**
 * Represents a command container object for the Sensor listener service,
 * that is executed when the related {@code Sensor}'s data changes.
 * For more information check out {@link DataChangeListenerLocal}.
 *
 * @see net.daergoth.serviceapi.changelistener.DataChangeListenerLocal
 */
public interface DataChangeHandler {

	/**
	 * Called when the listener detects change in the related {@code Sensor}'s data.
	 *
	 * @param newData  the new sensor reading
	 */
	public void onChange(SensorDataVO newData);

}


text:
package org.wildfly.swarm.ee.security;

import static org.fest.assertions.Assertions.assertThat;

import java.io.IOException;

import org.apache.http.client.fluent.Request;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.wildfly.swarm.undertow.WARArchive;

@RunWith(Arquillian.class)
public class EESecurityTest {

    @Deployment
    public static Archive createDeployment() throws Exception {
        WARArchive deployment = ShrinkWrap.create(WARArchive.class);
        deployment.addClass(EESecurityServlet.class);
        deployment.addClass(SimpleAuthenticationMechanism.class);
        deployment.addClass(SimpleIdentityStore.class);
        deployment.addAsWebInfResource("jboss-web.xml");
        return deployment;
    }

    @Test
    @RunAsClient
    public void testCustomAuthenticationMechanism() throws IOException {
        String response1 = Request.Get("http://localhost:8080/security?name=thorntail1&password=secret1")
                .execute().returnContent().asString().trim();
        assertThat(response1).isEqualTo("thorntail1, role1:true, role2:false");
        String response2 = Request.Get("http://localhost:8080/security?name=thorntail2&password=secret2")
                .execute().returnContent().asString().trim();
        assertThat(response2).isEqualTo("thorntail2, role1:false, role2:true");
    }
}


text:
package stackerr

import (
	"errors"
	"fmt"

	"github.com/facebookgo/stack"
)

// Error provides the wrapper that adds multiple Stacks to an error. Each Stack
// represents a location in code thru which this error was wrapped.
type Error struct {
	multiStack *stack.Multi
	underlying error
}

// Error provides a multi line error string that includes the stack trace.
func (e *Error) Error() string {
	return fmt.Sprintf("%s\n%s", e.underlying, e.multiStack)
}

// MultiStack identifies the locations this error was wrapped at.
func (e *Error) MultiStack() *stack.Multi {
	return e.multiStack
}

// Underlying returns the error that is being wrapped.
func (e *Error) Underlying() error {
	return e.underlying
}

type hasMultiStack interface {
	MultiStack() *stack.Multi
}

// WrapSkip the error and add the current Stack. The argument skip is the
// number of stack frames to ascend, with 0 identifying the caller of Wrap. If
// the error to be wrapped has a MultiStack, the current stack will be added to
// it.  If the error to be wrapped is nil, a nil error is returned.
func WrapSkip(err error, skip int) error {
	// nil errors are returned back as nil.
	if err == nil {
		return nil
	}

	// we're adding another Stack to an already wrapped error.
	if se, ok := err.(hasMultiStack); ok {
		se.MultiStack().AddCallers(skip + 1)
		return err
	}

	// we're create a freshly wrapped error.
	return &Error{
		multiStack: stack.CallersMulti(skip + 1),
		underlying: err,
	}
}

// Wrap provides a convenience function that calls WrapSkip with skip=0. That
// is, the Stack starts with the caller of Wrap.
func Wrap(err error) error {
	return WrapSkip(err, 1)
}

// New returns a new error that includes the Stack.
func New(s string) error {
	return WrapSkip(errors.New(s), 1)
}

// Newf formats and returns a new error that includes the Stack.
func Newf(format string, args ...interface{}) error {
	return WrapSkip(fmt.Errorf(format, args...), 1)
}

type hasUnderlying interface {
	Underlying() error
}

// Underlying returns all the underlying errors by iteratively checking if the
// error has an Underlying error. If e is nil, the returned slice will be nil.
func Underlying(e error) []error {
	if e == nil {
		return nil
	}

	var errs []error
	for {
		if e == nil {
			return errs
		}
		errs = append(errs, e)

		if eh, ok := e.(hasUnderlying); ok {
			e = eh.Underlying()
		} else {
			e = nil
		}
	}
}

// Matcher defines the interface to check if an error matches an expectation.
type Matcher interface {
	Match(e error) bool
}

type equals struct {
	error error
}

func (e *equals) Match(other error) bool {
	return e.error == other
}

// Equals returns a Matcher to check if an error equals the given error.
func Equals(e error) Matcher {
	return &equals{e}
}

// HasUnderlying returns true if any of the underlying errors satisfy the given
// Matcher.
func HasUnderlying(e error, m Matcher) bool {
	for _, o := range Underlying(e) {
		if m.Match(o) {
			return true
		}
	}
	return false
}

// MatcherFunc allows using a function as a Matcher. For example to use
// os.IsNotExist as a matcher.
type MatcherFunc func(err error) bool

// Match calls the underlying function.
func (f MatcherFunc) Match(err error) bool {
	return f(err)
}


text:
<?php
session_start();

require 'vendor/autoload.php';
use Aws\Sns\SnsClient;

$email = $_SESSION['email'];

print "Hello $email ! \n";

$arn = 'arn:aws:sns:us-east-1:519662356897:ImageUploaded';//hardcoded for now
$_SESSION['arn']=$arn;
$client = SnsClient::factory(array(
    'version' => 'latest',
    'region'  => 'us-east-1'
));

$result = $client->listSubscriptionsByTopic(array(
    // TopicArn is required
    'TopicArn' => $arn,
));

//print $result;

$subscription = $result->get('Subscriptions');
foreach ($subscription as $table) {
	if (in_array($email, $table)){
		echo "\n $email is already subscribed to the topic. \n";
		$subscriptionArn = $table['SubscriptionArn'];
		//print $subscriptionArn;
		if ($subscriptionArn == 'PendingConfirmation'){
		echo "\nPlease confirm your subscription with the email you received.\n";
		}
		else{
			header('Location:gallery.php');
		}
	}
}

if ($subscriptionArn == 'PendingConfirmation'){
	echo "\n";
}
else{
	echo "\nPlease subscribe";
}

?>

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <meta name="description" content="">
    <meta name="author" content="">
    <link rel="icon" href="../favicon.ico">

    <title>Subscription to access the gallery</title>

    <link href="../css/bootstrap.min.css" rel="stylesheet">

    <link href="signin.css" rel="stylesheet">

      <form method="post">

Subscription

        <input class="btn btn-lg btn-primary btn-block" type="submit" name="conf" value="Confirm subscription"/>
        <input class="btn btn-lg btn-primary btn-block" type="submit" name="subs" value="Subscribe" />

      </form>

<?php

if(isset($_POST['conf'])){

	$result = $client->listSubscriptionsByTopic(array(
   		// TopicArn is required
    	'TopicArn' => $arn,
	));
	$subscription = $result->get('Subscriptions');
	foreach ($subscription as $table) {
		if (in_array('mhubert1@hawk.iit.edu', $table)){
			echo "$email is already subscribed to the topic. \n";
			$subscriptionArn = $table['SubscriptionArn'];
			print $subscriptionArn;
			if ($subscriptionArn == 'PendingConfirmation'){
				echo "\nPlease confirm your subscription with the email you received.\n";
				header('Location:subscription.php');
			}
			else{ //user's subscription already confirmed
				header('Location:subscription.php');
			}
		}
	}

		/*
		echo "\n publishing";
		$result = $client->publish(array(
    	'TopicArn' => $arn,
    	// Message is required
    	'Message' => 'Hello ! Your image has been successfully uploaded',
    	'Subject' => 'Successful upload',
    	'MessageAttributes' => array(
    	    // Associative array of custom 'String' key names
    	    'String' => array(
    	        // DataType is required
    	        'DataType' => 'String',
    	        'StringValue' => 'string',
    	    	),
    	    	// ... repeated
    		),
		));*/

}

if(isset($_POST['subs'])){
	$result = $client->subscribe(array(
    	// TopicArn is required
    	'TopicArn' => $arn,
    	// Protocol is required
    	'Protocol' => 'email',
    	'Endpoint' => $email,
	));

	print $result;
	header('Location:subscription.php');
}

?>


text:
#pragma once

#include <memory>
#include <string>
#include <vector>

#include <folly/Optional.h>
#include <folly/experimental/fibers/ForEach.h>

#include "mcrouter/lib/fbi/cpp/FuncGenerator.h"
#include "mcrouter/lib/RouteHandleTraverser.h"
#include "mcrouter/lib/routes/NullRoute.h"

namespace facebook { namespace memcache {

/**
 * Sends the same request to all child route handles.
 * Collects all the replies and responds with the "most awful" reply.
 */
template <class RouteHandleIf>
class AllSyncRoute {
 public:
  static std::string routeName() { return "all-sync"; }

  explicit AllSyncRoute(std::vector<std::shared_ptr<RouteHandleIf>> rh)
      : children_(std::move(rh)) {
  }

  template <class Operation, class Request>
  void traverse(const Request& req, Operation,
                const RouteHandleTraverser<RouteHandleIf>& t) const {
    t(children_, req, Operation());
  }

  template <class Operation, class Request>
  typename ReplyType<Operation, Request>::type route(
    const Request& req, Operation) const {

    typedef typename ReplyType<Operation, Request>::type Reply;

    if (children_.empty()) {
      return NullRoute<RouteHandleIf>::route(req, Operation());
    }

    /* Short circuit if one destination */
    if (children_.size() == 1) {
      return children_.back()->route(req, Operation());
    }

    const auto& children = children_;
    auto fs = makeFuncGenerator([&req, &children](size_t id) {
      return children[id]->route(req, Operation());
    }, children_.size());

    folly::Optional<Reply> reply;
    folly::fibers::forEach(fs.begin(), fs.end(),
                           [&reply] (size_t id, Reply newReply) {
      if (!reply || newReply.worseThan(reply.value())) {
        reply = std::move(newReply);
      }
    });
    return std::move(reply.value());
  }

 private:
  const std::vector<std::shared_ptr<RouteHandleIf>> children_;
};

}}


text:
from autopyfactory.interfaces import SchedInterface
import logging

class MinPerCycle(SchedInterface):
    id = 'minpercycle'

    def __init__(self, apfqueue, config, section):

        try:
            self.apfqueue = apfqueue
            self.log = logging.getLogger('autopyfactory.sched.%s' %apfqueue.apfqname)
            self.min_pilots_per_cycle = self.apfqueue.qcl.generic_get(self.apfqueue.apfqname, 'sched.minpercycle.minimum', 'getint')
            self.log.debug("SchedPlugin: Object initialized.")
        except Exception as ex:
            self.log.error("SchedPlugin object initialization failed. Raising exception")
            raise ex

    def calcSubmitNum(self, n=0):

        self.log.debug('Starting with n=%s' %n)

        out = n
        msg = "MinPerCycle:comment=Not set"

        if self.min_pilots_per_cycle is not None:
            out = max(n, self.min_pilots_per_cycle)
            msg = "MinPerCycle:in=%s,minpercycle=%s,ret=%s" %(n, self.min_pilots_per_cycle, out)

        self.log.info(msg)
        return (out, msg)


text:
/**
 * Provides a Fact module for the Family Tree Project
 *
 * @module components/individualList/individualList
 * @requires knockout, config, text!./individualList.html
 */
define("fact", ["knockout"], function (ko) {

    // ReSharper disable once InconsistentNaming
    var Fact = function (data) {
        var self = this;

        if (data === undefined || data === null) {
            self.date = ko.observable("");
            self.factType = ko.observable("");
            self.place = ko.observableArray("");
        } else {
            self.date = ko.observable(data.date);
            self.factType = ko.observable(data.factType);
            self.place = ko.observable(data.place);
        }
    }

    // Return component definition
    return function(parentViewModel, data) {
        return new Fact(parentViewModel, data);
    }
});


text:
/*!
 * \file intrin_rule_vhls.cc
 * \brief VHLS intrinsic rules.
 */
#include <tvm/tir/op_attr_types.h>

#include "../intrin_rule.h"

namespace tvm {
namespace codegen {
namespace intrin {
using tir::FLowerIntrinsic;

TVM_REGISTER_OP("tir.floor")
    .set_attr<FLowerIntrinsic>("sdaccel.FLowerIntrinsic", DispatchPureExtern<Direct>);

TVM_REGISTER_OP("tir.ceil")
    .set_attr<FLowerIntrinsic>("sdaccel.FLowerIntrinsic", DispatchPureExtern<Direct>);

TVM_REGISTER_OP("tir.trunc")
    .set_attr<FLowerIntrinsic>("sdaccel.FLowerIntrinsic", DispatchPureExtern<Direct>);

TVM_REGISTER_OP("tir.fabs")
    .set_attr<FLowerIntrinsic>("sdaccel.FLowerIntrinsic", DispatchPureExtern<Direct>);

TVM_REGISTER_OP("tir.round")
    .set_attr<FLowerIntrinsic>("sdaccel.FLowerIntrinsic", DispatchPureExtern<Direct>);

TVM_REGISTER_OP("tir.exp").set_attr<FLowerIntrinsic>("sdaccel.FLowerIntrinsic",
                                                     DispatchPureExtern<Direct>);

TVM_REGISTER_OP("tir.exp2")
    .set_attr<FLowerIntrinsic>("sdaccel.FLowerIntrinsic", DispatchPureExtern<Direct>);

TVM_REGISTER_OP("tir.exp10")
    .set_attr<FLowerIntrinsic>("sdaccel.FLowerIntrinsic", DispatchPureExtern<Direct>);

TVM_REGISTER_OP("tir.log").set_attr<FLowerIntrinsic>("sdaccel.FLowerIntrinsic",
                                                     DispatchPureExtern<Direct>);

TVM_REGISTER_OP("tir.log2")
    .set_attr<FLowerIntrinsic>("sdaccel.FLowerIntrinsic", DispatchPureExtern<Direct>);

TVM_REGISTER_OP("tir.log10")
    .set_attr<FLowerIntrinsic>("sdaccel.FLowerIntrinsic", DispatchPureExtern<Direct>);

TVM_REGISTER_OP("tir.tanh")
    .set_attr<FLowerIntrinsic>("sdaccel.FLowerIntrinsic", DispatchPureExtern<Direct>);

TVM_REGISTER_OP("tir.sqrt")
    .set_attr<FLowerIntrinsic>("sdaccel.FLowerIntrinsic", DispatchPureExtern<Direct>);

TVM_REGISTER_OP("tir.pow").set_attr<FLowerIntrinsic>("sdaccel.FLowerIntrinsic",
                                                     DispatchPureExtern<Direct>);

TVM_REGISTER_OP("tir.popcount")
    .set_attr<FLowerIntrinsic>("sdaccel.FLowerIntrinsic", DispatchPureExtern<Direct>);

TVM_REGISTER_OP("tir.sin").set_attr<FLowerIntrinsic>("sdaccel.FLowerIntrinsic",
                                                     DispatchPureExtern<Direct>);

TVM_REGISTER_OP("tir.sinh")
    .set_attr<FLowerIntrinsic>("sdaccel.FLowerIntrinsic", DispatchPureExtern<Direct>);

TVM_REGISTER_OP("tir.cos").set_attr<FLowerIntrinsic>("sdaccel.FLowerIntrinsic",
                                                     DispatchPureExtern<Direct>);

TVM_REGISTER_OP("tir.cosh")
    .set_attr<FLowerIntrinsic>("sdaccel.FLowerIntrinsic", DispatchPureExtern<Direct>);

}  // namespace intrin
}  // namespace codegen
}  // namespace tvm


text:
AuthConstField::AuthConstField(QString key, QString value)
	: AuthField(QString(), std::move(key), AuthField::Const), m_value(std::move(value))
{}

QString AuthConstField::value(MixedSettings *settings) const
{
	Q_UNUSED(settings);

	return m_value;
}


text:
module Pohoda
  module Parsers
    module Pre
      class PrevodkaResponseType < Rdc::DocumentResponseType
        include ParserCore::BaseParser
      end
    end
  end
end


text:
{[include file='common/head.html']}

 {[$msg]}

{[include file='common/foot.html']}


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Runtime.InteropServices;

namespace Microsoft.Diagnostics.Runtime.Interop
{
    [StructLayout(LayoutKind.Sequential)]
    public unsafe struct IMAGEHLP_MODULE64
    {
        private const int MAX_PATH = 260;

        public uint SizeOfStruct;
        public ulong BaseOfImage;
        public uint ImageSize;
        public uint TimeDateStamp;
        public uint CheckSum;
        public uint NumSyms;
        public DEBUG_SYMTYPE SymType;
        private fixed char _ModuleName[32];
        private fixed char _ImageName[256];
        private fixed char _LoadedImageName[256];
        private fixed char _LoadedPdbName[256];
        public uint CVSig;
        public fixed char CVData[MAX_PATH * 3];
        public uint PdbSig;
        public Guid PdbSig70;
        public uint PdbAge;
        private uint _bPdbUnmatched; /* BOOL */
        private uint _bDbgUnmatched; /* BOOL */
        private uint _bLineNumbers; /* BOOL */
        private uint _bGlobalSymbols; /* BOOL */
        private uint _bTypeInfo; /* BOOL */
        private uint _bSourceIndexed; /* BOOL */
        private uint _bPublics; /* BOOL */

        public bool PdbUnmatched
        {
            get => _bPdbUnmatched != 0;
            set => _bPdbUnmatched = value ? 1U : 0U;
        }

        public bool DbgUnmatched
        {
            get => _bDbgUnmatched != 0;
            set => _bDbgUnmatched = value ? 1U : 0U;
        }

        public bool LineNumbers
        {
            get => _bLineNumbers != 0;
            set => _bLineNumbers = value ? 1U : 0U;
        }

        public bool GlobalSymbols
        {
            get => _bGlobalSymbols != 0;
            set => _bGlobalSymbols = value ? 1U : 0U;
        }

        public bool TypeInfo
        {
            get => _bTypeInfo != 0;
            set => _bTypeInfo = value ? 1U : 0U;
        }

        public bool SourceIndexed
        {
            get => _bSourceIndexed != 0;
            set => _bSourceIndexed = value ? 1U : 0U;
        }

        public bool Publics
        {
            get => _bPublics != 0;
            set => _bPublics = value ? 1U : 0U;
        }

        public string ModuleName
        {
            get
            {
                fixed (char* moduleNamePtr = _ModuleName)
                {
                    return Marshal.PtrToStringUni((IntPtr)moduleNamePtr, 32);
                }
            }
        }

        public string ImageName
        {
            get
            {
                fixed (char* imageNamePtr = _ImageName)
                {
                    return Marshal.PtrToStringUni((IntPtr)imageNamePtr, 256);
                }
            }
        }

        public string LoadedImageName
        {
            get
            {
                fixed (char* loadedImageNamePtr = _LoadedImageName)
                {
                    return Marshal.PtrToStringUni((IntPtr)loadedImageNamePtr, 256);
                }
            }
        }

        public string LoadedPdbName
        {
            get
            {
                fixed (char* loadedPdbNamePtr = _LoadedPdbName)
                {
                    return Marshal.PtrToStringUni((IntPtr)loadedPdbNamePtr, 256);
                }
            }
        }
    }
}


text:
package org.pentaho.di.ui.spoon.dialog;

import java.lang.reflect.InvocationTargetException;

import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.swt.widgets.Shell;
import org.pentaho.di.core.EngineMetaInterface;
import org.pentaho.di.core.ProgressMonitorAdapter;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.i18n.BaseMessages;
import org.pentaho.di.repository.Repository;
import org.pentaho.di.ui.core.dialog.ErrorDialog;
import org.pentaho.di.ui.trans.dialog.TransDialog;

/**
 * Takes care of displaying a dialog that will handle the wait while saving a transformation...
 *
 * @author Matt
 * @since 13-mrt-2005
 */
public class SaveProgressDialog {
  private static Class<?> PKG = TransDialog.class; // for i18n purposes, needed by Translator2!!

  private Shell shell;
  private Repository rep;
  private EngineMetaInterface meta;

  private String versionComment;

  /**
   * Creates a new dialog that will handle the wait while saving a transformation...
   */
  public SaveProgressDialog( Shell shell, Repository rep, EngineMetaInterface meta, String versionComment ) {
    this.shell = shell;
    this.rep = rep;
    this.meta = meta;
    this.versionComment = versionComment;
  }

  public boolean open() {
    boolean retval = true;

    IRunnableWithProgress op = new IRunnableWithProgress() {
      public void run( IProgressMonitor monitor ) throws InvocationTargetException, InterruptedException {
        try {
          rep.save( meta, versionComment, new ProgressMonitorAdapter( monitor ) );
        } catch ( KettleException e ) {
          throw new InvocationTargetException( e, BaseMessages.getString(
            PKG, "TransSaveProgressDialog.Exception.ErrorSavingTransformation" )
            + e.toString() );
        }
      }
    };

    try {
      ProgressMonitorDialog pmd = new ProgressMonitorDialog( shell );
      pmd.run( true, true, op );
    } catch ( InvocationTargetException e ) {
      new ErrorDialog( shell,
        BaseMessages.getString( PKG, "TransSaveProgressDialog.ErrorSavingTransformation.DialogTitle" ),
        BaseMessages.getString( PKG, "TransSaveProgressDialog.ErrorSavingTransformation.DialogMessage" ), e );
      retval = false;
    } catch ( InterruptedException e ) {
      new ErrorDialog( shell,
        BaseMessages.getString( PKG, "TransSaveProgressDialog.ErrorSavingTransformation.DialogTitle" ),
        BaseMessages.getString( PKG, "TransSaveProgressDialog.ErrorSavingTransformation.DialogMessage" ), e );
      retval = false;
    }

    return retval;
  }
}


text:
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ui;

import com.intellij.icons.AllIcons.Ide.RoundShadow;
import com.intellij.util.ui.JBValue;
import org.jetbrains.annotations.NotNull;

import java.awt.*;
import java.awt.geom.RoundRectangle2D;

/**
 * @author Alexander Lobas
 */
public class NotificationBalloonRoundShadowBorderProvider extends NotificationBalloonShadowBorderProvider {
  public static final JBValue CORNER_RADIUS = new JBValue.UIInteger("Notification.arc", 12);

  public NotificationBalloonRoundShadowBorderProvider(@NotNull Color fillColor, @NotNull Color borderColor) {
    super(fillColor, borderColor,
          RoundShadow.Top, RoundShadow.Left, RoundShadow.Bottom, RoundShadow.Right,
          RoundShadow.TopLeft, RoundShadow.TopRight, RoundShadow.BottomLeft, RoundShadow.BottomRight);
  }

  @Override
  public void paintBorder(@NotNull Rectangle bounds, @NotNull Graphics2D g) {
    int cornerRadius = CORNER_RADIUS.get();
    g.setColor(myFillColor);
    g.fill(new RoundRectangle2D.Double(bounds.x, bounds.y, bounds.width, bounds.height, cornerRadius, cornerRadius));
    g.setColor(myBorderColor);
    g.draw(new RoundRectangle2D.Double(bounds.x + 0.5, bounds.y + 0.5, bounds.width - 1, bounds.height - 1, cornerRadius, cornerRadius));
  }
}


text:
NLP4L-LTR provides a function to analyze logs of searches and clicks in an actual application by users, convert it to Annotation data that can be used as training data of learning-to-rank, and import it in the system.

![import](images/ltr_import_overview.png)

In order to use the import function, you need to covert a click log, which you acquired on the search application-side, into the import format for NLP4L-LTR . The following 2 formats are supported as the import formats.

- Impression Log (JSON format)
	- Impression log includes searched query character string, list of documents displayed by them, and clicked documents.
	- Probabilities are calculated by click models and are converted to annotation data for import.
	- Independent Click Model(ICM) and Dependent Click Model(DCM) are supported as the click models.

- Query Annotation Data(CSV)
	- Click logs are analyzed on the application-side and the data already converted to annotation data is imported.

Details of each log data format are described in the following.

## Screen Operation

This section describes the screen operations of the import function.

To use the import function, set up (or Load if there is already a setting) the Config to import and click the Import button on the Query screen.

![screenshot_import_query](images/screenshot_import_query.png)

Clicking the Import button will send you to the screen for import.

![screenshot_import](images/screenshot_import.png)

Select an import type on the import screen, set parameters in the import settings, select a data file to import, and click the Import button.

- Query Annotation Data
	- Select when importing Query Annotation Data(CSV).
	- Import settings are not required. (Import settings are ignored.)

- Impression Log as Independent Click Model (ICM)
	- Select when impression log (JSON format) is imported.
	- The impression log goes through click log analysis as ICM and will be imported.

	- The following import settings are required.

- Impression Log as Dependent Click Model (DCM)
	- Select when impression log (JSON format) is imported.
	- The impression log goes through click log analysis as DCM and will be imported.
	- The following import settings are required.

Clicking the Import button will display the import results in the area bellow the button.

![screenshot_import](images/screenshot_import_result.png)

Imported Query can be checked on the Query screen.
Annotation Status is "done" as they are already annotated.

![screenshot_import](images/screenshot_import_query_result.png)

## Importing Impression Log

### Impression Log Click Model Analysis

When you specify impression log, click models are calculated, converted to annotation data, and imported to the system.

Currently, click models for Independent Click Model (ICM) and Dependent Click Model (DCM) are supported.

- Independent Click Model (ICM)

	- Calculate the number of impressions (displays) and the number of clicks on the document for each query character string.
	- Regardless of the position of impression, simply dive the number of clicks for the target document by the number of impressions to calculate the click probability.

- Dependent Click Model (DCM)
	- DCM takes into account the impression position, exclude the impressions lower than the documents at last clicked position, calculates the number of impressions and click probability.
	- Note that if no document was clicked, the documents will be included into the impression total.

![import_icmdcm](images/ltr_import_icmdcm.png)

The Relevance Degree calculated as a click probability will be converted into the annotation data of Pointwise by relevanceDegreeMapping specified in the import settings and imported into the system.

### Impression Log Format

Impression log is in the JSON format as follows.

|name|description|
|:--|:--|
|query|Query character strings used for search|
|impressions|Array of impression (displayed) document ID
Array is in the order of rankings of positions displayed higher|
|clicks|Array of clicked document IDs
Elements are in the ad hoc order and are not necessarily in the order of clicks.
Document IDs can be redundant in the cases where there is more than one click.

Refer to the following impression log as a sample.
```
{
 "data": [
  {
   "query": "iPhone",
   "impressions": [ "docA", "docB", "docC", "docD", "docE" ],
   "clicks": [ "docA", "docC" ]
  },
  {
   "query": "iPhone",
   "impressions": [ "docA", "docB", "docC", "docD", "docE" ],
   "clicks": [ "docA" ]
  },
  {
   "query": "Android",
   "impressions": [ "docA", "docB", "docC", "docD", "docE" ],
   "clicks": [ "docD", "docC", "docD" ]
  },
  {
   "query": "Android",
   "impressions": [ "docA", "docB", "docC", "docD", "docE" ],
   "clicks": [ "docA" ]
  },
  {
   "query": "Android",
   "impressions": [ "docA", "docB", "docC", "docD", "docE" ],
   "clicks": []
  }
 ]
}

```

### Import Settings for Impression Log

Available settings for impression log are as follows.

|name|required|description|
|:--|:--:|:--|
|relevanceDegreeMapping|true|Boundary value that is referenced for mapping Relevance Degree that is calculated as click probability to Pointwise data during Pointwise to annotation data conversion.
Ex: [ 0.01, 0.3, 0.6 ]
The conversion is done in the following order for the above example.
(1) Convert to 0 when Relevance Degree < 0.01.
(2) Convert to 1 when Relevance Degree < 0.3.
(3) Convert to 2 when Relevance Degree < 0.6.
(4) Convert to 3 when Relevance Degree >= 0.6.|
|topQueries|false|Specify when importing the top N queries that involves more number of searches than others. The default is importing all queries.

## Importing Query Annotation Data

### Formating Query Annotation Data

Query Annotation Data is in the CSV format as follows.

|Column|Description|
|:--|:--|
|Column 1| Unique ID for each query.
Strictly for binding more than one line for CSV data. A new QueryID will be given again and inserted into DB during the internal import process.|
|Column 2|Query character string used for search.|
|Column 3|Document ID|
|Column 4|Relevance Degree (Relevance Degree) value for Pointwise|
Column 5 and the followings will be ignored if exist.

Refer to the following samples.

```
1,iPhone,docA,2
1,iPhone,docB,0
1,iPhone,docC,1
1,iPhone,docD,0
1,iPhone,docE,0
2,Android,docA,1
2,Android,docB,0
2,Android,docC,1
2,Android,docD,2
2,Android,docE,0

```


text:
/**
 *
This package contains Hot Restart classes needed for open source Hazelcast code

 */
package com.hazelcast.hotrestart;


text:
#region Usings

using System;

#endregion

namespace org.GraphDefined.Vanaheimr.Illias
{

    public static class VerbosityExtensions
    {

        public static Verbosity Parse(String Text)
        {

            switch (Text)
            {

                case "quiet":
                    return Verbosity.quiet;

                case "simple":
                    return Verbosity.simple;

                case "brief":
                    return Verbosity.brief;

                case "verbose":
                    return Verbosity.verbose;

                case "veryVerbose":
                    return Verbosity.veryVerbose;

                case "debug":
                    return Verbosity.debug;

                default:
                    return Verbosity.normal;

            }

        }

    }

    /// <summary>
    /// The verbosity.
    /// </summary>
    public enum Verbosity
    {

        quiet,

        simple,

        brief,

        normal,

        verbose,

        veryVerbose,

        debug

    }

}


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

namespace System
{
    /// <summary>
    /// Defines a property to indicate whether the <see cref="System.IDisposable.Dispose"/> method was called.
    /// </summary>
    public interface IDisposed : IDisposable
    {
        /// <summary>
        /// Gets a value indicating whether this instance is disposed.
        /// </summary>
        /// <value>
        ///   <c>true</c> if this instance is disposed; otherwise, <c>false</c>.
        /// </value>
        bool IsDisposed { get; }
    }
}


text:
var SsoController = function($scope, $location, authService, propertiesModel) {

	var init = function () {
        const authCodeTokenUrl = propertiesModel.properties.oAuth.oAuthCodeTokenUrl;
        const clientId = propertiesModel.properties.oAuth.clientId;
        const redirectUri = localStorage.getItem('redirectUri');

        var code = '';
        if ($location.hash()) {
            code = $location.hash().replace('code=', '');
        } else {
            code = $location.search()['code'];
        }
        authService.oauthLogin(authCodeTokenUrl, code, clientId, redirectUri);
	};
	init();

};

SsoController.$inject = ['$scope', '$location', 'authService', 'propertiesModel'];
module.exports = SsoController;


text:
package org.apache.solr.response.transform;

import java.io.IOException;

import org.apache.solr.common.SolrDocument;
import org.apache.solr.request.SolrQueryRequest;

/**
 * A DocTransformer can add, remove or alter a Document before it is written out to the Response.  For instance, there are implementations
 * that can put explanations inline with a document, add constant values and mark items as being artificially boosted (see {@link org.apache.solr.handler.component.QueryElevationComponent})
 *
 * <p/>
 * New instance for each request
 *
 * @see TransformerFactory
 *
 */
public abstract class DocTransformer
{
  /**
   *
   * @return The name of the transformer
   */
  public abstract String getName();

  /**
   * This is called before transform and sets
   * @param context The {@link org.apache.solr.response.transform.TransformContext} stores information about the current state of things in Solr that may be
   * useful for doing transformations.
   */
  public void setContext( TransformContext context ) {}

  /**
   * This is where implementations do the actual work
   *
   *
   * @param doc The document to alter
   * @param docid The Lucene internal doc id
   * @throws IOException If there is a low-level I/O error.
   */
  public abstract void transform(SolrDocument doc, int docid) throws IOException;

  @Override
  public String toString() {
    return getName();
  }
}