text:
package what.whatandroid.artist;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatDelegate;
import android.view.Window;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import api.soup.MySoup;
import what.whatandroid.R;
import what.whatandroid.announcements.AnnouncementsActivity;
import what.whatandroid.barcode.BarcodeActivity;
import what.whatandroid.bookmarks.BookmarksActivity;
import what.whatandroid.callbacks.ViewArtistCallbacks;
import what.whatandroid.callbacks.ViewRequestCallbacks;
import what.whatandroid.callbacks.ViewTorrentCallbacks;
import what.whatandroid.forums.ForumActivity;
import what.whatandroid.inbox.InboxActivity;
import what.whatandroid.login.LoggedInActivity;
import what.whatandroid.notifications.NotificationsActivity;
import what.whatandroid.profile.ProfileActivity;
import what.whatandroid.request.RequestActivity;
import what.whatandroid.search.SearchActivity;
import what.whatandroid.settings.SettingsActivity;
import what.whatandroid.subscriptions.SubscriptionsActivity;
import what.whatandroid.top10.Top10Activity;
import what.whatandroid.torrentgroup.TorrentGroupActivity;

/**
 * View information about the artist and a list of their torrent groups
 */
public class ArtistActivity extends LoggedInActivity implements ViewTorrentCallbacks, ViewRequestCallbacks, ViewArtistCallbacks {
	/**
	 * Param to pass the user id to display to the activity
	 * the USE_SEARCH parameter should be set to true and will indicate that the artist
	 * to be viewed is coming from the ArtistSearchFragment
	 */
	public static final String ARTIST_ID = "what.whatandroid.ARTIST_ID", ARTIST_NAME = "what.whatandroid.ARTIST_NAME",
		USE_SEARCH = "what.whatandroid.USE_SEARCH";
	/**
	 * Patterns to match artist names and ids
	 */
	private final static Pattern artistName = Pattern.compile(".*artistname=([^&]+).*"),
		artistId = Pattern.compile(".*id=(\\d+).*");
	private ArtistFragment artistFragment;

	@Override
	protected void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_frame);
		setupNavDrawer();

		if (savedInstanceState != null){
			artistFragment = (ArtistFragment)getSupportFragmentManager().findFragmentById(R.id.container);
		}
		else {
			Intent intent = getIntent();
			//Use -1 to force a load failure if no artist id or name was passed
			int id = intent.getIntExtra(ARTIST_ID, -1);
			String name = intent.getStringExtra(ARTIST_NAME);
			boolean useSearch = intent.getBooleanExtra(USE_SEARCH, false);
			//If we're opening an artist url parse out the artist we're trying to view
			String site = MySoup.getSite();
			if (intent.getScheme() != null && intent.getData() != null && intent.getData().toString().contains(site)){
				String uri = intent.getData().toString();
				Matcher m = artistName.matcher(uri);
				if (m.find()){
					name = m.group(1);
					try {
						//Remove the url formatting in the name
						name = URLDecoder.decode(name, "UTF-8");
					}
					catch (UnsupportedEncodingException e){
						e.printStackTrace();
					}
				}
				else {
					//Is it possible that people will send the artist id instead of the name?
					m = artistId.matcher(uri);
					if (m.find()){
						id = Integer.parseInt(m.group(1));
					}
				}
			}
			artistFragment = ArtistFragment.newInstance(id, name, useSearch);
			getSupportFragmentManager().beginTransaction().add(R.id.container, artistFragment).commit();
		}
	}

	@Override
	public void onLoggedIn(){
		artistFragment.onLoggedIn();
	}

	@Override
	public void viewTorrentGroup(int id){
		Intent intent = new Intent(this, TorrentGroupActivity.class);
		intent.putExtra(TorrentGroupActivity.GROUP_ID, id);
		startActivity(intent);
	}

	@Override
	public void viewTorrent(int group, int torrent){
	}

	@Override
	public void viewRequest(int id){
		Intent intent = new Intent(this, RequestActivity.class);
		intent.putExtra(RequestActivity.REQUEST_ID, id);
		startActivity(intent);
	}

	@Override
	public void viewArtist(int id){
		artistFragment = ArtistFragment.newInstance(id, null, false);
		setTitle(getString(R.string.artist));
		getSupportFragmentManager().beginTransaction()
			.replace(R.id.container, artistFragment)
			.addToBackStack(null)
			.commit();
	}

	@Override
	public void onBackPressed(){
		FragmentManager fm = getSupportFragmentManager();
		if (fm.getBackStackEntryCount() > 0){
			setTitle(getString(R.string.artist));
			fm.popBackStackImmediate();
			artistFragment = (ArtistFragment)fm.findFragmentById(R.id.container);
		}
		else {
			super.onBackPressed();
		}
	}

	@Override
	public void onNavigationDrawerItemSelected(int position){
		if (navDrawer == null){
			return;
		}
		String selection = navDrawer.getItem(position);
		if (selection.equalsIgnoreCase(getString(R.string.announcements))){
			//Launch AnnouncementsActivity viewing announcements
			//For now both just return to the announcements view
			Intent intent = new Intent(this, AnnouncementsActivity.class);
			intent.putExtra(AnnouncementsActivity.SHOW, AnnouncementsActivity.ANNOUNCEMENTS);
			startActivity(intent);
		}
		else if (selection.equalsIgnoreCase(getString(R.string.blog))){
			//Launch AnnouncementsActivity viewing blog posts
			Intent intent = new Intent(this, AnnouncementsActivity.class);
			intent.putExtra(AnnouncementsActivity.SHOW, AnnouncementsActivity.BLOGS);
			startActivity(intent);
		}
		else if (selection.equalsIgnoreCase(getString(R.string.profile))){
			//Launch profile view activity
			Intent intent = new Intent(this, ProfileActivity.class);
			intent.putExtra(ProfileActivity.USER_ID, MySoup.getUserId());
			startActivity(intent);
		}
		else if (selection.equalsIgnoreCase(getString(R.string.bookmarks))){
			Intent intent = new Intent(this, BookmarksActivity.class);
			startActivity(intent);
		}
		else if (selection.contains(getString(R.string.messages))){
			Intent intent = new Intent(this, InboxActivity.class);
			startActivity(intent);
		}
		else if (selection.contains(getString(R.string.notifications))){
			Intent intent = new Intent(this, NotificationsActivity.class);
			startActivity(intent);
		}
		else if (selection.contains(getString(R.string.subscriptions))){
			Intent intent = new Intent(this, SubscriptionsActivity.class);
			startActivity(intent);
		}
		else if (selection.equalsIgnoreCase(getString(R.string.forums))){
			Intent intent = new Intent(this, ForumActivity.class);
			startActivity(intent);
		}
		else if (selection.equalsIgnoreCase(getString(R.string.top10))){
			Intent intent = new Intent(this, Top10Activity.class);
			startActivity(intent);
		}
		else if (selection.equalsIgnoreCase(getString(R.string.torrents))){
			Intent intent = new Intent(this, SearchActivity.class);
			intent.putExtra(SearchActivity.SEARCH, SearchActivity.TORRENT);
			startActivity(intent);
		}
		else if (selection.equalsIgnoreCase(getString(R.string.artists))){
			Intent intent = new Intent(this, SearchActivity.class);
			intent.putExtra(SearchActivity.SEARCH, SearchActivity.ARTIST);
			startActivity(intent);
		}
		else if (selection.equalsIgnoreCase(getString(R.string.requests))){
			Intent intent = new Intent(this, SearchActivity.class);
			intent.putExtra(SearchActivity.SEARCH, SearchActivity.REQUEST);
			startActivity(intent);
		}
		else if (selection.equalsIgnoreCase(getString(R.string.users))){
			Intent intent = new Intent(this, SearchActivity.class);
			intent.putExtra(SearchActivity.SEARCH, SearchActivity.USER);
			startActivity(intent);
		}
		else if (selection.equalsIgnoreCase(getString(R.string.barcode_lookup))){
			Intent intent = new Intent(this, BarcodeActivity.class);
			startActivity(intent);
		}
	}
}


text:
/* hlpstr.h
   ========
   Author: R.J.Barnes
*/

/*
 $License$
*/

char *hlpstr[]={
"inxdump - Dump the contents of a DataMap index file.\n",
"inxdump --help\n",
"inxdump [-xtd] [name]\n",

"--help\tprint the help message and exit.\n",
"-xtd\tthe index file is an extended index that contains both start and stop time.\n",
"name\tfilename of the DataMap index file, if this is omitted the document will be read from standard input.\n",

NULL};

redpajama_set_name: RedPajamaGithub


