text:
% datadlg: create a data dialog box
%
%
function answer=datadlg_STFT(name,label,default,options)

% handle input
if (nargin<1) || isempty(name)
    name='Data Dialog';
end

if (nargin<2) || isempty(label)
    label={'Parameter:'};
end

if (nargin<3) || isempty(default)
    default={''};
end

if (nargin<4) || isempty(options)
    options=struct();
end
field='style';
if ~isfield(options,field) || isempty(options.(field))
    options.(field)='modal';
end
field='minwidth';
if ~isfield(options,field) || isempty(options.(field))
    options.(field)=20; % characters
end
field='root';
if ~isfield(options,field) || isempty(options.(field))
    options.(field)=0; % root object (the screen)
end
field='location';
if ~isfield(options,field) || isempty(options.(field))
    options.(field)='center';
end
field='fontname';
if ~isfield(options,field) || isempty(options.(field))
    options.(field)=get(0,'DefaultUIcontrolFontName');
end
field='fontsize';
if ~isfield(options,field) || isempty(options.(field))
    options.(field)=get(0,'DefaultUIcontrolFontSize');
end

popupstring1={'boxcar','hamming','hann','blackman'};
switch default{4};
    case popupstring1{1}
        popupval1=1;
    case popupstring1{2}
        popupval1=2;
    case popupstring1{3}
        popupval1=3;
    case popupstring1{4}
        popupval1=4;
end

popupstring2={'global','local'};
switch default{5}
    case popupstring2{1}
        popupval2=1;
    case popupstring2{2}
        popupval2=2;
end

popupstring3={'yes','no'};
switch default{6};
    case 1
        popupval3=1;
    case 0
        popupval3=2;
end

edit{1}=default{1};
edit{2}=default{2};
edit{3}=default{3};
edit{4}=default{4};
edit{5}=default{5};
edit{6}=default{6};
data.edit=edit;

% create and size dialog
fig=figure('NumberTitle','off','Name',name,...
    'Menubar','none','Toolbar','none',...
    'Resize','off','Units','characters',...
    'ToolBar','none','MenuBar','none',...
    'IntegerHandle','off','Visible','on');
hgap=1.00; % horizontal gap [characters]
vgap=0.50; % vertical gap [characters]
textbg=get(fig,'Color');

set(fig,'Position',[0 0 30 30],'Visible','off');
movedlg(fig,options.root,options.location);
set(fig,'Visible','on');

edittext(1) = uicontrol('Style','text','String',label{1},...
        'Units','characters','Position',[5 27 25 1.2],...
        'BackgroundColor',textbg,'HorizontalAlignment','left');
editbox(1) = uicontrol('Style','edit','String',edit{1},...
        'Units','characters','Position',[5 25 18 2],...
        'BackgroundColor','w','HorizontalAlignment','left');

edittext(2) = uicontrol('Style','text','String',label{2},...
        'Units','characters','Position',[5 23 30 1.2],...
        'BackgroundColor',textbg,'HorizontalAlignment','left');
editbox(2) = uicontrol('Style','edit','String',edit{2},...
        'Units','characters','Position',[5 21 18 2],...
        'BackgroundColor','w','HorizontalAlignment','left');

edittext(3) = uicontrol('Style','text','String',label{3},...
        'Units','characters','Position',[5 19 30 1.2],...
        'BackgroundColor',textbg,'HorizontalAlignment','left');
editbox(3) = uicontrol('Style','edit','String',edit{3},...
        'Units','characters','Position',[5 17 18 2],...
        'BackgroundColor','w','HorizontalAlignment','left');

popuptext1 = uicontrol('Style','Text','String',label{4},...
    'Units','characters','HorizontalAlignment','left',...
    'BackgroundColor',textbg,'Position',[5 15 15 1.2]);
popupbox1 = uicontrol('style','popupmenu',...
    'Units','characters',...
    'position',[5 13.5 20 1.2],...
    'string',popupstring1,...
    'backgroundcolor','w',...
    'value',popupval1, ...
    'tag','listbox',...
    'callback', {@doPopupClick,4,popupval1,popupstring1});

popuptext2 = uicontrol('Style','Text','String',label{5},'Units','characters',...
    'Units','characters','HorizontalAlignment','left',...
    'BackgroundColor',textbg,'Position',[5 11 15 1.2]);
popupbox2 = uicontrol('style','popupmenu',...
    'Units','characters',...
    'position',[5 9.5 20 1.2],...
    'string',popupstring2,...
    'backgroundcolor','w',...
    'value',popupval2, ...
    'tag','listbox',...
    'callback', {@doPopupClick,5,popupval2,popupstring2});

popuptext3 = uicontrol('Style','Text','String',label{6},'Units','characters',...
    'Units','characters','HorizontalAlignment','left',...
    'BackgroundColor',textbg,'Position',[5 7 15 1.2]);
popupbox3 = uicontrol('style','popupmenu',...
    'Units','characters',...
    'position',[5 5.5 20 1.2],...
    'string',popupstring3,...
    'backgroundcolor','w',...
    'value',popupval3, ...
    'tag','listbox',...
    'callback', {@doPopupClick2,6,popupval3});

pushbutton1 = uicontrol('Style','pushbutton','String','OK',...
        'Units','characters','Position',[5 1 10 2],...
        'Callback',@callbackOK);
pushbutton2 = uicontrol('Style','pushbutton','String','Cancel',...
        'Units','characters','Position',[15 1 10 2],...
        'Callback',@callbackCancel);

% store data in figure
data.editbox=editbox;
data.previous=default;
data.current=default;
set(fig,'UserData',data);

% finish up and wait for user input
set(fig,'Visible','on','HandleVisibility','Callback');
if strcmp(options.style,'modal')
    set(fig,'WindowStyle',options.style);
end
uiwait(fig);
if ishandle(fig)
    data=get(fig,'UserData');
    answer=data.current;
    delete(fig);
else
    answer={};
end

%%%%%%%%%%%%%%%%%%%%%
% utility functions %
%%%%%%%%%%%%%%%%%%%%%
function movedlg(dlg,target,location)

if (nargin<1) || isempty(location)
    location='center';
end

% determine absolute figure position
units=get(target,'Units');
set(target,'Units','pixels');
if target==0
   targetpos=get(target,'MonitorPositions');
   targetpos=targetpos(1,:);
else
    targetpos=get(target,'Position');
end
set(target,'Units',units);

% position dialog relative to figure
units=get(dlg,'Units') ;
set(dlg,'Units','pixels');
dlgpos=get(dlg,'Position');
x=targetpos(1)+(targetpos(3)-dlgpos(3))*[0 1/2 1];
y=targetpos(2)+(targetpos(4)-dlgpos(4))*[0 1/2 1];
switch lower(location)
    case 'north'
        dlgpos(1:2)=[x(2) y(3)];
    case 'south'
        dlgpos(1:2)=[x(2) y(1)];
    case 'east'
        dlgpos(1:2)=[x(1) y(2)];
    case 'west'
        dlgpos(1:2)=[x(3) y(2)];
    case 'northeast'
        dlgpos(1:2)=[x(3) y(3)];
    case 'northwest'
        dlgpos(1:2)=[x(1) y(3)];
    case 'southeast'
        dlgpos(1:2)=[x(3) y(1)];
    case 'southwest'
        dlgpos(1:2)=[x(1) y(1)];
    case 'center'
        dlgpos(1:2)=[x(2) y(2)];
    otherwise
        error('ERROR: %s is not a valid location',location);
end
set(dlg,'Position',dlgpos);
set(dlg,'Units',units);

function doPopupClick(src,eventdata,popupnum,oldval,popupstring)

fig=gcbf;
data=get(fig,'UserData');
nold = oldval;
n = get(src,'Value');
if n == 0
    n = nold;
end
set(src,'Value',n);
data.edit{popupnum}=popupstring{n};

set(fig,'UserData',data);

function doPopupClick2(src,eventdata,popupnum,oldval)

fig=gcbf;
data=get(fig,'UserData');
nold = oldval;
popupstring = {'1','0'};
n = get(src,'Value');
if n == 0
    n = nold;
end
set(src,'Value',n);

data.edit{popupnum}=str2num(popupstring{n});

set(fig,'UserData',data);

%%%%%%%%%%%%%%%%%%%%%
% default callbacks %
%%%%%%%%%%%%%%%%%%%%%
function callbackOK(src,varargin)
fig=gcbf;
data=get(fig,'UserData');
uiresume(fig);
data.edit{1}=get(data.editbox(1),'String');
data.edit{2}=get(data.editbox(2),'String');
data.edit{3}=get(data.editbox(3),'String');
data.current=data.edit;
set(fig,'UserData',data);

function callbackCancel(varargin)
fig=gcbf;
uiresume(fig);
data=get(fig,'UserData');
data.current={};
set(fig,'UserData',data);


text:
This is my bio page.
It is last updated on October, 2017.

redpajama_set_name: RedPajamaGithub


text:
package edu.uco.cgarien1.program6;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Bundle;

public class DepartmentDialogFragment extends DialogFragment {

	public interface PickDepartmentListener {
		public void onPickDepartmentClick(int itemIndex, DialogFragment dialog);
	}

	PickDepartmentListener listener;

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            listener = (PickDepartmentListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString() + " must implement PickDepartmentListener");
        }
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle(R.string.dlg_dept).setItems(R.array.department_array, new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int which) {
            	   listener.onPickDepartmentClick(which, DepartmentDialogFragment.this);
               }
        });
        return builder.create();
    }
}


text:
static LjsHTTPFileLogger *singleton = nil;

@implementation LjsHTTPFileLogger

+ (id) sharedInstance {
  @synchronized(self) {
    if (singleton == nil) {
      singleton = [[super allocWithZone:NULL] init];
    }
  }
  return singleton;
}

+ (id)allocWithZone:(NSZone *)zone {
  return [self sharedInstance];
}

- (id)copyWithZone:(NSZone *)zone {
  return self;
}

- (id) init {
  self = [super init];
  if (self != nil) {
  }
  return self;
}

@end


text:
<?php

namespace TijsVerkoyen\ActiveCollab;

class ActiveCollab
{
    // internal constant to enable/disable debugging
    const DEBUG = true;

    // current version
    const VERSION = '3.0.0';

    /**
     * The API url
     *
     * @var string
     */
    private $apiUrl;

    /**
     * The token to use
     *
     * @var string
     */
    private $token;

    /**
     * The timeout
     *
     * @var int
     */
    private $timeOut = 60;

    /**
     * The user agent
     *
     * @var string
     */
    private $userAgent;

