text:
%Section 72 Group 8 Biweekly 2
%Drew Lentz, Stephen Wetzel

function varargout = FrolfSimulation(varargin)
% FROLFSIMULATION MATLAB code for FrolfSimulation.fig
%      FROLFSIMULATION, by itself, creates a new FROLFSIMULATION or raises the existing
%      singleton*.
%
%      H = FROLFSIMULATION returns the handle to a new FROLFSIMULATION or the handle to
%      the existing singleton*.
%
%      FROLFSIMULATION('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in FROLFSIMULATION.M with the given input arguments.
%
%      FROLFSIMULATION('Property','Value',...) creates a new FROLFSIMULATION or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before FrolfSimulation_OpeningFcn gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to FrolfSimulation_OpeningFcn via varargin.
%
%      *See GUI Options on GUIDE's Tools menu.  Choose "GUI allows only one
%      instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES

% Edit the above text to modify the response to help FrolfSimulation

% Last Modified by GUIDE v2.5 12-Mar-2014 13:06:07

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
    'gui_Singleton',  gui_Singleton, ...
    'gui_OpeningFcn', @FrolfSimulation_OpeningFcn, ...
    'gui_OutputFcn',  @FrolfSimulation_OutputFcn, ...
    'gui_LayoutFcn',  [] , ...
    'gui_Callback',   []);