text:
<?php
class DeliveryModel {
	public function getDeliveriesAdmin($brandName, $status, $table, $connect){

		$db = new db_config();

		$data = '';

		$sql .= "SELECT tbl_delivery_report.delivery_report_id, tbl_delivery_report.brand_name, tbl_delivery_report.delivery_status, SUM(tbl_deliveries.quantity_received), tbl_delivery_report.date_accepted, SUM(tbl_deliveries.quantity) FROM tbl_deliveries INNER JOIN tbl_delivery_report ON tbl_deliveries.delivery_report_id = tbl_delivery_report.delivery_report_id WHERE tbl_delivery_report.brand_name = '".$brandName."' AND tbl_delivery_report.delivery_status = '".$status."' GROUP BY tbl_delivery_report.delivery_report_id";

		$result = mysqli_query($connect, $sql);

		$counter = 1;
		while ($row = mysqli_fetch_array($result)) {

			$delivery_id = $row['delivery_report_id'];
			$brand_name = $row['brand_name'];
			$status = $row['delivery_status'];
			$quantity_reported = $row['SUM(tbl_deliveries.quantity)'];
			$quantity_received = $row['SUM(tbl_deliveries.quantity_received)'];
			$date_accepted = $row['date_accepted'];

			$data .= "
";
			$data .= "" . $delivery_id . "	";
			$data .= "" . $brand_name . "	";
			$data .= "" . $status . "	";
  			$data .= "" . $quantity_reported . "	";
			$data .= "" .  $quantity_received . "	";
			$data .= "" .  $date_accepted . "	";
			$data .= "
					View
					Edit
			 	";
			$data .= "
";
    	}

		return $data;

	}
}?>


text:
from test.framework.pylint.clusterrunner_token_checker import ClusterRunnerTokenChecker

def register(linter):
    """
    Register custom lint checkers with pylint. Any new checkers should also be registered here.
    """
    linter.register_checker(ClusterRunnerTokenChecker(linter))


text:
<!DOCTYPE html>

<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link href="/releases/4.0.0/css/style.css" rel="stylesheet" />

<title>-buildpath PATH</title>
<meta name="generator" content="Jekyll v3.7.3" />
<meta property="og:title" content="-buildpath PATH" />
<meta property="og:locale" content="en_US" />
<meta name="description" content="The -buildpath instruction is the main mechanism to add build-time dependencies to a project. A dependency is either another project in the workspace, or a bundle in a repository. The -buildpath is only used during compile and build time; it is never used to run projects. Because -buildpath dependencies are only used compile time it's recommended to add bundles containing only APIs; you don't need bundles containing implementations." />
<meta property="og:description" content="The -buildpath instruction is the main mechanism to add build-time dependencies to a project. A dependency is either another project in the workspace, or a bundle in a repository. The -buildpath is only used during compile and build time; it is never used to run projects. Because -buildpath dependencies are only used compile time it's recommended to add bundles containing only APIs; you don't need bundles containing implementations." />
<meta property="og:type" content="article" />
<meta property="article:published_time" content="2019-10-12T20:27:56-04:00" />

			Intro
			Headers
			Instructions
			Macros

<button class="dropbtn">4.0.0</button>

Release

Introduction

How to install bnd

Guided Tour

Guided Tour Workspace & Projects

Concepts

Best practices

Build

Generating JARs

Versioning

Baselining

Service Components

Metatype

Contracts

Manifest Annotations

Resolving Dependencies

Launching

Testing

Packaging Applications

Wrapping Libraries to OSGi Bundles

From the command line

For Developers

Plugins

Tools bound to bnd

File Format

Header Reference

Instruction

Instruction Index

Macro Reference

Command Reference

Plugins Reference

Settings

Errors

Warnings

Frequently Asked Questions

Supported by OSGi enRoute

 -buildpath PATH

The -buildpath instruction is the main mechanism to add build-time dependencies to a project. A dependency is either another project in the workspace, or a bundle in a repository. The -buildpath is only used during compile and build time; it is never used to run projects.  Because -buildpath dependencies are only used compile time it's recommended to add bundles containing only APIs; you don't need bundles containing implementations.