    // class methods
    /**
     * Create an instance
     *
     * @param string $token  The token to use.
     * @param string $apiUrl The url of the API.
     */
    public function __construct($token, $apiUrl)
    {
        $this->setToken($token);
        $this->setApiUrl($apiUrl);
    }

    /**
     * Make a call
     *
     * @param  string           $path       The method to be called.
     * @param  array[optional]  $parameters The parameters to pass.
     * @param  string[optional] $method     The method to use. Possible values are GET or POST.
     * @return mixed
     */
    private function doCall($path, array $parameters = null, $method = 'GET')
    {
        // redefine
        $path = (string) $path;
        $parameters = (array) $parameters;

        // init var
        $options = array();

        // build the url
        $url = $this->getApiUrl();

        // add the path
        $url .= '?path_info=' . $path;

        // add token for authentication
        $url .= '&auth_api_token=' . $this->getToken();
        $url .= '&format=json';

        // HTTP method
        if ($method == 'POST') {
            $options[CURLOPT_POST] = true;
            $options[CURLOPT_POSTFIELDS] = http_build_query($parameters);
        } else {
            $options[CURLOPT_POST] = false;
            if (!empty($parameters)) {
                $url .= '&' . http_build_query($parameters);
            }
        }

        // set options
        $options[CURLOPT_URL] = $url;
        $options[CURLOPT_USERAGENT] = $this->getUserAgent();
        if (ini_get('open_basedir') == '' && ini_get('safe_mode' == 'Off')) {
            $options[CURLOPT_FOLLOWLOCATION] = true;
        }
        $options[CURLOPT_RETURNTRANSFER] = true;
        $options[CURLOPT_TIMEOUT] = (int) $this->getTimeOut();
        $options[CURLOPT_SSL_VERIFYPEER] = false;
        $options[CURLOPT_SSL_VERIFYHOST] = false;

        // init
        $curl = curl_init();

        // set options
        curl_setopt_array($curl, $options);

        // execute
        $response = curl_exec($curl);
        $headers = curl_getinfo($curl);

        // fetch errors
        $errorNumber = curl_errno($curl);
        $errorMessage = curl_error($curl);

        // close
        curl_close($curl);

        // we expect JSON, so decode it
        return @json_decode($response, true);
    }

    /**
     * Get the url of the instance making the request
     *
     * @return string
     */
    public function getApiUrl()
    {
        return (string) $this->apiUrl;
    }

    /**
     * Get the timeout that will be used
     *
     * @return int
     */
    public function getTimeOut()
    {
        return (int) $this->timeOut;
    }

    /**
     * Get the token
     *
     * @return string
     */
    public function getToken()
    {
        return (string) $this->token;
    }

    /**
     * Get the useragent that will be used.
     * Our version will be prepended to yours.
     * It will look like: "PHP ActiveCollab/<version> <your-user-agent>"
     *
     * @return string
     */
    public function getUserAgent()
    {
        return (string) 'PHP ActiveCollab/' . self::VERSION . ' ' . $this->userAgent;
    }

    /**
     * Set the url of the API.
     *
     * @param string $apiUrl
     */
    public function setApiurl($apiUrl)
    {
        $this->apiUrl = (string) $apiUrl;
    }

    /**
     * Set the timeout
     * After this time the request will stop.
     * You should handle any errors triggered by this.
     *
     * @param $seconds int timeout in seconds.
     */
    public function setTimeOut($seconds)
    {
        $this->timeOut = (int) $seconds;
    }

    /**
     * Set the token
     *
     * @param string $token
     */
    public function setToken($token)
    {
        $this->token = (string) $token;
    }

    /**
     * Set the user-agent for you application
     * It will be appended to ours, the result will look like: "PHP
     * ActiveCollab/<version> <your-user-agent>"
     *
     * @param $userAgent string user-agent, it should look like
     *        <app-name>/<app-version>.
     */
    public function setUserAgent($userAgent)
    {
        $this->userAgent = (string) $userAgent;
    }

    /**
     * Lists all active milestones for a specific project.
     *
     * @param  string $slug The slug of the project.
     * @return array
     */
    public function projectsMilestones($slug)
    {
        $path = 'projects/' . (string) $slug . '/milestones';

        return $this->doCall($path);
    }

    /**
     * Returns system information about the installation you are working with.
     * This information includes system versions; info about logged in users;
     * the mode the API is in etc.
     *
     * @return array
     */
    public function info()
    {
        return $this->doCall('info');
    }

    /**
     * Lists all available project labels.
     *
     * @return array
     */
    public function infoLabelsProject()
    {
        return $this->doCall('info/labels/project');
    }

    /**
     * Lists all available assignment labels. These labels are used by tasks and subtasks.
     *
     * @return array
     */
    public function infoLabelsAssignment()
    {
        return $this->doCall('info/labels/assignment');
    }

    /**
     * Lists all system roles and role details (permissions included).
     *
     * @return array
     */
    public function infoRoles()
    {
        return $this->doCall('info/roles');
    }

    /**
     * Lists all project roles and displays their permissions.
     *
     * @return array
     */
    public function infoRolesProject()
    {
       return $this->doCall('info/roles/project');
    }

    /**
     * Lists all active companies that are defined in People section.
     *
     * @return array
     */
    public function people()
    {
        return $this->doCall('people');
    }

    /**
     * Display all, non-archived projects that this user has access to.
     * In case of administrators and project managers, system will return all
     * non-archived projects and properly populate is_member flag value (when 0,
     * administrator and project manager can see and manage the project, but
     * they are not directly involved with it).
     *
     * @return mixed
     */
    public function projects()
    {
        $return = $this->doCall('projects');

        // because in some methods we need a slug and it isn't returned we calculate the slug in this method
        if (!empty($return)) {
            foreach ($return as &$row) {
                $parts = parse_url($row['permalink']);
                if (isset($parts['query'])) {
                    $chunks = explode('&', $parts['query']);

                    foreach ($chunks as $parameter) {
                        $parameterChunks = explode('=', $parameter);

                        if (count($parameterChunks) == 2 && $parameterChunks[0] == 'path_info') {
                            $data = explode('/', urldecode($parameterChunks[1]));

                            if (isset($data[1])) {
                                $row['slug'] = $data[1];
                                break;
                            }
                        }
                    }
                }
            }
        }

        return $return;
    }

    /**
     * Displays the list of people involved with the project and the permissions
     * included in their Project Role. Project Permissions are organized per
     * module and have four possible values:
     *  - 0: no access
     *  - 1: has access, but can't create or manage objects
     *  - 2: has access and permission to create objects in a given module
     *  - 3: has access, creation and management permissions in a given module
     *
     * @param  string $slug The slug of the project.
     * @return array
     */
    public function projectsPeople($slug)
    {
        $path = 'projects/' . (string) $slug . '/people';

        return $this->doCall($path);
    }

    /**
     * Displays all non-archived discussions in a project.
     *
     * @param  string $slug The slug of the project.
     * @return array
     */
    public function projectsDiscussions($slug)
    {
        $path = 'projects/' . (string) $slug . '/discussions';

        return $this->doCall($path);
    }

    /**
     * Lists all open and completed, non-archived tasks from a project.
     *
     * @param  string $slug The slug of the project.
     * @return array
     */
    public function projectsTasks($slug)
    {
        $path = 'projects/' . (string) $slug . '/tasks';

        return $this->doCall($path);
    }

    /**
     * This command will display last 300 time records and expenses in a given
     * project.
     * If you wish to return all time records and expenses from a project, set
     * $dontLimit to true.
     *
     * @param  string         $slug      The slug of the project.
     * @param  bool[optional] $dontLimit Don't limit the results.
     * @return mixed
     */
    public function projectsTracking($slug, $dontLimit = false)
    {
        $parameters = null;
        if($dontLimit) $parameters['dont_limit_results'] = '1';

        $path = 'projects/' . (string) $slug . '/tracking';

        return $this->doCall($path, $parameters);
    }
}


text:
package inujini_.hatate.sqlite.dao;

import inujini_.hatate.data.Character;
import inujini_.hatate.data.meta.MetaCharacter;
import inujini_.hatate.function.Function.Func1;
import inujini_.hatate.linq.Linq;
import inujini_.hatate.sqlite.DatabaseHelper;
import inujini_.hatate.sqlite.helper.CursorExtensions;
import inujini_.hatate.sqlite.helper.QueryBuilder;
import inujini_.hatate.sqlite.helper.SqliteUtil;

import java.util.List;

import lombok.val;
import lombok.experimental.ExtensionMethod;
import android.content.Context;
import android.database.Cursor;

/**
 * {@link Character}のDAO.
 */
@ExtensionMethod({SqliteUtil.class, CursorExtensions.class, Linq.class})
public class CharacterDao {

	private static final Func1<Cursor, Character> _converter = new Func1<Cursor, Character>() {
		@Override
		public Character call(Cursor c) {
			val character = new Character();
			character.setId(c.getLongByMeta(MetaCharacter.Id));
			character.setName(c.getStringByMeta(MetaCharacter.Name));
			return character;
		}
	};

	/**
	 * 全キャラクターの取得.
	 * @param context
	 * @return DBに登録されている全ての{@link Character}.
	 */
	public static List<Character> getAllCharacter(Context context) {
		return new DatabaseHelper(context).selectAll(context, MetaCharacter.TBL_NAME, _converter);
	}

	/**
	 * キャラクターの取得.
	 * @param context
	 * @param id キャラクターのId
	 * @return idで指定された{@link Character}.
	 */
	public static Character getCharacter(Context context, long id) {
		val q = new QueryBuilder()
					.selectAll()
					.from(MetaCharacter.TBL_NAME)
					.where().equal(MetaCharacter.Id, id)
					.toString();

		return new DatabaseHelper(context).get(q, context, _converter);
	}

}


text:
@interface WIRouterTests : SenTestCase
@property(nonatomic, strong)WIRouter    *router;
@end

@implementation WIRouterTests

- (void)setUp {
    WIRoute *route = [[WIRoute alloc] initWithPath:@"/slash/:titan"];
    self.router = [[WIRouter alloc] initWithRoute:route];
}

- (void)tearDown {
    self.router = nil;
}

- (void)testRoute {
    STAssertEqualObjects([self.router route:@{ @"titan": @"3" }], @"/slash/3", nil);
}

- (void)testMatch {
    STAssertEqualObjects([self.router match:@"/slash/3"], @{@"titan": @"3"}, nil);
}

@end


text:
package com.usermodule.dto;

import java.util.Collection;
import java.util.HashSet;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import com.usermodule.entities.User;
import com.usermodule.entities.User.Role;

public class UserDetailsImpl implements UserDetails {