if nargin && ischar(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT

% --- Executes just before FrolfSimulation is made visible.
function FrolfSimulation_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   command line arguments to FrolfSimulation (see VARARGIN)

% Choose default command line output for FrolfSimulation
handles.output = hObject;
% Initializing the Rolling Plot
handles.buf_len = 200;

% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % %
% INITIALIZATION OF VARIABLES                                             %
% All initialization of variables take place in the opening function unless
% required elsewhere                                                      %
% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % %

% create variables for all the three axis and the resultant
handles.gxdata = zeros(handles.buf_len,1); %X axis
handles.gydata = zeros(handles.buf_len,1); %Y axis
handles.gzdata = zeros(handles.buf_len,1); %Z axis
handles.redata = zeros(handles.buf_len,1); %Resultant magnitude
handles.index = 1:handles.buf_len; %Time Index

%initializing vectors for x,y,z filtered data
handles.gxFiltData = zeros(handles.buf_len,1); %X axis
handles.gyFiltData = zeros(handles.buf_len,1); %Y axis
handles.gzFiltData = zeros(handles.buf_len,1); %Z axis
handles.reFiltData = zeros(handles.buf_len,1); %Resultant Filtered

%initialize vectors for filtered throw data
handles.throwXFilterData = zeros(10,1);
handles.throwYFilterData = zeros(10,1);
handles.throwZFilterData = zeros(10,1);
handles.throwResFilterData = zeros(10,1);

%initialized threshold flag
handles.tFlag = 0;

%initializing filtered data
handles.gxFilt = 0;
handles.gyFilt = 0;
handles.gzFilt = 0;

%Hole Placement Vector for the 9 hole course
handles.hole = [480, 3; 640, 4; 320, 3; 800, 5; 200, 2; 555, 4; 381, 3; 684, 4; 932 5];
handles.inHole = 0;%flag for in the hole

%initializing starting points, hole index, throw number
handles.xi=0; %initial throw position in x
handles.yi=0; %initial throw position in y
handles.holeIndex=1; %hole index for hole placement vector
handles.throwNumber = 1; % counter for throws
handles.setupFlag = 0; % Initialize setup flag for reading/calibrating the accelerometer
handles.readyFlag = 1; %initialize the ready button for read accelerometer loop

% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % %
% DEFAULT VALUES                                                          %
% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % %
handles.player = 1; %default player number
handles.numberOfPlayers = 1; % Default number of players
handles.difficulty = 1; %1 easy, 3 hard
handles.holeSize = 5; %size of hole
handles.score = cell(4,11); % Default score placement in the scorecard
handles.wind = 0; %Default wind speed
handles.alphaVal = .33;
handles.threshold = 2.8;

% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % %
% Sound for successful shots, from:
% https://freesound.org/people/grunz/sounds/109663/
[handles.goalWav, handles.goalFs] = audioread('success2.wav');

% Birdy, one under par:
% https://freesound.org/people/cajo/sounds/34207/
[handles.birdWav, handles.birdFs] = audioread('birds.wav');

% Eagle, two under par:
%https://freesound.org/people/thecluegeek/sounds/140847/
[handles.eagleWav, handles.eagleFs] = audioread('eagle.wav');

% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % %
% OPENING SERIAL COMMUNICATION, CALIBRATING, READING THE ACCELEROMETER    %
% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % %

%Specifies the COM port that the Arduino board is connected to
handles.comPort = 'COM4';
%comPort = '/dev/tty.usbmodemfd121';

% Initialize the Serial Port - setupSerial() (not to be altered)
%connect MATLAB to the accelerometer
if (~exist('serialFlag','var'))
    [handles.accelerometer.s,handles.serialFlag] = setupSerial(handles.comPort);
end

if(~exist('calCo', 'var'))
    handles.calCo = calibrate(handles.accelerometer.s);
end

handles.setupFlag = 1; % Update setup flag when successful
% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % %

% Update handles structure
guidata(hObject, handles);

% --- Outputs from this function are returned to the command line.
function varargout = FrolfSimulation_OutputFcn(hObject, eventdata, handles)
% varargout  cell array for returning output args (see VARARGOUT);
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure
varargout{1} = handles.output;
% Update handles structure
guidata(hObject, handles);

% --- Executes on button press in beginGameButton.
function beginGameButton_Callback(hObject, eventdata, handles)
% hObject    handle to beginGameButton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

if strcmp(get(handles.beginGameButton, 'string'), 'Begin Game');
    set(handles.beginGameButton, 'string', 'Ready');
    %get info from player:
    handles.difficulty = get(handles.difficultyMenu, 'Value');
    handles.score = ''; %delete any previous value
    if isempty(get(handles.playerName1, 'string'))
        set(handles.playerName1, 'string', 'CPU');
    end

    guidata(hObject, handles); %update handles
    handles.score{1,1} = get(handles.playerName1, 'string');
    handles.score{2,1} = get(handles.playerName2, 'string');
    handles.score{3,1} = get(handles.playerName3, 'string');
    handles.score{4,1} = get(handles.playerName4, 'string');

    %hide the input fields, show the score card:
    set(handles.playerName1, 'visible', 'off');
    set(handles.playerName2, 'visible', 'off');
    set(handles.playerName3, 'visible', 'off');
    set(handles.playerName4, 'visible', 'off');
    set(handles.difficultyMenu, 'visible', 'off');
    set(handles.text34, 'visible', 'off');
    set(handles.text35, 'visible', 'off');
    set(handles.text36, 'visible', 'off');
    set(handles.text37, 'visible', 'off');
    set(handles.text40, 'visible', 'off');
    set(handles.text41, 'visible', 'off');
    set(handles.scoreTable, 'visible', 'on');
    set(handles.discMenu, 'visible', 'on');
    set(handles.textDiscType, 'visible', 'on');

    %set up number of players:
    handles.score{1,11} = 0; %total

    if isempty(handles.score{2,1})
        handles.numberOfPlayers = 1;
    elseif isempty(handles.score{3,1})
        handles.numberOfPlayers = 2;
        handles.score{2,11} = 0; %total
    elseif isempty(handles.score{4,1})
        handles.numberOfPlayers = 3;
        handles.score{2,11} = 0; %total
        handles.score{3,11} = 0; %total
    else
        handles.numberOfPlayers = 4;
        handles.score{2,11} = 0; %total
        handles.score{3,11} = 0; %total
        handles.score{4,11} = 0; %total
    end
    %determining difficulty, changes dimensions of the hole
    if handles.difficulty == 3
        handles.holeSize = 1;
    elseif handles.difficulty == 2
        handles.holeSize = 3;
    else
        handles.holeSize = 10;
    end

    %initializing the throw positions, hole index, throw number, this is
    %done here to accomodate for new games
    handles.xi=0;
    handles.yi=0;
    handles.holeIndex=1;
    handles.throwNumber = 1;

    set(handles.textPlayerName, 'String', handles.score{1,1}); %set player name text on GUI
    set(handles.scoreTable, 'data', handles.score); %set scorecard
    guidata(hObject, handles); %update handles
end

%If statement for first throw of each hole
if handles.throwNumber == 1
    handles.distanceToPin = handles.hole(handles.holeIndex,1);
end
% Plots the view of the next throw
plotPre(handles.distanceToPin, handles); %function to plot the view of the next throw

handles.readyFlag = 1; %setting the ready flag to start reading accel. data

if handles.setupFlag %ensures that the initial calibration is completed

    while handles.readyFlag %loop once the ready button is pushed & setup is complete
        plotPre(handles.distanceToPin, handles); %function to plot the view of the next throw

        % Get the new values from the accelerometer
        [handles.gx handles.gy handles.gz] = readAcc(handles.accelerometer,handles.calCo);
        %alpha filtering the input signal
        handles.gxFilt = (1-handles.alphaVal)*handles.gxFilt + handles.alphaVal * handles.gx;
        handles.gyFilt = (1-handles.alphaVal)*handles.gyFilt + handles.alphaVal * handles.gy;
        handles.gzFilt = (1-handles.alphaVal)*handles.gzFilt + handles.alphaVal * handles.gz;
        handles.resultantFilt = sqrt(handles.gxFilt^2 + handles.gyFilt^2 + handles.gzFilt^2);
        %alpha filtered data, used for throw calculations
        handles.gxFiltData = [handles.gxFiltData(2:end); handles.gxFilt];
        handles.gyFiltData = [handles.gyFiltData(2:end); handles.gyFilt];
        handles.gzFiltData = [handles.gzFiltData(2:end); handles.gzFilt];
        handles.reFiltData = [handles.reFiltData(2:end); handles.resultantFilt];

        % Calculate the magnitude of the accelerometer axis readings
        handles.resultant = sqrt(handles.gx^2 + handles.gy^2 + handles.gz^2);

        % Append the new reading to the end of the rolling plot data. Drop the
        % first value
        handles.gxdata = [handles.gxdata(2:end) ; handles.gx];
        handles.gydata = [handles.gydata(2:end) ; handles.gy];
        handles.gzdata = [handles.gzdata(2:end) ; handles.gz];
        handles.redata = [handles.redata(2:end) ; handles.resultant];
        %plotting/relabeling
        if handles.resultant > handles.threshold && ~handles.tFlag %set threshold flag when it is crossed
            handles.tFlag = 1;
        elseif handles.resultant < handles.threshold && handles.tFlag || strcmpi(handles.score{handles.player,1}, 'CPU')
            %collect data when reading goes back under the threshold

            handles.tFlag = 0; %reset threshold flag
            %collecting throw data in x, y , z, and the resultant
            handles.throwXFilterData = [handles.gxFiltData(191:end)];
            handles.throwYFilterData = [handles.gyFiltData(191:end)];
            handles.throwZFilterData = [handles.gzFiltData(191:end)];
            handles.throwResFilterData = [handles.reFiltData(191:end)];

            if handles.throwNumber == 1
                handles.distanceToPin = handles.hole(handles.holeIndex,1);
            end

            %SETTING TEXT BOXES ON THE GUI AFTER EACH THROW
            set(handles.parVal,'String', num2str(handles.hole(handles.holeIndex,2))); %PAR VALUE
            set(handles.pinDistance,'String',num2str(handles.distanceToPin)); %DISTANCE TO THE PIN
            set(handles.holeNumber,'String',num2str(handles.holeIndex)); %HOLE NUMBER

            %CALCULATING THE THROW USING THE COLLECTED DATA
            if strcmpi(handles.score{handles.player,1}, 'CPU') %CHECKS FOR COMPUTER OPPONENT
                [handles.v0, handles.theta, handles.alpha, handles.yTilt,...
                    handles.discN, handles.yVel] = cpuThrow(handles.distanceToPin, handles.difficulty);
            else %FOR HUMAN THROWS
                handles.discN = get(handles.discMenu, 'Value'); %receiving disc selection
                [handles.v0,handles.theta,handles.alpha,handles.yTilt,handles.discN,handles.yVel] = ...
                    findThrowData(handles.throwXFilterData, handles.throwYFilterData, handles.throwZFilterData, handles.throwResFilterData);
            end

            %finding disc flight using function throwDisk4
            [handles.xHist, handles.yHist, handles.zHist, handles.inHole] =...
                throwDisk4(handles.v0,handles.theta,handles.alpha,...
                handles.yTilt,handles.discN,handles.yVel,handles.distanceToPin,handles.holeSize);

            %%% Externally plotting the throw%%%
            plotThrow(handles.xHist, handles.yHist, handles.zHist, handles.inHole, handles.distanceToPin, handles);

            if handles.inHole %checks to see if the throw went in the hole
                %next player

                if handles.throwNumber <= handles.hole(handles.holeIndex, 2)-2 %eagle
                    sound(handles.eagleWav, handles.eagleFs);
                elseif handles.throwNumber <= handles.hole(handles.holeIndex, 2)-1 %birdy
                    sound(handles.birdWav, handles.birdFs);
                else
                    sound(handles.goalWav, handles.goalFs);
                end

                handles.score{handles.player, handles.holeIndex+1} = handles.throwNumber; %updating scorecard
                handles.score{handles.player, 11} = handles.score{handles.player, 11} + handles.throwNumber; %updating scorecard
                set(handles.scoreTable, 'data', handles.score);%updating scorecard
                handles.player = handles.player + 1;%get next players name. set to GUI screen
                if handles.player > handles.numberOfPlayers %see if end of players is reached
                    %next hole
                    handles.player = 1; %resets player number
                    handles.holeIndex = handles.holeIndex+1;

                    %checking to see if end of game is reached
                    if handles.holeIndex > 9
                        checkWinner(handles.score, handles.numberOfPlayers, handles);%find winner
                        set(handles.beginGameButton, 'string', 'Begin Game');%restarts the game
                    end

                end
                set(handles.textPlayerName, 'String', handles.score{handles.player, 1});
                clear handles.xHist; %clearing previous throw history
                clear handles.yHist; %clearing previous throw history
                handles.xi = 0; %resets the starting point to origin
                handles.yi = 0; %resets the starting point to origin

                handles.inHole = 0;%reset in hole flag
                handles.throwNumber = 1; %resets throw number
                set(handles.shotNumber,'String',num2str(handles.throwNumber)); %sets throw number to GUI screen

            else %FOR THROWS THAT DON'T LAND IN THE HOLE
                handles.xi = handles.xHist(end); %find x starting point for next throw
                handles.yi = handles.yHist(end);%find x starting point for next throw
                handles.distanceToPin = sqrt((handles.distanceToPin-handles.xi)^2 + (handles.yi)^2);%finds distance to pin for replotting
                set(handles.pinDistance,'String',num2str(handles.distanceToPin)); %set distance to pin to GUI screen
                handles.throwNumber = handles.throwNumber + 1; %update throw number
                hold off
                set(handles.shotNumber,'String',num2str(handles.throwNumber)); %setting throw number to GUI screen

            end % END IN HOLE IF STATEMENT

            set(handles.scoreTable, 'data', handles.score); %update scorecard
            handles.score;
            handles.readyFlag = 0; %wait for user to press ready button
            guidata(hObject, handles); %UPDATE HANDLES
        end

        guidata(hObject, handles); %UPDATE HANDLES
    end
end

guidata(hObject, handles); %UPDATE HANDLES

% --- Executes on button press in closeButton.
function closeButton_Callback(hObject, eventdata, handles)
% hObject    handle to closeButton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

closeSerial; %Closes the serial connection

%%% No actual code below this %%%

% --- Executes during object creation, after setting all properties.
function playerName1_CreateFcn(hObject, eventdata, handles)
% hObject    handle to playerName1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% --- Executes during object creation, after setting all properties.
function playerName2_CreateFcn(hObject, eventdata, handles)
% hObject    handle to playerName2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% --- Executes during object creation, after setting all properties.
function playerName3_CreateFcn(hObject, eventdata, handles)
% hObject    handle to playerName3 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% --- Executes during object creation, after setting all properties.
function playerName4_CreateFcn(hObject, eventdata, handles)
% hObject    handle to playerName4 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% --- Executes during object creation, after setting all properties.
function difficultyMenu_CreateFcn(hObject, eventdata, handles)
% hObject    handle to difficultyMenu (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% --- Executes during object creation, after setting all properties.
function discMenu_CreateFcn(hObject, eventdata, handles)
% hObject    handle to discMenu (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% --- Executes during object creation, after setting all properties.
function readyButton_CreateFcn(hObject, eventdata, handles)
% hObject    handle to readyButton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% --- Executes during object creation, after setting all properties.
function scoreTable_CreateFcn(hObject, eventdata, handles)
% hObject    handle to scoreTable (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

function playerName1_Callback(hObject, eventdata, handles)
% hObject    handle to playerName1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of playerName1 as text
%        str2double(get(hObject,'String')) returns contents of playerName1 as a double

function playerName2_Callback(hObject, eventdata, handles)
% hObject    handle to playerName2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of playerName2 as text
%        str2double(get(hObject,'String')) returns contents of playerName2 as a double

function playerName3_Callback(hObject, eventdata, handles)
% hObject    handle to playerName3 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of playerName3 as text
%        str2double(get(hObject,'String')) returns contents of playerName3 as a double

function playerName4_Callback(hObject, eventdata, handles)
% hObject    handle to playerName4 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of playerName4 as text
%        str2double(get(hObject,'String')) returns contents of playerName4 as a double

% --- Executes on selection change in difficultyMenu.
function difficultyMenu_Callback(hObject, eventdata, handles)
% hObject    handle to difficultyMenu (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns difficultyMenu contents as cell array
%        contents{get(hObject,'Value')} returns selected item from difficultyMenu

% --- Executes on selection change in discMenu.
function discMenu_Callback(hObject, eventdata, handles)
% hObject    handle to discMenu (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns discMenu contents as cell array
%        contents{get(hObject,'Value')} returns selected item from discMenu


text:
import 'babel-polyfill';
import {createConversation, ALL_CONVERSATIONS}  from './conversations';
import * as Sequelize from 'sequelize';
import {defineModels} from './models';
import {Reminder} from './conversations/reminder';
const commandlineArgs = require('command-line-args');

const parser = commandlineArgs([
  {name: 'force', alias: 'F', type: Boolean,
    description: '強制的にDBスキーマを再作成するか'},
  {name: 'token', alias: 't', type: String, required: true,
    description: 'SlackのAPIトークン'},
  {name: 'reminder-channel', alias: 'c', type: String,
    description: 'リマインダを送信するチャネルの名称'},
  {name: 'help', alias: 'h', type: Boolean,
    description: 'ヘルプを表示する'},
  {name: 'database-url', alias: 'd', type: String, required: true,
    description: 'データベースのURL(例: mysql://user:pass@localhost:3306/hx)'},
]);

const options = parser.parse(process.argv);
// console.log(options);
if (options.help) {
  console.log(parser.getUsage());
  process.exit(0);
}
const token = options.token;
if (!token) {
  console.log('トークンが指定されていません' + parser.getUsage());
  process.exit(1);
}

const databaseUrl: string = options['database-url'];
if (!databaseUrl) {
  console.log('--database-urlが指定されていません' + parser.getUsage());
  process.exit(1);
}

// Sequelizeのトランザクションを、全てのクエリで自動的に利用する設定
// http://docs.sequelizejs.com/en/latest/docs/transactions/#automatically-pass-transactions-to-all-queries
const cls = require('continuation-local-storage');
Sequelize.cls = cls.createNamespace('hx');

const botkit = require('botkit');

const controller = botkit.slackbot({
  debug: false
});

const bot = controller.spawn({
  token,
  incoming_webhook: {
    url: 'https://hooks.slack.com/services/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'
  }
})
  .startRTM(function(err: any): void {
    if (err) {
      throw new Error(err);
    }
  });

const sequelize = new Sequelize(databaseUrl, {
  dialect: 'mysql'
});

defineModels(sequelize);
sequelize.sync({force: !!options.force});

for (const conversationClass of ALL_CONVERSATIONS) {
  let conversation;
  if (conversationClass === Reminder) {
    conversation = new Reminder(sequelize, bot, undefined, undefined, options['reminder-channel'] || undefined);
  } else {
    conversation = createConversation(conversationClass, sequelize, bot);
  }
  conversation.start();
}

redpajama_set_name: RedPajamaGithub


text:
from __future__ import unicode_literals

from alexia.apps.billing.models import Order
from alexia.test import APITestCase

from ..common import format_order

class BillingTest(APITestCase):

    def test_order_unsynchronized_empty(self):
        self.send_and_compare_request('order.unsynchronized', [0], [])

    def test_order_unsynchronized_with_parameter(self):
        # Load data
        self.load_billing_data()
        self.load_scheduling_data()
        self.load_billing_order_data()

        expected_result = [
            format_order(self.data['order1']),
            format_order(self.data['order2']),
        ]

        self.send_and_compare_request('order.unsynchronized', [0], expected_result)

    def test_order_unsynchronized_without_parameter(self):
        # Load data
        self.load_billing_data()
        self.load_scheduling_data()
        self.load_billing_order_data()

        expected_result = [
            format_order(self.data['order1']),
            format_order(self.data['order2']),
        ]

        self.send_and_compare_request('order.unsynchronized', [], expected_result)

    def test_order_unsynchronized_synchronized(self):
        # Load data
        self.load_billing_data()
        self.load_scheduling_data()
        self.load_billing_order_data()

        self.data['order1'].synchronized = True
        self.data['order1'].save()

        expected_result = [
            format_order(self.data['order2']),
        ]

        self.send_and_compare_request('order.unsynchronized', [0], expected_result)

    def test_order_marksynchronized(self):
        # Load data
        self.load_billing_data()
        self.load_scheduling_data()
        self.load_billing_order_data()

        self.send_and_compare_request('order.marksynchronized', [self.data['order1'].id], True)

        self.assertTrue(Order.objects.get(id=self.data['order1'].id).synchronized)

    def test_order_marksynchronized_synchronized(self):
        # Load data
        self.load_billing_data()
        self.load_scheduling_data()
        self.load_billing_order_data()

        self.data['order1'].synchronized = True
        self.data['order1'].save()

        self.send_and_compare_request('order.marksynchronized', [self.data['order1'].id], False)

        self.assertTrue(Order.objects.get(id=self.data['order1'].id).synchronized)

    def test_order_marksynchronized_invalid_order(self):
        # Load data
        self.load_billing_data()
        self.load_scheduling_data()
        self.load_billing_order_data()

        self.send_and_compare_request_error('order.marksynchronized', [self.data['order1'].id*10],
                                            status_code=422,
                                            error_code=-32602,
                                            error_name='InvalidParamsError',
                                            error_message='InvalidParamsError: Order with id not found',
                                            )


text:
layout: default
title : SSH Keys
tagline: Creating and Uploading an SSH key
group: documentation
subnavgroup: documentation
---
{% include JB/setup %}

To use ssh/scp/sftp login to OSIRIS xfer nodes you must use an SSH keypair.

Your ssh key should work to login to the following nodes which have the OSiRIS CephFS mounted at /osiris.  Your COU will have a directory named the same as your COU but in lowercase (/osiris/mycou).

um-xfer01.osris.org

wsu-xfer01.osris.org

msu-xfer01.osris.org

Generating a keypair

If you do not already a key use ssh-keygen to generate one.
Do not leave the passphrase blank.The only exception is if you must use the key in an automated process.  We recommend generating a 2nd key used only for this purpose if that is the case.  You can upload as many keys as you like to OSiRIS.

[user@host ~]$ ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/home/user/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:

Your identification has been saved in /home/user/.ssh/id_rsa.
Your public key has been saved in /home/user/.ssh/id_rsa.pub.

Keep the 'id_rsa' file private and protected.  The contents of id_rsa.pub will be uploaded to OSiRIS.

Uploading public key to OSiRIS

After your OSiRIS enrollment has been approved login to OSiRIS COmanage.  Open your identity using the Person menu at the upper right:

Select Authenticators from the sidebar menu.

Click on Manage under the Actions section of the SSH Key Authenticator.

Click on Add SSH Key in the following page. You can add multiple keys by repeating this process.

On the following screen you can specify an ssh keyfile to upload.  This will be the id_rsa.pub file created in the example.  You will  have to copy this file to your computer if it was created on another machine.  Be sure to only copy and upload the .pub file - the other id_rsa or id_dsa file should remain private.

Once attached to your identity you can login to one of the xfer gateways noted above.  Note that your username can be found under Identifiers on the same 'My OSiRIS Identity' page.

So for this example the user name is 'eben':

ssh eben@um-xfer01.osris.org


text:
import {store} from './Tw2Store';
import {Tw2MotherLode} from './Tw2MotherLode';
import {Tw2LoadingObject} from '../../core/resource/Tw2LoadingObject';
import {Tw2EventEmitter} from '../../core/Tw2EventEmitter';
import {
    Tw2Error,
    ErrHTTPInstance,
    ErrHTTPReadyState,
    ErrHTTPRequestSend,
    ErrHTTPStatus,
    ErrFeatureNotImplemented,
    ErrResourceExtensionUndefined,
    ErrResourceExtensionUnregistered,
    ErrResourcePrefixUndefined,
    ErrResourcePrefixUnregistered
} from '../../core';
import {assignIfExists} from '../util';

/**
 * Resource Manager
 *
 * @property {Tw2MotherLode} motherLode
 * @property {Boolean} systemMirror - Toggles whether {@link Tw2GeometryRes} Index and Buffer data arrays are visible
 * @property {Number} maxPrepareTime
 * @property {Boolean} autoPurgeResources=true - Sets whether resources should be purged automatically
 * @property {Number} purgeTime=30 = Sets how long resources can remain inactive before they are purged
 * @property {Number} activeFrame
 * @property {Number} _prepareBudget
 * @property {Array} _prepareQueue
 * @property {Number} _purgeTime
 * @property {Number} _purgeFrame
 * @property {Number} _purgeFrameLimit
 * @property {Number} _pendingLoads - a count of how many things are pending load
 * @property {Number} _noLoadFrames
 * @class
 */
export class Tw2ResMan extends Tw2EventEmitter
{

    motherLode = new Tw2MotherLode();
    systemMirror = false;
    maxPrepareTime = 0.05;
    autoPurgeResources = true;
    activeFrame = 0;
    purgeTime = 30;
    _prepareBudget = 0;
    _prepareQueue = [];
    _purgeTime = 0;
    _purgeFrame = 0;
    _purgeFrameLimit = 1000;
    _pendingLoads = 0;
    _noLoadFrames = 0;

    /**
     * Sets resource manager options
     * @param {*} [opt]
     */
    Set(opt)
    {
        if (!opt) return;
        assignIfExists(this, opt, ['systemMirror', 'maxPrepareTime', 'autoPurgeResources', 'purgeTime']);
    }

    /**
     * Fires on resource errors
     * - Used when a resource can only be identified by it's path
     * @param {string} path
     * @param {Error} err
     * @returns {Error} err
     */
    OnResError(path, err = new Tw2Error({path}))
    {
        path = Tw2ResMan.NormalizePath(path);
        const res = this.motherLode.Find(path);
        if (res)
        {
            res.OnError(err);
        }
        else
        {
            this.OnResEvent('error', path, {type: 'error', message: err.message, err});
        }
        return err;
    }

    /**
     * Fires on resource events
     * @param {string} eventName - The event's name
     * @param {string} path      - The resource's path
     * @param {*} [log={}]       - The event's log
     */
    OnResEvent(eventName, path, log = {})
    {
        const defaultLog = Tw2ResMan.DefaultLog[eventName.toUpperCase()];
        if (defaultLog)
        {
            log = Object.assign({}, defaultLog, log);
            const eventData = {res: this.motherLode.Find(path), path, log};

            const err = log.err;
            if (err)
            {
                this.motherLode.AddError(path, err);
                eventData.err = err;
                Object.assign(eventData, err.data);
            }

            log.message = log.message.includes(path) ? log.message : log.message += ` "${path}"`;
            this.emit(eventName.toLowerCase(), eventData);
        }
    }

    /**
     * IsLoading
     * @returns {Boolean}
     *
     */
    IsLoading()
    {
        return this._noLoadFrames < 2;
    }

    /**
     * Clears the motherLode {@link Tw2MotherLode}
     */
    Clear()
    {
        this.motherLode.Clear();
    }

    /**
     * Unloads and Clears the motherLode {@link Tw2MotherLode}
     */
    UnloadAndClear()
    {
        this.motherLode.UnloadAndClear();
    }

    /**
     * Internal update function. It is called every frame.
     * @param {Number} dt - deltaTime
     * @returns {Boolean}
     */
    PrepareLoop(dt)
    {
        if (this._prepareQueue.length === 0 && this._pendingLoads === 0)
        {
            if (this._noLoadFrames < 2)
            {
                this._noLoadFrames++;
            }
        }
        else
        {
            this._noLoadFrames = 0;
        }

        this._prepareBudget = this.maxPrepareTime;

        const startTime = Date.now();
        while (this._prepareQueue.length)
        {
            const
                res = this._prepareQueue[0][0],
                data = this._prepareQueue[0][1],
                xml = this._prepareQueue[0][2];

            this._prepareQueue.shift();

            try
            {
                res.Prepare(data, xml);
            }
            catch (err)
            {
                res.OnError(err);
            }

            this._prepareBudget -= (Date.now() - startTime) * 0.001;
            if (this._prepareBudget < 0) break;
        }

        this._purgeTime += dt;

        if (this._purgeTime > 1)
        {
            this.activeFrame += 1;
            this._purgeTime -= Math.floor(this._purgeTime);
            this._purgeFrame += 1;

            if (this._purgeFrame >= 5)
            {
                if (this.autoPurgeResources)
                {
                    this.motherLode.PurgeInactive(this._purgeFrame, this._purgeFrameLimit, this.purgeTime);
                }
            }
        }

        return true;
    }

    /**
     * Gets a resource
     * @param {String} path
     * @returns {Tw2Resource} resource
     */
    GetResource(path)
    {
        let res;
        path = Tw2ResMan.NormalizePath(path);

        // Check if already loaded
        res = this.motherLode.Find(path);
        if (res)
        {
            if (res.IsPurged()) res.Reload();
            return res;
        }

        if (path.indexOf('dynamic:/') === 0)
        {
            this.OnResError(path, new ErrFeatureNotImplemented({feature: 'Dynamic resources'}));
            return null;
        }

        const extension = Tw2ResMan.GetPathExt(path);
        if (extension === null)
        {
            this.OnResError(path, new ErrResourceExtensionUndefined({path}));
            return null;
        }

        const Constructor = store.GetExtension(extension);
        if (!Constructor)
        {
            this.OnResError(path, new ErrResourceExtensionUnregistered({path, extension}));
            return null;
        }

        try
        {
            res = new Constructor();
            res.path = path;
            return Tw2ResMan.LoadResource(this, res);
        }
        catch (err)
        {
            this.OnResError(path, err);
            return null;
        }
    }

    /**
     * Gets a resource object
     * @param {string} path
     * @param {Function} onResolved - Callback fired when the object has loaded
     * @param {Function} onRejected - Callback fired when the object fails to load
     */
    GetObject(path, onResolved, onRejected)
    {
        path = Tw2ResMan.NormalizePath(path);

        // Check if already loaded
        let res = this.motherLode.Find(path);
        if (res)
        {
            res.AddObject(onResolved, onRejected);
            return;
        }

        try
        {
            res = new Tw2LoadingObject();
            res.path = path;
            res.AddObject(onResolved, onRejected);
            Tw2ResMan.LoadResource(this, res);
        }
        catch (err)
        {
            this.OnResError(path, err);
        }
    }

    /**
     * Reloads a resource
     * @param {Tw2Resource} resource
     * @returns {Tw2Resource} resource
     */
    ReloadResource(resource)
    {
        const path = resource.path;

        // Check if already loaded and good
        const res = this.motherLode.Find(path);
        if (res && !res.IsPurged())
        {
            return res;
        }

        try
        {
            return Tw2ResMan.LoadResource(this, resource);
        }
        catch (err)
        {
            this.OnResError(path, err);
            return resource;
        }
    }

    /**
     * Builds a url from a resource path
     * @param {string} path
     * @returns {string}
     */
    BuildUrl(path)
    {
        const prefixIndex = path.indexOf(':/');
        if (prefixIndex === -1)
        {
            throw new ErrResourcePrefixUndefined({path});
        }

        const prefix = path.substr(0, prefixIndex);
        if (prefix === 'http' || prefix === 'https')
        {
            return path;
        }

        const fullPrefix = store.GetPath(prefix);
        if (!fullPrefix)
        {
            throw new ErrResourcePrefixUnregistered({path, prefix});
        }

        return fullPrefix + path.substr(prefixIndex + 2);
    }

    /**
     * Normalizes a file path by making it lower case and replaces all '\\' with '/'
     * @param {string} path
     * @returns {string}
     */
    static NormalizePath(path)
    {
        if (path.substr(0, 5) === 'str:/') return path;
        path = path.toLowerCase();
        path.replace('\\', '/');
        return path;
    }

    /**
     * Gets a path's extension
     * @param {string} path
     * @returns {?string}
     */
    static GetPathExt(path)
    {
        if (path.substr(0, 5) === 'str:/')
        {
            const slash = path.indexOf('/', 5);
            if (slash === -1) return null;
            return path.substr(5, slash - 5);
        }
        else
        {
            const dot = path.lastIndexOf('.');
            if (dot === -1) return null;
            return path.substr(dot + 1);
        }
    }

    /**
     * Loads a resource
     * @param {Tw2ResMan} resMan
     * @param {Tw2Resource|Tw2LoadingObject} res
     * @returns {Tw2Resource|Tw2LoadingObject} res
     */
    static LoadResource(resMan, res)
    {
        const
            path = res.path,
            url = resMan.BuildUrl(path);

        resMan.motherLode.Add(path, res);

        if (res.DoCustomLoad && res.DoCustomLoad(url, Tw2ResMan.GetPathExt(url)))
        {
            return res;
        }

        const httpRequest = Tw2ResMan.CreateHttpRequest(res);
        httpRequest.onreadystatechange = Tw2ResMan.DoLoadResource(resMan, res);
        httpRequest.open('GET', url);

        try
        {
            httpRequest.send();
            resMan._pendingLoads++;
            res.OnRequested();
        }
        catch (err)
        {
            throw new ErrHTTPRequestSend({path});
        }

        return res;
    }

    /**
     * Creates an onreadystatechange callback
     * @param {Tw2ResMan} resMan
     * @param {Tw2Resource} res
     */
    static DoLoadResource(resMan, res)
    {
        const path = res.path;

        return function ()
        {
            let readyState = 0;

            try
            {
                readyState = this.readyState;
            }
            catch (err)
            {
                resMan._pendingLoads--;
                res.OnError(new ErrHTTPReadyState({path}));
                return;
            }

            if (readyState === 4)
            {
                const status = this.status;
                if (status === 200)
                {
                    let data = null,
                        xml = null;

                    try
                    {
                        data = this.responseText;
                        xml = this.responseXML;
                    }
                    catch (e)
                    {
                        data = this.response;
                    }

                    resMan._prepareQueue.push([res, data, xml]);
                    res.OnLoaded();
                }
                else
                {
                    res.OnError(new ErrHTTPStatus({path, status}));
                }
                resMan._pendingLoads--;
            }
        };
    }

    /**
     * Creates an HTTP request
     * @param {Tw2Resource} res
     * @returns {XMLHttpRequest|ActiveXObject}
     */
    static CreateHttpRequest(res)
    {
        let httpRequest = null;

        if (window.XMLHttpRequest)
        {
            // Mozilla, Safari, ...
            httpRequest = new XMLHttpRequest();
        }
        else if (window.ActiveXObject)
        {
            // IE
            try
            {
                httpRequest = new window['ActiveXObject']('Msxml2.XMLHTTP');
            }
            catch (e)
            {
                try
                {
                    httpRequest = new window['ActiveXObject']('Microsoft.XMLHTTP');
                }
                catch (e)
                {
                    /*eslint-disable-line-no-empty*/
                }
            }
        }

        if (!httpRequest)
        {
            throw new ErrHTTPInstance({path: res.path});
        }
        else if (res.requestResponseType)
        {
            httpRequest.responseType = res.requestResponseType;
        }

        return httpRequest;
    }

    // Default log outputs for resource events
    static DefaultLog = {
        ERROR: {type: 'error', message: 'Uncaught error'},
        WARNING: {type: 'warn', message: 'Undefined warning'},
        REQUESTED: {type: 'info', message: 'Requested'},
        RELOADING: {type: 'info', message: 'Reloading'},
        LOADED: {type: 'info', message: 'Loaded'},
        PREPARED: {type: 'log', message: 'Prepared'},
        PURGED: {type: 'info', message: 'Purged'},
        UNLOADED: {type: 'info', message: 'Unloaded'},
        DEBUG: {type:'debug', message: 'Debug'}
    };

    /**
     * Class category
     * @type {string}
     */
    static category = 'resource_manager';

}

// Global instance of Tw2ResMan
export const resMan = new Tw2ResMan();


text:
<?php

namespace Emayk\Ics\Repo\Taxtype;
use Emayk\Ics\Controllers\BaseController as Base;
use \Input;

class TaxtypeController extends Base {
 protected  $taxtype;
    function __construct(TaxtypeInterface $taxtype)
    {
        $this->taxtype = $taxtype;
    }

	/**
	 * Display a listing of the resource.
	 *
	 * @return Response
	 */
	public function index()
	{
		return $this->taxtype->all();
	}

	/**
	 * Show the form for creating a new resource.
	 *
	 * @return Response
	 */
	public function create()
	{
		return $this->taxtype->create();
	}

	/**
	 * Store a newly created resource in storage.
	 *
	 * @return Response
	 */
	public function store()
	{
		return $this->taxtype->store();
	}

	/**
	 * Display the specified resource.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function show($id)
	{
			return $this->taxtype->show($id);
	}

	/**
	 * Show the form for editing the specified resource.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function edit($id)
	{
			return $this->taxtype->edit($id);
	}

	/**
	 * Update the specified resource in storage.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function update($id)
	{
			return $this->taxtype->update($id);
	}

	/**
	 * Remove the specified resource from storage.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function destroy($id)
	{
			return $this->taxtype->destroy($id);
	}

}


text:
package org.batfish.datamodel.questions;

import static com.google.common.base.MoreObjects.firstNonNull;
import static com.google.common.base.Preconditions.checkArgument;
import static org.batfish.datamodel.OriginMechanism.LEARNED;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.base.MoreObjects;
import com.google.common.collect.ImmutableSortedSet;
import java.util.Objects;
import java.util.Set;
import java.util.SortedSet;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.annotation.ParametersAreNonnullByDefault;
import org.batfish.datamodel.AsPath;
import org.batfish.datamodel.Ip;
import org.batfish.datamodel.OriginMechanism;
import org.batfish.datamodel.OriginType;
import org.batfish.datamodel.Prefix;
import org.batfish.datamodel.Route;
import org.batfish.datamodel.RoutingProtocol;
import org.batfish.datamodel.bgp.TunnelEncapsulationAttribute;
import org.batfish.datamodel.bgp.community.Community;

/** A user facing representation for IPv4 BGP route */
@ParametersAreNonnullByDefault
public final class BgpRoute {
  public static final String PROP_AS_PATH = "asPath";
  public static final String PROP_COMMUNITIES = "communities";
  public static final String PROP_LOCAL_PREFERENCE = "localPreference";
  public static final String PROP_METRIC = "metric";
  public static final String PROP_NETWORK = "network";
  public static final String PROP_NEXT_HOP_IP = "nextHopIp";
  public static final String PROP_ORIGINATOR_IP = "originatorIp";
  public static final String PROP_ORIGIN_MECHANISM = "originMechanism";
  public static final String PROP_ORIGIN_TYPE = "originType";
  public static final String PROP_PATH_ID = "pathId";
  public static final String PROP_PROTOCOL = "protocol";
  public static final String PROP_SRC_PROTOCOL = "srcProtocol";
  public static final String PROP_TAG = "tag";
  public static final String PROP_TUNNEL_ENCAPSULATION_ATTRIBUTE = "tunnelEncapsulationAttribute";
  public static final String PROP_WEIGHT = "weight";
  public static final String PROP_CLASS = "class";

  @Nonnull private final AsPath _asPath;
  @Nonnull private final SortedSet<Community> _communities;
  private final long _localPreference;
  private final long _metric;
  @Nonnull private final Prefix _network;
  @Nonnull private final Ip _nextHopIp;
  @Nonnull private final Ip _originatorIp;
  @Nonnull private final OriginMechanism _originMechanism;
  @Nonnull private final OriginType _originType;
  @Nullable private final Integer _pathId;
  @Nonnull private final RoutingProtocol _protocol;
  @Nullable private final RoutingProtocol _srcProtocol;
  private final long _tag;
  @Nullable private final TunnelEncapsulationAttribute _tunnelEncapsulationAttribute;
  private final int _weight;

  private BgpRoute(
      AsPath asPath,
      SortedSet<Community> communities,
      long localPreference,
      long metric,
      Prefix network,
      Ip nextHopIp,
      Ip originatorIp,
      OriginMechanism originMechanism,
      OriginType originType,
      @Nullable Integer pathId,
      RoutingProtocol protocol,
      @Nullable RoutingProtocol srcProtocol,
      long tag,
      @Nullable TunnelEncapsulationAttribute tunnelEncapsulationAttribute,
      int weight) {
    _asPath = asPath;
    _communities = communities;
    _localPreference = localPreference;
    _metric = metric;
    _network = network;
    _nextHopIp = nextHopIp;
    _originatorIp = originatorIp;
    _originMechanism = originMechanism;
    _originType = originType;
    _pathId = pathId;
    _protocol = protocol;
    _srcProtocol = srcProtocol;
    _tag = tag;
    _tunnelEncapsulationAttribute = tunnelEncapsulationAttribute;
    _weight = weight;
  }

  @JsonCreator
  private static BgpRoute jsonCreator(
      @Nullable @JsonProperty(PROP_AS_PATH) AsPath asPath,
      @Nullable @JsonProperty(PROP_COMMUNITIES) SortedSet<Community> communities,
      @JsonProperty(PROP_LOCAL_PREFERENCE) long localPreference,
      @JsonProperty(PROP_METRIC) long metric,
      @Nullable @JsonProperty(PROP_NETWORK) Prefix network,
      @Nullable @JsonProperty(PROP_NEXT_HOP_IP) Ip nextHopIp,
      @Nullable @JsonProperty(PROP_ORIGINATOR_IP) Ip originatorIp,
      @Nullable @JsonProperty(PROP_ORIGIN_MECHANISM) OriginMechanism originMechanism,
      @Nullable @JsonProperty(PROP_ORIGIN_TYPE) OriginType originType,
      @Nullable @JsonProperty(PROP_PATH_ID) Integer pathId,
      @Nullable @JsonProperty(PROP_PROTOCOL) RoutingProtocol protocol,
      @Nullable @JsonProperty(PROP_SRC_PROTOCOL) RoutingProtocol srcProtocol,
      @JsonProperty(PROP_TAG) long tag,
      @Nullable @JsonProperty(PROP_TUNNEL_ENCAPSULATION_ATTRIBUTE)
          TunnelEncapsulationAttribute tunnelEncapsulationAttribute,
      @JsonProperty(PROP_WEIGHT) int weight,
      // For backwards compatibility, does nothing
      @Nullable @JsonProperty(PROP_CLASS) String clazz) {
    checkArgument(network != null, "%s must be specified", PROP_NETWORK);
    checkArgument(originatorIp != null, "%s must be specified", PROP_ORIGINATOR_IP);
    checkArgument(originType != null, "%s must be specified", PROP_ORIGIN_TYPE);
    checkArgument(protocol != null, "%s must be specified", PROP_PROTOCOL);
    return new BgpRoute(
        firstNonNull(asPath, AsPath.empty()),
        firstNonNull(communities, ImmutableSortedSet.of()),
        localPreference,
        metric,
        network,
        firstNonNull(nextHopIp, Route.UNSET_ROUTE_NEXT_HOP_IP),
        originatorIp,
        firstNonNull(originMechanism, LEARNED),
        originType,
        pathId,
        protocol,
        srcProtocol,
        tag,
        tunnelEncapsulationAttribute,
        weight);
  }

  @Nonnull
  @JsonProperty(PROP_AS_PATH)
  public AsPath getAsPath() {
    return _asPath;
  }

  @Nonnull
  @JsonProperty(PROP_COMMUNITIES)
  public SortedSet<Community> getCommunities() {
    return _communities;
  }

  @JsonProperty(PROP_LOCAL_PREFERENCE)
  public long getLocalPreference() {
    return _localPreference;
  }

  @JsonProperty(PROP_METRIC)
  public long getMetric() {
    return _metric;
  }

  @Nonnull
  @JsonProperty(PROP_NETWORK)
  public Prefix getNetwork() {
    return _network;
  }

  /**
   * Returns next hop IP suitable for internal consumption. See {@link #getNextHopIpJson()} for
   * retrieving this field in a manner that is suitable for external deserialization.
   */
  @Nonnull
  @JsonIgnore
  public Ip getNextHopIp() {
    return _nextHopIp;
  }

  /**
   * Returns next hop IP in a manner suitable for deserialization to JSON. See {@link
   * #getNextHopIp()} for retrieving this field in a manner suitable for internal processing.
   */
  @JsonProperty(PROP_NEXT_HOP_IP)
  private @Nullable Ip getNextHopIpJson() {
    return _nextHopIp.equals(Route.UNSET_ROUTE_NEXT_HOP_IP) ? null : _nextHopIp;
  }

  @Nonnull
  @JsonProperty(PROP_ORIGINATOR_IP)
  public Ip getOriginatorIp() {
    return _originatorIp;
  }

  @Nonnull
  @JsonProperty(PROP_ORIGIN_MECHANISM)
  public OriginMechanism getOriginMechanism() {
    return _originMechanism;
  }

  @Nonnull
  @JsonProperty(PROP_ORIGIN_TYPE)
  public OriginType getOriginType() {
    return _originType;
  }

  @Nullable
  @JsonProperty(PROP_PATH_ID)
  public Integer getPathId() {
    return _pathId;
  }

  @Nonnull
  @JsonProperty(PROP_PROTOCOL)
  public RoutingProtocol getProtocol() {
    return _protocol;
  }

  @Nullable
  @JsonProperty(PROP_SRC_PROTOCOL)
  public RoutingProtocol getSrcProtocol() {
    return _srcProtocol;
  }

  @JsonProperty(PROP_TAG)
  public long getTag() {
    return _tag;
  }

  @Nullable
  @JsonProperty(PROP_TUNNEL_ENCAPSULATION_ATTRIBUTE)
  public TunnelEncapsulationAttribute getTunnelEncapsulationAttribute() {
    return _tunnelEncapsulationAttribute;
  }

  @JsonProperty(PROP_WEIGHT)
  public int getWeight() {
    return _weight;
  }

  @Override
  public boolean equals(Object o) {
    if (this == o) {
      return true;
    }
    if (!(o instanceof BgpRoute)) {
      return false;
    }
    BgpRoute bgpRoute = (BgpRoute) o;
    return _localPreference == bgpRoute._localPreference
        && _metric == bgpRoute._metric
        && _tag == bgpRoute._tag
        && _weight == bgpRoute._weight
        && Objects.equals(_asPath, bgpRoute._asPath)
        && Objects.equals(_communities, bgpRoute._communities)
        && Objects.equals(_network, bgpRoute._network)
        && Objects.equals(_nextHopIp, bgpRoute._nextHopIp)
        && Objects.equals(_originatorIp, bgpRoute._originatorIp)
        && _originMechanism == bgpRoute._originMechanism
        && _originType == bgpRoute._originType
        && Objects.equals(_pathId, bgpRoute._pathId)
        && _protocol == bgpRoute._protocol
        && _srcProtocol == bgpRoute._srcProtocol
        && Objects.equals(_tunnelEncapsulationAttribute, bgpRoute._tunnelEncapsulationAttribute);
  }

  @Override
  public int hashCode() {
    return Objects.hash(
        _asPath,
        _communities,
        _localPreference,
        _metric,
        _network,
        _nextHopIp,
        _originatorIp,
        _originMechanism.ordinal(),
        _originType.ordinal(),
        _pathId,
        _protocol.ordinal(),
        _srcProtocol != null ? _srcProtocol.ordinal() : null,
        _tag,
        _tunnelEncapsulationAttribute,
        _weight);
  }

  public static Builder builder() {
    return new Builder();
  }

  public Builder toBuilder() {
    return builder()
        .setAsPath(_asPath)
        .setCommunities(_communities)
        .setLocalPreference(_localPreference)
        .setMetric(_metric)
        .setNetwork(_network)
        .setNextHopIp(_nextHopIp)
        .setOriginatorIp(_originatorIp)
        .setOriginMechanism(_originMechanism)
        .setOriginType(_originType)
        .setPathId(_pathId)
        .setProtocol(_protocol)
        .setSrcProtocol(_srcProtocol)
        .setTag(_tag)
        .setTunnelEncapsulationAttribute(_tunnelEncapsulationAttribute)
        .setWeight(_weight);
  }

  /** Builder for {@link BgpRoute} */
  @ParametersAreNonnullByDefault
  public static final class Builder {

    @Nonnull private AsPath _asPath;
    @Nonnull private SortedSet<Community> _communities;
    private long _localPreference;
    private long _metric;
    @Nullable private Prefix _network;
    @Nullable private Ip _nextHopIp;
    @Nullable private Ip _originatorIp;
    @Nullable private OriginMechanism _originMechanism;
    @Nullable private OriginType _originType;
    @Nullable private Integer _pathId;
    @Nullable private RoutingProtocol _protocol;
    @Nullable private RoutingProtocol _srcProtocol;
    private long _tag;
    @Nullable private TunnelEncapsulationAttribute _tunnelEncapsulationAttribute;
    private int _weight;

    public Builder() {
      _asPath = AsPath.empty();
      _communities = ImmutableSortedSet.of();
      _nextHopIp = Route.UNSET_ROUTE_NEXT_HOP_IP;
    }

    public BgpRoute build() {
      checkArgument(_network != null, "%s must be specified", PROP_NETWORK);
      checkArgument(_nextHopIp != null, "%s must be specified", PROP_NEXT_HOP_IP);
      checkArgument(_originatorIp != null, "%s must be specified", PROP_ORIGINATOR_IP);
      checkArgument(_originType != null, "%s must be specified", PROP_ORIGIN_TYPE);
      checkArgument(_protocol != null, "%s must be specified", PROP_PROTOCOL);
      return new BgpRoute(
          _asPath,
          _communities,
          _localPreference,
          _metric,
          _network,
          _nextHopIp,
          _originatorIp,
          firstNonNull(_originMechanism, LEARNED),
          _originType,
          _pathId,
          _protocol,
          _srcProtocol,
          _tag,
          _tunnelEncapsulationAttribute,
          _weight);
    }

    public Builder setAsPath(AsPath asPath) {
      _asPath = asPath;
      return this;
    }

    public Builder setCommunities(Set<Community> communities) {
      _communities = ImmutableSortedSet.copyOf(communities);
      return this;
    }

    public Builder setLocalPreference(long localPreference) {
      _localPreference = localPreference;
      return this;
    }

    public Builder setMetric(long metric) {
      _metric = metric;
      return this;
    }

    public Builder setNetwork(Prefix network) {
      _network = network;
      return this;
    }

    public Builder setNextHopIp(Ip nextHopIp) {
      _nextHopIp = nextHopIp;
      return this;
    }

    public Builder setOriginatorIp(Ip originatorIp) {
      _originatorIp = originatorIp;
      return this;
    }

    public Builder setOriginMechanism(OriginMechanism originMechanism) {
      _originMechanism = originMechanism;
      return this;
    }

    public Builder setOriginType(OriginType originType) {
      _originType = originType;
      return this;
    }

    public Builder setPathId(@Nullable Integer pathId) {
      _pathId = pathId;
      return this;
    }

    public Builder setProtocol(RoutingProtocol protocol) {
      _protocol = protocol;
      return this;
    }

    public Builder setSrcProtocol(@Nullable RoutingProtocol srcProtocol) {
      _srcProtocol = srcProtocol;
      return this;
    }

    public Builder setTag(long tag) {
      _tag = tag;
      return this;
    }

    public Builder setTunnelEncapsulationAttribute(
        @Nullable TunnelEncapsulationAttribute tunnelEncapsulationAttribute) {
      _tunnelEncapsulationAttribute = tunnelEncapsulationAttribute;
      return this;
    }

    public Builder setWeight(int weight) {
      _weight = weight;
      return this;
    }
  }

  @Override
  public String toString() {
    return MoreObjects.toStringHelper(this)
        .omitNullValues()
        .add("network", _network)
        .add("metric", _metric)
        .add("asPath", _asPath)
        .add("communities", _communities)
        .add("localPreference", _localPreference)
        .add("nextHopIp", _nextHopIp)
        .add("originatorIp", _originatorIp)
        .add("originMechanism", _originMechanism)
        .add("originType", _originType)
        .add("pathId", _pathId)
        .add("protocol", _protocol)
        .add("srcProtocol", _srcProtocol)
        .add("tag", _tag)
        .add("tunnelEncapsulationAttribute", _tunnelEncapsulationAttribute)
        .add("weight", _weight)
        .toString();
  }
}


text:
'use strict'
import {is, List} from 'immutable'
import test from 'ava'

import {default as commits} from '../../src/reducers/commits'

test('default value of commits is empty List', t => {
  t.true(is(commits(), List()))
})

test('SET_COMMITS sets commits', t => {
  const state =
    List.of('commit1', 'commit2')
  const action =
    { type: 'SET_COMMITS'
    , commits:
      [ 'commit3'
      , 'commit4'
      ]
    }

  const nextState = commits(state, action)

  t.true(is(nextState, List.of('commit3', 'commit4')))
})


text:
+  手机内存资源有限,一个应用最少可能只有16MB的内存
+  使用Bitmap显示图片,如果不压缩,很可能一个图片就会占用十几MB的内存
+  ListView, GridView, ViewPager这种View,可能显示在屏幕上的只有几个图片,但是还有很多是没有显示在屏幕上的,如果没有显示在屏幕上的也占用着内存,那将很快导致OOM
+  在解码/载入图片到内存(Bitmap对象)之前,要先判断一下图片的尺寸,获取图片的尺寸和类型:

  ```java
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeResource(getResources(), R.id.myimage, options);
    int imageHeight = options.outHeight;
    int imageWidth = options.outWidth;
    String imageType = options.outMimeType;
  ```

  设置`options.inJustDecodeBounds = true`,将只读取文件信息,不会为图片分配内存

+  载入和屏幕尺寸适配的图片尺寸,否则空占内存却没有视觉效果的提升,需要考虑以下因素:
  +  预计完全载入图片所需的内存大小
  +  预期为加载此图片愿意分配的内存
  +  用来显示该图片的View的尺寸
  +  当前设备的屏幕尺寸和像素密度

    ```java
        public static int calculateInSampleSize(
                    BitmapFactory.Options options, int reqWidth, int reqHeight) {
            // Raw height and width of image
            final int height = options.outHeight;
            final int width = options.outWidth;
            int inSampleSize = 1;

            if (height > reqHeight || width > reqWidth) {

                final int halfHeight = height / 2;
                final int halfWidth = width / 2;

                // Calculate the largest inSampleSize value that is a power of 2 and keeps both
                // height and width larger than the requested height and width.
                while ((halfHeight / inSampleSize) > reqHeight
                        && (halfWidth / inSampleSize) > reqWidth) {
                    inSampleSize *= 2;
                }
            }

            return inSampleSize;
        }

        public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId,
                int reqWidth, int reqHeight) {

            // First decode with inJustDecodeBounds=true to check dimensions
            final BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeResource(res, resId, options);

            // Calculate inSampleSize
            options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

            // Decode bitmap with inSampleSize set
            options.inJustDecodeBounds = false;
            return BitmapFactory.decodeResource(res, resId, options);
        }

        ...
        mImageView.setImageBitmap(
            decodeSampledBitmapFromResource(getResources(), R.id.myimage, 100, 100));
        ...
    ```

+  加载、处理图片要在非UI线程执行,使用rx可以方便地做到这一点
+  缓存Bitmap
  +  内存缓存:LruCache,放入cache的要用SoftReference或者WeakReference,以免放入缓存的数据未被按时移出缓存,导致内存泄漏
  +  磁盘缓存:DiskLruCache,;当要缓存的数据经常被访问时,使用ContentProvider会更合适
  +  响应Configuration change:使用headless fragment,是实现方式之一
+  管理bitmap内存
  +  API <= 10:当确定bitmap不会被使用之后,调用bitmap.recycle()
  +  API >= 11:`BitmapFactory.Options.inBitmap`,会使得bitmap mutable,不太建议使用
+  显示bitmap,将资源加载到内存的过程要在非UI线程执行,避免程序未响应

##  Displaying Graphics with OpenGL ES
+  Transitions Framework原生API支持,需要API >= 19, [Animations backported to Android 4.0+. API compatible with Android 2.2+](https://github.com/andkulikov/Transitions-Everywhere)
+  The Transitions Framework
  +  动效的意义:帮助用户理解app的行为,理解视觉变化的意义
  +  包含的功能
    +  Group-level animations:可以应用于整个View hierarchy
    +  Transition-based animation:基于property animation
    +  Built-in animations:内置了很多动效实现
    +  Resource file support:支持在xml中定义动效
    +  Lifecycle callbacks:具备生命周期回调,便于响应动效状态进行逻辑操作
  +  原理

  ![transitions_diagram.png](../assets/transitions_diagram.png)

    +  Scene
      +  记录View hierarchy的状态
      +  支持从xml创建/从ViewGroup对象创建
      +  通常不需要显式指定开始的Scene,默认是前一个ending Scene,或者当前屏幕上显示的view hierarchy
      +  Scene的转化都发生在同一个Scene root中
  +  Transition
      +  在动效框架中,通过把scene的变化转化为一系列的关键帧,动画的信息保存在Transition对象中,通过TransitionManager来播放动画
      +  可以为两个Scene创建动画,也可以为当前Scene的不同状态创建动画
      +  内部实现了常用的动效:fading, resizing...
  +  Limitations
      +  对SurfaceView应用动效可能不会正常显示,SurfaceView在非UI线程进行更新
      +  有些动效可能对TextureView无效
      +  对AdapterView(例如ListView)使用动效,可能会导致界面卡住
      +  对TextView使用resize动效时,文字可能会在动效完成之前先"弹"出去,所以避免对有文字的view使用resize动效
+  Creating a Scene
  +  从xml创建

    scene root

    ```xml
        <FrameLayout
            android:id="@+id/scene_root">
            <include layout="@layout/a_scene" />
        </FrameLayout>
    ```

    starting scene

    ```xml
        <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@+id/scene_container"
            android:orientation="vertical"
            android:layout_width="match_parent"
            android:layout_height="match_parent" >
            <TextView
                android:id="@+id/text_view1
                android:text="Text Line 1" />
            <TextView
                android:id="@+id/text_view2
                android:text="Text Line 2" />
        </LinearLayout>
    ```

    ending scene

    ```xml
        <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@+id/scene_container"
            android:orientation="vertical"
            android:layout_width="match_parent"
            android:layout_height="match_parent" >
            <TextView
                android:id="@+id/text_view2
                android:text="Text Line 2" />
            <TextView
                android:id="@+id/text_view1
                android:text="Text Line 1" />
        </LinearLayout>
    ```

    创建scene

    ```java
        Scene mAScene;
        Scene mAnotherScene;

        // Create the scene root for the scenes in this app
        mSceneRoot = (ViewGroup) findViewById(R.id.scene_root);

        // Create the scenes
        mAScene = Scene.getSceneForLayout(mSceneRoot, R.layout.a_scene, this);
        mAnotherScene =
            Scene.getSceneForLayout(mSceneRoot, R.layout.another_scene, this);
    ```

  +  代码创建

    ```java
        Scene mScene;

        // Obtain the scene root element
        mSceneRoot = (ViewGroup) mSomeLayoutElement;

        // Obtain the view hierarchy to add as a child of
        // the scene root when this scene is entered
        mViewHierarchy = (ViewGroup) someOtherLayoutElement;

        // Create a scene
        mScene = new Scene(mSceneRoot, mViewHierarchy);
    ```

  +  Create Scene Actions
      +  当涉及的View不在同一个view hierarchy中时,可以通过创建scene action来辅助实现动效
      +  动效框架无法自动创建scene action时,可以手动创建,例如ListView
      +  把要执行的操作封装到Runnable中,设置给`Scene.setExitAction()`和`Scene.setEnterAction()`
      +  注意:不要在scene action中传递数据
+  应用动效
  +  内置动效
      +  AutoTransition/<autoTransition/>:Default transition. Fade out, move and resize, and fade in views, in that order.
      +  Fade/<fade/>:fade_in fades in views; fade_out fades out views; fade_in_out (default) does a fade_out followed by a fade_in.
      +  ChangeBounds/<changeBounds/>:Moves and resizes views.
  +  从xml创建

    res/transition/fade_transition.xml

    ```xml
        <fade xmlns:android="http://schemas.android.com/apk/res/android" />
    ```

    inflate

    ```java
        Transition mFadeTransition =
                TransitionInflater.from(this).
                inflateTransition(R.transition.fade_transition);
    ```

  +  代码创建:`Transition mFadeTransition = new Fade();`
  +  应用动效:`TransitionManager.go(mEndingScene, mFadeTransition);`
  +  支持只对view hierarchy中的部分view应用动效:`removeTarget()`,`addTarget()`
  +  同时使用多种效果:TransitionSet

    在res/transitions/目录下创建资源文件

    ```xml
        <transitionSet xmlns:android="http://schemas.android.com/apk/res/android"
            android:transitionOrdering="sequential">
            <fade android:fadingMode="fade_out" />
            <changeBounds />
            <fade android:fadingMode="fade_in" />
        </transitionSet>
    ```

  +  不使用Scene而直接应用动效
      +  通过removeView/addView来改变view hierarchy, 并使用delayed transition
      +  改变view hierarchy之前调用TransitionManager.beginDelayedTransition()
      +  修改view:增/减/改
  +  实现TransitionListener以在动效生命周期回调中执行操作
+  自定义Transition
  +  继承Transition类

    ```java
        public class CustomTransition extends Transition {

            @Override
            public void captureStartValues(TransitionValues values) {}

            @Override
            public void captureEndValues(TransitionValues values) {}

            @Override
            public Animator createAnimator(ViewGroup sceneRoot,
                                        TransitionValues startValues,
                                        TransitionValues endValues) {}
        }
    ```

  +  Capture View Property Values
    +  `captureStartValues`

    scene中的每个view都会调用一遍,TransitionValues包含view对象,和一个map,用于记录view对象的各个感兴趣的属性值

    ```java
    public class CustomTransition extends Transition {

        // Define a key for storing a property value in
        // TransitionValues.values with the syntax
        // package_name:transition_class:property_name to avoid collisions
        private static final String PROPNAME_BACKGROUND =
            "com.example.android.customtransition:CustomTransition:background";

        @Override
        public void captureStartValues(TransitionValues transitionValues) {
            // Call the convenience method captureValues
            captureValues(transitionValues);
        }

        // For the view in transitionValues.view, get the values you
        // want and put them in transitionValues.values
        private void captureValues(TransitionValues transitionValues) {
            // Get a reference to the view
            View view = transitionValues.view;
            // Store its background property in the values map
            transitionValues.values.put(PROPNAME_BACKGROUND, view.getBackground());
        }
        ...
    }
    ```

    +  `captureEndValues`和`captureStartValues`类似

    ```java
    @Override
    public void captureEndValues(TransitionValues transitionValues) {
        captureValues(transitionValues);
    }
    ```

  +  `createAnimator`,transition framework调用此函数的次数与scene的变化有关
    +  例如5个view,变化后有2个被移除,1个新加入,则会调用6次:3个保持存在,2个移除,1个加入;
    +  保持存在的view,调用时两个TransitionValues都不为null,而只存在于一个状态的,另一个状态对应的TransitionValues参数为null;
    +  最终利用两个TransitionValues参数,返回一个property animator

##  Adding Animations
+  交叉隐现
  +  `View.animate()`方法返回`ViewPropertyAnimator`对象,对其可以进行各种property animation
+  `ViewPager`的使用
  +  通常结合`Fragment`使用
  +  和`ListView`类似,`ViewPager`也需要一个Adapter,`FragmentStatePagerAdapter`的实现类
  +  [ViewPagerIndicator](https://github.com/JakeWharton/ViewPagerIndicator)
  +  实现`ViewPager.PageTransformer`接口,通过其`transformPage`函数自定义page切换动效
    +  `position`参数表示当前page的位置
    +  小于0表示位于屏幕中心点左侧
    +  小于-1表示完全移出了屏幕
    +  大于0表示位于屏幕中心点右侧
    +  大于1表示完全移出了屏幕
  +  [ViewPagerTransforms](https://github.com/ToxicBakery/ViewPagerTransforms), [VerticalViewPager](https://github.com/kaelaela/VerticalViewPager)
+  Displaying Card Flip Animations
  +  为FragmentTransition设置过场动效:`setCustomAnimations`,注意:这个函数的调用顺序很重要,一定在`add`, `replace`等操作之前。
+  Zooming a View
  +  示例演示了组合使用`ObjectAnimator`来实现缩略图放大到大图的动画效果,以及反向效果。
+  Animating Layout Changes
  +  使用`setLayoutTransition()`设置自定义layout变化动效
  +  新的`Scene`框架也可以做这个事情
  +  back-port的transition everywhere库也有相应接口:`TransitionManager.beginDelayedTransition(ViewGroup)`
+  更多,[安卓系统动效专题](AndroidAnimation.md)


text:
using NeuroSpeech.UIAtoms;
using System;
using System.Collections.Generic;
using System.Text;

namespace UIAtomsDemo.RestServices.Models
{
    public class Movie: AtomModel
    {

        #region Property Title

        private string _Title = null;

        public string Title
        {
            get
            {
                return _Title;
            }
            set
            {
                SetProperty(ref _Title, value);
            }
        }
        #endregion

        #region Property Category

        private string _Category = null;

        public string Category
        {
            get
            {
                return _Category;
            }
            set
            {
                SetProperty(ref _Category, value);
            }
        }
        #endregion

    }
}


text:
FROM ros:noetic-ros-base-buster

# install ros packages
RUN apt-get update && apt-get install -y --no-install-recommends \
    ros-noetic-robot=1.5.0-1* \
    && rm -rf /var/lib/apt/lists/*


text:
package org.apache.commons.lang3.arch;

/**
 * The {@link Processor} represents a microprocessor and defines
 * some properties like architecture and type of the microprocessor.
 *
 * @since 3.6
 */
public class Processor {

    /**
     * The {@link Arch} enum defines the architecture of
     * a microprocessor. The architecture represents the bit value
     * of the microprocessor.
     * The following architectures are defined:
     *

     *
32-bit

     *
64-bit

     *
Unknown

     *

     */
    public enum Arch {

        /**
         * A 32-bit processor architecture.
         */
        BIT_32("32-bit"),

        /**
         * A 64-bit processor architecture.
         */
        BIT_64("64-bit"),

        /**
         * An unknown-bit processor architecture.
         */
        UNKNOWN("Unknown");

        /**
         * A label suitable for display.
         */
        private final String label;

        Arch(final String label) {
            this.label = label;
        }

        /**
         * Gets the label suitable for display.
         *
         * @return the label.
         */
        public String getLabel() {
            return label;
        }
    }

    /**
     * The {@link Type} enum defines types of a microprocessor.
     * The following types are defined:
     *

     *
AArch64

     *
x86

     *
ia64

     *
PPC

     *
Unknown

     *

     */
    public enum Type {

        /**
         * ARM 64-bit.
         *
         * @since 3.13.0
         */
        AARCH_64("AArch64"),

        /**
         * Intel x86 series of instruction set architectures.
         */
        X86("x86"),

        /**
         * Intel Itanium 64-bit architecture.
         */
        IA_64("IA-64"),

        /**
         * Apple–IBM–Motorola PowerPC architecture.
         */
        PPC("PPC"),

        /**
         * Unknown architecture.
         */
        UNKNOWN("Unknown");

        /**
         * A label suitable for display.
         */
        private final String label;

        Type(final String label) {
            this.label = label;
        }

        /**
         * Gets the label suitable for display.
         *
         * @return the label.
         * @since 3.13.0
         */
        public String getLabel() {
            return label;
        }

    }

    private final Arch arch;
    private final Type type;

    /**
     * Constructs a {@link Processor} object with the given
     * parameters.
     *
     * @param arch The processor architecture.
     * @param type The processor type.
     */
    public Processor(final Arch arch, final Type type) {
        this.arch = arch;
        this.type = type;
    }

    /**
     * Gets the processor architecture as an {@link Arch} enum.
     * The processor architecture defines, if the processor has
     * a 32 or 64 bit architecture.
     *
     * @return A {@link Arch} enum.
     */
    public Arch getArch() {
        return arch;
    }

    /**
     * Gets the processor type as {@link Type} enum.
     * The processor type defines, if the processor is for example
     * an x86 or PPA.
     *
     * @return A {@link Type} enum.
     */
    public Type getType() {
        return type;
    }

    /**
     * Tests if {@link Processor} is 32 bit.
     *
     * @return {@code true}, if {@link Processor} is {@link Arch#BIT_32}, else {@code false}.
     */
    public boolean is32Bit() {
        return Arch.BIT_32 == arch;
    }

    /**
     * Tests if {@link Processor} is 64 bit.
     *
     * @return {@code true}, if {@link Processor} is {@link Arch#BIT_64}, else {@code false}.
     */
    public boolean is64Bit() {
        return Arch.BIT_64 == arch;
    }

    /**
     * Tests if {@link Processor} is type of Aarch64.
     *
     * @return {@code true}, if {@link Processor} is {@link Type#X86}, else {@code false}.
     *
     * @since 3.13.0
     */
    public boolean isAarch64() {
        return Type.AARCH_64 == type;
    }

    /**
     * Tests if {@link Processor} is type of Intel Itanium.
     *
     * @return {@code true}. if {@link Processor} is {@link Type#IA_64}, else {@code false}.
     */
    public boolean isIA64() {
        return Type.IA_64 == type;
    }

    /**
     * Tests if {@link Processor} is type of Power PC.
     *
     * @return {@code true}. if {@link Processor} is {@link Type#PPC}, else {@code false}.
     */
    public boolean isPPC() {
        return Type.PPC == type;
    }

    /**
     * Tests if {@link Processor} is type of x86.
     *
     * @return {@code true}, if {@link Processor} is {@link Type#X86}, else {@code false}.
     */
    public boolean isX86() {
        return Type.X86 == type;
    }

    @Override
    public String toString() {
        final StringBuilder builder = new StringBuilder();
        builder.append(type.getLabel()).append(' ').append(arch.getLabel());
        return builder.toString();
    }

}


text:
from xml.sax.handler import ContentHandler,EntityResolver
from ValueTypeParameters import ValueTypeParameters
from TemplateAssetParameters import TemplateAssetParameters
from Borg import Borg

def a2i(spLabel):
  if spLabel == 'Low':
    return 1
  elif spLabel == 'Medium':
    return 2
  elif spLabel == 'High':
    return 3
  else:
    return 0

def it2Id(itLabel):
  if itLabel == 'required':
    return 1
  else:
    return 0

class TemplateAssetsContentHandler(ContentHandler,EntityResolver):
  def __init__(self):
    self.theValueTypes = []
    self.theAssets = []
    self.resetAssetAttributes()
    self.resetSecurityPropertyAttributes()
    b = Borg()
    self.configDir = b.configDir

  def assets(self):
    return self.theAssets

  def valueTypes(self):
    return self.theValueTypes

  def resolveEntity(self,publicId,systemId):
    return self.configDir + '/template_assets.dtd'

  def resetValueTypeAttributes(self):
    self.inDescription = 0
    self.inRationale = 0
    self.theName = ''
    self.theDescription = ''
    self.theRationale = ''
    self.theScore = 0

  def resetAssetAttributes(self):
    self.inDescription = 0
    self.inSignificance = 0
    self.theName = ''
    self.theShortCode = ''
    self.theAssetType = ''
    self.theSurfaceType = ''
    self.theAccessRight = ''
    self.theDescription = ''
    self.theSignificance = ''
    self.theTags = []
    self.theInterfaces = []
    self.theSecurityProperties = []

  def resetSecurityPropertyAttributes(self):
    self.thePropertyName = ''
    self.thePropertyValue = 'None'
    self.inRationale = 0
    self.theRationale = ''

  def startElement(self,name,attrs):
    if (name == 'description'):
      self.inDescription = 1
      self.theDescription = ''
    elif (name == 'fit_criterion'):
      self.inFitCriterion = 1
      self.theFitCriterion = ''
    elif name == 'significance':
      self.inSignificance = 1
      self.theSignificance = ''
    elif name == 'rationale':
      self.inRationale = 1
      self.theRationale = ''
    elif name == 'interface':
      self.theInterfaces.append((attrs['name'],it2Id(attrs['type']),attrs['access_right'],attrs['privilege']))
    elif name == 'asset':
      self.theName = attrs['name']
      self.theShortCode = attrs['short_code']
      self.theAssetType = attrs['type']
      self.theSurfaceType = attrs['surface_type']
      self.theAccessRight = attrs['access_right']
      self.theSecurityProperties = []
    elif name == 'tag':
      self.theTags.append(attrs['name'])
    elif name == 'security_property':
      self.thePropertyName = attrs['property']
      self.thePropertyValue = attrs['value']
    elif name == 'access_right' or name == 'surface_type':
      self.theName = attrs['name']
      self.theScore = int(attrs['value'])

  def characters(self,data):
    if self.inDescription:
      self.theDescription += data
    elif self.inSignificance:
      self.theSignificance += data
    elif self.inRationale:
      self.theRationale += data

  def endElement(self,name):
    if name == 'asset':
      spDict = {}
      spDict['confidentiality'] = (0,'None')
      spDict['integrity'] = (0,'None')
      spDict['availability'] = (0,'None')
      spDict['accountability'] = (0,'None')
      spDict['anonymity'] = (0,'None')
      spDict['pseudonymity'] = (0,'None')
      spDict['unlinkability'] = (0,'None')
      spDict['unobservability'] = (0,'None')
      for sp in self.theSecurityProperties:
        spName = sp[0]
        spValue = a2i(sp[1])
        spRationale = sp[2]
        if spName in spDict:
          spDict[spName] = (spValue,spRationale)
      spValues = []
      spValues.append(spDict['confidentiality'])
      spValues.append(spDict['integrity'])
      spValues.append(spDict['availability'])
      spValues.append(spDict['accountability'])
      spValues.append(spDict['anonymity'])
      spValues.append(spDict['pseudonymity'])
      spValues.append(spDict['unlinkability'])
      spValues.append(spDict['unobservability'])
      p = TemplateAssetParameters(self.theName,self.theShortCode,self.theDescription,self.theSignificance,self.theAssetType,self.theSurfaceType,self.theAccessRight,spValues,self.theTags,self.theInterfaces)
      self.theAssets.append(p)
      self.resetAssetAttributes()
    elif name == 'security_property':
      self.theSecurityProperties.append((self.thePropertyName,self.thePropertyValue,self.theRationale))
      self.resetSecurityPropertyAttributes()
    elif name == 'description':
      self.inDescription = 0
    elif name == 'rationale':
      self.inRationale = 0
    elif name == 'significance':
      self.inSignificance = 0
    elif name == 'access_right' or name == 'surface_type':
      p = ValueTypeParameters(self.theName,self.theDescription,name,'',self.theScore,self.theRationale)
      self.theValueTypes.append(p)
      self.resetValueTypeAttributes()


text:
package io.fouad.jtb.core.beans;

/**
 * This class represents a chat identifier, either by its ID or by its @username.
 */
public class ChatIdentifier
{
	private final Long id;
	private final String username;

	private ChatIdentifier(Long id, String username)
	{
		this.id = id;
		this.username = username;
	}

	public static ChatIdentifier byId(long id)
	{
		return new ChatIdentifier(id, null);
	}

	public static ChatIdentifier byUsername(String username)
	{
		return new ChatIdentifier(null, username);
	}

	public Long getId(){return id;}
	public String getUsername(){return username;}

	public String getIdentifier()
	{
		if(id != null) return String.valueOf(id);
		else return username;
	}

	@Override
	public boolean equals(Object o)
	{
		if(this == o) return true;
		if(o == null || getClass() != o.getClass()) return false;

		ChatIdentifier that = (ChatIdentifier) o;

		if(id != null ? !id.equals(that.id) : that.id != null) return false;
		return username != null ? username.equals(that.username) : that.username == null;

	}

	@Override
	public int hashCode()
	{
		int result = id != null ? id.hashCode() : 0;
		result = 31 * result + (username != null ? username.hashCode() : 0);
		return result;
	}

	@Override
	public String toString()
	{
		return "ChatIdentifier{" +
				"id=" + id +
				", username='" + username + '\'' +
				'}';
	}
}


text:
import React from 'react';
import PureComponent from 'react-pure-render/component';

import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { ActionCreators } from '../actions';

const { initMap } = ActionCreators;

export class MapCanvas extends PureComponent {
  constructor(props) {
    super(props);
  }

  render () {
    return (

Map Canvas

    );
  }
}

function mapDispatchToProps(dispatch) {
  return bindActionCreators({ initMap }, dispatch);
}

export default connect(undefined, mapDispatchToProps)(MapCanvas);


text:
package mysql

import (
	"encoding/json"

	"github.com/ergochat/ergo/irc/history"
	"github.com/ergochat/ergo/irc/utils"
)

// 123 / '{' is the magic number that means JSON;
// if we want to do a binary encoding later, we just have to add different magic version numbers

func marshalItem(item *history.Item) (result []byte, err error) {
	return json.Marshal(item)
}

func unmarshalItem(data []byte, result *history.Item) (err error) {
	return json.Unmarshal(data, result)
}

func decodeMsgid(msgid string) ([]byte, error) {
	return utils.B32Encoder.DecodeString(msgid)
}