The `-buildpath

Example

An example of the -buildpath could be the following, where three dependencies are defined:

-buildpath: \
	some.other.workspace.project;version=project,\
	osgi.core;version=4.3.1,\
	osgi.cmpn;version=4.3.1

See Also

-testpath

TODO

New function wildcards for bsns & additional repos that can limit the repos (done by Neil)

Contact

Developers

More


text:
package com.andrewhatrus.brainbeantrialtask.screen.search;

import android.arch.lifecycle.LiveData;
import android.arch.lifecycle.MutableLiveData;
import android.support.annotation.MainThread;
import android.support.annotation.Nullable;
import android.widget.Toast;

import com.andrewhatrus.brainbeantrialtask.App;
import com.andrewhatrus.brainbeantrialtask.data.model.GitHubUser;
import com.andrewhatrus.brainbeantrialtask.screen.base.BaseViewModel;

import java.util.List;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by Andrew on 19.08.2017.
 */
public class SearchViewModel extends BaseViewModel {

    @Nullable
    private MutableLiveData<List<GitHubUser>> usersLiveData;
    private int page;

    MutableLiveData<List<GitHubUser>> getCurrentData() {
        if(usersLiveData == null)
            usersLiveData = new MutableLiveData<>();
        return usersLiveData;
    }

    @MainThread
    LiveData<List<GitHubUser>> searchUsers(String query) {
        isLoading.setValue(true);
        usersLiveData = new MutableLiveData<>();
        repository.searchUsers(query, ++page)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(list -> {
                    usersLiveData.setValue(list);
                    isLoading.setValue(false);
                }, throwable -> {
                    Toast.makeText(App.getAppContext(),
                            "error: " + throwable.getMessage(),
                            Toast.LENGTH_LONG).show();
                    isLoading.setValue(false);
                });
        return usersLiveData;
    }

    int getPage() {
        return page;
    }

    void setPage(int page) {
        this.page = page;
    }
}


text:
<?xml version="1.0" encoding="utf-8"?><!--
   Copyright 2012 Google Inc. All rights reserved.

   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.
-->
<resources>
    <string name="app_name">Trivial Drive</string>
    <string name="menu_settings">Settings</string>
    <string name="title_activity_main">Trivial Drive</string>

    <string name="subscription_period_prompt">Select your subscription period</string>
    <string name="subscription_resignup_prompt">To reactivate your subscription, select your subscription period</string>
    <string name="subscription_update_prompt">To change your subscription, select your new subscription period</string>
    <string name="subscription_period_monthly">Monthly</string>
    <string name="subscription_period_yearly">Yearly</string>
    <string name="subscription_prompt_continue">Continue</string>
    <string name="subscription_prompt_cancel">Cancel</string>
    <string name="content_description_app_loading_image">App loading image</string>
    <string name="content_description_title_image">80\'s Video Game Style Car Logo</string>
    <string name="content_desc_gas_gauge_indicator">Gas gauge indicator</string>
    <string name="content_desc_free_vs_premium_indicator">Free or Premium Image Indicator</string>
</resources>


text:
<?php declare(strict_types=1);

namespace alkemann\h2l\attributes;

use alkemann\h2l\util\Http;
use Attribute;

/**
 * Class Get
 *
 * Http GET method
 *
 * Attribute type that takes in a string for the url path
 * and one ore more valid http methods for this path.
 * The method this attribute is attached to will be added
 * as a static callable route.
 *
 * @package alkemann\h2l
 */
#[Attribute(Attribute::TARGET_METHOD|ATTRIBUTE::IS_REPEATABLE)]
class Post extends Route
{
    public function __construct(public string $path)
    {
        parent::__construct($this->path, Http::POST);
    }
}


text:
function textualaudiocue (Ntrial, IdleDuration, WalkDuration, SWheadphone, IdleString, WalkString)
% Gives the cues IDLE, WALK for a total number of Ntrial times.
% Also produces sound for re-acquisition.

setmatlabtitle('CUE');

ProgramStart = tic;

%Idle.String = '';
Idle.Color = [0.9 0.1 0.1];
Idle.FontSize = 96;
Idle.FontName = 'Times New Roman';
%Walk.String = '';
Walk.Color = [0.1 0.9 0.1];
Walk.FontSize = 96;
Walk.FontName = 'Times New Roman';

if nargin < 3
    error('Requires 3 arguments.');
end

if ~exist('SWheadphone','var') || isempty(SWheadphone)
    SWheadphone = 0;
end

if ~exist('IdleString','var') || isempty(IdleString)
    IdleString = 'IDLE';
end

if ~exist('WalkString','var') || isempty(WalkString)
    WalkString = 'WALK';
end

Idle.String = IdleString;
Walk.String = WalkString;

%% Set up audio signals
if SWheadphone
    AStruct = load('VoiceStartStop.mat');
    Audio.Fs = AStruct.VoiceFs;
    Audio.IdleY = AStruct.VoiceStop * 1e-1;
    Audio.WalkY = AStruct.VoiceStart * 1e-1;
else
    Audio.Lag = 0.03;
    Audio.Fs = 22050;
    Audio.IdleFreq = 220;
    Audio.IdleAmp = 0;
    Audio.WalkFreq = 350;
    Audio.WalkAmp = 0.750;
    Audio.IdleT = (1:Audio.Fs*(IdleDuration-Audio.Lag))/Audio.Fs;
    Audio.WalkT = (1:Audio.Fs*(WalkDuration-Audio.Lag))/Audio.Fs;
    Audio.IdleY = Audio.IdleAmp*sin(2*pi*Audio.IdleFreq*Audio.IdleT);
    Audio.WalkY = Audio.WalkAmp*sin(2*pi*Audio.WalkFreq*Audio.WalkT);
end

%% Set up the User Figure
close all
MonitorPositions = get(0,'MonitorPositions');
if size(MonitorPositions,1) < 2
    warning('No second monitor');
else
    UserFigurePosition = MonitorPositions(2,:) + [-1 1 1-MonitorPositions(1,3) 0];
    UserFigurePosition(2) = MonitorPositions(1,4) - MonitorPositions(2,4);
end

figure(1);
set(gcf,'Toolbar','none','MenuBar','none', 'NumberTitle','off','DoubleBuffer','on');
try
    set(gcf,'Position',UserFigurePosition);
end
hold on
set(gca,'Position',[0 0 1 1],'XTick',[],'YTick',[],'XLim',[-1 1],'YLim',[-1 1], 'Color',[0 0 0]);
sbuffer = text(0,0,'','HorizontalAlignment','center');
s2buffer = text(0.0,-0.2,'','HorizontalAlignment','center','FontSize',24,'Color',[0 0.5 0.5]);
fprintf('[%.3f] User Figure window configured. Get ready to start ..\n',toc(ProgramStart));
%UpdateInstantStatus('started', 'clearall');

q = questdlg('Ready to start texual cue?', 'textualaudiocue');
drawnow
switch q
    case 'Yes'
    otherwise
        close all
        return
end

EstTime = Ntrial * (IdleDuration + WalkDuration)/2 + 3.0;
%UpdateCueStatus(0, EstTime);   %JL 3/10/21
pause(3.0);

CuesGivenC = cell(1,Ntrial);

%% Start

for tri = 1:Ntrial
    cui = mod(tri-1,2)+1;
    switch cui
        case 1
            CueDuration = IdleDuration;
            CueString = Idle.String;
            Props = struct2cellpairs(Idle);
        case 2
            CueDuration = WalkDuration;
            CueString = Walk.String;
            Props = struct2cellpairs(Walk);
    end
    if length(CueDuration) > 1 && CueDuration(2) > CueDuration(1)
        CueDuration = CueDuration(1) + rand*(CueDuration(2) - CueDuration(1));
    else
        CueDuration = CueDuration(1);
    end
    CueGivenTime = toc(ProgramStart);
    fprintf('[%.3f] Trial #%3i, Cue#%3i, CueDuration=%6.3f, CueText: %s\n',CueGivenTime, tri, cui, CueDuration, CueString);
    UpdateInstantStatus(['TRIAL_' num2str(tri,'%03i')], ['TRIAL_' num2str(tri-1,'%03i')]);
    set(sbuffer, Props{:});
    Extent1 = get(sbuffer,'Extent');
    Extent2 = get(s2buffer,'Extent');
    bottom = Extent1(2);
    Pos2 = get(s2buffer,'Position');
    Pos2(2) = [bottom - Extent2(4)];
    set(s2buffer, 'String', [num2str(Ntrial-tri)], 'Position', Pos2);
    CuesGivenC{tri} = {CueGivenTime, CueDuration, CueString};
    drawnow
    audioplaystart = tic;
    switch cui
        case 1
            wavplay(Audio.IdleY,Audio.Fs);
        case 2
            wavplay(Audio.WalkY,Audio.Fs);
    end
    %CueDuration - toc(audioplaystart)
    pause(CueDuration - toc(audioplaystart));
end

Props = struct2cellpairs(Idle);
set(sbuffer, Props{:});
Extent1 = get(sbuffer,'Extent');
Extent2 = get(s2buffer,'Extent');
bottom = Extent1(2);
Pos2 = get(s2buffer,'Position');
Pos2(2) = [bottom - Extent2(4)];
set(s2buffer, 'String', 'End of session.', 'Position', Pos2);
pause(3.5);
fprintf('[%.3f] End of session.\n',toc(ProgramStart));
UpdateInstantStatus('done', 'clearall');
close all


text:
<?php
/**
 *
 * @author h.woltersdorf
 */

namespace PHPinDD\CqrsNewsletter\Domains\Newsletter\Read;

use Fortuneglobe\IceHawk\DomainRequestHandlers\GetRequestHandler;
use Fortuneglobe\IceHawk\Interfaces\ServesGetRequestData;
use PHPinDD\CqrsNewsletter\Domains\Newsletter\Read\Queries\ShowSubscriptionInitializedQuery;
use PHPinDD\CqrsNewsletter\Domains\Newsletter\Read\QueryHandlers\ShowSubscriptionInitializedQueryHandler;
use PHPinDD\CqrsNewsletter\Domains\Newsletter\Services\NewsletterReadService;

/**
 * Class ShowSubscriptionInitializedRequestHandler
 *
 * @package PHPinDD\CqrsNewsletter\Domains\Newsletter\Read
 */
final class ShowSubscriptionInitializedRequestHandler extends GetRequestHandler
{
	/**
	 * @param ServesGetRequestData $request
	 */
	public function handle( ServesGetRequestData $request )
	{
		$newsletterReadService = new NewsletterReadService();

		$query   = new ShowSubscriptionInitializedQuery( $request );
		$handler = new ShowSubscriptionInitializedQueryHandler( $newsletterReadService );

		$handler->handle( $query );
	}
}


text:
@interface JSONUtilities:NSObject {
}

+(NSString *)getJSONElement:(NSString *)json element:(NSString *)elementName;

@end


text:
import * as React from "react"
import getLogger from "common/log/Logger"
import {
  child,
  CursorPointer, FillWidth,
  FlexRow, FlexRowCenter,
  IThemedProperties, makeDimensionConstraints,
  mergeClasses, mergeStyles, rem,
  withStatefulStyles
} from "renderer/styles/ThemedStyles"
import {ILabel} from "common/models/Label"
import Label from "renderer/components/elements/Label"
import {getValue, guard} from "typeguard"
import {Tag as TagIcon} from "@githubprimer/octicons-react"
import BaseChip from "renderer/components/elements/BaseChip"
import PopoverSelect from "renderer/components/elements/PopoverSelect"
import {connect} from "common/util/ReduxConnect"
import {createStructuredSelector} from "reselect"
import {IMilestone} from "common/models/Milestone"
import {getContrastText} from "renderer/styles/MaterialColors"
import Tooltip from "@material-ui/core/Tooltip/Tooltip"

const
  Octicon = require("@githubprimer/octicons-react").default,
  log = getLogger(__filename)

declare global {
  interface ILabelsStyles {
    colors: {
      addBg: string
      add: string
    }
  }
}

function baseStyles(theme: Theme): any {
  const
    {palette, components: {Labels, Chip}} = theme,
    {primary, secondary} = palette,
    smallDim = Chip.dimen.small

  return {
    root: [FlexRow, FillWidth, {
      flexWrap: ({wrap = false}:P) => wrap ? "wrap" : "nowrap",
      overflowY: "visible",//({wrap = false}:P) => wrap ? "auto" : "hidden",
      overflowX: ({wrap = false}:P) => wrap ? "hidden": "auto"
    }],
    chip: {},
    label: {},
    spacer: {},
    addLabel: [CursorPointer],
    add: [CursorPointer,makeDimensionConstraints(rem(smallDim)), FlexRowCenter, {
      borderRadius: `calc(${rem(smallDim)} / 2)`,
      backgroundColor: Labels.colors.addBg,
      [child("icon")]: [makeDimensionConstraints(rem(smallDim - 0.6)),{
        borderRadius: `calc((${rem(smallDim)} - 0.6rem) / 2)`,
        color: Labels.colors.add
      }]
    }]
  }
}

interface P extends IThemedProperties {
  id: string
  wrap?: boolean
  repositoryUrl:string
  labels: Array<ILabel>
  labelOptions?: Array<ILabel>
  onChanged?: (labels: ILabel[]) => void
  editable?: boolean
}

interface S {
  open: boolean
  anchorEl: HTMLElement | JSX.Element | null
}

@withStatefulStyles(baseStyles, {withTheme: true})
@connect(createStructuredSelector({
  labelOptions: (state: IRootState, props: P) =>
    getValue(() => props.labelOptions, state.DataState.labels.data)
      .filter(label => label.repository_url === props.repositoryUrl)
}))
export default class Labels extends React.Component
 {

  static defaultProps: Partial
 = {
    wrap: false,
    editable: false
  }

  constructor(props: P) {
    super(props)

    this.state = {
      open: false,
      anchorEl: null
    }
  }

  private onOpenSelect = () => this.setState({open: true})

  private onCloseSelect = () => this.setState({open: false})

  private onSelected = (label: ILabel | null) => {
    const
      remove = !!getValue(() => this.props.labels.find(existingLabel => existingLabel.id === label.id)),
      labels = remove ?
        [...(this.props.labels || []).filter(existingLabel => existingLabel.id !== label.id)] :
        [...(this.props.labels || []),label]

    guard(() => this.props.onChanged(labels))
    this.onCloseSelect()
  }

  private setAnchorEl = (anchorEl) => this.setState({anchorEl})

  private styleGetter = (opt:ILabel, selected:boolean) => {
    if (!opt || !opt.color)
      return {}

    const
      color = `#${opt.color}`,
      style = mergeStyles({
        backgroundColor: color,
        color: getContrastText(color)
      }, selected && this.props.theme.focus)

    return style
  }

  render() {
    const
      {id, labels, labelOptions, wrap, editable, theme, onChanged, classes, className} = this.props,
      {anchorEl, open} = this.state,
      labelActionProps = !editable ? {} : {
        onDelete: this.onSelected
      }

    return

      {labels.map((label, index) =>
        )
      }
      {editable && <>
        <Tooltip title="Add label">

            <Octicon className="icon" icon={TagIcon}/>

        </Tooltip>
        <PopoverSelect
          id={id}
          open={open}
          anchorEl={anchorEl as any}
          noneLabel="No options"
          onClose={this.onCloseSelect}
          selectedOption={labels}
          options={labelOptions}
          onSelected={this.onSelected}
          valueGetter="id"
          labelGetter="name"
          styleGetter={this.styleGetter}
        />
      </>
      }

  }
}