	/**
	 * Since UserDetails is Serializable, UserDetailsImpl should also be
	 */
	private static final long serialVersionUID = 2728050777976360974L;
	private User user;

	public UserDetailsImpl(User user) {
		this.user=user;
	}

	/*Matched rows, return all the roles the user having*/
	@Override
	public Collection<? extends GrantedAuthority> getAuthorities() {
		Collection<GrantedAuthority> authorities = new HashSet<GrantedAuthority>(
				user.getRoles().size() + 1);

		for (Role role : user.getRoles())
			authorities.add(new SimpleGrantedAuthority("ROLE_" + role.name()));

		authorities.add(new SimpleGrantedAuthority("ROLE_USER"));

		return authorities;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	@Override
	public String getPassword() {
		return user.getPassword();
	}

	@Override
	public String getUsername() {
		return user.getEmail();
	}

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

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

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

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

}


text:
using System;
using System.Diagnostics;

namespace Darjeel
{
    internal static class Logging
    {
        private static readonly Lazy<TraceSource> DarjeelTraceSource = new Lazy<TraceSource>(() => new TraceSource("Darjeel"));

        public static TraceSource Darjeel => DarjeelTraceSource.Value;
    }
}


text:
TOP := $(shell dirname $(realpath $(lastword $(MAKEFILE_LIST))))

SHELL := /bin/bash
LOCAL_ARTIFACTS_DIR ?= $(abspath artifacts)
ARTIFACTS_DIR ?= $(LOCAL_ARTIFACTS_DIR)
BAZEL_STARTUP_ARGS ?=
BAZEL_BUILD_ARGS ?=
BAZEL_TEST_ARGS ?=
HUB ?=
TAG ?=
ifeq "$(origin CC)" "default"
CC := clang-6.0
endif
ifeq "$(origin CXX)" "default"
CXX := clang++-6.0
endif

build:
	CC=$(CC) CXX=$(CXX) bazel $(BAZEL_STARTUP_ARGS) build $(BAZEL_BUILD_ARGS) //...
	@bazel shutdown

# Build only envoy - fast
build_envoy:
	CC=$(CC) CXX=$(CXX) bazel $(BAZEL_STARTUP_ARGS) build $(BAZEL_BUILD_ARGS) //src/envoy:envoy
	@bazel shutdown

clean:
	@bazel clean
	@bazel shutdown

test:
	CC=$(CC) CXX=$(CXX) bazel $(BAZEL_STARTUP_ARGS) test $(BAZEL_TEST_ARGS) //...
	@bazel shutdown

test_asan:
	CC=$(CC) CXX=$(CXX) bazel $(BAZEL_STARTUP_ARGS) test $(BAZEL_TEST_ARGS) --config=clang-asan //...
	@bazel shutdown

test_tsan:
	CC=$(CC) CXX=$(CXX) bazel $(BAZEL_STARTUP_ARGS) test $(BAZEL_TEST_ARGS) --config=clang-tsan //...
	@bazel shutdown

check:
	@script/check-license-headers
	@script/check-repositories
	@script/check-style

artifacts: build
	@script/push-debian.sh -c opt -p $(ARTIFACTS_DIR)

deb:
	CC=$(CC) CXX=$(CXX) bazel $(BAZEL_STARTUP_ARGS) build $(BAZEL_BUILD_ARGS) //tools/deb:istio-proxy
	@bazel shutdown

.PHONY: build clean test check artifacts


text:
module IJulia
using Compat

# in the IPython front-end, enable verbose output via IJulia.set_verbose()
verbose = false
function set_verbose(v::Bool=true)
    global verbose::Bool = v
end

# set this to false for debugging, to disable stderr redirection
const capture_stderr = true

using ZMQ
using JSON
using Nettle
include("../deps/ipython.jl")

# use our own random seed for msg_id so that we
# don't alter the user-visible random state (issue #336)
const IJulia_RNG = MersenneTwister()
function uuid4()
    # TODO: merge into Julia Base `uuid4` function
    u = rand(IJulia_RNG, UInt128)
    u &= 0xffffffffffff0fff3fffffffffffffff
    u |= 0x00000000000040008000000000000000
    return repr(Base.Random.UUID(u))
end

function __init__()
    srand(IJulia_RNG)
end

inited = false

function init(args)
    if length(args) > 0
        global const profile = open(JSON.parse,args[1])
        verbose && println("PROFILE = $profile")
    else
        # generate profile and save
        let port0 = 5678
            global const profile = @compat Dict{AbstractString,Any}(
                "ip" => "127.0.0.1",
                "transport" => "tcp",
                "stdin_port" => port0,
                "control_port" => port0+1,
                "hb_port" => port0+2,
                "shell_port" => port0+3,
                "iopub_port" => port0+4,
                "key" => uuid4()
            )
            fname = "profile-$(getpid()).json"
            println("connect ipython with --existing $(pwd())/$fname")
            open(fname, "w") do f
                JSON.print(f, profile)
            end
        end
    end
    global hmac
    if isempty(profile["key"])
        hmac(s1,s2,s3,s4) = ""
    else
        signature_scheme = get(profile, "signature_scheme", "hmac-sha256")
        isempty(signature_scheme) && (signature_scheme = "hmac-sha256")
        signature_scheme = split(signature_scheme, "-")
        if signature_scheme[1] != "hmac" || length(signature_scheme) != 2
            error("unrecognized signature_scheme")
        end
        global const hmacstate = HMACState(eval(symbol(uppercase(signature_scheme[2]))),
                                    profile["key"])
        function hmac(s1,s2,s3,s4)
            update!(hmacstate, s1)
            update!(hmacstate, s2)
            update!(hmacstate, s3)
            update!(hmacstate, s4)
            hexdigest!(hmacstate)
        end
    end

    global const ctx = Context()
    global const publish = Socket(ctx, PUB)
    global const raw_input = Socket(ctx, ROUTER)
    global const requests = Socket(ctx, ROUTER)
    global const control = Socket(ctx, ROUTER)
    global const heartbeat = Socket(ctx, ROUTER)
    bind(publish, "$(profile["transport"])://$(profile["ip"]):$(profile["iopub_port"])")
    bind(requests, "$(profile["transport"])://$(profile["ip"]):$(profile["shell_port"])")
    bind(control, "$(profile["transport"])://$(profile["ip"]):$(profile["control_port"])")
    bind(raw_input, "$(profile["transport"])://$(profile["ip"]):$(profile["stdin_port"])")
    bind(heartbeat, "$(profile["transport"])://$(profile["ip"]):$(profile["hb_port"])")

    global const heartbeat_c = cfunction(heartbeat_thread, Void, (Ptr{Void},))
    global const threadid = Array(Int, 128) # sizeof(uv_thread_t) <= 8 on Linux, OSX, Win
    start_heartbeat(heartbeat)

    global const orig_STDIN = STDIN
    global const orig_STDOUT = STDOUT
    global const orig_STDERR = STDERR

    global read_stdin
    global write_stdin
    global read_stdout
    global write_stdout
    global read_stderr
    global write_stderr
    read_stdin, write_stdin = redirect_stdin()
    read_stdout, write_stdout = redirect_stdout()
    if capture_stderr
        read_stderr, write_stderr = redirect_stderr()
    else
        read_stderr, write_stderr = IOBuffer(), IOBuffer()
    end

    send_status("starting")
    global inited = true
end

include("stdio.jl")
include("msg.jl")
include("history.jl")
include("handlers.jl")
include("heartbeat.jl")

function eventloop(socket)
    try
        while true
            msg = recv_ipython(socket)
            try
                send_status("busy", msg.header)
                handlers[msg.header["msg_type"]](socket, msg)
            catch e
                # Try to keep going if we get an exception, but
                # send the exception traceback to the front-ends.
                # (Ignore SIGINT since this may just be a user-requested
                #  kernel interruption to interrupt long calculations.)
                if !isa(e, InterruptException)
                    content = error_content(e, msg="KERNEL EXCEPTION")
                    map(s -> println(orig_STDERR, s), content["traceback"])
                    send_ipython(publish,
                                 execute_msg == nothing ?
                                 Msg([ "error" ],
                                     @compat(Dict("msg_id" => uuid4(),
                                                  "username" => "jlkernel",
                                                  "session" => uuid4(),
                                                  "msg_type" => "error",
                                                  "version" => "5.0")),
                                     content) :
                                 msg_pub(execute_msg, "error", content))
                end
            finally
                send_status("idle", msg.header)
            end
        end
    catch e
        # the IPython manager may send us a SIGINT if the user
        # chooses to interrupt the kernel; don't crash on this
        if isa(e, InterruptException)
            eventloop(socket)
        else
            rethrow()
        end
    end
end

function waitloop()
    @async eventloop(control)
    requests_task = @async eventloop(requests)
    while true
        try
            wait()
        catch e
            # send interrupts (user SIGINT) to the code-execution task
            if isa(e, InterruptException)
                @async Base.throwto(requests_task, e)
            else
                rethrow()
            end
        end
    end
end

export notebook
function notebook(ipython=find_ipython()[1])
    inited && error("IJulia is already running")
    run(`$ipython notebook`)
end

end # IJulia


text:
<?php namespace Basset\Filter;

use Closure;
use Basset\Asset;
use ReflectionClass;
use ReflectionException;
use Illuminate\Log\Logger;
use Illuminate\Support\Str;
use Assetic\Filter\FilterInterface;
use Symfony\Component\Process\ExecutableFinder;

class Filter {

    /**
     * Array of instantiation arguments.
     *
     * @var array
     */
    protected $arguments = array();

    /**
     * Array of before filtering callbacks.
     *
     * @var array
     */
    protected $before = array();

    /**
     * Filter name.
     *
     * @var string
     */
    protected $filter;

    /**
     * Resource being filtered.
     *
     * @var \Basset\Filterable
     */
    protected $resource;

    /**
     * Array of filter requirements.
     *
     * @var array
     */
    protected $requirements = array();

    /**
     * Array of node module paths.
     *
     * @var array
     */
    protected $nodePaths = array();

    /**
     * Array of valid executable argument suffixes.
     *
     * @var array
     */
    protected $validSuffixes = array('bin', 'path');

    /**
     * Indicates if the filter should be ignored when building assets.
     *
     * @var bool
     */
    protected $ignored = false;

    /**
     * Application working environment.
     *
     * @var string
     */
    protected $appEnvironment;

    /**
     * Illuminate log writer instance.
     *
     * @var \Illuminate\Log\Logger
     */
    protected $log;

    /**
     * Indicates if the build is a production build.
     *
     * @var bool
     */
    protected $production = false;

    /**
     * Create a new filter instance.
     *
     * @param  \Illuminate\Log\Logger  $log
     * @param  string  $filter
     * @param  array  $nodePaths
     * @param  string  $appEnvironment
     * @return void
     */
    public function __construct(Logger $log, $filter, array $nodePaths, $appEnvironment)
    {
        $this->log = $log;
        $this->filter = $filter;
        $this->nodePaths = $nodePaths;
        $this->appEnvironment = $appEnvironment;
    }

    /**
     * Find and set any missing constructor arguments.
     *
     * @return \Basset\Filter\Filter
     */
    public function findMissingConstructorArgs()
    {
        try
        {
            $class = new ReflectionClass($this->getClassName());
        }
        catch (ReflectionException $e)
        {
            return $this;
        }

        if ($constructor = $class->getConstructor())
        {
            $finder = $this->getExecutableFinder();

            // Spin through all of the constructor parameters and for those that we can find the executable
            // path for we'll attempt to locate the executable. If we can't find the path then its more
            // then we'll ignore this filter as it will fail during the build.
            foreach ($constructor->getParameters() as $key => $parameter)
            {
                if ($this->hasArgumentAtPosition($key))
                {
                    continue;
                }

                $snakeParameter = $this->normalizeConstructorParameter($parameter->name);

                list($name, $suffix) = explode('_', $snakeParameter);

                // If the suffix is in the array of valid suffixes we can attempt to locate the parameter
                // first as an environment variable and secondly by recursively searching through our
                // paths defined in PATH. If we can't find it then ignore the filter.
                if (in_array($suffix, $this->validSuffixes))
                {
                    $path = $this->getEnvironmentVariable($snakeParameter) ?: $finder->find($name);

                    if ($path)
                    {
                        $this->setArgument($path, $key);
                    }
                    else
                    {
                        // There was a problem locating the path to the argument, we'll log that the
                        // filter was ignored here so that the developer can debug this better.
                        $this->log->error(sprintf('Failed to find required constructor argument for filter "%s". (%s)', $this->filter, $parameter));

                        $this->ignored = true;
                    }
                }
                elseif(Str::is('nodePaths', $parameter->name))
                {
                    $this->setArgument($this->nodePaths, $key);
                }
            }
        }

        return $this;
    }

    /**
     * Get an environment variable.
     *
     * @param  string  $key
     * @return string|bool
     */
    public function getEnvironmentVariable($key)
    {
        return getenv(strtoupper($key));
    }

    /**
     * Convert a constructor parameter to snake case and all lowercase.
     *
     * @param  string  $name
     * @return string
     */
    protected function normalizeConstructorParameter($name)
    {
        return strtolower(snake_case($name));
    }

    /**
     * Get an executable finder instance.
     *
     * @return \Symfony\Component\Process\ExecutableFinder
     */
    public function getExecutableFinder()
    {
        return new ExecutableFinder;
    }

    /**
     * Add a requirement to the filter.
     *
     * @param  \Closure  $callback
     * @return \Basset\Filter\Filter
     */
    public function when(Closure $callback)
    {
        $this->requirements[] = $callback;

        return $this;
    }

    /**
     * Add a class exists requirement to the filter.
     *
     * @param  string  $class
     * @return \Basset\Filter\Filter
     */
    public function whenClassExists($class)
    {
        return $this->when(function() use ($class)
        {
            return class_exists($class);
        });
    }

    /**
     * Add a asset name pattern requirement to the filter.
     *
     * @param  string  $pattern
     * @return \Basset\Filter\Filter
     */
    public function whenAssetIs($pattern)
    {
        return $this->when(function($asset) use ($pattern)
        {
            return (bool) preg_match('#'.$pattern.'#', $asset->getRelativePath());
        });
    }

    /**
     * Add an environment requirement to the filter.
     *
     * @return \Basset\Filter\Filter
     */
    public function whenEnvironmentIs()
    {
        $environments = func_get_args();

        $appEnvironment = $this->appEnvironment;

        return $this->when(function($asset) use ($environments, $appEnvironment)
        {
            return in_array($appEnvironment, $environments);
        });
    }

    /**
     * Add a stylesheets only requirement to the filter.
     *
     * @return \Basset\Filter\Filter
     */
    public function whenAssetIsStylesheet()
    {
        return $this->when(function($asset)
        {
            return $asset->isStylesheet();
        });
    }

    /**
     * Add a javascripts only requirement to the filter.
     *
     * @return \Basset\Filter\Filter
     */
    public function whenAssetIsJavascript()
    {
        return $this->when(function($asset)
        {
            return $asset->isJavascript();
        });
    }

    /**
     * Add a production build requirement to the filter.
     *
     * @return \Basset\Filter\Filter
     */
    public function whenProductionBuild()
    {
        return $this->when(function($asset, $filter)
        {
            return $filter->getProduction() === true;
        });
    }

    /**
     * Add a development build requirement to the filter.
     *
     * @return \Basset\Filter\Filter
     */
    public function whenDevelopmentBuild()
    {
        return $this->when(function($asset, $filter)
        {
            return $filter->getProduction() === false;
        });
    }

    /**
     * Add a before filtering callback.
     *
     * @param  \Closure  $callback
     * @return \Basset\Filter\Filter
     */
    public function beforeFiltering(Closure $callback)
    {
        $this->before[] = $callback;

        return $this;
    }

    /**
     * Determine if the filter has an instantiation argument at a given position.
     *
     * @param  int  $position
     * @return bool
     */
    public function hasArgumentAtPosition($position)
    {
        return isset($this->arguments[$position]);
    }

    /**
     * Set a single instantiation argument.
     *
     * @param  string  $argument
     * @param  int  $position
     * @return \Basset\Filter\Filter
     */
    public function setArgument($argument, $position = null)
    {
        array_splice($this->arguments, $position ?: count($this->arguments), 0, array($argument));

        return $this;
    }

    /**
     * Set the filters instantiation arguments
     *
     * @return Basset\Filter\Filter
     */
    public function setArguments()
    {
        $this->arguments = func_get_args();

        return $this;
    }

    /**
     * Set the resource on the filter.
     *
     * @param  \Basset\Filter\Filterable  $resource
     * @return \Basset\Filter\Filter
     */
    public function setResource(Filterable $resource)
    {
        $this->resource = $resource;

        return $this;
    }

    /**
     * Get the parent resource.
     *
     * @return mixed
     */
    public function getResource()
    {
        return $this->resource;
    }

    /**
     * Get the filter name.
     *
     * @return string
     */
    public function getFilter()
    {
        return $this->filter;
    }

    /**
     * Get the array of environments.
     *
     * @return array
     */
    public function getEnvironments()
    {
        return $this->environments;
    }

    /**
     * Get the filters instantiation arguments.
     *
     * @return array
     */
    public function getArguments()
    {
        return $this->arguments;
    }

    /**
     * Determine if filter is ignored.
     *
     * @return bool
     */
    public function isIgnored()
    {
        return $this->ignored;
    }

    /**
     * Get the class name for the filter if it exists.
     *
     * @return string
     */
    public function getClassName()
    {
        if (class_exists("Assetic\\Filter\\{$this->filter}"))
        {
            return "Assetic\\Filter\\{$this->filter}";
        }
        elseif (class_exists("Basset\\Filter\\{$this->filter}"))
        {
            return "Basset\\Filter\\{$this->filter}";
        }
    }

    /**
     * Attempt to instantiate the filter if it exists and has not been ignored.
     *
     * @return null|\Assetic\Filter\FilterInterface
     */
    public function getInstance()
    {
        if ( ! $class = $this->getClassName())
        {
            $this->log->error(sprintf('"%s" will not be applied to asset "%s" due to an invalid filter name.', $this->filter, $this->resource->getRelativePath()));
        }

        if ($this->ignored or is_null($class) or ! $this->processRequirements()) return;

        // If the class returned is already implements Assetic\Filter\FilterInterface then
        // we can set the instance directly and not worry about using reflection.
        if ($class instanceof FilterInterface)
        {
            $instance = $class;
        }
        else
        {
            $reflection = new ReflectionClass($class);

            // If no constructor is available on the filters class then we'll instantiate
            // the filter without passing in any arguments.
            if ( ! $reflection->getConstructor())
            {
                $instance = $reflection->newInstance();
            }
            else
            {
                $instance = $reflection->newInstanceArgs($this->arguments);
            }
        }

        // Spin through each of the before filtering callbacks and fire each one. We'll
        // pass in an instance of the filter to the callback.
        foreach ($this->before as $callback)
        {
            if (is_callable($callback))
            {
                call_user_func($callback, $instance);
            }
        }

        return $instance;
    }

    /**
     * Process any requirements on the filter.
     *
     * @return bool
     */
    public function processRequirements()
    {
        foreach ($this->requirements as $requirement)
        {
            if ( ! call_user_func($requirement, $this->resource, $this))
            {
                return false;
            }
        }

        return true;
    }

    /**
     * Get the filter requirements.
     *
     * @return array
     */
    public function getRequirements()
    {
        return $this->requirements;
    }

    /**
     * Set the production build indicator.
     *
     * @param  bool  $production
     * @return \Basset\Filter\Filter
     */
    public function setProduction($production)
    {
        $this->production = $production;

        return $this;
    }

    /**
     * Get the production build indicator.
     *
     * @return bool
     */
    public function getProduction()
    {
        return $this->production;
    }

    /**
     * Get the array of node paths.
     *
     * @return array
     */
    public function getNodePaths()
    {
        return $this->nodePaths;
    }

    /**
     * Dynamically chain uncallable methods to the belonging resource.
     *
     * @param  string  $method
     * @param  array  $parameters
     * @return mixed
     */
    public function __call($method, $parameters)
    {
        // If the method starts with "andWhen" then we'll call the method without
        // the "and" as this provides some syntactical sugar when chaining
        // filter requirements.
        if (Str::startsWith($method, 'andWhen'))
        {
            $method = lcfirst(substr($method, 3));

            return call_user_func_array(array($this, $method), $parameters);
        }

        return call_user_func_array(array($this->resource, $method), $parameters);
    }

}


text:
function differenceByIdService() {
    return function differenceById(from, others) {
        var idsFrom = from.map(function(entry) {
            return entry.id;
        });
        var idsOthers = others.map(function(entry) {
            return entry.id;
        });

        var diff = _.difference(idsFrom, idsOthers);
        return from.filter(function(entry) {
            return _.indexOf(diff, function(e) {
                    return e == entry.id;
                }) !== -1;
        });
    };
}

angular.module('materialscommons').factory('differenceById', differenceByIdService);


text:
import { Ordered } from './$types';

export function $<T extends Ordered>(min: T, max: T, value: T): T;


text:
package net.cockamamy.dataloader;

import java.util.*;

/**
 *
 * Consumes data loaded by a {@link DataLoader}. All implementations of this
 * class should be thread-safe and re-entrant in order to allow
 * {@link DataLoader} implementations to control threading.
 *
 * @author jburwell
 *
 * @since 1.0.0
 *
 */
public interface DataConsumer {