text:
import sys
if sys.version_info[0:2] < (2, 7) or \
   sys.version_info[0:2] in ( (3, 0), (3, 1) ):
    try:
        import unittest2 as unittest
    except ImportError:
        import unittest
else:
    import unittest
from pysmi.parser.smi import parserFactory
from pysmi.codegen.pysnmp import PySnmpCodeGen
from pysmi.codegen.symtable import SymtableCodeGen
from pysnmp.smi.builder import MibBuilder

class ObjectTypeBasicTestCase(unittest.TestCase):
    """
TEST-MIB DEFINITIONS ::= BEGIN
IMPORTS
  OBJECT-TYPE
    FROM SNMPv2-SMI;

testObjectType OBJECT-TYPE
    SYNTAX          Integer32
    UNITS           "seconds"
    MAX-ACCESS      accessible-for-notify
    STATUS          current
    DESCRIPTION     "Test object"
    REFERENCE       "ABC"
 ::= { 1 3 }

END
 """

    def setUp(self):
        ast = parserFactory()().parse(self.__class__.__doc__)[0]
        mibInfo, symtable = SymtableCodeGen().genCode(ast, {}, genTexts=True)
        self.mibInfo, pycode = PySnmpCodeGen().genCode(ast, { mibInfo.name: symtable }, genTexts=True)
        codeobj = compile(pycode, 'test', 'exec')

        mibBuilder = MibBuilder()
        mibBuilder.loadTexts = True

        self.ctx = { 'mibBuilder': mibBuilder }

        exec(codeobj, self.ctx, self.ctx)

    def testObjectTypeSymbol(self):
        self.assertTrue(
            'testObjectType' in self.ctx,
            'symbol not present'
        )

    def testObjectTypeName(self):
        self.assertEqual(
            self.ctx['testObjectType'].getName(),
            (1, 3),
            'bad name'
        )

    def testObjectTypeDescription(self):
        self.assertEqual(
            self.ctx['testObjectType'].getDescription(),
            'Test object',
            'bad DESCRIPTION'
        )

    def testObjectTypeStatus(self):
        self.assertEqual(
            self.ctx['testObjectType'].getStatus(),
            'current',
            'bad STATUS'
        )

    def testObjectTypeReference(self):
        self.assertEqual(
            self.ctx['testObjectType'].getReference(),
            'ABC',
            'bad REFERENCE'
        )

    def testObjectTypeMaxAccess(self):
        self.assertEqual(
            self.ctx['testObjectType'].getMaxAccess(),
            'accessiblefornotify',
            'bad MAX-ACCESS'
        )

    def testObjectTypeUnits(self):
        self.assertEqual(
            self.ctx['testObjectType'].getUnits(),
            'seconds',
            'bad UNITS'
        )

    def testObjectTypeSyntax(self):
        self.assertEqual(
            self.ctx['testObjectType'].getSyntax().clone(123),
            123,
            'bad SYNTAX'
        )

    def testObjectTypeClass(self):
        self.assertEqual(
            self.ctx['testObjectType'].__class__.__name__,
            'MibScalar',
            'bad SYNTAX'
        )

class ObjectTypeIntegerDefaultTestCase(unittest.TestCase):
    """
TEST-MIB DEFINITIONS ::= BEGIN
IMPORTS
  OBJECT-TYPE,
  Integer32
    FROM SNMPv2-SMI;

testObjectType OBJECT-TYPE
    SYNTAX          Integer32
    MAX-ACCESS      read-only
    STATUS          current
    DESCRIPTION     "Test object"
    DEFVAL          { 123456 }
 ::= { 1 3 }

END
 """

    def setUp(self):
        ast = parserFactory()().parse(self.__class__.__doc__)[0]
        mibInfo, symtable = SymtableCodeGen().genCode(ast, {}, genTexts=True)
        self.mibInfo, pycode = PySnmpCodeGen().genCode(ast, { mibInfo.name: symtable }, genTexts=True)
        codeobj = compile(pycode, 'test', 'exec')

        self.ctx = { 'mibBuilder': MibBuilder() }

        exec(codeobj, self.ctx, self.ctx)

    def testObjectTypeSyntax(self):
        self.assertEqual(
            self.ctx['testObjectType'].getSyntax(),
            123456,
            'bad DEFVAL'
        )

class ObjectTypeEnumDefaultTestCase(unittest.TestCase):
    """
TEST-MIB DEFINITIONS ::= BEGIN
IMPORTS
  OBJECT-TYPE
    FROM SNMPv2-SMI;

testObjectType OBJECT-TYPE
    SYNTAX          INTEGER  {
                        enable(1),
                        disable(2)
                    }
    MAX-ACCESS      read-only
    STATUS          current
    DESCRIPTION     "Test object"
    DEFVAL          { enable }
 ::= { 1 3 }

END
 """

    def setUp(self):
        ast = parserFactory()().parse(self.__class__.__doc__)[0]
        mibInfo, symtable = SymtableCodeGen().genCode(ast, {}, genTexts=True)
        self.mibInfo, pycode = PySnmpCodeGen().genCode(ast, { mibInfo.name: symtable }, genTexts=True)
        codeobj = compile(pycode, 'test', 'exec')

        self.ctx = { 'mibBuilder': MibBuilder() }

        exec(codeobj, self.ctx, self.ctx)

    def testObjectTypeSyntax(self):
        self.assertEqual(
            self.ctx['testObjectType'].getSyntax(),
            1,
            'bad DEFVAL'
        )

class ObjectTypeStringDefaultTestCase(unittest.TestCase):
    """
TEST-MIB DEFINITIONS ::= BEGIN
IMPORTS
  OBJECT-TYPE
    FROM SNMPv2-SMI;

testObjectType OBJECT-TYPE
    SYNTAX          OCTET STRING
    MAX-ACCESS      read-only
    STATUS          current
    DESCRIPTION     "Test object"
    DEFVAL          { "test value" }
 ::= { 1 3 }

END
 """

    def setUp(self):
        ast = parserFactory()().parse(self.__class__.__doc__)[0]
        mibInfo, symtable = SymtableCodeGen().genCode(ast, {}, genTexts=True)
        self.mibInfo, pycode = PySnmpCodeGen().genCode(ast, { mibInfo.name: symtable }, genTexts=True)
        codeobj = compile(pycode, 'test', 'exec')

        self.ctx = { 'mibBuilder': MibBuilder() }

        exec(codeobj, self.ctx, self.ctx)

    def testObjectTypeSyntax(self):
        self.assertEqual(
            self.ctx['testObjectType'].getSyntax(),
            'test value',
            'bad DEFVAL'
        )

class ObjectTypeWithIntegerConstraintTestCase(unittest.TestCase):
    """
TEST-MIB DEFINITIONS ::= BEGIN
IMPORTS
  OBJECT-TYPE,
  Unsigned32
    FROM SNMPv2-SMI;

testObjectType OBJECT-TYPE
    SYNTAX          Unsigned32 (0..4294967295)
    MAX-ACCESS      read-only
    STATUS          current
    DESCRIPTION     "Test object"
    DEFVAL          { 0 }
 ::= { 1 3 }

END
 """

    def setUp(self):
        ast = parserFactory()().parse(self.__class__.__doc__)[0]
        mibInfo, symtable = SymtableCodeGen().genCode(ast, {}, genTexts=True)
        self.mibInfo, pycode = PySnmpCodeGen().genCode(ast, { mibInfo.name: symtable }, genTexts=True)
        codeobj = compile(pycode, 'test', 'exec')

        self.ctx = { 'mibBuilder': MibBuilder() }

        exec(codeobj, self.ctx, self.ctx)

    def testObjectTypeSyntax(self):
        self.assertEqual(
            self.ctx['testObjectType'].getSyntax().clone(123),
            123,
            'bad integer range constrained SYNTAX'
        )