	/**
	 *
	 * Processes a record loaded by a data loader.
	 *
	 * @param aRecord A record loaded by a data loader.
	 *
	 * @since 1.0.0
	 *
	 */
	void consume(Map<String, Object> aRecord);

}


text:
xgestures_plus_applescript
==========================

xGestures + AppleScript = Google Chrome SmoothGestures

=

global frontApp, frontAppName, windowTitle

set windowTitle to ""
tell application "System Events"
	set frontApp to first application process whose frontmost is true
	set frontAppName to name of frontApp
	--display dialog frontAppName

	if frontAppName = "Google Chrome" then
		tell application "System Events" to keystroke "[" using command down
	end if
end tell

=

global frontApp, frontAppName, windowTitle

set windowTitle to ""
tell application "System Events"
	set frontApp to first application process whose frontmost is true
	set frontAppName to name of frontApp
	--display dialog frontAppName

	if frontAppName = "Google Chrome" then
		tell application "System Events" to keystroke "]" using command down
	end if
end tell

=

tell application "System Events" to keystroke "w" using command down

=

tell application "System Events" to keystroke "F" using {shift down, command down}

=

tell application "System Events" to keystroke "0" using command down

!=

tell application "System Events" to keystroke "t" using {command down, 126 down}


text:
namespace VTorque
{
    bool            isCamera( SceneObjectType *pObject );
    void            setCamera( SceneObjectType *pObject );

    void            startCameraShake( const F32 &pDuration, const F32 &pFalloff, const VectorF &pAmplitude, const VectorF &pFrequency );
    void            stopCameraShake( void );
};

#endif // _VT_TORQUE_CAMERA_H_


text:
Z3DVolumeSliceRenderer::Z3DVolumeSliceRenderer(QObject *parent)
  : Z3DPrimitiveRenderer(parent)
{
  m_volumes.resize(5,NULL);
  for (size_t i=0; i<m_volumes.size(); ++i) {
    m_volumeUniformNames.push_back(QString("volume_struct_%1").arg(i+1));
  }
}

Z3DVolumeSliceRenderer::~Z3DVolumeSliceRenderer()
{
}

void Z3DVolumeSliceRenderer::setChannel1(Z3DVolume *vol)
{
  if (vol && !vol->is3DData()) {
    LERROR() << "Input is not 3D volume";
    return;
  }
  if (m_volumes[0] != vol) {
    Z3DVolume *oldvol = m_volumes[0];
    m_volumes[0] = vol;
    if ((oldvol && vol == NULL) ||
        (oldvol == NULL && vol))
      compile();
  }
}

void Z3DVolumeSliceRenderer::setChannel2(Z3DVolume *vol)
{
  if (vol && !vol->is3DData()) {
    LERROR() << "Input is not 3D volume";
    return;
  }
  if (m_volumes[1] != vol) {
    Z3DVolume *oldvol = m_volumes[1];
    m_volumes[1] = vol;
    if ((oldvol && vol == NULL) ||
        (oldvol == NULL && vol))
      compile();
  }
}

void Z3DVolumeSliceRenderer::setChannel3(Z3DVolume *vol)
{
  if (vol && !vol->is3DData()) {
    LERROR() << "Input is not 3D volume";
    return;
  }
  if (m_volumes[2] != vol) {
    Z3DVolume *oldvol = m_volumes[2];
    m_volumes[2] = vol;
    if ((oldvol && vol == NULL) ||
        (oldvol == NULL && vol))
      compile();
  }
}

void Z3DVolumeSliceRenderer::setChannel4(Z3DVolume *vol)
{
  if (vol && !vol->is3DData()) {
    LERROR() << "Input is not 3D volume";
    return;
  }
  if (m_volumes[3] != vol) {
    Z3DVolume *oldvol = m_volumes[3];
    m_volumes[3] = vol;
    if ((oldvol && vol == NULL) ||
        (oldvol == NULL && vol))
      compile();
  }
}

void Z3DVolumeSliceRenderer::setChannel5(Z3DVolume *vol)
{
  if (vol && !vol->is3DData()) {
    LERROR() << "Input is not 3D volume";
    return;
  }
  if (m_volumes[4] != vol) {
    Z3DVolume *oldvol = m_volumes[4];
    m_volumes[4] = vol;
    if ((oldvol && vol == NULL) ||
        (oldvol == NULL && vol))
      compile();
  }
}

void Z3DVolumeSliceRenderer::setChannels(std::vector<Z3DVolume *> vols)
{
  for (size_t i=0; i<vols.size(); ++i) {
    if (vols[i] && !vols[i]->is3DData()) {
      LERROR() << "Input is not 3D volume";
      return;
    }
  }
  vols.resize(m_volumes.size(), NULL);
  if (m_volumes != vols) {
    m_volumes = vols;
    compile();
  }
}

void Z3DVolumeSliceRenderer::addQuad(const Z3DTriangleList &quad)
{
  if (quad.empty() ||
      (quad.getVertices().size() != 4 && quad.getVertices().size() != 6) ||
      quad.getVertices().size() != quad.get3DTextureCoordinates().size()) {
    LERROR() << "Input quad should be 2D slice with 3D texture coordinates";
    return;
  }
  m_quads.push_back(quad);
}

void Z3DVolumeSliceRenderer::bindVolumes(Z3DShaderProgram &shader)
{
  for (size_t i=0; i < m_volumes.size(); ++i) {
    Z3DVolume *volume = m_volumes[i];
    if (!volume)
      continue;

    // volumes
    shader.bindVolume(m_volumeUniformNames[i], volume, GL_NEAREST, GL_NEAREST);

    CHECK_GL_ERROR;
  }
}

bool Z3DVolumeSliceRenderer::hasVolume() const
{
  for (size_t i=0; i<m_volumes.size(); ++i)
    if (m_volumes[i])
      return true;
  return false;
}

void Z3DVolumeSliceRenderer::compile()
{
  m_volumeSliceShader.setHeaderAndRebuild(generateHeader());
}

void Z3DVolumeSliceRenderer::initialize()
{
  Z3DPrimitiveRenderer::initialize();
  m_volumeSliceShader.loadFromSourceFile("transform_with_3dtexture.vert", "volume_slice.frag", generateHeader());
  m_volumeSliceShader.bindFragDataLocation(0, "FragData0");
}

void Z3DVolumeSliceRenderer::deinitialize()
{
  m_volumeSliceShader.removeAllShaders();
  CHECK_GL_ERROR;
  Z3DPrimitiveRenderer::deinitialize();
}

QString Z3DVolumeSliceRenderer::generateHeader()
{
  QString headerSource = Z3DPrimitiveRenderer::generateHeader();

  if (hasVolume()) {
    if (m_volumes[0]) {
      headerSource += "#define VOLUME_1_EXIST\n";
    }
    if (m_volumes[1]) {
      headerSource += "#define VOLUME_2_EXIST\n";
    }
    if (m_volumes[2]) {
      headerSource += "#define VOLUME_3_EXIST\n";
    }
    if (m_volumes[3]) {
      headerSource += "#define VOLUME_4_EXIST\n";
    }
    if (m_volumes[4]) {
      headerSource += "#define VOLUME_5_EXIST\n";
    }
  } else {
    headerSource += "#define DISABLE_TEXTURE_COORD_OUTPUT\n";
  }

  return headerSource;
}

void Z3DVolumeSliceRenderer::renderUsingOpengl()
{
  //renderUsingGLSL();
}

void Z3DVolumeSliceRenderer::renderPickingUsingOpengl()
{
}

void Z3DVolumeSliceRenderer::renderUsingGLSL(Z3DEye eye)
{
  if (!m_initialized)
    return;

  bool needRender = hasVolume() && !m_quads.empty();
  if (!needRender)
    return;

  m_volumeSliceShader.bind();
  m_rendererBase->setGlobalShaderParameters(m_volumeSliceShader, eye);

  bindVolumes(m_volumeSliceShader);

  for (size_t i=0; i<m_quads.size(); ++i)
    renderTriangleList(m_volumeSliceShader, m_quads[i]);

  m_volumeSliceShader.release();
}

void Z3DVolumeSliceRenderer::renderPickingUsingGLSL(Z3DEye)
{
}


text:
/***************************************************************************
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/

import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.lang.Integer;
import javax.swing.tree.*;

/**
  * Dialog to edit notes for the task
  */
public class GanttDialogNotes extends JDialog
{

	/** JTexteArea to edit notes */
	JTextArea tanotes;

	/** The specify GanttTask*/
	private GanttTask ttask;
	/** The GanttTree of the application. */
	private GanttTree ttree;

	/** Constructor. */
	public GanttDialogNotes(JFrame parent, GanttTree tree, GanttTask task,GanttLanguage language)
	{
		super(parent, language.notesFor()+task.toString(),true);

		this.ttask = task;
		this.ttree = tree;

		Box b1 = Box.createVerticalBox();

		b1.add(new JLabel("Notes"));
		tanotes = new JTextArea (task.getNotes());
		JScrollPane scrollPane = new JScrollPane(tanotes);
		scrollPane.setPreferredSize(new Dimension(300, 250));
		b1.add(scrollPane);

		getContentPane().add(b1,"Center");

		JPanel p = new JPanel();

		//Add the current date and hour at the end of the notes
		JButton bdate = new JButton (new ImageIcon("icons/clock.gif"));
		bdate.setToolTipText(""+language.putDate()+"");
		p.add(bdate);
		bdate.addActionListener(new ActionListener()
		 	{	public void actionPerformed(ActionEvent evt)
				{
					tanotes.append("\n\n"+GanttCalendar.getDateAndTime()+"\n-------------------------------\n");
				}
			});

		JButton ok = new JButton(language.getOk(), new ImageIcon("icons/yes.gif") );
		p.add(ok);
		getRootPane().setDefaultButton(ok);
		//Listener on ok button
		ok.addActionListener(new ActionListener()
		 	{	public void actionPerformed(ActionEvent evt)
				{
					//hide the window
					setVisible (false);

					//Change parameters
					ttask.setNotes(tanotes.getText());

					DefaultMutableTreeNode node = ttree.getNode(ttask.toString());
					node.setUserObject(ttask);

				}
			});

		//cancel button
		JButton cancel = new JButton(language.getCancel(), new ImageIcon("icons/no.gif") );
		p.add(cancel);
		cancel.addActionListener(new ActionListener()
		 	{	public void actionPerformed(ActionEvent evt)
				{ setVisible (false); }
			});

		getContentPane().add(p,BorderLayout.SOUTH);

		pack();
		setResizable(true);
		Point point = parent.getLocationOnScreen();
		int x = (int)point.getX() + parent.getWidth()/2;
		int y = (int)point.getY() + parent.getHeight()/2;
		setLocation(x - getWidth()/2, y-getHeight()/2);
	}

}


text:
module SchemaPlus::Helpers
  extend self

  def suppress_messages
    ActiveRecord::Migration.suppress_messages { yield }
  end

end


text:
package com.github.edgar615.gateway.plugin.version;

import com.google.common.collect.Lists;

import com.github.edgar615.gateway.core.apidiscovery.ApiDiscovery;
import com.github.edgar615.gateway.core.apidiscovery.ApiDiscoveryOptions;
import com.github.edgar615.gateway.core.dispatch.ApiContext;
import com.github.edgar615.gateway.core.dispatch.Filter;
import com.github.edgar615.gateway.core.utils.Filters;
import com.github.edgar615.util.base.Randoms;
import com.github.edgar615.util.exception.DefaultErrorCode;
import com.github.edgar615.util.exception.SystemException;
import com.github.edgar615.util.vertx.task.Task;
import io.vertx.core.Vertx;
import io.vertx.core.http.HttpMethod;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.unit.Async;
import io.vertx.ext.unit.TestContext;
import io.vertx.ext.unit.junit.VertxUnitRunner;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * Created by Edgar on 2017/1/9.
 *
 * @author Edgar  Date 2017/1/9
 */
@RunWith(VertxUnitRunner.class)
public class VersionApiSplitterFilterTest {

    ApiDiscovery apiDiscovery;

    int devicePort = Integer.parseInt(Randoms.randomNumber(4));

    private Vertx vertx;

    private String namespace = UUID.randomUUID().toString();

    private JsonObject config = new JsonObject().put("api.discovery", new JsonObject()
            .put("name", namespace));

    @Before
    public void setUp(TestContext testContext) {
        vertx = Vertx.vertx();
        apiDiscovery = ApiDiscovery.create(vertx, new ApiDiscoveryOptions());
        ApiUtils.registerApi(apiDiscovery, devicePort);
    }

    @Test
    public void testFoundApi(TestContext testContext) {
        ApiContext apiContext =
                ApiContext.create(HttpMethod.POST, "/devices", null, null, null);
        Task<ApiContext> task = Task.create();
        task.complete(apiContext);
        Async async = testContext.async();
        Filter filter = Filter.create(VersionSplitterFilter.class.getSimpleName(), vertx, config);
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Filters.doFilter(task, Lists.newArrayList(filter))
                .andThen(context -> {
                    testContext.assertNotNull(context.apiDefinition());
                    testContext.assertEquals("add_device", context.apiDefinition().name());
                    async.complete();
                }).onFailure(throwable -> {
            throwable.printStackTrace();
            testContext.fail();
        });
    }

    @Test
    public void testNotFoundApi(TestContext testContext) {
        ApiContext apiContext =
                ApiContext.create(HttpMethod.GET, "/users", null, null, null);
        Task<ApiContext> task = Task.create();
        task.complete(apiContext);
        Async async = testContext.async();
        Filter filter = Filter.create(VersionSplitterFilter.class.getSimpleName(), vertx, config);
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Filters.doFilter(task, Lists.newArrayList(filter))
                .andThen(context -> {
                    testContext.fail();
                }).onFailure(throwable -> {
            throwable.printStackTrace();
            testContext.assertTrue(throwable instanceof SystemException);
            SystemException se = (SystemException) throwable;
            testContext.assertEquals(DefaultErrorCode.RESOURCE_NOT_FOUND, se.getErrorCode());
            async.complete();
        });
    }

    @Test
    public void testTwoApiButNoGray(TestContext testContext) {
        ApiContext apiContext =
                ApiContext.create(HttpMethod.GET, "/devices", null, null, null);
        Task<ApiContext> task = Task.create();
        task.complete(apiContext);
        Async async = testContext.async();
        Filter filter = Filter.create(VersionSplitterFilter.class.getSimpleName(), vertx, config);
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Filters.doFilter(task, Lists.newArrayList(filter))
                .andThen(context -> {
                    testContext.fail();
                }).onFailure(throwable -> {
            throwable.printStackTrace();
            testContext.assertTrue(throwable instanceof SystemException);
            SystemException se = (SystemException) throwable;
            testContext.assertEquals(DefaultErrorCode.CONFLICT, se.getErrorCode());
            async.complete();
        });
    }

    @Test
    public void testFoundSingleVersion(TestContext testContext) {
        ApiContext apiContext =
                ApiContext.create(HttpMethod.POST, "/users", null, null, null);
        Task<ApiContext> task = Task.create();
        task.complete(apiContext);
        Async async = testContext.async();
        Filter filter = Filter.create(VersionSplitterFilter.class.getSimpleName(), vertx, config);
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Filters.doFilter(task, Lists.newArrayList(filter))
                .andThen(context -> {
                    testContext.assertNotNull(context.apiDefinition());
                    testContext.assertEquals("add_user2", context.apiDefinition().name());
                    async.complete();
                }).onFailure(throwable -> {
            throwable.printStackTrace();
            testContext.fail();
        });
    }

    @Test
    public void testFoundFloor(TestContext testContext) {
        ApiContext apiContext =
                ApiContext.create(HttpMethod.POST, "/menus", null, null, null);
        Task<ApiContext> task = Task.create();
        task.complete(apiContext);
        Async async = testContext.async();
        Filter filter = Filter.create(VersionSplitterFilter.class.getSimpleName(), vertx, config);
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Filters.doFilter(task, Lists.newArrayList(filter))
                .andThen(context -> {
                    testContext.assertNotNull(context.apiDefinition());
                    testContext.assertEquals("add_menu2", context.apiDefinition().name());
                    async.complete();
                }).onFailure(throwable -> {
            throwable.printStackTrace();
            testContext.fail();
        });
    }

    @Test
    public void testFoundCeil(TestContext testContext) {
        ApiContext apiContext =
                ApiContext.create(HttpMethod.GET, "/menus", null, null, null);
        Task<ApiContext> task = Task.create();
        task.complete(apiContext);
        Async async = testContext.async();
        Filter filter = Filter.create(VersionSplitterFilter.class.getSimpleName(), vertx, config);
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Filters.doFilter(task, Lists.newArrayList(filter))
                .andThen(context -> {
                    testContext.assertNotNull(context.apiDefinition());
                    testContext.assertEquals("list_menu3", context.apiDefinition().name());
                    async.complete();
                }).onFailure(throwable -> {
            throwable.printStackTrace();
            testContext.fail();
        });
    }

    @Test
    public void testIpRangeMatch(TestContext testContext) {
        ApiContext apiContext =
                ApiContext.create(HttpMethod.GET, "/ip-splitter", null, null, null);
        Task<ApiContext> task = Task.create();
        task.complete(apiContext);
        apiContext.addVariable("request_clientIp", "192.168.1.3");
        Async async = testContext.async();
        Filter filter = Filter.create(VersionSplitterFilter.class.getSimpleName(), vertx, config);
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Filters.doFilter(task, Lists.newArrayList(filter))
                .andThen(context -> {
                    testContext.assertNotNull(context.apiDefinition());
                    testContext.assertEquals("ip-hash1", context.apiDefinition().name());
                    async.complete();
                }).onFailure(throwable -> {
            throwable.printStackTrace();
            testContext.fail();
        });
    }

    @Test
    public void testIpRangeUnMatch(TestContext testContext) {
        ApiContext apiContext =
                ApiContext.create(HttpMethod.GET, "/ip-splitter", null, null, null);
        Task<ApiContext> task = Task.create();
        task.complete(apiContext);
        apiContext.addVariable("request_clientIp", "172.168.1.103");
        Async async = testContext.async();
        Filter filter = Filter.create(VersionSplitterFilter.class.getSimpleName(), vertx, config);
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Filters.doFilter(task, Lists.newArrayList(filter))
                .andThen(context -> {
                    testContext.assertNotNull(context.apiDefinition());
                    testContext.assertEquals("ip-hash3", context.apiDefinition().name());
                    async.complete();
                }).onFailure(throwable -> {
            throwable.printStackTrace();
            testContext.fail();
        });
    }

    @Test
    public void testIpHashMatch(TestContext testContext) {
        ApiContext apiContext =
                ApiContext.create(HttpMethod.GET, "/ip-splitter", null, null, null);
        Task<ApiContext> task = Task.create();
        task.complete(apiContext);
        apiContext.addVariable("request_clientIp", "192.168.1.102");
        Async async = testContext.async();
        Filter filter = Filter.create(VersionSplitterFilter.class.getSimpleName(), vertx, config);
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Filters.doFilter(task, Lists.newArrayList(filter))
                .andThen(context -> {
                    testContext.assertNotNull(context.apiDefinition());
                    testContext.assertEquals("ip-hash2", context.apiDefinition().name());
                    async.complete();
                }).onFailure(throwable -> {
            throwable.printStackTrace();
            testContext.fail();
        });
    }

    @Test
    public void testIpHashUnMatch(TestContext testContext) {
        ApiContext apiContext =
                ApiContext.create(HttpMethod.GET, "/ip-splitter", null, null, null);
        Task<ApiContext> task = Task.create();
        task.complete(apiContext);
        apiContext.addVariable("request_clientIp", "172.168.1.103");
        Async async = testContext.async();
        Filter filter = Filter.create(VersionSplitterFilter.class.getSimpleName(), vertx, config);
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Filters.doFilter(task, Lists.newArrayList(filter))
                .andThen(context -> {
                    testContext.assertNotNull(context.apiDefinition());
                    testContext.assertEquals("ip-hash3", context.apiDefinition().name());
                    async.complete();
                }).onFailure(throwable -> {
            throwable.printStackTrace();
            testContext.fail();
        });
    }

    @Test
    public void testIpAppointMatch(TestContext testContext) {
        ApiContext apiContext =
                ApiContext.create(HttpMethod.GET, "/ip-splitter", null, null, null);
        Task<ApiContext> task = Task.create();
        task.complete(apiContext);
        apiContext.addVariable("request_clientIp", "192.169.1.1");
        Async async = testContext.async();
        Filter filter = Filter.create(VersionSplitterFilter.class.getSimpleName(), vertx, config);
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Filters.doFilter(task, Lists.newArrayList(filter))
                .andThen(context -> {
                    testContext.assertNotNull(context.apiDefinition());
                    testContext.assertEquals("ip-hash1", context.apiDefinition().name());
                    async.complete();
                }).onFailure(throwable -> {
            throwable.printStackTrace();
            testContext.fail();
        });
    }