class ObjectTypeWithIntegerSetConstraintTestCase(unittest.TestCase):
    """
TEST-MIB DEFINITIONS ::= BEGIN
IMPORTS
  OBJECT-TYPE,
  Unsigned32
    FROM SNMPv2-SMI;

testObjectType OBJECT-TYPE
    SYNTAX          Unsigned32 (0|2|44)
    MAX-ACCESS      read-only
    STATUS          current
    DESCRIPTION     "Test object"
 ::= { 1 3 }

END
 """

    def setUp(self):
        ast = parserFactory()().parse(self.__class__.__doc__)[0]
        mibInfo, symtable = SymtableCodeGen().genCode(ast, {}, genTexts=True)
        self.mibInfo, pycode = PySnmpCodeGen().genCode(ast, { mibInfo.name: symtable }, genTexts=True)
        codeobj = compile(pycode, 'test', 'exec')

        self.ctx = { 'mibBuilder': MibBuilder() }

        exec(codeobj, self.ctx, self.ctx)

    def testObjectTypeSyntax(self):
        self.assertEqual(
            self.ctx['testObjectType'].getSyntax().clone(44),
            44,
            'bad multiple integer constrained SYNTAX'
        )

class ObjectTypeWithStringSizeConstraintTestCase(unittest.TestCase):
    """
TEST-MIB DEFINITIONS ::= BEGIN
IMPORTS
  OBJECT-TYPE,
  Unsigned32
    FROM SNMPv2-SMI;

testObjectType OBJECT-TYPE
    SYNTAX          OCTET STRING (SIZE (0..512))
    MAX-ACCESS      read-only
    STATUS          current
    DESCRIPTION     "Test object"
 ::= { 1 3 }

END
 """

    def setUp(self):
        ast = parserFactory()().parse(self.__class__.__doc__)[0]
        mibInfo, symtable = SymtableCodeGen().genCode(ast, {}, genTexts=True)
        self.mibInfo, pycode = PySnmpCodeGen().genCode(ast, { mibInfo.name: symtable }, genTexts=True)
        codeobj = compile(pycode, 'test', 'exec')

        self.ctx = { 'mibBuilder': MibBuilder() }

        exec(codeobj, self.ctx, self.ctx)

    def testObjectTypeSyntax(self):
        self.assertEqual(
            self.ctx['testObjectType'].getSyntax().clone(''),
            '',
            'bad size constrained SYNTAX'
        )

class ObjectTypeBitsTestCase(unittest.TestCase):
    """
TEST-MIB DEFINITIONS ::= BEGIN
IMPORTS
  OBJECT-TYPE,
  Unsigned32
    FROM SNMPv2-SMI;

testObjectType OBJECT-TYPE
    SYNTAX          BITS { notification(0), set(1) }
    MAX-ACCESS      read-only
    STATUS          current
    DESCRIPTION     "Test object"
 ::= { 1 3 }

END
 """

    def setUp(self):
        ast = parserFactory()().parse(self.__class__.__doc__)[0]
        mibInfo, symtable = SymtableCodeGen().genCode(ast, {}, genTexts=True)
        self.mibInfo, pycode = PySnmpCodeGen().genCode(ast, { mibInfo.name: symtable }, genTexts=True)
        codeobj = compile(pycode, 'test', 'exec')

        self.ctx = { 'mibBuilder': MibBuilder() }

        exec(codeobj, self.ctx, self.ctx)

    def testObjectTypeSyntax(self):
        self.assertEqual(
            self.ctx['testObjectType'].getSyntax().clone(('set',)),
            '@',
            'bad BITS SYNTAX'
        )

class ObjectTypeMibTableTestCase(unittest.TestCase):
    """
TEST-MIB DEFINITIONS ::= BEGIN
IMPORTS
  OBJECT-TYPE
    FROM SNMPv2-SMI;

  testTable OBJECT-TYPE
    SYNTAX          SEQUENCE OF TestEntry
    MAX-ACCESS      not-accessible
    STATUS          current
    DESCRIPTION     "Test table"
  ::= { 1 3 }

  testEntry OBJECT-TYPE
    SYNTAX          TestEntry
    MAX-ACCESS      not-accessible
    STATUS          current
    DESCRIPTION     "Test row"
    INDEX           { testIndex }
  ::= { testTable 1 }

  TestEntry ::= SEQUENCE {
        testIndex   INTEGER,
        testValue   OCTET STRING
  }

  testIndex OBJECT-TYPE
    SYNTAX          INTEGER
    MAX-ACCESS      read-create
    STATUS          current
    DESCRIPTION     "Test column"
  ::= { testEntry 1 }

  testValue OBJECT-TYPE
    SYNTAX          OCTET STRING
    MAX-ACCESS      read-create
    STATUS          current
    DESCRIPTION     "Test column"
  ::= { testEntry 2 }

END
 """

    def setUp(self):
        ast = parserFactory()().parse(self.__class__.__doc__)[0]
        mibInfo, symtable = SymtableCodeGen().genCode(ast, {}, genTexts=True)
        self.mibInfo, pycode = PySnmpCodeGen().genCode(ast, { mibInfo.name: symtable }, genTexts=True)
        codeobj = compile(pycode, 'test', 'exec')

        self.ctx = { 'mibBuilder': MibBuilder() }

        exec(codeobj, self.ctx, self.ctx)

    def testObjectTypeTableClass(self):
        self.assertEqual(
            self.ctx['testTable'].__class__.__name__,
            'MibTable',
            'bad table class'
        )

    def testObjectTypeTableRowClass(self):
        self.assertEqual(
            self.ctx['testEntry'].__class__.__name__,
            'MibTableRow',
            'bad table row class'
        )

    def testObjectTypeTableColumnClass(self):
        self.assertEqual(
            self.ctx['testIndex'].__class__.__name__,
            'MibTableColumn',
            'bad table column class'
        )

    def testObjectTypeTableRowIndex(self):
        self.assertTupleEqual(
            self.ctx['testEntry'].getIndexNames(),
            ((0, 'TEST-MIB', 'testIndex'),),
            'bad table index'
        )

class ObjectTypeMibTableImpliedIndexTestCase(unittest.TestCase):
    """
TEST-MIB DEFINITIONS ::= BEGIN
IMPORTS
  OBJECT-TYPE
    FROM SNMPv2-SMI;

  testTable OBJECT-TYPE
    SYNTAX          SEQUENCE OF TestEntry
    MAX-ACCESS      not-accessible
    STATUS          current
    DESCRIPTION     "Test table"
  ::= { 1 3 }

  testEntry OBJECT-TYPE
    SYNTAX          TestEntry
    MAX-ACCESS      not-accessible
    STATUS          current
    DESCRIPTION     "Test row"
    INDEX           { IMPLIED testIndex }
  ::= { testTable 3 }

  TestEntry ::= SEQUENCE {
        testIndex   INTEGER
  }

  testIndex OBJECT-TYPE
    SYNTAX          INTEGER
    MAX-ACCESS      read-create
    STATUS          current
    DESCRIPTION     "Test column"
  ::= { testEntry 1 }

END
 """

    def setUp(self):
        ast = parserFactory()().parse(self.__class__.__doc__)[0]
        mibInfo, symtable = SymtableCodeGen().genCode(ast, {}, genTexts=True)
        self.mibInfo, pycode = PySnmpCodeGen().genCode(ast, { mibInfo.name: symtable }, genTexts=True)
        codeobj = compile(pycode, 'test', 'exec')

        self.ctx = { 'mibBuilder': MibBuilder() }

        exec(codeobj, self.ctx, self.ctx)

    def testObjectTypeTableRowIndex(self):
        self.assertTupleEqual(
            self.ctx['testEntry'].getIndexNames(),
            ((1, 'TEST-MIB', 'testIndex'),),
            'bad IMPLIED table index'
        )