    @Test
    public void testIpAppointUnMatch(TestContext testContext) {
        ApiContext apiContext =
                ApiContext.create(HttpMethod.GET, "/ip-splitter", null, null, null);
        Task<ApiContext> task = Task.create();
        task.complete(apiContext);
        apiContext.addVariable("request_clientIp", "172.168.1.101");
        Async async = testContext.async();
        Filter filter = Filter.create(VersionSplitterFilter.class.getSimpleName(), vertx, config);
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Filters.doFilter(task, Lists.newArrayList(filter))
                .andThen(context -> {
                    testContext.assertNotNull(context.apiDefinition());
                    testContext.assertEquals("ip-hash3", context.apiDefinition().name());
                    async.complete();
                }).onFailure(throwable -> {
            throwable.printStackTrace();
            testContext.fail();
        });
    }
}


text:
var ERROR_MSG_INPUT = 'Input must be an string, Buffer or Uint8Array'

// For convenience, let people hash a string, not just a Uint8Array
function normalizeInput (input) {
  var ret
  if (input instanceof Uint8Array) {
    ret = input
  } else if (input instanceof Buffer) {
    ret = new Uint8Array(input)
  } else if (typeof (input) === 'string') {
    ret = new Uint8Array(new Buffer(input, 'utf8'))
  } else {
    throw new Error(ERROR_MSG_INPUT)
  }
  return ret
}

// Converts a Uint8Array to a hexadecimal string
// For example, toHex([255, 0, 255]) returns "ff00ff"
function toHex (bytes) {
  return Array.prototype.map.call(bytes, function (n) {
    return (n < 16 ? '0' : '') + n.toString(16)
  }).join('')
}

// Converts any value in [0...2^32-1] to an 8-character hex string
function uint32ToHex (val) {
  return (0x100000000 + val).toString(16).substring(1)
}

// For debugging: prints out hash state in the same format as the RFC
// sample computation exactly, so that you can diff
function debugPrint (label, arr, size) {
  var msg = '\n' + label + ' = '
  for (var i = 0; i < arr.length; i += 2) {
    if (size === 32) {
      msg += uint32ToHex(arr[i]).toUpperCase()
      msg += ' '
      msg += uint32ToHex(arr[i + 1]).toUpperCase()
    } else if (size === 64) {
      msg += uint32ToHex(arr[i + 1]).toUpperCase()
      msg += uint32ToHex(arr[i]).toUpperCase()
    } else throw new Error('Invalid size ' + size)
    if (i % 6 === 4) {
      msg += '\n' + new Array(label.length + 4).join(' ')
    } else if (i < arr.length - 2) {
      msg += ' '
    }
  }
  console.log(msg)
}

// For performance testing: generates N bytes of input, hashes M times
// Measures and prints MB/second hash performance each time
function testSpeed (hashFn, N, M) {
  var startMs = new Date().getTime()

  var input = new Uint8Array(N)
  for (var i = 0; i < N; i++) {
    input[i] = i % 256
  }
  var genMs = new Date().getTime()
  console.log('Generated random input in ' + (genMs - startMs) + 'ms')
  startMs = genMs

  for (i = 0; i < M; i++) {
    var hashHex = hashFn(input)
    var hashMs = new Date().getTime()
    var ms = hashMs - startMs
    startMs = hashMs
    console.log('Hashed in ' + ms + 'ms: ' + hashHex.substring(0, 20) + '...')
    console.log(Math.round(N / (1 << 20) / (ms / 1000) * 100) / 100 + ' MB PER SECOND')
  }
}

module.exports = {
  normalizeInput: normalizeInput,
  toHex: toHex,
  debugPrint: debugPrint,
  testSpeed: testSpeed
}


text:
#define BOOST_TEST_MODULE icl::cmp_msvc_value_born_error unit test
#include <boost/config.hpp>
#include "../unit_test_unwarned.hpp"

namespace unhelpful{
    // This declaration of a class template will cause
    // the compilation of line 17 to fail with syntax error C2059
    template<class T> class value{};
}

//--- affected code ---------------------------------------
template <class Type> struct meta_attribute
{
    BOOST_STATIC_CONSTANT(int, value = 0);
};

template <class Type> struct meta_predicate
{
    BOOST_STATIC_CONSTANT(bool, value =
        ( meta_attribute<Type>::value  < 1)
        //error C2059: syntax error : ')'
        //IF class template value declared before
    //  ((meta_attribute<Type>::value) < 1) // Remedy#1 enclose into ()
    //  ( meta_attribute<Type>::value  <=0) // Remedy#2 use operator <=
        );
};

BOOST_AUTO_TEST_CASE(dummy)
{
    BOOST_CHECK( meta_predicate<int>::value );
}


text:
require 'spec_helper'

describe SCSSLint::Linter::ExtendDirective do
  context 'when extending with a class' do
    let(:scss) { <<-SCSS }
      p {
        @extend .error;
      }
    SCSS

    it { should report_lint line: 2 }
  end

  context 'when extending with a type' do
    let(:scss) { <<-SCSS }
      p {
        @extend span;
      }
    SCSS

    it { should report_lint line: 2 }
  end

  context 'when extending with an id' do
    let(:scss) { <<-SCSS }
      p {
        @extend #some-identifer;
      }
    SCSS

    it { should report_lint line: 2 }
  end

  context 'when extending with a placeholder' do
    let(:scss) { <<-SCSS }
      p {
        @extend %placeholder;
      }
    SCSS

    it { should report_lint line: 2 }
  end

  context 'when extending with a selector whose prefix is not a placeholder' do
    let(:scss) { <<-SCSS }
      p {
        @extend .blah-\#{$dynamically_generated_name};
      }
    SCSS

    it { should report_lint line: 2 }
  end

  context 'when extending with a selector whose prefix is dynamic' do
    let(:scss) { <<-SCSS }
      p {
        @extend \#{$dynamically_generated_placeholder_name};
      }
    SCSS

    it { should report_lint line: 2 }
  end

  context 'when not using extend' do
    let(:scss) { <<-SCSS }
      p {
        @include mixin;
      }
    SCSS

    it { should_not report_lint }
  end
end


text:
from InsightToolkit import *

from sys import argv

readerInput = itkImageFileReaderUC2_New()
readerPrior = itkImageFileReaderUC2_New()

readerInput.SetFileName( argv[1] )
readerPrior.SetFileName( argv[2] )

readerInput.Update()
readerPrior.Update()

filter  = itkVoronoiSegmentationImageFilterUC2UC2UC2_New()

filter.SetInput(   readerInput.GetOutput() )
filter.TakeAPrior( readerPrior.GetOutput() )

filter.SetMeanPercentError( eval( argv[4] )  )
filter.SetSTDPercentError( eval( argv[5] )  )

writer = itkImageFileWriterUC2_New()
writer.SetFileName( argv[3] )
writer.SetInput( filter.GetOutput() )

writer.Update()


text:
namespace DataTest
{
    using System;
    using System.Collections.Generic;

    public partial class WishList
    {
        public int Item_id { get; set; }
        public int Priority { get; set; }
        public int Copy { get; set; }
        public string Reason { get; set; }

        public virtual Item Item { get; set; }
    }
}


text:
package main

import (
	"github.com/solo-io/go-utils/log"
	"github.com/solo-io/solo-kit/pkg/code-generator/cmd"
	"github.com/solo-io/solo-kit/pkg/code-generator/docgen/options"
)

func main() {
	log.Printf("Starting generate...")
	opts := cmd.GenerateOptions{
		CompileProtos: true,
		RelativeRoot:  ".",
		GenDocs: &cmd.DocsOptions{
			Output: options.Hugo,
		},
		SkipGenMocks: true,
	}
	if err := cmd.Generate(opts); err != nil {
		log.Fatalf("generate failed!: %v", err)
	}
}


text:
package com.datatorrent.stram;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.apache.hadoop.yarn.api.records.NodeReport;
import org.apache.hadoop.yarn.api.records.NodeState;
import org.apache.hadoop.yarn.server.utils.BuilderUtils;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

import com.datatorrent.api.AffinityRule;
import com.datatorrent.api.AffinityRule.Type;
import com.datatorrent.api.AffinityRulesSet;
import com.datatorrent.api.Context.DAGContext;
import com.datatorrent.api.Context.OperatorContext;
import com.datatorrent.api.DAG.Locality;
import com.datatorrent.common.partitioner.StatelessPartitioner;
import com.datatorrent.stram.StreamingContainerAgent.ContainerStartRequest;
import com.datatorrent.stram.engine.GenericTestOperator;
import com.datatorrent.stram.engine.TestGeneratorInputOperator;
import com.datatorrent.stram.plan.logical.LogicalPlan;
import com.datatorrent.stram.plan.physical.PTContainer;
import com.datatorrent.stram.plan.physical.PTOperator;
import com.datatorrent.stram.support.StramTestSupport.MemoryStorageAgent;
import com.datatorrent.stram.support.StramTestSupport.TestMeta;

public class AffinityRulesTest
{
  private static final Logger LOG = LoggerFactory.getLogger(AffinityRulesTest.class);

  @Rule
  public TestMeta testMeta = new TestMeta();