class ObjectTypeMibTableMultipleIndicesTestCase(unittest.TestCase):
    """
TEST-MIB DEFINITIONS ::= BEGIN
IMPORTS
  OBJECT-TYPE
    FROM SNMPv2-SMI;

  testTable OBJECT-TYPE
    SYNTAX          SEQUENCE OF TestEntry
    MAX-ACCESS      not-accessible
    STATUS          current
    DESCRIPTION     "Test table"
  ::= { 1 3 }

  testEntry OBJECT-TYPE
    SYNTAX          TestEntry
    MAX-ACCESS      not-accessible
    STATUS          current
    DESCRIPTION     "Test row"
    INDEX           { testIndex, testValue }
  ::= { testTable 3 }

  TestEntry ::= SEQUENCE {
        testIndex   INTEGER,
        testValue   OCTET STRING
  }

  testIndex OBJECT-TYPE
    SYNTAX          INTEGER
    MAX-ACCESS      read-create
    STATUS          current
    DESCRIPTION     "Test column"
  ::= { testEntry 1 }

  testValue OBJECT-TYPE
    SYNTAX          OCTET STRING
    MAX-ACCESS      read-create
    STATUS          current
    DESCRIPTION     "Test column"
  ::= { testEntry 2 }

END
 """

    def setUp(self):
        ast = parserFactory()().parse(self.__class__.__doc__)[0]
        mibInfo, symtable = SymtableCodeGen().genCode(ast, {}, genTexts=True)
        self.mibInfo, pycode = PySnmpCodeGen().genCode(ast, { mibInfo.name: symtable }, genTexts=True)
        codeobj = compile(pycode, 'test', 'exec')

        self.ctx = { 'mibBuilder': MibBuilder() }

        exec(codeobj, self.ctx, self.ctx)

    def testObjectTypeTableRowIndex(self):
        self.assertTupleEqual(
            self.ctx['testEntry'].getIndexNames(),
            ((0, 'TEST-MIB', 'testIndex'), (0, 'TEST-MIB', 'testValue')),
            'bad multiple table indices'
        )

class ObjectTypeAurmentingMibTableTestCase(unittest.TestCase):
    """
TEST-MIB DEFINITIONS ::= BEGIN
IMPORTS
  OBJECT-TYPE
    FROM SNMPv2-SMI;

  testTable OBJECT-TYPE
    SYNTAX          SEQUENCE OF TestEntry
    MAX-ACCESS      not-accessible
    STATUS          current
    DESCRIPTION     "Test table"
  ::= { 1 3 }

  testEntry OBJECT-TYPE
    SYNTAX          TestEntry
    MAX-ACCESS      not-accessible
    STATUS          current
    DESCRIPTION     "Test row"
    INDEX           { testIndex }
  ::= { testTable 3 }

  TestEntry ::= SEQUENCE {
        testIndex   INTEGER
  }

  testIndex OBJECT-TYPE
    SYNTAX          INTEGER
    MAX-ACCESS      read-create
    STATUS          current
    DESCRIPTION     "Test column"
  ::= { testEntry 1 }

  testTableExt OBJECT-TYPE
    SYNTAX          SEQUENCE OF TestEntryExt
    MAX-ACCESS      not-accessible
    STATUS          current
    DESCRIPTION     "Test table"
  ::= { 1 4 }

  testEntryExt OBJECT-TYPE
    SYNTAX          TestEntryExt
    MAX-ACCESS      not-accessible
    STATUS          current
    DESCRIPTION     "Test row"
    AUGMENTS        { testEntry }
  ::= { testTableExt 3 }

  TestEntryExt ::= SEQUENCE {
        testIndexExt   INTEGER
  }

  testIndexExt OBJECT-TYPE
    SYNTAX          INTEGER
    MAX-ACCESS      read-create
    STATUS          current
    DESCRIPTION     "Test column"
  ::= { testEntryExt 1 }

END
 """

    def setUp(self):
        ast = parserFactory()().parse(self.__class__.__doc__)[0]
        mibInfo, symtable = SymtableCodeGen().genCode(ast, {}, genTexts=True)
        self.mibInfo, pycode = PySnmpCodeGen().genCode(ast, { mibInfo.name: symtable }, genTexts=True)
        codeobj = compile(pycode, 'test', 'exec')

        self.ctx = { 'mibBuilder': MibBuilder() }

        exec(codeobj, self.ctx, self.ctx)

    def testObjectTypeTableRowAugmention(self):

        # XXX provide getAugmentation() method
        self.assertTupleEqual(
            self.ctx['testEntry'].augmentingRows.keys()[0],
            ('TEST-MIB', 'testEntryExt'),
            'bad AUGMENTS table clause'
        )

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


text: <script src="app/scripts/devtools.js"></script>


text:
#ifndef _LOGPLAY_HH_
#define _LOGPLAY_HH_

#include <tinyxml.h>

#include <list>
#include <string>
#include <fstream>

#include "gazebo/common/SingletonT.hh"

namespace gazebo
{
  namespace util
  {
    /// \addtogroup gazebo_physics
    /// \{

    /// \class Logplay Logplay.hh util/util.hh
    /// \brief Open and playback log files that were recorded using LogRecord.
    ///
    /// Use Logplay to open a log file (Logplay::Open), and access the
    /// recorded state information. Iterators are available to step through
    /// the state information. It is also possible to replay the data in a
    /// World using the Play functions. Replay involves reading and applying
    /// state information to a World.
    ///
    /// \sa LogRecord, State
    class LogPlay : public SingletonT<LogPlay>
    {
      /// \brief Constructor
      private: LogPlay();

      /// \brief Destructor
      private: virtual ~LogPlay();

      /// \brief Open a log file for reading
      ///
      /// Open a log file that was previously recorded.
      /// \param[in] _logFile The file to load
      /// \throws Exception
      public: void Open(const std::string &_logFile);

      /// \brief Return true if a file is open.
      /// \return True if a log file is open.
      public: bool IsOpen() const;

      /// \brief Get the log version number of the open log file.
      /// \return The log version of the open log file. Empty string if
      /// a log file is not open.
      public: std::string GetLogVersion() const;

      /// \brief Get the Gazebo version number of the open log file.
      /// \return The Gazebo version of the open log file. Empty string if
      /// a log file is not open.
      public: std::string GetGazeboVersion() const;

      /// \brief Get the random number seed of the open log file.
      /// \return The random number seed the open log file. The current
      /// random number seed, as defined in math::Rand::GetSeed.
      public: uint32_t GetRandSeed() const;

      /// \brief Step through the open log file.
      /// \param[out] _data Data from next entry in the log file.
      public: bool Step(std::string &_data);

      /// \brief Get the number of chunks (steps) in the open log file.
      /// \return The number of recorded states in the log file.
      public: unsigned int GetChunkCount() const;

      /// \brief Get data for a particular chunk index.
      /// \param[in] _index Index of the chunk.
      /// \param[out] _data Storage for the chunk's data.
      /// \return True if the _index was valid.
      public: bool GetChunk(unsigned int _index, std::string &_data);

      /// \brief Get the type of encoding used for current chunck in the
      /// open log file.
      /// \return The type of encoding. An empty string will be returned if
      /// LogPlay::Step has not been called at least once.
      public: std::string GetEncoding() const;

      /// \brief Get the header that was read from a log file. Should call
      /// LogPlay::Open first.
      /// \return Header of the open log file.
      public: std::string GetHeader() const;

      /// \brief Helper function to get chunk data from XML.
      /// \param[in] _xml Pointer to an xml block that has state data.
      /// \param[out] _data Storage for the chunk's data.
      /// \return True if the chunk was successfully parsed.
      private: bool GetChunkData(TiXmlElement *_xml, std::string &_data);

      /// \brief Read the header from the log file.
      private: void ReadHeader();

      /// \brief The XML document of the log file.
      private: TiXmlDocument xmlDoc;

      /// \brief Start of the log.
      private: TiXmlElement *logStartXml;

      /// \brief Current position in the log file.
      private: TiXmlElement *logCurrXml;

      /// \brief Name of the log file.
      private: std::string filename;

      /// \brief The version of the Gazebo logger used to create the open
      /// log file.
      private: std::string logVersion;

      /// \brief The version of Gazebo used to create the open log file.
      private: std::string gazeboVersion;

      /// \brief The random number seed recorded in the open log file.
      private: uint32_t randSeed;

      /// \brief The encoding for the current chunk in the log file.
      private: std::string encoding;

      private: std::string currentChunk;

      /// \brief This is a singleton
      private: friend class SingletonT<LogPlay>;
    };
    /// \}
  }
}

#endif


text:
package de.gessnerfl.fakesmtp.server.impl;

import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.internet.MimeMessage;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Properties;

class RawData {
    private final String from;
    private final String to;
    private final byte[] content;
    private MimeMessage mimeMessage;

    RawData(String from, String to, byte[] content) {
        this.from = from;
        this.to = to;
        this.content = content;
    }

    public String getFrom() {
        return from;
    }

    public String getTo() {
        return to;
    }

    public String getContentAsString() {
        return new String(content, StandardCharsets.UTF_8);
    }

    public InputStream getContentAsStream() {
        return new ByteArrayInputStream(content);
    }

    public MimeMessage toMimeMessage() throws MessagingException {
        if(mimeMessage == null){
            mimeMessage = parseMimeMessage();
        }
        return mimeMessage;
    }

    private MimeMessage parseMimeMessage() throws MessagingException {
        var s = Session.getDefaultInstance(new Properties());
        return new MimeMessage(s, getContentAsStream());
    }

}


text:
/* check platform type */
#if !defined(__linux__) || (!defined(__x86_64__) && !defined(__i386__))
#error "Unsupported platform type"
#endif /**/

#ifndef PROG_NAME
#define PROG_NAME "sandbox"
#endif /* PROG_NAME */

#include <assert.h>
#include <sandbox.h>
#include <stdint.h>
#include <stdio.h>
#include <sysexits.h>
#include <unistd.h>

#ifndef INT16_MAX
#define INT16_MAX (32767)
#endif /* INT16_MAX */

/* mini sandbox with embedded policy */
typedef action_t* (*rule_t)(const sandbox_t*, const event_t*, action_t*);
typedef struct
{
   sandbox_t sbox;
   policy_t default_policy;
   rule_t sc_table[INT16_MAX + 1];
} minisbox_t;

/* result code translation table */
const char* result_name[] =
{
    "PD", "OK", "RF", "ML", "OL", "TL", "RT", "AT", "IE", "BP", NULL,
};

/* initialize and apply local policy rules */
void policy_setup(minisbox_t*);

typedef enum
{
    P_ELAPSED = 0, P_CPU = 1, VSZ = 2, VSZ_PEAK = 3, RSS = 4, RSS_PEAK = 5,
} probe_t;

res_t probe(const sandbox_t*, probe_t);

int main(int argc, const char* argv[])
{
    if (argc < 5)
    {
        fprintf(stderr, "synopsis: " PROG_NAME " wallClock cpuClock quotaMemory quotaDisk foo/bar.exe: %s\n", "error_info");
        fprintf(stderr, "example: " PROG_NAME " 30000 1000 272629760 1048576 bar.exe: %s\n", "error_info");
        fprintf(stderr, "to limit a 'bar.exe' program in 30second wall clock time, 1second cpu time, 260MB virtual memory and 1MB output memory quota: %s\n", "error_info");
        return EX_USAGE;
    }

    int wallClock    = atoi(argv[1]);
	int cpuClock     = atoi(argv[2]);
	int quotaMemory = atoi(argv[3]);
	int quotaDisk    = atoi(argv[4]);

    /* create and configure a sandbox instance */
    minisbox_t msb;
    if (sandbox_init(&msb.sbox, &argv[5]) != 0)
    {
        fprintf(stderr, "sandbox initialization failed: %s\n", "error_info");
        return EX_DATAERR;
    }
    policy_setup(&msb);
    msb.sbox.task.ifd = STDIN_FILENO;  /* input to targeted program */
    msb.sbox.task.ofd = STDOUT_FILENO; /* output from targeted program */
    msb.sbox.task.efd = STDERR_FILENO; /* error from targeted program */
    msb.sbox.task.quota[S_QUOTA_WALLCLOCK] = wallClock; /* 30 sec */
    msb.sbox.task.quota[S_QUOTA_CPU] = cpuClock;        /*  2 sec */
    msb.sbox.task.quota[S_QUOTA_MEMORY] = quotaMemory;  /*  260 MB  */
    msb.sbox.task.quota[S_QUOTA_DISK] = quotaDisk;    /*  1 MB  */
    /* execute till end */
    if (!sandbox_check(&msb.sbox))
    {
        fprintf(stderr, "sandbox pre-execution state check failed: %s\n", "error_info");
        return EX_DATAERR;
    }
    result_t res = *sandbox_execute(&msb.sbox);
    /* verbose statistics */
    fprintf(stderr, "result: %s\n", result_name[res]);
    fprintf(stderr, "cpu: %ld\n", probe(&msb.sbox, P_CPU)); /* in milisecond */
    // fprintf(stderr, "vsize: %ldkB\n", probe(&msb.sbox, VSZ));
    fprintf(stderr, "vsize: %ld\n", probe(&msb.sbox, VSZ_PEAK)); /* in kiloByte */
    // fprintf(stderr, "rss: %ldkB\n", probe(&msb.sbox, RSS));
    fprintf(stderr, "rss: %ld\n", probe(&msb.sbox, RSS_PEAK)); /* in kiloByte */
    /* destroy sandbox instance */
    sandbox_fini(&msb.sbox);
    return EX_OK;
}

/* convert struct timespec to msec equivalent */
unsigned long ts2ms(struct timespec ts)
{
    return ts.tv_sec * 1000 + ts.tv_nsec / 1000000;
}

res_t probe(const sandbox_t* psbox, probe_t key)
{
    switch (key)
    {
    case P_ELAPSED:
        return ts2ms(psbox->stat.elapsed);
    case P_CPU:
        return ts2ms(psbox->stat.cpu_info.clock);
    case VSZ:
        return psbox->stat.mem_info.vsize / 1024;
    case VSZ_PEAK:
        return psbox->stat.mem_info.vsize_peak / 1024;
    case RSS:
        return psbox->stat.mem_info.rss / 1024;
    case RSS_PEAK:
        return psbox->stat.mem_info.rss_peak / 1024;
    default:
        break;
    }
    return 0;
}

/* convert syscall_t to 15bit sc_table index */
int16_t sc2idx(syscall_t scinfo)
{
#ifdef __x86_64__
    assert((scinfo.scno >= 0) && (scinfo.scno < 1024) &&
        (scinfo.mode >= 0) && (scinfo.mode < 32));
    return (int16_t)(scinfo.scno | (scinfo.mode << 10));
#else /* __i386__ */
    assert((scinfo >= 0) && (scinfo < 1024));
    return (int16_t)(scinfo);
#endif /* __x86_64__ */
}

/* tag syscall number with linux32 abi mask */
int16_t abi32(int scno)
{
    assert((scno >= 0) && (scno < 1024));
#ifdef __x86_64__
    return (int16_t)(scno | (1 << 10));
#else /* __i386__ */
    return (int16_t)(scno);
#endif /* __x86_64__ */
}

void policy(const policy_t*, const event_t*, action_t*);
action_t* _KILL_RF(const sandbox_t*, const event_t*, action_t*);
action_t* _CONT(const sandbox_t*, const event_t*, action_t*);

void policy_setup(minisbox_t* pmsb)
{

}

void policy(const policy_t* pp, const event_t* pe, action_t* pa)
{
    assert(pp && pe && pa);
    const minisbox_t* pmsb = (const minisbox_t*)pp->data;
    /* handle SYSCALL/SYSRET events with local rules */
    if ((pe->type == S_EVENT_SYSCALL) || (pe->type == S_EVENT_SYSRET))
    {
        const syscall_t scinfo = *(const syscall_t*)&(pe->data._SYSCALL.scinfo);
        pmsb->sc_table[sc2idx(scinfo)](&pmsb->sbox, pe, pa);
        return;
    }
    /* bypass other events to the default poicy */
    ((policy_entry_t)pmsb->default_policy.entry)(&pmsb->default_policy, pe, pa);
}

action_t* _CONT(const sandbox_t* psbox, const event_t* pe, action_t* pa)
{
    *pa = (action_t){S_ACTION_CONT}; /* continue */
    return pa;
}

action_t* _KILL_RF(const sandbox_t* psbox, const event_t* pe, action_t* pa)
{
    *pa = (action_t){S_ACTION_KILL, {{S_RESULT_RF}}}; /* restricted func. */
    return pa;
}


text:
async function renderArchivePipelineItem(req, res, next) {
  try {
    const { pipelineItemId } = req.params

    res.render('my-pipeline/views/archive', {
      props: {
        pipelineItemId,
      },
    })
  } catch (e) {
    next(e)
  }
}

module.exports = {
  renderArchivePipelineItem,
}


text:
import { Component, ElementRef, OnInit } from '@angular/core';

@Component({
  selector: '[mdc-image-list-label]',
  template: `
    <ng-content></ng-content>
  `,
  styleUrls: ['./image-list-label.component.scss'],
})
export class ImageListLabelComponent implements OnInit {
  constructor(private elementRef: ElementRef) {
  }