  @Test
  public void testOperatorPartitionsAntiAffinity()
  {
    LogicalPlan dag = new LogicalPlan();
    TestGeneratorInputOperator o1 = dag.addOperator("O1", new TestGeneratorInputOperator());
    GenericTestOperator o2 = dag.addOperator("O2", new GenericTestOperator());
    GenericTestOperator o3 = dag.addOperator("O3", new GenericTestOperator());
    dag.addStream("stream1", o1.outport, o2.inport1);
    dag.addStream("stream2", o2.outport1, o3.inport1);

    dag.setOperatorAttribute(o2, OperatorContext.PARTITIONER, new StatelessPartitioner<GenericTestOperator>(5));

    AffinityRulesSet ruleSet = new AffinityRulesSet();
    // Valid case:
    List<AffinityRule> rules = new ArrayList<>();
    ruleSet.setAffinityRules(rules);
    AffinityRule rule1 = new AffinityRule(Type.ANTI_AFFINITY, Locality.NODE_LOCAL, false, "O2", "O2");
    rules.add(rule1);
    dag.setAttribute(DAGContext.AFFINITY_RULES_SET, ruleSet);
    dag.validate();
    dag.getAttributes().put(com.datatorrent.api.Context.DAGContext.APPLICATION_PATH, testMeta.getAbsolutePath());
    dag.setAttribute(OperatorContext.STORAGE_AGENT, new MemoryStorageAgent());

    StreamingContainerManager scm = new StreamingContainerManager(dag);

    // Check Physical Plan assigns anti-affinity preferences correctly

    for (ContainerStartRequest csr : scm.containerStartRequests) {
      PTContainer container = csr.container;
      // Check that for containers for O2 partitions, anti-affinity Preference
      // are set properly

      if (container.getOperators().get(0).getName().equals("O2")) {
        Assert.assertEquals("Anti-affinity containers set should have 4 containers for other partitions ", 4, container.getStrictAntiPrefs().size());
        for (PTContainer c : container.getStrictAntiPrefs()) {
          for (PTOperator operator : c.getOperators()) {
            Assert.assertEquals("Partion for O2 should be Anti Prefs", "O2", operator.getName());
          }
        }
      }
    }

    // Check resource handler assigns different hosts for each partition

    ResourceRequestHandler rr = new ResourceRequestHandler();
    int containerMem = 1000;
    Map<String, NodeReport> nodeReports = Maps.newHashMap();
    for (int i = 0; i < 10; i++) {
      String hostName = "host" + i;
      NodeReport nr = BuilderUtils.newNodeReport(BuilderUtils.newNodeId(hostName, 0), NodeState.RUNNING, "httpAddress", "rackName", BuilderUtils.newResource(0, 0), BuilderUtils.newResource(containerMem * 2, 2), 0, null, 0);
      nodeReports.put(nr.getNodeId().getHost(), nr);
    }

    // set resources
    rr.updateNodeReports(Lists.newArrayList(nodeReports.values()));

    Set<String> partitionHostNames = new HashSet<>();
    for (ContainerStartRequest csr : scm.containerStartRequests) {
      String host = rr.getHost(csr, true);
      csr.container.host = host;
      if (csr.container.getOperators().get(0).getName().equals("O2")) {
        Assert.assertNotNull("Host name should not be null", host);
        LOG.info("Partition {} for operator O2 has host = {} ", csr.container.getId(), host);
        Assert.assertTrue("Each Partition should have a different host", !partitionHostNames.contains(host));
        partitionHostNames.add(host);
      }
    }
  }

  @Test
  public void testAntiAffinityInOperators()
  {
    LogicalPlan dag = new LogicalPlan();
    dag.getAttributes().put(com.datatorrent.api.Context.DAGContext.APPLICATION_PATH, testMeta.getAbsolutePath());
    dag.setAttribute(OperatorContext.STORAGE_AGENT, new MemoryStorageAgent());

    GenericTestOperator o1 = dag.addOperator("O1", GenericTestOperator.class);
    dag.setOperatorAttribute(o1, OperatorContext.MEMORY_MB, 256);

    GenericTestOperator o2 = dag.addOperator("O2", GenericTestOperator.class);
    dag.setOperatorAttribute(o2, OperatorContext.MEMORY_MB, 256);

    dag.getMeta(o1).getAttributes().put(OperatorContext.LOCALITY_HOST, "host1");
    AffinityRulesSet ruleSet = new AffinityRulesSet();

    List<AffinityRule> rules = new ArrayList<>();
    ruleSet.setAffinityRules(rules);
    AffinityRule rule1 = new AffinityRule(Type.ANTI_AFFINITY, Locality.NODE_LOCAL, false, "O1", "O2");
    rules.add(rule1);
    dag.setAttribute(DAGContext.AFFINITY_RULES_SET, ruleSet);

    dag.addStream("o1_outport1", o1.outport1, o2.inport1);// .setLocality(Locality.NODE_LOCAL);

    StreamingContainerManager scm = new StreamingContainerManager(dag);

    ResourceRequestHandler rr = new ResourceRequestHandler();

    int containerMem = 1000;
    Map<String, NodeReport> nodeReports = Maps.newHashMap();
    NodeReport nr = BuilderUtils.newNodeReport(BuilderUtils.newNodeId("host1", 0), NodeState.RUNNING, "httpAddress", "rackName", BuilderUtils.newResource(0, 0), BuilderUtils.newResource(containerMem * 2, 2), 0, null, 0);
    nodeReports.put(nr.getNodeId().getHost(), nr);
    nr = BuilderUtils.newNodeReport(BuilderUtils.newNodeId("host2", 0), NodeState.RUNNING, "httpAddress", "rackName", BuilderUtils.newResource(0, 0), BuilderUtils.newResource(containerMem * 2, 2), 0, null, 0);
    nodeReports.put(nr.getNodeId().getHost(), nr);

    // set resources
    rr.updateNodeReports(Lists.newArrayList(nodeReports.values()));

    for (ContainerStartRequest csr : scm.containerStartRequests) {
      String host = rr.getHost(csr, true);
      csr.container.host = host;
      if (csr.container.getOperators().get(0).getName().equals("O1")) {
        Assert.assertEquals("Hosts set to host1 for Operator O1", "host1", host);
      }
      if (csr.container.getOperators().get(0).getName().equals("O2")) {
        Assert.assertEquals("Hosts set to host2 for Operator O2", "host2", host);
      }
    }
  }
}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.blogspot.na5cent.resourcelocal.model;

import java.io.Serializable;
import java.util.Objects;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

/**
 *
 * @author anonymous
 */
@Entity
@Table(name = "employees")
public class Employee implements Serializable {

    @Id
    @Column(name = "employee_id")
    private Integer id;
    @Column(name = "first_name")
    private String firstName;
    @Column(name = "last_name")
    private String lastName;

    public Integer getId() {
        return id;
    }

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

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    @Override
    public int hashCode() {
        int hash = 5;
        hash = 41 * hash + Objects.hashCode(this.id);
        return hash;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final Employee other = (Employee) obj;
        if (!Objects.equals(this.id, other.id)) {
            return false;
        }
        return true;
    }

}


text:
app.controller('UserCtrl', ['$scope', '$auth', function($scope, $auth) {
	$scope.user = {
		email: '',
		password: '',
		username: ''
	};

	$scope.socialAuth = function (provider) {
		$auth.authenticate(provider);
	};

	$scope.logout = function () {
		$auth.logout();
	};

	$scope.login = function () {
		$auth.login($scope.user);
	};

	$scope.signup = function () {
		$auth.signup($scope.user);
	};
}]);


text:
from __future__ import absolute_import, unicode_literals

from django.conf.urls import url
from django.core.exceptions import ImproperlyConfigured
from django.forms.models import modelform_factory

from wagtail.wagtailadmin.views import generic
from wagtail.wagtailcore.permissions import ModelPermissionPolicy

from .base import ViewSet

class ModelViewSet(ViewSet):
    icon = ""

    index_view_class = generic.IndexView
    add_view_class = generic.CreateView
    edit_view_class = generic.EditView
    delete_view_class = generic.DeleteView

    @property
    def permission_policy(self):
        return ModelPermissionPolicy(self.model)

    @property
    def index_view(self):
        return self.index_view_class.as_view(
            model=self.model,
            permission_policy=self.permission_policy,
            index_url_name=self.get_url_name('index'),
            add_url_name=self.get_url_name('add'),
            edit_url_name=self.get_url_name('edit'),
            header_icon=self.icon,
        )

    @property
    def add_view(self):
        return self.add_view_class.as_view(
            model=self.model,
            permission_policy=self.permission_policy,
            form_class=self.get_form_class(),
            index_url_name=self.get_url_name('index'),
            add_url_name=self.get_url_name('add'),
            edit_url_name=self.get_url_name('edit'),
            header_icon=self.icon,
        )

    @property
    def edit_view(self):
        return self.edit_view_class.as_view(
            model=self.model,
            permission_policy=self.permission_policy,
            form_class=self.get_form_class(for_update=True),
            index_url_name=self.get_url_name('index'),
            edit_url_name=self.get_url_name('edit'),
            delete_url_name=self.get_url_name('delete'),
            header_icon=self.icon,
        )

    @property
    def delete_view(self):
        return self.delete_view_class.as_view(
            model=self.model,
            permission_policy=self.permission_policy,
            index_url_name=self.get_url_name('index'),
            delete_url_name=self.get_url_name('delete'),
            header_icon=self.icon,
        )

    def formfield_for_dbfield(self, db_field, **kwargs):
        return db_field.formfield(**kwargs)

    def get_form_class(self, for_update=False):
        fields = getattr(self, 'form_fields', None)
        exclude = getattr(self, 'exclude_form_fields', None)

        if fields is None and exclude is None:
            raise ImproperlyConfigured(
                "Subclasses of ModelViewSet must specify 'get_form_class', 'form_fields' "
                "or 'exclude_form_fields'."
            )

        return modelform_factory(
            self.model,
            formfield_callback=self.formfield_for_dbfield,
            fields=fields,
            exclude=exclude
        )

    def get_urlpatterns(self):
        return super(ModelViewSet, self).get_urlpatterns() + [
            url(r'^$', self.index_view, name='index'),
            url(r'^new/$', self.add_view, name='add'),
            url(r'^(\d+)/$', self.edit_view, name='edit'),
            url(r'^(\d+)/delete/$', self.delete_view, name='delete'),
        ]


text:
<template name="LeaveEntry">

{{name type}} {{description}}

                             Duration of Leave Request {{toTwoDecimalPlaces duration}} Day(s)
                            {{#if isRelieverEnabledForLeaveRequests}}
                                 Reliever: {{getRelieverFullName relieverUserId}}
                            {{/if}}

 From: {{formatTime startDate}}

 To: {{formatTime endDate}}

 {{approvalStatus}}

 Date Created: {{formatTime createdAt}}

                        {{#if canEdit}}

                                        <button class="btn btn-default btn-sm" type="button" id="delete" > Delete</button>

                        {{/if}}

</template>


text:
import Relay from 'react-relay';

export default class extends Relay.Route {
  static queries = {
    viewer: () => Relay.QL`
      query {
        viewer
      }
    `,
  };
  static routeName = 'AppHomeRoute';
}


text:
module SlackGamebot
  module Commands
    class Leaderboard < SlackRubyBot::Commands::Base
      def self.call(client, data, match)
        max = 3
        arguments = match['expression'].split.reject(&:blank?) if match.names.include?('expression')
        arguments ||= []
        case arguments.first.downcase
        when 'infinity'
          max = nil
        else
          max = Integer(arguments.first)
        end if arguments.any?
        message = User.ranked.asc(:rank).limit(max).map do |user|
          "#{user.rank}. #{user}"
        end.join("\n")
        send_message client, data.channel, message
      end
    end
  end
end