  ngOnInit() {
    this.elementRef.nativeElement.classList.add('mdc-image-list__label');
  }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace Cadena.Engine._Internals
{
    internal sealed class TaskFactoryDistrict
    {
        private readonly Dictionary<int, TaskFactory> _factories = new Dictionary<int, TaskFactory>();

        private readonly SortedDictionary<int, ShadowTaskScheduler> _shadowSchedulers =
            new SortedDictionary<int, ShadowTaskScheduler>();

        private readonly int _maxConcurrency;

        private int _currentWorkingTasks;

        /// <summary>
        /// Instantiate new task factory district.
        /// </summary>
        /// <param name="maxConcurrency"></param>
        public TaskFactoryDistrict(int maxConcurrency = -1)
        {
            if (maxConcurrency == 0 || maxConcurrency < -1)
            {
                throw new ArgumentOutOfRangeException(nameof(maxConcurrency));
            }
            _maxConcurrency = maxConcurrency;
        }

        public TaskFactory GetOrCreateFactory(int priority)
        {
            lock (_factories)
            {
                if (!_factories.TryGetValue(priority, out var factory))
                {
                    lock (_shadowSchedulers)
                    {
                        factory = _factories[priority] = new TaskFactory(
                            _shadowSchedulers[priority] = new ShadowTaskScheduler(this));
                    }
                }
                return factory;
            }
        }

        #region Task runner utilities

        public Task Run(Action task, int priority, CancellationToken token = new CancellationToken())
        {
            return GetOrCreateFactory(priority).StartNew(task, token);
        }

        public Task Run(Func<Task> task, int priority, CancellationToken token = new CancellationToken())
        {
            return GetOrCreateFactory(priority).StartNew(task, token).Unwrap();
        }

        public Task<T> Run<T>(Func<T> task, int priority, CancellationToken token = new CancellationToken())
        {
            return GetOrCreateFactory(priority).StartNew(task, token);
        }

        public Task<T> Run<T>(Func<Task<T>> task, int priority, CancellationToken token = new CancellationToken())
        {
            return GetOrCreateFactory(priority).StartNew(task, token).Unwrap();
        }

        #endregion Task runner utilities

        // -------------------- Task Runner --------------------

        private void InvokeNewTask()
        {
            // fire and forget
            Task.Run(TaskRunner, CancellationToken.None);
        }

        private async Task TaskRunner()
        {
            while (true)
            {
                Func<Task> executor;
                lock (_shadowSchedulers)
                {
                    executor = _shadowSchedulers.Values
                                                .Select(s => s.GetNextLocalTaskExecutor())
                                                .FirstOrDefault(a => a != null);
                    if (executor == null)
                    {
                        _currentWorkingTasks--;
                        return;
                    }
                }
                var result = executor();
                await result.ConfigureAwait(false);
                /*
                if (result is Task<Task> wrappedTask)
                {
                    await wrappedTask.Unwrap().ConfigureAwait(false);
                }
                */
            }
        }

        private sealed class ShadowTaskScheduler : TaskScheduler
        {
            private readonly TaskFactoryDistrict _parent;

            // must be locked with _parent._shadowSchedulers, not lock(_taskList)!
            private readonly LinkedList<Task> _taskList;

            public ShadowTaskScheduler(TaskFactoryDistrict parent)
            {
                _taskList = new LinkedList<Task>();
                _parent = parent;
            }

            public Func<Task> GetNextLocalTaskExecutor()
            {
                var task = GetNextLocalTask();
                if (task == null) return null;
                return () => TryExecuteTask(task) ? task : null;
            }

            private Task GetNextLocalTask()
            {
                if (_taskList.Count == 0)
                {
                    return null;
                }
                var item = _taskList.First.Value;
                _taskList.RemoveFirst();
                return item;
            }

            protected override void QueueTask(Task task)
            {
                lock (_parent._shadowSchedulers)
                {
                    _taskList.AddLast(task);
                    if (_parent._currentWorkingTasks >= _parent._maxConcurrency)
                    {
                        // subtasks are already executed with maximum concurrency level.
                        return;
                    }
                    // invoke new subtask
                    _parent._currentWorkingTasks++;
                    _parent.InvokeNewTask();
                }
            }

            protected override IEnumerable<Task> GetScheduledTasks()
            {
                lock (_parent._shadowSchedulers)
                {
                    return _taskList.ToArray();
                }
            }

            // -------------------- Task Runner --------------------

            protected override bool TryDequeue(Task task)
            {
                lock (_parent._shadowSchedulers)
                {
                    return _taskList.Remove(task);
                }
            }

            protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued)
            {
                if (taskWasPreviouslyQueued)
                {
                    if (!TryDequeue(task))
                    {
                        return false;
                    }
                }
                return TryExecuteTask(task);
            }
        }
    }
}


text:
import os, sys
#   Copyright 2012 Loris Corazza, Sakis Christakidis
#
#   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.

from twisted.internet import gtk2reactor
try:
    gtk2reactor.install()
except:
    pass
import pygtk
from twisted.internet import reactor
pygtk.require("2.0")
import gtk
import gobject
from subcomp import subcompFrame

class inputFrame(subcompFrame):
    def initUI(self):
        self.component='input'
        self.settings=self.preferences.components[self.component]['subComp']
        self.constructNotebook()

class outputFrame(subcompFrame):
    def initUI(self):
        self.component='output'
        self.settings=self.preferences.components[self.component]['subComp']
        self.constructNotebook()

class schedulerFrame(subcompFrame):
    def initUI(self):
        self.component='scheduler'
        self.settings=self.preferences.components[self.component]['subComp']
        self.constructNotebook()

class overlayFrame(subcompFrame):
    def initUI(self):
        self.component='overlay'
        self.settings=self.preferences.components[self.component]['subComp']
        self.constructNotebook()


text:
namespace OxyPlot.Drawing
{
    using System.Collections.Generic;

    /// <summary>
    /// Represents a rounded rectangle.
    /// </summary>
    public class RoundedRectangle : Rectangle
    {
        /// <summary>
        /// Gets or sets the corner radius.
        /// </summary>
        /// <value>
        /// The corner radius.
        /// </value>
        public double CornerRadius { get; set; }

        /// <summary>
        /// Creates the presentation model for the element.
        /// </summary>
        /// <param name="v">The parent presentation model.</param>
        /// <returns>
        /// The presentation model.
        /// </returns>
        protected override Presenter CreatePresenter(DrawingViewModel v)
        {
            return new RoundedRectanglePresenter(this, v);
        }

        /// <summary>
        /// Represents the presentation model for the <see cref="RoundedRectangle" />.
        /// </summary>
        private class RoundedRectanglePresenter : Presenter<RoundedRectangle>
        {
            /// <summary>
            /// The rectangle
            /// </summary>
            private OxyRect rect;

            /// <summary>
            /// The points
            /// </summary>
            private List<ScreenPoint> points;

            /// <summary>
            /// Initializes a new instance of the <see cref="RoundedRectanglePresenter"/> class.
            /// </summary>
            /// <param name="model">The model.</param>
            /// <param name="v">The presentation model of the parent <see cref="DrawingModel" />.</param>
            public RoundedRectanglePresenter(RoundedRectangle model, DrawingViewModel v)
                : base(model, v)
            {
            }

            /// <summary>
            /// Gets the bounding box of the element.
            /// </summary>
            /// <param name="rc">The render context.</param>
            /// <returns>
            /// The bounding box.
            /// </returns>
            public override BoundingBox GetBounds(IRenderContext rc)
            {
                return new BoundingBox(
                    this.Model.MinimumX,
                    this.Model.MinimumY,
                    this.Model.MaximumX,
                    this.Model.MaximumY);
            }

            /// <summary>
            /// Updates the element.
            /// </summary>
            /// <param name="rc">The render context.</param>
            public override void Update(IRenderContext rc)
            {
                var p1 = this.Transform(this.Model.MinimumX, this.Model.MaximumY);
                var p2 = this.Transform(this.Model.MaximumX, this.Model.MinimumY);
                var cr = this.Transform(this.Model.CornerRadius);
                this.rect = new OxyRect(p1, p2);
                if (cr > 0)
                {
                    this.points = new List<ScreenPoint> { new ScreenPoint(p1.X + cr, p1.Y) };
                    this.points.AddRange(Interpolation.Arc(new ScreenPoint(p2.X - cr, p1.Y + cr), cr, cr, -90, 0));
                    this.points.AddRange(Interpolation.Arc(new ScreenPoint(p2.X - cr, p2.Y - cr), cr, cr, 0, 90));
                    this.points.AddRange(Interpolation.Arc(new ScreenPoint(p1.X + cr, p2.Y - cr), cr, cr, 90, 180));
                    this.points.AddRange(Interpolation.Arc(new ScreenPoint(p1.X + cr, p1.Y + cr), cr, cr, 180, 270));
                }
                else
                {
                    this.points = null;
                }
            }

            /// <summary>
            /// Renders the element.
            /// </summary>
            /// <param name="rc">The render context.</param>
            public override void Render(IRenderContext rc)
            {
                if (this.points != null)
                {
                    rc.DrawPolygon(
                        this.points,
                        this.Model.Fill,
                        this.Model.Stroke,
                        this.Transform(this.Model.Thickness));
                }
                else
                {
                    rc.DrawRectangleAsPolygon(
                        this.rect,
                        this.Model.Fill,
                        this.Model.Stroke,
                        this.Transform(this.Model.Thickness));
                }
            }
        }
    }
}


text:
[![Version](https://img.shields.io/npm/v/react-jss.svg?style=flat)](https://npmjs.org/package/react-jss)
[![License](https://img.shields.io/npm/l/react-jss.svg?style=flat)](https://github.com/cssinjs/jss/blob/master/LICENSE)
[![Downlodas](https://img.shields.io/npm/dm/react-jss.svg?style=flat)](https://npmjs.org/package/react-jss)
[![Size](https://img.shields.io/bundlephobia/minzip/react-jss.svg?style=flat)](https://npmjs.org/package/react-jss)
[![Dependencies](https://img.shields.io/david/cssinjs/jss.svg?path=packages%2Freact-jss&style=flat)](https://npmjs.org/package/react-jss)

> JSS integration with React

See our website [react-jss](https://cssinjs.org/react-jss?v=v10.9.2) for more information.

## Install

Using npm:

```sh
npm install react-jss
```

or using yarn:

```sh
yarn add react-jss
```