text:
package org.xdi.oxauth.ws.rs;

import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
import org.xdi.oxauth.BaseTest;
import org.xdi.oxauth.client.*;
import org.xdi.oxauth.model.common.*;
import org.xdi.oxauth.model.crypto.OxAuthCryptoProvider;
import org.xdi.oxauth.model.register.ApplicationType;
import org.xdi.oxauth.model.util.StringUtils;

import java.util.Arrays;
import java.util.List;
import java.util.UUID;

import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;

/**
 * @author Javier Rojas Blum
 * @version July 19, 2017
 */
public class UserAuthenticationFilterHttpTest extends BaseTest {

    @Parameters({"redirectUris", "userInum", "userEmail", "sectorIdentifierUri"})
    @Test
    public void requestAccessTokenCustomAuth1(
            final String redirectUris, final String userInum, final String userEmail, final String sectorIdentifierUri) throws Exception {
        showTitle("requestAccessTokenCustomAuth1");

        List<GrantType> grantTypes = Arrays.asList(
                GrantType.RESOURCE_OWNER_PASSWORD_CREDENTIALS
        );

        RegisterRequest registerRequest = new RegisterRequest(ApplicationType.WEB, "oxAuth test app",
                StringUtils.spaceSeparatedToList(redirectUris));
        registerRequest.setTokenEndpointAuthMethod(AuthenticationMethod.CLIENT_SECRET_POST);
        registerRequest.setSectorIdentifierUri(sectorIdentifierUri);
        registerRequest.setGrantTypes(grantTypes);

        RegisterClient registerClient = new RegisterClient(registrationEndpoint);
        registerClient.setRequest(registerRequest);
        RegisterResponse registerResponse = registerClient.exec();

        showClient(registerClient);
        assertEquals(registerResponse.getStatus(), 200, "Unexpected response code: " + registerResponse.getEntity());
        assertNotNull(registerResponse.getClientId());
        assertNotNull(registerResponse.getClientSecret());
        assertNotNull(registerResponse.getRegistrationAccessToken());
        assertNotNull(registerResponse.getClientIdIssuedAt());
        assertNotNull(registerResponse.getClientSecretExpiresAt());

        String clientId = registerResponse.getClientId();
        String clientSecret = registerResponse.getClientSecret();

        TokenRequest tokenRequest = new TokenRequest(GrantType.RESOURCE_OWNER_PASSWORD_CREDENTIALS);
        tokenRequest.setScope("openid");
        tokenRequest.setAuthUsername(clientId);
        tokenRequest.setAuthPassword(clientSecret);
        tokenRequest.addCustomParameter("mail", userEmail);
        tokenRequest.addCustomParameter("inum", userInum);
        tokenRequest.setAuthenticationMethod(AuthenticationMethod.CLIENT_SECRET_POST);

        TokenClient tokenClient = new TokenClient(tokenEndpoint);
        tokenClient.setRequest(tokenRequest);
        TokenResponse response1 = tokenClient.exec();

        showClient(tokenClient);
        assertEquals(response1.getStatus(), 200, "Unexpected response code: " + response1.getStatus());
        assertNotNull(response1.getEntity(), "The entity is null");
        assertNotNull(response1.getAccessToken(), "The access token is null");
        assertNotNull(response1.getTokenType(), "The token type is null");
        assertNotNull(response1.getRefreshToken(), "The refresh token is null");
        assertNotNull(response1.getScope(), "The scope is null");
        assertNotNull(response1.getIdToken(), "The id token is null");
    }

    @Parameters({"redirectUris", "userId", "userSecret", "sectorIdentifierUri"})
    @Test
    public void requestAccessTokenCustomAuth2(
            final String redirectUris, final String userId, final String userSecret, final String sectorIdentifierUri) throws Exception {
        showTitle("requestAccessTokenCustomAuth2");

        List<GrantType> grantTypes = Arrays.asList(
                GrantType.RESOURCE_OWNER_PASSWORD_CREDENTIALS
        );

        RegisterRequest registerRequest = new RegisterRequest(ApplicationType.WEB, "oxAuth test app",
                StringUtils.spaceSeparatedToList(redirectUris));
        registerRequest.setTokenEndpointAuthMethod(AuthenticationMethod.CLIENT_SECRET_POST);
        registerRequest.setSectorIdentifierUri(sectorIdentifierUri);
        registerRequest.setGrantTypes(grantTypes);

        RegisterClient registerClient = new RegisterClient(registrationEndpoint);
        registerClient.setRequest(registerRequest);
        RegisterResponse registerResponse = registerClient.exec();

        showClient(registerClient);
        assertEquals(registerResponse.getStatus(), 200, "Unexpected response code: " + registerResponse.getEntity());
        assertNotNull(registerResponse.getClientId());
        assertNotNull(registerResponse.getClientSecret());
        assertNotNull(registerResponse.getRegistrationAccessToken());
        assertNotNull(registerResponse.getClientIdIssuedAt());
        assertNotNull(registerResponse.getClientSecretExpiresAt());

        String clientId = registerResponse.getClientId();
        String clientSecret = registerResponse.getClientSecret();

        TokenRequest tokenRequest = new TokenRequest(GrantType.RESOURCE_OWNER_PASSWORD_CREDENTIALS);
        tokenRequest.setScope("openid");
        tokenRequest.setAuthUsername(clientId);
        tokenRequest.setAuthPassword(clientSecret);
        tokenRequest.addCustomParameter("uid", userId);
        tokenRequest.addCustomParameter("pwd", userSecret);
        tokenRequest.setAuthenticationMethod(AuthenticationMethod.CLIENT_SECRET_POST);

        TokenClient tokenClient = new TokenClient(tokenEndpoint);
        tokenClient.setRequest(tokenRequest);
        TokenResponse response1 = tokenClient.exec();

        showClient(tokenClient);
        assertEquals(response1.getStatus(), 200, "Unexpected response code: " + response1.getStatus());
        assertNotNull(response1.getEntity(), "The entity is null");
        assertNotNull(response1.getAccessToken(), "The access token is null");
        assertNotNull(response1.getTokenType(), "The token type is null");
        assertNotNull(response1.getRefreshToken(), "The refresh token is null");
        assertNotNull(response1.getScope(), "The scope is null");
        assertNotNull(response1.getIdToken(), "The id token is null");
    }

    @Parameters({"redirectUris", "userInum", "userEmail", "sectorIdentifierUri"})
    @Test
    public void requestAccessTokenCustomAuth3(
            final String redirectUris, final String userInum, final String userEmail, final String sectorIdentifierUri) throws Exception {
        showTitle("requestAccessTokenCustomAuth3");

        List<GrantType> grantTypes = Arrays.asList(
                GrantType.RESOURCE_OWNER_PASSWORD_CREDENTIALS
        );

        RegisterRequest registerRequest = new RegisterRequest(ApplicationType.WEB, "oxAuth test app",
                StringUtils.spaceSeparatedToList(redirectUris));
        registerRequest.setTokenEndpointAuthMethod(AuthenticationMethod.CLIENT_SECRET_BASIC);
        registerRequest.setSectorIdentifierUri(sectorIdentifierUri);
        registerRequest.setGrantTypes(grantTypes);

        RegisterClient registerClient = new RegisterClient(registrationEndpoint);
        registerClient.setRequest(registerRequest);
        RegisterResponse registerResponse = registerClient.exec();

        showClient(registerClient);
        assertEquals(registerResponse.getStatus(), 200, "Unexpected response code: " + registerResponse.getEntity());
        assertNotNull(registerResponse.getClientId());
        assertNotNull(registerResponse.getClientSecret());
        assertNotNull(registerResponse.getRegistrationAccessToken());
        assertNotNull(registerResponse.getClientIdIssuedAt());
        assertNotNull(registerResponse.getClientSecretExpiresAt());

        String clientId = registerResponse.getClientId();
        String clientSecret = registerResponse.getClientSecret();

        TokenRequest tokenRequest = new TokenRequest(GrantType.RESOURCE_OWNER_PASSWORD_CREDENTIALS);
        tokenRequest.setScope("openid");
        tokenRequest.setAuthUsername(clientId);
        tokenRequest.setAuthPassword(clientSecret);
        tokenRequest.addCustomParameter("mail", userEmail);
        tokenRequest.addCustomParameter("inum", userInum);
        tokenRequest.setAuthenticationMethod(AuthenticationMethod.CLIENT_SECRET_BASIC);

        TokenClient tokenClient = new TokenClient(tokenEndpoint);
        tokenClient.setRequest(tokenRequest);
        TokenResponse response1 = tokenClient.exec();

        showClient(tokenClient);
        assertEquals(response1.getStatus(), 200, "Unexpected response code: " + response1.getStatus());
        assertNotNull(response1.getEntity(), "The entity is null");
        assertNotNull(response1.getAccessToken(), "The access token is null");
        assertNotNull(response1.getTokenType(), "The token type is null");
        assertNotNull(response1.getRefreshToken(), "The refresh token is null");
        assertNotNull(response1.getScope(), "The scope is null");
        assertNotNull(response1.getIdToken(), "The id token is null");
    }

    @Parameters({"userId", "userSecret", "redirectUris", "sectorIdentifierUri"})
    @Test
    public void requestAccessTokenCustomAuth4(
            final String userId, final String userSecret, final String redirectUris, final String sectorIdentifierUri) throws Exception {
        showTitle("requestAccessTokenCustomAuth4");

        List<GrantType> grantTypes = Arrays.asList(
                GrantType.RESOURCE_OWNER_PASSWORD_CREDENTIALS
        );

        RegisterRequest registerRequest = new RegisterRequest(ApplicationType.WEB, "oxAuth test app",
                StringUtils.spaceSeparatedToList(redirectUris));
        registerRequest.setTokenEndpointAuthMethod(AuthenticationMethod.CLIENT_SECRET_JWT);
        registerRequest.setSectorIdentifierUri(sectorIdentifierUri);
        registerRequest.setGrantTypes(grantTypes);

        RegisterClient registerClient = new RegisterClient(registrationEndpoint);
        registerClient.setRequest(registerRequest);
        RegisterResponse registerResponse = registerClient.exec();

        showClient(registerClient);
        assertEquals(registerResponse.getStatus(), 200, "Unexpected response code: " + registerResponse.getEntity());
        assertNotNull(registerResponse.getClientId());
        assertNotNull(registerResponse.getClientSecret());
        assertNotNull(registerResponse.getRegistrationAccessToken());
        assertNotNull(registerResponse.getClientIdIssuedAt());
        assertNotNull(registerResponse.getClientSecretExpiresAt());

        String clientId = registerResponse.getClientId();
        String clientSecret = registerResponse.getClientSecret();

        OxAuthCryptoProvider cryptoProvider = new OxAuthCryptoProvider();

        TokenRequest tokenRequest = new TokenRequest(GrantType.RESOURCE_OWNER_PASSWORD_CREDENTIALS);
        tokenRequest.setScope("openid");
        tokenRequest.setAuthUsername(clientId);
        tokenRequest.setAuthPassword(clientSecret);
        tokenRequest.addCustomParameter("uid", userId);
        tokenRequest.addCustomParameter("pwd", userSecret);
        tokenRequest.setAudience(tokenEndpoint);
        tokenRequest.setAuthenticationMethod(AuthenticationMethod.CLIENT_SECRET_JWT);
        tokenRequest.setCryptoProvider(cryptoProvider);

        TokenClient tokenClient = new TokenClient(tokenEndpoint);
        tokenClient.setRequest(tokenRequest);
        TokenResponse response1 = tokenClient.exec();

        showClient(tokenClient);
        assertEquals(response1.getStatus(), 200, "Unexpected response code: " + response1.getStatus());
        assertNotNull(response1.getEntity(), "The entity is null");
        assertNotNull(response1.getAccessToken(), "The access token is null");
        assertNotNull(response1.getTokenType(), "The token type is null");
        assertNotNull(response1.getRefreshToken(), "The refresh token is null");
        assertNotNull(response1.getScope(), "The scope is null");
        assertNotNull(response1.getIdToken(), "The id token is null");
    }

    @Parameters({"redirectUris", "redirectUri", "userInum", "userEmail", "sectorIdentifierUri"})
    @Test
    public void requestAccessTokenCustomAuth5(
            final String redirectUris, final String redirectUri, final String userInum, final String userEmail,
            final String sectorIdentifierUri) throws Exception {
        showTitle("requestAccessTokenCustomAuth5");

        List<ResponseType> responseTypes = Arrays.asList(
                ResponseType.CODE,
                ResponseType.ID_TOKEN);

        // 1. Register client.
        RegisterRequest registerRequest = new RegisterRequest(ApplicationType.WEB, "oxAuth test app",
                StringUtils.spaceSeparatedToList(redirectUris));
        registerRequest.setResponseTypes(responseTypes);
        registerRequest.setTokenEndpointAuthMethod(AuthenticationMethod.CLIENT_SECRET_POST);
        registerRequest.setSectorIdentifierUri(sectorIdentifierUri);

        RegisterClient registerClient = new RegisterClient(registrationEndpoint);
        registerClient.setRequest(registerRequest);
        RegisterResponse registerResponse = registerClient.exec();

        showClient(registerClient);
        assertEquals(registerResponse.getStatus(), 200, "Unexpected response code: " + registerResponse.getEntity());
        assertNotNull(registerResponse.getClientId());
        assertNotNull(registerResponse.getClientSecret());
        assertNotNull(registerResponse.getRegistrationAccessToken());
        assertNotNull(registerResponse.getClientIdIssuedAt());
        assertNotNull(registerResponse.getClientSecretExpiresAt());

        String clientId = registerResponse.getClientId();
        String clientSecret = registerResponse.getClientSecret();

        // 2. Request authorization and receive the authorization code.
        List<String> scopes = Arrays.asList(
                "openid",
                "profile",
                "address",
                "email");
        String state = UUID.randomUUID().toString();
        String nonce = UUID.randomUUID().toString();

        AuthorizationRequest authorizationRequest = new AuthorizationRequest(responseTypes, clientId, scopes, redirectUri, nonce);
        authorizationRequest.setState(state);
        authorizationRequest.getPrompts().add(Prompt.NONE);
        authorizationRequest.addCustomParameter("mail", userEmail);
        authorizationRequest.addCustomParameter("inum", userInum);
        authorizationRequest.setAuthorizationMethod(AuthorizationMethod.FORM_ENCODED_BODY_PARAMETER);

        AuthorizationResponse authorizationResponse = authorizationRequestAndGrantAccess(
                authorizationEndpoint, authorizationRequest);

        assertNotNull(authorizationResponse.getLocation(), "The location is null");
        assertNotNull(authorizationResponse.getCode(), "The authorization code is null");
        assertNotNull(authorizationResponse.getState(), "The state is null");
        assertNotNull(authorizationResponse.getScope(), "The scope is null");

        String authorizationCode = authorizationResponse.getCode();

        // 3. Request access token using the authorization code.
        TokenRequest tokenRequest = new TokenRequest(GrantType.AUTHORIZATION_CODE);
        tokenRequest.setCode(authorizationCode);
        tokenRequest.setRedirectUri(redirectUri);
        tokenRequest.setAuthUsername(clientId);
        tokenRequest.setAuthPassword(clientSecret);
        tokenRequest.setAuthenticationMethod(AuthenticationMethod.CLIENT_SECRET_POST);

        TokenClient tokenClient1 = new TokenClient(tokenEndpoint);
        tokenClient1.setRequest(tokenRequest);
        TokenResponse response2 = tokenClient1.exec();

        showClient(tokenClient1);
        assertEquals(response2.getStatus(), 200, "Unexpected response code: " + response2.getStatus());
        assertNotNull(response2.getEntity(), "The entity is null");
        assertNotNull(response2.getAccessToken(), "The access token is null");
        assertNotNull(response2.getExpiresIn(), "The expires in value is null");
        assertNotNull(response2.getTokenType(), "The token type is null");
        assertNotNull(response2.getRefreshToken(), "The refresh token is null");
    }
}


text:
class FileFlags
{
public:
	FileFlags(int flags);

	int openFlags() const;
	int createFlags() const;

protected:
	int _flags;
};

inline FileFlags::FileFlags(int flags)
	: _flags(flags)
{}

redpajama_set_name: RedPajamaGithub


text:
package org.apache.flink.core.memory;

import org.apache.flink.annotation.Internal;
import org.apache.flink.util.Preconditions;

/** Use cases of managed memory. */
@Internal
public enum ManagedMemoryUseCase {

    /** Currently, weights are defined as mebibyte values. */
    OPERATOR(Scope.OPERATOR),

    STATE_BACKEND(Scope.SLOT),

    PYTHON(Scope.SLOT);

    public final Scope scope;

    ManagedMemoryUseCase(Scope scope) {
        this.scope = Preconditions.checkNotNull(scope);
    }

    /** Scope at which memory is managed for a use case. */
    public enum Scope {
        SLOT,
        OPERATOR
    }
}


text:
**Namespace:** [OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201605](OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201605.md)
**Assembly:** OfficeDevPnP.Core.dll
## Syntax
```C#
public bool Overwrite { get; set; }
```

### Property Value
Type: System.Boolean

## See also
- [PropertyBagEntry](OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201605.PropertyBagEntry.md)
- [OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201605](OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201605.md)


text:
import optparse
import sys
from smimeX509validation import TrustAnchor
import logging, logging.config
import os.path
from smimeX509validation import TrustStore, LoadDirChainOfTrust,smimeX509validation

def main():
    p = optparse.OptionParser()
    p.add_option('-m', '--message', action ='append',
        help='adds a message to be tested.')
    p.add_option('-c', '--certs-dir', action ='store',
        help='Path of certificates dir',
        default='/etc/grid-security/certificates/')
    options, arguments = p.parse_args()
    if not os.path.isdir(options.certs_dir):
        print ("Warning not a directory:%s" % (options.certs_dir))
        sys.exit(1)
    anchor =  LoadDirChainOfTrust(options.certs_dir)
    if options.message == None:
        sys.exit(1)
    else:
        for item in options.message:

            #print anchor.validate_file(item)
            smimeProcessor = smimeX509validation(anchor)
            smimeProcessor.ProcessFile(item)
            print smimeProcessor.InputCertMetaDataList
            print smimeProcessor.verified
            print smimeProcessor.InputDaraStringIO.getvalue()

if __name__ == "__main__":
    logging.basicConfig(level=logging.WARNING)
    main()


text:
const addCounter = (list) => {
  return [...list, 0];
};

const removeCounter = (list, index) => {
  return [
      ...list.slice(0, index),
      ...list.slice(index+1)
  ];
};

const incrementCounter = (list, index) => {
  return list
    .slice(0, index)
    .concat([list[index] +1])
    .concat(list.slice(index+1));
};

const testAddCounter = () => {
  const listBefore = [];
  const listAfter = [0];

  deepFreeze(listBefore);

  expect(
    addCounter(listBefore)
  ).toEqual(listAfter);
};

const testRemoveCounter = () => {
  const listBefore = [0,10, 20];
  const listAfter = [0,20];

  deepFreeze(listBefore);

  expect(
    removeCounter(listBefore, 1)
  ).toEqual(listAfter);
};

const testIncrementCounter = () => {
  const listBefore = [0,10,20];
  const listAfter = [0,11,20];

  deepFreeze(listBefore);

  expect(
    incrementCounter(listBefore,1)
  ).toEqual(listAfter);
};

testAddCounter();
testRemoveCounter();
testIncrementCounter();

console.info('All test passed.');


text:
window.$ = window.jQuery = require('jquery');

require('babel-polyfill');
require('promise-polyfill');
require('./_common/lib/polyfills/nodelist.foreach');

require('@binary-com/binary-style');
require('@binary-com/binary-style/binary.more');

// used by gtm to update page after a new release
window.check_new_release = require('./_common/check_new_release').checkNewRelease;

require('event-source-polyfill');
require('./_common/lib/jquery.sparkline.js');
require('./_common/lib/plugins');
require('jquery.scrollto');

const BinaryLoader = require('./app/base/binary_loader');

document.addEventListener('DOMContentLoaded', BinaryLoader.init);
$(window).on('pageshow', (e) => { // Safari doesn't fire load event when using back button
    if (e.originalEvent.persisted) {
        BinaryLoader.init();
    }
});


text:
#ifndef FUNC_H
#define FUNC_H

namespace Common { class PatchManager; }

namespace patch_func {
    struct Eax {};
    struct Ecx {};
    struct Edx {};
    struct Ebx {};
    struct Esp {};
    struct Ebp {};
    struct Esi {};
    struct Edi {};
    struct Stack {};

    template <typename Signature>
    class Stdcall;

    template <typename Ret, typename... Args>
    class Stdcall<Ret (Args...)> {
        public:
            constexpr Stdcall() : wrapper_code(nullptr) { }

            template <typename... ArgLoc>
            void Init(Common::PatchManager *exec_heap, uintptr_t address);

            template <typename... ArgLoc>
            static uintptr_t WrapperSize();

            template <typename... ArgLoc>
            static int WriteWrapper(uint8_t *out, uintptr_t out_len, uintptr_t target);

            Ret operator()(Args... args) const {
                return wrapper_code(args...);
            }

        private:
            Ret (*wrapper_code)(Args...);
    };

} // namespace patch_func

#endif /* FUNC_H */


text:
class CrispyError(Exception):
    pass

class FormHelpersException(CrispyError):
    """
    This is raised when building a form via helpers throws an error.
    We want to catch form helper errors as soon as possible because
    debugging templatetags is never fun.
    """

    pass

class DynamicError(CrispyError):
    pass


text:
package com.study.controller.ch03;

import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;

/**
 * Servlet implementation class resonseDemo4
 */
@WebServlet("/resonseDemo4")
public class resonseDemo4 extends HttpServlet {
	private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public resonseDemo4() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		//1.Ê×ÏÈÉèÖÃ5ÃëË¢ÐÂÒ»´Î
		response.setHeader("refresh","5");
		//2.ÉùÃ÷Éú³ÉͼƬ¶ÔÏó£¬ÔÚÄÚ´æÖд´½¨Ò»ÕÅͼƬ
		BufferedImage img=new BufferedImage(80, 20, BufferedImage.TYPE_INT_BGR);
		//3.µÃµ½Í¼Æ¬
		Graphics2D g=(Graphics2D)img.getGraphics();
		g.setColor(Color.WHITE); //ÉèÖÃͼƬ±³¾°

		g.fillRect(0,0,80,20);	//Ìî³ä±³¾°É«
		//4.ÏòͼƬÉÏдÊý¾Ý
		g.setColor(Color.BLUE); //ÉèÖÃͼƬÉϵı³¾°ÑÕÉ«
		g.setFont(new Font(null,Font.BOLD,20));  //ÉèÖÃ×ÖÌå´óС
		g.drawString(makeNum(), 0,20);
		//5.ÉèÖÃÏìӦͷ¿ØÖÆä¯ÀÀÆ÷ÒÔͼƬµÄ·½Ê½´ò¿ª
		response.setContentType("image/jpeg");
//		response.setHeader("content-type","image/jpeg");
		//6.ÉèÖÃÏìӦͷ¿ØÖÆä¯ÀÀÆ÷²»»º´æͼƬÊý¾Ý
		response.setDateHeader("expires", -1);
		response.setHeader("Cache-Control","no-cache");
		response.setHeader("Pragma","no-cache");
		//7.½«Í¼Æ¬Êä³öµ½ä¯ÀÀÆ÷
		ImageIO.write(img, "jpg", response.getOutputStream());

	}

	private String makeNum() {
		// TODO Auto-generated method stub
		Random rnd=new Random();
		String num=rnd.nextInt(9999999)+"";
		StringBuffer sb=new StringBuffer();

		for(int i=0;i<7-num.length();i++){
			sb.append(0);
		}
		num=sb.toString()+num;
		return num;
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}


text:
#Region "Microsoft.VisualBasic::3b7b3c7547f5be7457622b23852d5f03, src\assembly\assembly\MarkupData\mzML\Extensions.vb"

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

    ' /********************************************************************************/

    ' Summaries:

    '     Module Extensions
    '
    '         Function: ByteArray, FilterAllSpectrum, GetAllMs1, GetAllMs2, (+2 Overloads) GetIonsChromatogram
    '                   LoadChromatogramList, MRMTargetMz, PopulateMS1, PopulateMS2, Ticks
    '
    '
    ' /********************************************************************************/

#End Region

Imports System.Runtime.CompilerServices
Imports BioNovoGene.Analytical.MassSpectrometry.Assembly.MarkupData.mzML.IonTargeted
Imports BioNovoGene.Analytical.MassSpectrometry.Math.Chromatogram
Imports BioNovoGene.Analytical.MassSpectrometry.Math.Spectra
Imports Microsoft.VisualBasic.ComponentModel.Collection
Imports Microsoft.VisualBasic.Linq
Imports Microsoft.VisualBasic.Math.LinearAlgebra
Imports Microsoft.VisualBasic.Text.Xml.Linq
Imports Microsoft.VisualBasic.Math

Namespace MarkupData.mzML

    <HideModuleName>
    Public Module Extensions

        <MethodImpl(MethodImplOptions.AggressiveInlining)>
        <Extension>
        Public Function GetAllMs1(spectrums As IEnumerable(Of spectrum)) As IEnumerable(Of spectrum)
            Return spectrums.FilterAllSpectrum(msLevel:=1)
        End Function

        <MethodImpl(MethodImplOptions.AggressiveInlining)>
        <Extension>
        Public Function GetAllMs2(spectrums As IEnumerable(Of spectrum)) As IEnumerable(Of spectrum)
            Return spectrums.FilterAllSpectrum(msLevel:=2)
        End Function

        <MethodImpl(MethodImplOptions.AggressiveInlining)>
        <Extension>
        Public Function FilterAllSpectrum(spectrums As IEnumerable(Of spectrum), msLevel$) As IEnumerable(Of spectrum)
            Return spectrums.Where(Function(s) s.ms_level = msLevel)
        End Function

        <MethodImpl(MethodImplOptions.AggressiveInlining)>
        <Extension>
        Public Function PopulateMS1(filePath As String) As IEnumerable(Of (scan_time#, mz#, intensity#))
            Return filePath _
                .LoadXmlDataSet(Of spectrum)(, xmlns:=indexedmzML.xmlns) _
                .GetAllMs1 _
                .Select(Function(ms1)
                            Dim time# = ms1.scan_time
                            Dim mz = ms1.ByteArray("m/z array").Base64Decode
                            Dim intensity = ms1.ByteArray("intensity array").Base64Decode

                            Return CInt(ms1.defaultArrayLength) _
                                .Sequence _
                                .Select(Function(index)
                                            Return (time, mz(index), intensity(index))
                                        End Function)
                        End Function) _
                .IteratesALL
        End Function

        <MethodImpl(MethodImplOptions.AggressiveInlining)>
        <Extension>
        Public Function PopulateMS2(filePath As String) As IEnumerable(Of LibraryMatrix)
            Return filePath _
                .LoadUltraLargeXMLDataSet(Of spectrum)(, xmlns:=indexedmzML.xmlns) _
                .GetAllMs2 _
                .Select(Function(ms2)
                            Return New LibraryMatrix With {
                                .name = ms2.id,
                                .ms2 = ms2.GetRawMatrix
                            }
                        End Function)
        End Function

        ''' <summary>
        ''' Working for MRM method
        ''' </summary>
        ''' <param name="path"></param>
        ''' <returns></returns>
        '''
        <MethodImpl(MethodImplOptions.AggressiveInlining)>
        <Extension>
        Public Function LoadChromatogramList(path As String) As IEnumerable(Of chromatogram)
            Return path.LoadXmlDataSet(Of chromatogram)(, xmlns:=indexedmzML.xmlns)
        End Function

        <MethodImpl(MethodImplOptions.AggressiveInlining)>
        <Extension>
        Public Function MRMTargetMz(selector As IMRMSelector) As Double
            Return selector _
                .isolationWindow _
                .cvParams _
                .KeyItem("isolation window target m/z") _
                .value
        End Function

        ''' <summary>
        '''
        ''' </summary>
        ''' <param name="data"></param>
        ''' <param name="type$">
        ''' + ``m/z`` array
        ''' + intensity array
        ''' + time array
        ''' </param>
        ''' <returns></returns>
        <MethodImpl(MethodImplOptions.AggressiveInlining)>
        <Extension>
        Public Function ByteArray(data As BinaryData, type$) As binaryDataArray
            Return data _
                .binaryDataArrayList _
                .list _
                .Where(Function(a)
                           Return Not a.cvParams.KeyItem(type) Is Nothing
                       End Function) _
                .FirstOrDefault
        End Function

        ''' <summary>
        ''' Get this chromatogram signal ticks.(返回来的时间的单位都统一为秒)
        ''' </summary>
        ''' <param name="chromatogram"></param>
        ''' <returns></returns>
        <Extension>
        Public Function Ticks(chromatogram As chromatogram) As ChromatogramTick()
            Dim time = chromatogram.ByteArray("time array")
            Dim into = chromatogram.ByteArray("intensity array")
            Dim timeUnit = time.cvParams.KeyItem("time array").unitName
            Dim intoUnit = into.cvParams.KeyItem("intensity array").unitName
            Dim time_array = time.Base64Decode.AsVector
            Dim intensity_array = into.Base64Decode

            If timeUnit.TextEquals("minute") Then
                time_array = time_array * 60
            End If

            Dim data = time_array _
                .Select(Function(t, i)
                            Return New ChromatogramTick(t, intensity_array(i))
                        End Function) _
                .ToArray

            Return data
        End Function

        Public Function GetIonsChromatogram(file As String) As DataReader.Chromatogram
            Return file.LoadChromatogramList.GetIonsChromatogram
        End Function

        <Extension>
        Public Function GetIonsChromatogram(channels As IEnumerable(Of chromatogram)) As DataReader.Chromatogram
            Dim allTicks As ChromatogramTick() = channels _
                .Where(Function(chr) chr.id <> "TIC" AndAlso chr.id <> "BPC") _
                .Select(AddressOf Ticks) _
                .IteratesALL _
                .OrderBy(Function(t) t.Time) _
                .ToArray
            Dim time_groups = allTicks _
                .GroupBy(Function(t) t.Time, offsets:=0.1) _
                .OrderBy(Function(d) Val(d.name)) _
                .ToArray
            Dim TIC As Double() = time_groups.Select(Function(d) d.Sum(Function(p) p.Intensity)).ToArray
            Dim BPC As Double() = time_groups.Select(Function(d) d.Max(Function(p) p.Intensity)).ToArray

            Return New DataReader.Chromatogram With {
                .scan_time = time_groups _
                    .Select(Function(p) Val(p.name)) _
                    .ToArray,
                .TIC = TIC,
                .BPC = BPC
            }
        End Function
    End Module
End Namespace


text:
import java.util.*;
import java.io.*;
import java.math.*;

class Solution {

    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        int N = in.nextInt(); // Number of elements which make up the association table.
        int Q = in.nextInt(); // Number Q of file names to be analyzed.
        in.nextLine();
        HashMap<String, String> map = new HashMap<>();
        for (int i = 0; i < N; i++) {
            String EXT = in.next();
            String MT = in.next();
            map.put(EXT.toLowerCase(), MT);
            in.nextLine();
        }

        String exten="";
        for(int i=0; i<Q; i++)
        {
            String FNAME = in.nextLine().toLowerCase();
            int pos = FNAME.lastIndexOf('.');
          exten = (pos == -1) ? "" : FNAME.substring(pos+1, FNAME.length());
         if(exten.length()>10) System.out.println("UNKNOWN");
            if(map.containsKey(exten)) System.out.println(map.get(exten));
            else System.out.println("UNKNOWN");
        }

    }
}


text:
This detector checks for Nacos < 1.4.1 Authentication Bypass and disclosure vulnerability (CVE-2021-29441).
When configured to use authentication (-Dnacos.core.auth.enabled=true) Nacos uses the AuthFilter servlet filter to enforce authentication. This filter has a backdoor that enables Nacos servers to bypass this filter and therefore skip authentication checks. This mechanism relies on the user-agent HTTP header so it can be easily spoofed.
This issue is known to be exploited in the wild.
This issue is for Nacos <1.4.1 versions.
https://github.com/advisories/GHSA-36hp-jr8h-556f
https://nvd.nist.gov/vuln/detail/CVE-2021-29441

## Build jar file for this plugin

Using `gradlew`:

```shell
./gradlew jar
```

Tsunami identifiable jar file is located at `build/libs` directory.


text:
FactoryBot.define do
  factory :character_corporation_history do
    character

    sequence(:corporation_id)

    is_deleted { [true, false].sample }

    sequence(:record_id)

    start_date { Time.zone.now }
  end
end


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Striga lutea Lour.

### Remarks
null


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>General Procedure for taking a Vote</title>

General Procedure for taking a Vote

Index:

Starting Out

Routine Matters

Running the Vote

Results Procedures

Starting Out

When you're ready to handle a vote, wait for the Co-Ordinator to send
      around the usual bleating mail to the mailing list asking for some
      volunteer to handle a vote because he has to put up shelves/work too
      hard/go yak herding in Patagonia.

Don't bite off more than you can chew on your first vote - unless you've
      been a proponent for a reorganization, your first vote should be a
      single-group non-controversial non-AV one.

Routine Matters

If you have questions, ask on the UKVoting mailling list. But don't give
      away results in your questions.

If other members ask questions, keep them confidential if they pertain
      to votes in progress.

If a UKVoting member is the proponent, use caution. If you are that
      proponent, be on your best behavior.

Voting in a CFV you are running is highly frowned upon. It is best to
      just not do it. Believe me, it'll save you a lot more hassle than a
      single vote is worth!

Running the Vote

Get the Vote assigned to you.

Contact the Proponent.

Write the CFV.

Post the CFV.

Post the 2nd CFV.

Get the Vote assigned to you

The coordinator will tell you that it has been assigned to you. This is
      the "passing of the baton." You should then get the proponent's latest RFD
      (which can be found in
      uk.net.news.announce) and the
      Template CFV. At this point, the proposal
      becomes your responsibility and you have the corresponding authority as
      votetaker.

Contact the Proponent

Contact the proponent to notify them that you will be the votetaker for
      their proposal and that you are writing the CFV.

This can also be a good time to tell the proponent a few things like:

Under no circumstances will information on the progress of the vote
        be available while voting is in progress. You may even tell them that,
        if such information were to get out, it would mean instant cancellation
        of the vote so they don't want that to happen.

They should refrain from campaigning and, instead, let real levels of
        interest drive voters. Proponent campaigning can cause a voter backlash
        and obtain the opposite result of that intended.

Since you can't take a position on the proposal, you will refer any
      voters with questions or comments about its content to them.

Write the CFV

Write the CFV based on the latest RFD.

Send a copy to the proponent for review.

Post the CFV

When the proponent says the CFV is OK, send it to the
      uk.net.news.announce moderator at control@usenet.org.uk. The CFV
      including headers should be an attachment to a message which tells the
      moderator the name of the proposal if it's cross-posted to any moderated
      newsgroups (list them) where the places are that he needs to fill in
      dates (usually two: expires and voting deadline). This is followed by the
      headers and CFV such that the moderator can clip out the remaining lines
      in the message and post them.

Post the 2nd CFV

This should be done approximately halfway through the voting period. The
      subject should now start with "2nd CFV:".

Results Procedures

Do not disclose results, even to the proponent, before they are posted
      in uk.net.news.announce. It's hard to know whether a proponent will be
      able to restrain themselves or how they'll tell others. When results time
      arrives, there is a possibility that many people will have an equal
      interest as the proponent in the results.


text:
<?php
/**
 * Implements a shortcode that wraps the existing event coundtown widget. Basic usage
 * is as follows (using an event's post ID):
 *
 *     [tribe_event_countdown id="123"]
 *
 * If preferred, the event slug can be used:
 *
 *     [tribe_event_countdown slug="some-event"]
 *
 * Display of seconds is optional but can be enabled by adding a show_seconds="1"
 * attribute. To specify the text that should display once the event time rolls round
 * a complete attribute is available.
 *
 *     [tribe_event_countdown slug="party-time" show_seconds="1" complete="The party is on!"]
 */
class Tribe__Events__Pro__Shortcodes__Event_Countdown {
	public $output = '';

	/**
	 * Default arguments expected by the countdown widget.
	 *
	 * @var array
	 */
	protected $default_args = array(
		// General widget properties
		'before_widget' => '',
		'before_title'  => '',
		'title'         => '',
		'after_title'   => '',
		'after_widget'  => '',

		// Widget specific properties
		'id'           => '',
		'slug'         => '',
		'show_seconds' => '',
		'complete'     => '',
	);

	protected $arguments = array();

	public function __construct( $attributes ) {
		$this->arguments = shortcode_atts( $this->default_args, $attributes );
		$this->parse_args();
		$this->set_date();

		// If we don't have an event date we cannot display the timer
		if ( ! isset( $this->arguments['event_date'] ) ) {
			return;
		}

		// If the ECP CSS has not already been added lets lazily add it now
		Tribe__Events__Pro__Template_Factory::asset_package( 'events-pro-css' );

		ob_start();
		the_widget( 'Tribe__Events__Pro__Countdown_Widget', $this->arguments, $this->arguments );
		$this->output = ob_get_clean();
	}

	protected function parse_args() {
		if ( ! empty( $this->arguments['id'] ) ) {
			$this->arguments['event_ID'] = (int) $this->arguments['id'];
		} elseif ( ! empty( $this->arguments['slug'] ) ) {
			$this->set_by_slug();
		}
	}

	/**
	 * Facilitates specifying the event by providing its slug.
	 */
	protected function set_by_slug() {
		$events = get_posts( array(
			'post_type' => Tribe__Events__Main::POSTTYPE,
			'name' => $this->arguments['slug'],
			'posts_per_page' => 1,
		) );

		if ( empty( $events ) ) {
			return;
		}

		$event = array_shift( $events );
		$this->arguments['event_ID'] = (int) $event->ID;
	}

	/**
	 * The countdown widget requires the date of the event to be passed in
	 * as an argument.
	 */
	protected function set_date() {
		if ( ! isset( $this->arguments['event_ID'] ) ) {
			return;
		}

		$this->arguments['event_date'] = tribe_get_start_date( $this->arguments['event_ID'], false, Tribe__Events__Date_Utils::DBDATEFORMAT );
	}
}


text:
package com.zimbra.soap.admin.type;

import com.google.common.collect.Lists;

import java.util.Collection;
import java.util.Collections;
import java.util.List;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;

import com.zimbra.common.soap.AdminConstants;
import com.zimbra.soap.admin.type.ConstraintInfo;
import com.zimbra.soap.json.jackson.annotate.ZimbraJsonArrayForWrapper;

@XmlAccessorType(XmlAccessType.NONE)
public class EffectiveAttrInfo {

    /**
     * @zm-api-field-tag attribute-name
     * @zm-api-field-description Attribute name
     */
    @XmlAttribute(name=AdminConstants.A_N /* n */, required=true)
    private final String name;

    /**
     * @zm-api-field-description Constraint information
     */
    @XmlElement(name=AdminConstants.E_CONSTRAINT /* constraint */, required=false)
    private ConstraintInfo constraint;

    /**
     * @zm-api-field-description Inherited default value(or values if the attribute is multi-valued)
     */
    @ZimbraJsonArrayForWrapper
    @XmlElementWrapper(name=AdminConstants.E_DEFAULT /* default */, required=false)
    @XmlElement(name=AdminConstants.E_VALUE /* v */, required=false)
    private List <String> values = Lists.newArrayList();

    /**
     * no-argument constructor wanted by JAXB
     */
    @SuppressWarnings("unused")
    private EffectiveAttrInfo() {
        this((String) null, (ConstraintInfo) null);
    }

    public EffectiveAttrInfo(String name) {
        this(name, (ConstraintInfo) null);
    }

    public EffectiveAttrInfo(String name, ConstraintInfo constraint) {
        this.name = name;
        this.setConstraint(constraint);
    }

    public EffectiveAttrInfo setValues(Collection <String> values) {
        this.values.clear();
        if (values != null) {
            this.values.addAll(values);
        }
        return this;
    }

    public EffectiveAttrInfo addValue(String value) {
        values.add(value);
        return this;
    }

    public List <String> getValues() {
        return Collections.unmodifiableList(values);
    }

    public String getName() {
        return name;
    }

    public void setConstraint(ConstraintInfo constraint) {
        this.constraint = constraint;
    }

    public ConstraintInfo getConstraint() {
        return constraint;
    }
}


text:
package de.felixbruns.jotify.protocol;

public class Command {
	/* Core functionality. */
	public static final int COMMAND_SECRETBLK    = 0x02;
	public static final int COMMAND_PING         = 0x04;
	public static final int COMMAND_GETSUBSTREAM = 0x08;
	public static final int COMMAND_CHANNELDATA  = 0x09;
	public static final int COMMAND_CHANNELERR   = 0x0a;
	public static final int COMMAND_CHANNELABRT  = 0x0b;
	public static final int COMMAND_REQKEY       = 0x0c;
	public static final int COMMAND_AESKEY       = 0x0d;
	public static final int COMMAND_AESKEYERR    = 0x0e;
	public static final int COMMAND_CACHEHASH    = 0x0f;
	public static final int COMMAND_SHAHASH      = 0x10;
	public static final int COMMAND_IMAGE        = 0x19;

	/* Rights management. */
	public static final int COMMAND_COUNTRYCODE = 0x1b;

	/* P2P related. */
	public static final int COMMAND_P2P_SETUP   = 0x20;
	public static final int COMMAND_P2P_INITBLK = 0x21;

	/* Search and metadata. */
	public static final int COMMAND_BROWSE          = 0x30;
	public static final int COMMAND_SEARCH          = 0x31;
	public static final int COMMAND_PLAYLISTCHANGED = 0x34;
	public static final int COMMAND_GETPLAYLIST     = 0x35;
	public static final int COMMAND_CHANGEPLAYLIST  = 0x36;
	public static final int COMMAND_GETTOPLIST      = 0x38;

	/* Session management. */
	public static final int COMMAND_NOTIFY      = 0x42;
	public static final int COMMAND_LOG         = 0x48;
	public static final int COMMAND_PONG        = 0x49;
	public static final int COMMAND_PONGACK     = 0x4a;
	public static final int COMMAND_PAUSE       = 0x4b;
	public static final int COMMAND_REQUESTAD   = 0x4e;
	public static final int COMMAND_REQUESTPLAY = 0x4f;

	/* Internal. */
	public static final int COMMAND_PRODINFO    = 0x50;
	public static final int COMMAND_WELCOME     = 0x69;
}


text:
/**
 * @fileoverview Earth Engine Developer's Guide examples
 *   from 'Image collections - Compositing and mosaicking' page
 */

// [START earthengine__image_collections085__quality_mosaic]
// Define a function that scales and masks Landsat 8 surface reflectance images.
function prepSrL8(image) {
  // Develop masks for unwanted pixels (fill, cloud, cloud shadow).
  var qaMask = image.select('QA_PIXEL').bitwiseAnd(parseInt('11111', 2)).eq(0);
  var saturationMask = image.select('QA_RADSAT').eq(0);

  // Apply the scaling factors to the appropriate bands.
  var getFactorImg = function(factorNames) {
    var factorList = image.toDictionary().select(factorNames).values();
    return ee.Image.constant(factorList);
  };
  var scaleImg = getFactorImg([
    'REFLECTANCE_MULT_BAND_.|TEMPERATURE_MULT_BAND_ST_B10']);
  var offsetImg = getFactorImg([
    'REFLECTANCE_ADD_BAND_.|TEMPERATURE_ADD_BAND_ST_B10']);
  var scaled = image.select('SR_B.|ST_B10').multiply(scaleImg).add(offsetImg);

  // Replace original bands with scaled bands and apply masks.
  return image.addBands(scaled, null, true)
    .updateMask(qaMask).updateMask(saturationMask);
}

// This function masks clouds and adds quality bands to Landsat 8 images.
var addQualityBands = function(image) {
  // Normalized difference vegetation index.
  var ndvi = image.normalizedDifference(['SR_B5', 'SR_B4']);
  // Image timestamp as milliseconds since Unix epoch.
  var millis = ee.Image(image.getNumber('system:time_start'))
                   .rename('millis').toFloat();
  return prepSrL8(image).addBands([ndvi, millis]);
};

// Load a 2014 Landsat 8 ImageCollection.
// Map the cloud masking and quality band function over the collection.
var collection = ee.ImageCollection('LANDSAT/LC08/C02/T1_L2')
  .filterDate('2014-06-01', '2014-12-31')
  .map(addQualityBands);

// Create a cloud-free, most recent value composite.
var recentValueComposite = collection.qualityMosaic('millis');

// Create a greenest pixel composite.
var greenestPixelComposite = collection.qualityMosaic('nd');

// Display the results.
Map.setCenter(-122.374, 37.8239, 12); // San Francisco Bay
var vizParams = {bands: ['SR_B5', 'SR_B4', 'SR_B3'], min: 0, max: 0.4};
Map.addLayer(recentValueComposite, vizParams, 'Recent value composite');
Map.addLayer(greenestPixelComposite, vizParams, 'Greenest pixel composite');

// Compare to a cloudy image in the collection.
var cloudy = ee.Image('LANDSAT/LC08/C02/T1_TOA/LC08_044034_20140825');
Map.addLayer(cloudy, {bands: ['B5', 'B4', 'B3'], min: 0, max: 0.4}, 'Cloudy');
// [END earthengine__image_collections085__quality_mosaic]


text:
export GOPATH=~/Code/workspace-go
export PATH=$PATH:$GOPATH/bin


text:
import os
import sys
import argparse
from EMAN2 import *

def main():
	progname = os.path.basename(sys.argv[0])
	usage = progname + """ [options] <micrograph.mrc>
	Generate boxes to cover the entire micrograph. The module (micrograph size % box size) will be treaded as edge.
	"""

	args_def = {'boxsize':120, 'overlap':0}
	parser = argparse.ArgumentParser()
	parser.add_argument("mic", help="specify a micrograph to be processed")
	parser.add_argument("-b", "--boxsize", type=int, help="specify boxsize, by default {}".format(args_def['boxsize']))
	parser.add_argument("-o", "--overlap", type=int, help="specify the overlap between two neighbouring boxes, by default {}".format(args_def['overlap']))
	args = parser.parse_args()

	if len(sys.argv) == 1:
		print "usage: " + usage
		print "Please run '" + progname + " -h' for detailed options."
		sys.exit(1)
	# get default values
	for i in args_def:
		if args.__dict__[i] == None:
			args.__dict__[i] = args_def[i]
	#
	d = EMData(args.mic)
	X = d["nx"]
	Y = d["ny"]
	box = args.boxsize
	interval = box-args.overlap
	modX = X % interval
	modY = Y % interval
	edgeX = modX/2 - args.overlap/2
	edgeY = modY/2 - args.overlap/2
	with open(args.mic+'.box', 'w') as box_w:
		for x in xrange(X/interval):
			for y in xrange(Y/interval):
				box_w.write('{} {} {} {}\n'.format(x*interval+edgeX, y*interval+edgeY, box, box))

if __name__ == '__main__':
	main()


text:
package org.sirix.saxon.wrapper;

import java.io.File;

import javax.xml.stream.XMLEventReader;

import org.junit.Test;
import org.sirix.TestHelper;
import org.sirix.TestHelper.PATHS;
import org.sirix.access.Databases;
import org.sirix.access.conf.DatabaseConfiguration;
import org.sirix.access.conf.ResourceConfiguration;
import org.sirix.access.conf.SessionConfiguration;
import org.sirix.api.Database;
import org.sirix.api.NodeWriteTrx;
import org.sirix.api.Session;
import org.sirix.service.xml.shredder.Insert;
import org.sirix.service.xml.shredder.XMLShredder;

public final class BookShredding {

	public BookShredding() {
	}

	/** Path to books file. */
	public static final File MY_BOOKS = new File(new StringBuilder("src")
			.append(File.separator).append("test").append(File.separator)
			.append("resources").append(File.separator).append("data")
			.append(File.separator).append("my-books.xml").toString());

	/** Books XML file. */
	public static final File BOOKS = new File("src" + File.separator + "test"
			+ File.separator + "resources" + File.separator + "data" + File.separator
			+ "books.xml");

	public static void createMyBookDB() throws Exception {
		shredder(MY_BOOKS);
	}

	public static void createBookDB() throws Exception {
		shredder(BOOKS);
	}

	private static void shredder(final File pBooks) throws Exception {
		final DatabaseConfiguration config = new DatabaseConfiguration(
				TestHelper.PATHS.PATH1.getFile());
		Databases.truncateDatabase(config);
		Databases.createDatabase(config);
		final Database database = Databases.openDatabase(config.getFile());
		database.createResource(new ResourceConfiguration.Builder(
				TestHelper.RESOURCE, PATHS.PATH1.getConfig()).build());
		final Session session = database
				.getSession(new SessionConfiguration.Builder(TestHelper.RESOURCE)
						.build());
		final NodeWriteTrx wtx = session.beginNodeWriteTrx();
		final XMLEventReader reader = XMLShredder.createFileReader(pBooks);
		final XMLShredder shredder = new XMLShredder.Builder(wtx, reader,
				Insert.ASFIRSTCHILD).commitAfterwards().build();
		shredder.call();
		wtx.close();
		session.close();
	}

	@Test
	public void fakeTest() {
	}

}


text:
from xi_plugin import start_plugin, Plugin, edit

MATCHES = {"{": "}", "[": "]", "(": ")"}

class BracketCloser(Plugin):
    """Naively closes opened brackets, parens, & braces."""

    def update(self, view, author, rev, start, end,
               new_len, edit_type, text=None):
        resp = 0
        close_char = MATCHES.get(text)
        if close_char:
            # compute a delta from params:
            new_cursor = end + new_len
            # we set 'after_cursor' because we want the edit to appear to the right
            # of the active cursor. we set priority=HIGH because we want this edit
            # applied after concurrent edits.
            resp = self.new_edit(rev, (new_cursor, new_cursor), close_char,
                                 after_cursor=True, priority=edit.EDIT_PRIORITY_HIGH)
        return resp

def main():
    start_plugin(BracketCloser())

if __name__ == "__main__":
    main()


text:
package com.spectralogic.ds3autogen.python.model.type;

import static com.spectralogic.ds3autogen.utils.Helper.capFirst;

/**
 * Describes a single xml element child of a given type
 */
public class TypeElement implements TypeContent {

    private final String xmlTag;
    /** The name of the type model to use for parsing this element; if primitive type, then 'None' */
    private final String typeModel;

    public TypeElement(final String xmlTag, final String typeModel) {
        this.xmlTag = xmlTag;
        this.typeModel = typeModel;
    }

    public String toPythonCode() {
        final StringBuilder builder = new StringBuilder();
        builder.append("'").append(capFirst(xmlTag)).append("': ").append(typeModel);
        if (!typeModel.equals("None")) {
            builder.append("()");
        }
        return  builder.toString();
    }
}


text:
<?php

namespace MrcMorales\TyreBundle\Enum;

/**
 * Enum
 */
class Enum
{
    /**
     * @return array
     */
    public static function toArray()
    {
        $class = new \ReflectionClass(get_called_class());

        return $class->getConstants();
    }

    /**
     * @return array
     */
    public static function toHumanizedArray()
    {
        $class = new \ReflectionClass(get_called_class());

        return $class->getConstants();
    }

    /**
     * @return array
     */
    public static function values()
    {
        $class = new \ReflectionClass(get_called_class());

        return array_flip($class->getConstants());
    }

    /**
     * @return array
     */
    public static function humanizedValues()
    {
        $values = self::values();
        foreach ($values as $k => &$v) {
            $v = trim(strtolower($v));
            $v = preg_replace('/_/', ' ', $v);
            $v = explode(' ', $v);
            $v = array_map('ucwords', $v);
            $v = implode(' ', $v);
        }

        return $values;
    }
}


text:
package org.wso2.am.integration.tests.sample;

import org.json.JSONObject;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import org.wso2.am.integration.test.utils.base.AMIntegrationBaseTest;
import org.wso2.am.integration.test.utils.bean.*;
import org.wso2.am.integration.test.utils.clients.APIPublisherRestClient;
import org.wso2.am.integration.test.utils.clients.APIStoreRestClient;
import org.wso2.carbon.automation.test.utils.http.client.HttpRequestUtil;
import org.wso2.carbon.automation.test.utils.http.client.HttpResponse;
import org.wso2.carbon.integration.common.utils.mgt.ServerConfigurationManager;

import javax.ws.rs.core.Response;
import java.io.File;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;

public class RefreshTokenTestCase extends AMIntegrationBaseTest {

    private APIPublisherRestClient apiPublisher;
    private APIStoreRestClient apiStore;
    private ServerConfigurationManager serverConfigurationManager;

    @BeforeClass(alwaysRun = true)
    public void init() throws Exception {

        super.init();
        /*
          If test run in external distributed deployment you need to copy following resources accordingly.
          configFiles/hostobjecttest/api-manager.xml
          configFiles/tokenTest/log4j.properties
        */

        String publisherURLHttp = getPublisherServerURLHttp();
        String storeURLHttp = getStoreServerURLHttp();
        serverConfigurationManager = new ServerConfigurationManager(apimContext);
        serverConfigurationManager.applyConfigurationWithoutRestart(new File(getAMResourceLocation()
                + File.separator + "configFiles" + File.separator + "tokenTest" + File.separator +
                "api-manager.xml"));
        serverConfigurationManager.applyConfiguration(new File(getAMResourceLocation()
                + File.separator + "configFiles" + File.separator + "tokenTest" + File.separator +
                "log4j.properties"));
        super.init();

        apiPublisher = new APIPublisherRestClient(publisherURLHttp);
        apiStore = new APIStoreRestClient(storeURLHttp);

    }

    @Test(groups = {"wso2.am"}, description = "Token API Test sample")
    public void testTokenAPITestCase() throws Exception {

        String APIName = "RefreshTokenTestAPI";
        String APIContext = "refreshTokenTestAPI";
        String tags = "youtube, token, media";
        String url = "http://gdata.youtube.com/feeds/api/standardfeeds";
        String description = "This is test API create by API manager integration test";
        String name = apimContext.getSuperTenant().getContextUser().getUserName();
        String password = apimContext.getSuperTenant().getContextUser().getPassword();
        String APIVersion = "1.0.0";
        apiPublisher.login(apimContext.getContextTenant().getContextUser().getUserName(),
                apimContext.getContextTenant().getContextUser().getPassword());
        APIRequest apiRequest = new APIRequest(APIName, APIContext, new URL(url));
        apiRequest.setTags(tags);
        apiRequest.setDescription(description);
        apiRequest.setVersion(APIVersion);
        apiRequest.setSandbox(url);
        apiPublisher.addAPI(apiRequest);
        APILifeCycleStateRequest updateRequest =
                new APILifeCycleStateRequest(APIName, name, APILifeCycleState.PUBLISHED);
        apiPublisher.changeAPILifeCycleStatus(updateRequest);

        apiStore.login(apimContext.getContextTenant().getContextUser().getUserName(),
                apimContext.getContextTenant().getContextUser().getPassword());
        apiStore.addApplication("RefreshTokenTestAPI-Application", "Gold", "", "this-is-test");
        SubscriptionRequest subscriptionRequest = new SubscriptionRequest(APIName,
                apimContext.getContextTenant()
                        .getContextUser()
                        .getUserName());
        subscriptionRequest.setTier("Gold");
        subscriptionRequest.setApplicationName("RefreshTokenTestAPI-Application");
        apiStore.subscribe(subscriptionRequest);

        //Generate production token and invoke with that
        GenerateAppKeyRequest generateAppKeyRequest =
                new GenerateAppKeyRequest("RefreshTokenTestAPI-Application");
        String responseString = apiStore.generateApplicationKey(generateAppKeyRequest).getData();
        JSONObject response = new JSONObject(responseString);

        // get Consumer Key and Consumer Secret
        String consumerKey =
                response.getJSONObject("data").getJSONObject("key").getString("consumerKey");
        String consumerSecret =
                response.getJSONObject("data").getJSONObject("key").getString("consumerSecret");

        //Obtain user access token
        Thread.sleep(2000);
        String requestBody = "grant_type=password&username=" + name + "&password=" + password + "&scope=PRODUCTION";
        URL tokenEndpointURL = new URL(getGatewayServerURLHttps() + "/token");
        JSONObject accessTokenGenerationResponse = new JSONObject(
                apiStore.generateUserAccessKey(consumerKey, consumerSecret, requestBody,
                        tokenEndpointURL).getData());

        // get Access Token and Refresh Token
        String userAccessToken = accessTokenGenerationResponse.getString("access_token");
        String refreshToken = accessTokenGenerationResponse.getString("refresh_token");

        Map<String, String> requestHeaders = new HashMap<String, String>();
        //Check Access Token
        requestHeaders.put("Authorization", "Bearer " + userAccessToken);
        Thread.sleep(2000);
        HttpResponse youTubeResponse = HttpRequestUtil
                .doGet(getGatewayServerURLHttp() + "/refreshTokenTestAPI/1.0.0/most_popular", requestHeaders);
        //check JWT headers here
        assertEquals(youTubeResponse.getResponseCode(), Response.Status.OK.getStatusCode(), "Response code mismatched");
        assertTrue(youTubeResponse.getData().contains("<feed"), "Response data mismatched");
        assertTrue(youTubeResponse.getData().contains("<category"),
                "Response data mismatched");
        assertTrue(youTubeResponse.getData().contains("<entry>"),
                "Response data mismatched");

        // get a new access token using refresh token
        String getAccessTokenFromRefreshTokenRequestBody =
                "grant_type=refresh_token&refresh_token=" + refreshToken + "&scope=PRODUCTION";
        accessTokenGenerationResponse = new JSONObject(
                apiStore.generateUserAccessKey(consumerKey, consumerSecret,
                        getAccessTokenFromRefreshTokenRequestBody,
                        tokenEndpointURL).getData());
        userAccessToken = accessTokenGenerationResponse.getString("access_token");

        requestHeaders = new HashMap<String, String>();
        //Check with new Access Token
        requestHeaders.put("Authorization", "Bearer " + userAccessToken);
        Thread.sleep(2000);
        youTubeResponse = HttpRequestUtil
                .doGet(getGatewayServerURLHttp() + "/refreshTokenTestAPI/1.0.0/most_popular", requestHeaders);
        //check JWT headers here
        assertEquals(youTubeResponse.getResponseCode(), Response.Status.OK.getStatusCode(), "Response code mismatched");
        assertTrue(youTubeResponse.getData().contains("<feed"), "Response data mismatched");
        assertTrue(youTubeResponse.getData().contains("<category"),
                "Response data mismatched");
        assertTrue(youTubeResponse.getData().contains("<entry>"),
                "Response data mismatched");
    }

    @AfterClass(alwaysRun = true)
    public void destroy() throws Exception {
        apiStore.removeApplication("RefreshTokenTestAPI-Application");
        super.cleanup();
        serverConfigurationManager.restoreToLastConfiguration();
    }
}


text:
# neat-stack

[![NPM version](https://img.shields.io/npm/v/neat-stack.svg)](https://www.npmjs.com/package/neat-stack)
[![Build Status](https://travis-ci.org/shinnn/neat-stack.svg?branch=master)](https://travis-ci.org/shinnn/neat-stack)
[![Build status](https://ci.appveyor.com/api/projects/status/x8vq3s90c2x0putc/branch/master?svg=true)](https://ci.appveyor.com/project/ShinnosukeWatanabe/neat-stack/branch/master)
[![Coverage Status](https://img.shields.io/coveralls/shinnn/neat-stack.svg)](https://coveralls.io/github/shinnn/neat-stack?branch=master)

Make a color-coded stack trace from an error

```javascript
const neatStack = require('neat-stack');
const request = require('request');

request('foo', err => console.error(neatStack(err)));
```

![screenshot](screenshot.png)

Useful for CLI applications — stack traces are not very important for end users but needed for authors to receive meaningful bug reports.

## Installation

[Use npm.](https://docs.npmjs.com/cli/install)

```
npm install neat-stack
```

## API

```javascript
const neatStack = require('neat-stack');
```

### neatStack(*error*)

*error*: `Error`
Return: `string`

It returns a refined [`Error#stack`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error/Stack):

* Red-colored by [ANSI escape code](https://en.wikipedia.org/wiki/ANSI_escape_code).
* Lines starting with `'    at'` are dimmed.
* [Any lines from Node.js internals are omitted](https://github.com/sindresorhus/clean-stack).

```javascript
const error = new Error('Hi');

error.stack; /* => `Error: Hi
    at Object.<anonymous> (/Users/example/run.js:1:77)
    at Module._compile (module.js:571:32)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:488:32)
    at tryModuleLoad (module.js:447:12)
    at Function.Module._load (module.js:439:3)
    at Module.runMain (module.js:605:10)
    at run (bootstrap_node.js:423:7)
    at startup (bootstrap_node.js:147:9)
    at bootstrap_node.js:538:3` */

neatStack(error); /* => `\u001b[31mError: Hi\u001b[2m
    at Object.<anonymous> (/Users/example/run.js:1:77)\u001b[22m\u001b[39m` */
```

## License

[Creative Commons Zero v1.0 Universal](https://creativecommons.org/publicdomain/zero/1.0/deed)


text:
using FishKing.Entities;
using FishKing.GameClasses;
using FishKing.Managers;
using FishKing.Screens;
using FishKing.UtilityClasses;
using FlatRedBall.Glue.StateInterpolation;
using FlatRedBall.Instructions;
using StateInterpolationPlugin;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FishKing.GumRuntimes
{
    partial class TournamentStatusRuntime : IInstructable
    {
        public float AbsoluteHeight
        {
            get
            {
                return (this as RenderingLibrary.IPositionedSizedObject).Height - 14f;
            }
        }
        private int playerScore;
        public int PlayerScore
        {
            get { return playerScore; }
            private set { playerScore = value; UpdatePlayerScore(); }
        }
        private int playerFishNumber;
        public int PlayerFishNumber
        {
            get { return playerFishNumber; }
            set { playerFishNumber = value; SetPlayerFish(); }
        }
        private int goalScore;
        public int GoalScore
        {
            get { return goalScore; }
            set { goalScore = value; UpdateGoalScore(); }
        }
        private int playerPlace;
        public int PlayerPlace
        {
            get { return playerPlace; }
            private set { playerPlace = value; }
        }

        public InstructionList Instructions
        {
            get
            {
                return ((IInstructable)gameScreen).Instructions;
            }
        }

        private bool hasStartedCelebration;
        public bool HasStartedCelebration
        {
            get { return hasStartedCelebration; }
        }

        public GameScreen gameScreen;

        private int? lastTopFishPlace = null;
        private int? lastBottomFishPlace = null;
        private int? lastPlayerPlace = null;
        private int? lastTopFishNum = null;
        private int? lastBottomFishNum = null;
        private int? lastTopFishScore = null;
        private int? lastBottomFishScore = null;
        private int? lastPlayerScore = null;
        private int[] score;
        private int[] sortedScore;

        partial void CustomInitialize()
        {
            Reset();
            WaveMovementAnimation.Play();
            TopFishInstance.FishSwimAnimation.Play();
            PlayerFishInstance.FishSwimAnimation.Play();
            BottomFishInstance.FishSwimAnimation.Play();
            GlowingStarInstance.StarGlowAnimation.Play();
            TrophyDisplayInstance.TrophyPulseAnimation.Play();
            BottomFishInstance.Visible = false;
            TopFishInstance.Visible = false;
        }

        public void CustomActivity()
        {
            if (PlayerScore >= GoalScore && !ThrowConfettiAnimation.IsPlaying())
            {
                ThrowConfettiAnimation.Play();
            }
        }

        public void UpdateFishPlaceMarkers(int[] scoreArray)
        {
            score = scoreArray;
            sortedScore = (int[])scoreArray.Clone();
            Array.Sort<int>(sortedScore,
                new Comparison<int>(
                        (i1, i2) => i2.CompareTo(i1)
                ));

            playerScore = scoreArray[0];
            int maxScore = scoreArray.Max();
            int minScore = scoreArray.Min();

            bool playerInFirst = playerScore == maxScore;
            bool playerInLast = playerScore == minScore;
            playerPlace = (playerInFirst ? 1 : playerInLast ? scoreArray.Count() : Array.IndexOf(sortedScore, playerScore) + 1);

            int topFishNum = -1, bottomFishNum = -1,
                topFishPlace = 0, bottomFishPlace = 0,
                topFishScore = 0, bottomFishScore = 0;

            //Update player
            if (lastPlayerPlace != playerPlace)
            {
                SetFishPlaceFromNumber(PlayerFishInstance, playerPlace);
            }
            if (playerScore != lastPlayerScore)
            {
                JumpFishTo(PlayerFishInstance, GetGoalProgress(playerScore));
            }
            //Check if top fish needs updating
            if (lastTopFishNum.HasValue)
            {
                topFishNum = lastTopFishNum.Value;
                topFishScore = scoreArray[topFishNum];
                topFishPlace = Array.IndexOf(sortedScore, topFishScore) + 1;

                if (IsFishNearPlayerPlace(playerInFirst, playerInLast, topFishPlace) && topFishScore < goalScore)
                {
                    if (topFishScore != lastTopFishScore)
                    {
                        JumpFishTo(TopFishInstance, GetGoalProgress(topFishScore));
                    }
                    if (topFishPlace != lastTopFishPlace)
                    {
                        SetFishPlaceFromNumber(TopFishInstance, topFishPlace);
                    }
                }
                else //Choose a new fish for top
                {
                    int exceptNum = (lastBottomFishNum.HasValue ? lastBottomFishNum.Value : 0);
                    var newFish = GetSuitableFish(playerInFirst, playerInLast, exceptNum);
                    if (newFish.Item1 != -1)
                    {
                        topFishNum = newFish.Item1;
                        topFishScore = newFish.Item2;
                        topFishPlace = newFish.Item3;
                    }
                    else
                    {
                        topFishNum = -1;
                    }
                }
                if (topFishNum != lastTopFishNum.Value)
                {
                    if (scoreArray[lastTopFishNum.Value] > scoreArray[topFishNum])
                    {
                        FishPassing(TopFishInstance, topFishNum, topFishPlace, topFishScore);
                    }
                    else
                    {
                        FishPassedBy(TopFishInstance, topFishNum, topFishPlace, topFishScore);
                    }
                }
            }
            else
            {
                int exceptNum = (lastBottomFishNum.HasValue ? lastBottomFishNum.Value : 0);
                var newFish = GetSuitableFish(playerInFirst, playerInLast, exceptNum);
                if (newFish.Item1 != -1)
                {
                    topFishNum = newFish.Item1;
                    topFishScore = newFish.Item2;
                    topFishPlace = newFish.Item3;
                    TopFishInstance.TournamentFishProgress = GetGoalProgress(topFishScore);
                    SetFishPlaceFromNumber(TopFishInstance, topFishPlace);
                    SetFishTypeFromNumber(TopFishInstance, topFishNum);
                }
            }

            //Check if bottom fish needs updating
            if (lastBottomFishNum.HasValue)
            {
                bottomFishNum = lastBottomFishNum.Value;
                bottomFishScore = scoreArray[bottomFishNum];
                bottomFishPlace = Array.IndexOf(sortedScore, bottomFishScore) + 1;

                if (IsFishNearPlayerPlace(playerInFirst, playerInLast, bottomFishPlace) && bottomFishScore < goalScore)
                {
                    //Bottom fish keeps its place, update if necessary
                    if (bottomFishScore != lastBottomFishScore)
                    {
                        JumpFishTo(BottomFishInstance, GetGoalProgress(bottomFishScore));
                    }
                    if (bottomFishPlace != lastBottomFishPlace)
                    {
                        SetFishPlaceFromNumber(BottomFishInstance, bottomFishPlace);
                    }
                }
                else //Choose a new fish for bottom
                {
                    var newFish = GetSuitableFish(playerInFirst, playerInLast, topFishNum);
                    if (newFish.Item1 != -1)
                    {
                        bottomFishNum = newFish.Item1;
                        bottomFishScore = newFish.Item2;
                        bottomFishPlace = newFish.Item3;
                    }
                    else
                    {
                        bottomFishNum = -1;
                    }
                }
                if (bottomFishNum != lastBottomFishNum.Value)
                {
                    if (scoreArray[lastBottomFishNum.Value] > scoreArray[bottomFishNum])
                    {
                        FishPassing(BottomFishInstance, bottomFishNum, bottomFishPlace, bottomFishScore);
                    }
                    else
                    {
                        FishPassedBy(BottomFishInstance, bottomFishNum, bottomFishPlace, bottomFishScore);
                    }
                }
            }
            else //Choose a new fish for bottom
            {
                var newFish = GetSuitableFish(playerInFirst, playerInLast, topFishNum);
                if (newFish.Item1 != -1)
                {
                    bottomFishNum = newFish.Item1;
                    bottomFishScore = newFish.Item2;
                    bottomFishPlace = newFish.Item3;
                    BottomFishInstance.TournamentFishProgress = GetGoalProgress(bottomFishScore);
                    SetFishPlaceFromNumber(BottomFishInstance, bottomFishPlace);
                    SetFishTypeFromNumber(BottomFishInstance, bottomFishNum);
                }
            }

            //Handle tournamentplaceholder markers
            var maxPossiblePlace = score.Where(s => s >= goalScore).Count() + 1;
            if (playerPlace != maxPossiblePlace && topFishPlace != maxPossiblePlace && bottomFishPlace != maxPossiblePlace)
            {
                SetPlaceHolder(PlaceHolder1, maxPossiblePlace, GetGoalProgress(sortedScore[maxPossiblePlace - 1]));
            }
            else if (playerPlace == maxPossiblePlace && topFishPlace > 0 && bottomFishPlace > 0)
            {
                var placeToShow = Math.Max(topFishPlace, bottomFishPlace) + 1;
                if (placeToShow < score.Count())
                {
                    SetPlaceHolder(PlaceHolder1, placeToShow, GetGoalProgress(sortedScore[placeToShow - 1]));
                }
            }
            else
            {
                HidePlaceHolder(PlaceHolder1);
            }
            if (PlayerPlace > maxPossiblePlace + 2)
            {
                var placeToShow = PlayerPlace - 2;
                var scoreForPlace = sortedScore[placeToShow - 1];
                if (scoreForPlace > playerScore && scoreForPlace != topFishScore && scoreForPlace != bottomFishScore)
                {
                    SetPlaceHolder(PlaceHolder2, placeToShow, GetGoalProgress(scoreForPlace));
                }
            }
            else
            {
                HidePlaceHolder(PlaceHolder2);
            }

            if (topFishNum != -1)
            {
                lastTopFishNum = topFishNum;
                lastTopFishScore = topFishScore;
                lastTopFishPlace = topFishPlace;
                TopFishInstance.Visible = true;
            }
            else
            {
                lastTopFishNum = lastTopFishScore = lastTopFishPlace = null;
                TopFishInstance.Visible = false;
            }
            if (bottomFishNum != -1)
            {
                lastBottomFishNum = bottomFishNum;
                lastBottomFishScore = bottomFishScore;
                lastBottomFishPlace = bottomFishPlace;
                BottomFishInstance.Visible = true;
            }
            else
            {
                lastBottomFishNum = lastBottomFishScore = lastBottomFishPlace = null;
                BottomFishInstance.Visible = false;
            }

            lastPlayerScore = playerScore;
            lastPlayerPlace = PlayerPlace;
            PlayerScore = playerScore;

            TrophyDisplayInstance.SetTrophyByPlaceNumber(Math.Min(playerPlace,maxPossiblePlace));
        }

        private bool IsFishNearPlayerPlace(bool playerInFirst, bool playerInLast, int fishPlace)
        {
            int nonZeroPlace1 = -1;
            int nonZeroPlace2 = -1;
            var lastNonZero = sortedScore.Where(s => s > 0 && s < goalScore);
            if (lastNonZero.Count() > 0)
            {
                nonZeroPlace1 = Array.IndexOf(sortedScore, lastNonZero.Last())+1;
            }
            if (lastNonZero.Count() > 1)
            {
                nonZeroPlace2 = Array.IndexOf(sortedScore, lastNonZero.ElementAt(lastNonZero.Count() - 2))+1;
            }

            return ((fishPlace == PlayerPlace)
                    ||
                    (playerInFirst && fishPlace < 4) //Fish in top 3
                    ||
                    (playerInLast &&
                        (fishPlace == nonZeroPlace1 ||
                        fishPlace == nonZeroPlace2 ||
                        fishPlace == PlayerPlace + 1 || //Second-to-last
                        fishPlace == PlayerPlace + 2)) //Third-to-last
                    ||
                    (!playerInFirst && !playerInLast &&
                        (fishPlace == PlayerPlace + 1 || //One place ahead of player
                        fishPlace == PlayerPlace - 1))); //One place behind player
        }

        private Tuple<int, int, int> GetSuitableFish(bool playerInFirst, bool playerInLast, int exceptNum)
        {
            int fishScore = 0;
            int fishNum = 0;
            int fishPlace = 0;
            if (playerInFirst)
            {
                int possibleScore = sortedScore[1];
                int possibleFishNum = Array.IndexOf(score, possibleScore, 1);

                if (exceptNum == possibleFishNum)
                {
                    fishScore = sortedScore[2];
                    if (fishScore == possibleScore)
                    {
                        fishNum = Array.IndexOf(score, fishScore, exceptNum + 1);
                    }
                    else
                    {
                        fishNum = Array.IndexOf(score, fishScore, 1);
                    }
                }
                else
                {
                    fishScore = possibleScore;
                    fishNum = possibleFishNum;
                }
            }
            else if (playerInLast)
            {
                var nonZeroScores = sortedScore.Where(s => s > 0 && s < goalScore);
                if (nonZeroScores.Count() > 0)
                {
                    int possibleScore = nonZeroScores.Last();
                    int possibleFishNum = Array.IndexOf(score, possibleScore, 1);

                    if (exceptNum == possibleFishNum)
                    {
                        if (nonZeroScores.Count() > 1)
                        {
                            fishScore = nonZeroScores.ElementAt(nonZeroScores.Count() - 2);
                            if (fishScore == possibleScore)
                            {
                                fishNum = Array.IndexOf(score, fishScore, exceptNum + 1);
                            }
                            else
                            {
                                fishNum = Array.IndexOf(score, fishScore, 1);
                            }
                        }
                    }
                    else
                    {
                        fishScore = possibleScore;
                        fishNum = possibleFishNum;
                    }
                }
            }
            else
            {
                int possibleScore = sortedScore[PlayerPlace];
                int possibleFishNum = Array.IndexOf(score, possibleScore, 1);

                if (exceptNum == possibleFishNum)
                {
                    fishScore = sortedScore[PlayerPlace - 2];
                    if (fishScore == possibleScore)
                    {
                        fishNum = Array.IndexOf(score, fishScore, exceptNum + 1);
                    }
                    else
                    {
                        fishNum = Array.IndexOf(score, fishScore, 1);
                    }
                }
                else
                {
                    fishScore = possibleScore;
                    fishNum = possibleFishNum;
                }
            }
            fishPlace = Array.IndexOf(sortedScore, fishScore) + 1;

            if (fishScore == 0 && fishScore >= goalScore)
            {
                fishNum = -1;
            }

            return new Tuple<int, int, int>(fishNum, fishScore, fishPlace);
        }
        private float GetGoalProgress(int score)
        {
            return (float)Decimal.Divide(score, goalScore) * 100;
        }

        private void FishPassedBy(TournamentFishRuntime fish, int newFishNum, int newFishPlace, int newFishScore)
        {
            fish.Visible = true;
            fish.FishSwimAnimation.Stop();
            fish.PassedOutAnimation.Play();
            this.Call(() =>
            {
                SetFishTypeFromNumber(fish, newFishNum);
                fish.TournamentFishProgress = GetGoalProgress(newFishScore);
                SetFishPlaceFromNumber(fish, newFishPlace);
                fish.PassedInAnimation.Play();
                this.Call(fish.FishSwimAnimation.Play).After(fish.PassedInAnimation.Length);
            }).After(fish.PassedOutAnimation.Length);
        }

        private void FishPassing(TournamentFishRuntime fish, int newFishNum, int newFishPlace, int newFishScore)
        {
            fish.Visible = true;
            fish.FishSwimAnimation.Stop();
            fish.PassingOutAnimation.Play();
            this.Call(() =>
            {
                SetFishTypeFromNumber(fish, newFishNum);
                fish.TournamentFishProgress = GetGoalProgress(newFishScore);
                SetFishPlaceFromNumber(fish, newFishPlace);
                fish.PassingInAnimation.Play();
                this.Call(fish.FishSwimAnimation.Play).After(fish.PassingInAnimation.Length);
            }).After(fish.PassingOutAnimation.Length);
        }

        private void JumpFishTo(TournamentFishRuntime fish, float newPosition)
        {
            fish.Visible = true;
            var timeToTween = fish.FishJumpAnimation.Length;
            var startValue = fish.TournamentFishProgress;
            var tweenHolder = new TweenerHolder();
            tweenHolder.Caller = fish;
            var fishJumpTweener = new Tweener(startValue, newPosition, timeToTween, InterpolationType.Quartic, Easing.Out);
            fishJumpTweener.PositionChanged += (position) =>
            {
                fish.TournamentFishProgress = position;
            };
            //fishJumpTweener.Ended += afterAction;
            fishJumpTweener.Start();
            TweenerManager.Self.Add(fishJumpTweener);
            if (!fish.FishJumpAnimation.IsPlaying())
            {
                fish.FishJumpAnimation.Play();
            }
        }

        public void Reset()
        {
            hasStartedCelebration = false;
            ScoreText.Text = "0";

            lastTopFishScore = 0;
            PlayerScore = 0;
            lastBottomFishScore = 0;

            lastTopFishPlace = -1;
            lastPlayerPlace = -1;
            lastBottomFishPlace = -1;

            TopFishInstance.TournamentFishProgress = 0;
            PlayerFishInstance.TournamentFishProgress = 0;
            BottomFishInstance.TournamentFishProgress = 0;

            TopFishInstance.CurrentTournamentPlaceState = TournamentFishRuntime.TournamentPlace.None;
            PlayerFishInstance.CurrentTournamentPlaceState = TournamentFishRuntime.TournamentPlace.None;
            BottomFishInstance.CurrentTournamentPlaceState = TournamentFishRuntime.TournamentPlace.None;

            HidePlaceHolder(PlaceHolder1);
            HidePlaceHolder(PlaceHolder2);
        }

        private void SetPlaceHolder(TournamentPlaceHolderRuntime holder, int place, float progress)
        {
            TournamentPlaceHolderRuntime.Place placeState;
            switch (place)
            {
                case 1: placeState = TournamentPlaceHolderRuntime.Place.First; break;
                case 2: placeState = TournamentPlaceHolderRuntime.Place.Second; break;
                case 3: placeState = TournamentPlaceHolderRuntime.Place.Third; break;
                case 4: placeState = TournamentPlaceHolderRuntime.Place.Fourth; break;
                case 5: placeState = TournamentPlaceHolderRuntime.Place.Fifth; break;
                case 6: placeState = TournamentPlaceHolderRuntime.Place.Sixth; break;
                case 7: placeState = TournamentPlaceHolderRuntime.Place.Seventh; break;
                case 8: placeState = TournamentPlaceHolderRuntime.Place.Eighth; break;
                default: placeState = TournamentPlaceHolderRuntime.Place.First; break;
            }

            holder.TournamentPlaceHolderProgress = progress;
            holder.CurrentPlaceState = placeState;
            holder.Visible = true;
            if (!holder.PlacePulseAnimation.IsPlaying())
            {
                holder.PlacePulseAnimation.Play();
            }
        }

        private void HidePlaceHolder(TournamentPlaceHolderRuntime holder)
        {
            holder.PlacePulseAnimation.Stop();
            holder.Visible = false;
        }

        private void UpdateGoalScore()
        {
            GoalScoreText.Text = goalScore.ToString();
            if (goalScore > 199)
            {
                CurrentGoalValueState = GoalValue.More;
            }
            else
            {
                CurrentGoalValueState = GoalValue.OneHundreds;
            }
        }

        private void UpdatePlayerScore()
        {
            ScoreText.Text = PlayerScore.ToString();
            GlowingStarInstance.StarFlashAnimation.Play();
        }

        public void SetPlayerFish()
        {
            SetFishTypeFromNumber(PlayerFishInstance, PlayerFishNumber);
        }

        private void SetFishTypeFromNumber(TournamentFishRuntime fish, int fishNumber)
        {
            if (fish != PlayerFishInstance && fishNumber == PlayerFishNumber)
            {
                fishNumber = 0;
            }

            TournamentFishRuntime.FishType fishType;
            switch (fishNumber)
            {
                case 0: fishType = TournamentFishRuntime.FishType.FishType1; break;
                case 1: fishType = TournamentFishRuntime.FishType.FishType2; break;
                case 2: fishType = TournamentFishRuntime.FishType.FishType3; break;
                case 3: fishType = TournamentFishRuntime.FishType.FishType4; break;
                case 4: fishType = TournamentFishRuntime.FishType.FishType5; break;
                case 5: fishType = TournamentFishRuntime.FishType.FishType6; break;
                case 6: fishType = TournamentFishRuntime.FishType.FishType7; break;
                case 7: fishType = TournamentFishRuntime.FishType.FishType8; break;
                default: fishType = TournamentFishRuntime.FishType.FishType1; break;
            }
            fish.CurrentFishTypeState = fishType;
        }

        private void SetFishPlaceFromNumber(TournamentFishRuntime fish, int place)
        {
            TournamentFishRuntime.TournamentPlace fishPlace;
            switch (place)
            {
                case 1: fishPlace = TournamentFishRuntime.TournamentPlace.FirstPlace; break;
                case 2: fishPlace = TournamentFishRuntime.TournamentPlace.SecondPlace; break;
                case 3: fishPlace = TournamentFishRuntime.TournamentPlace.ThirdPlace; ; break;
                case 4: fishPlace = TournamentFishRuntime.TournamentPlace.FourthPlace; break;
                case 5: fishPlace = TournamentFishRuntime.TournamentPlace.FifthPlace; break;
                case 6: fishPlace = TournamentFishRuntime.TournamentPlace.SixthPlace; break;
                case 7: fishPlace = TournamentFishRuntime.TournamentPlace.SeventhPlace; break;
                case 8: fishPlace = TournamentFishRuntime.TournamentPlace.EighthPlace; break;
                default: fishPlace = TournamentFishRuntime.TournamentPlace.None; break;
            }
            fish.CurrentTournamentPlaceState = fishPlace;
        }

        private void CustomDestroy()
        {

        }

        private static void CustomLoadStaticContent(string contentManagerName)
        {

        }

        public void Setup(GameScreen screen)
        {
#if DEBUG
            if (DebuggingVariables.MapDebugMode) return;
#endif
            this.gameScreen = screen;
            PlayerFishNumber = SaveGameManager.CurrentSaveData.PlayerFishNumber;
            GoalScore = TournamentManager.CurrentTournament.GoalPoints;

            var currentScores = TournamentManager.CurrentScores.AsArray;

            if (currentScores.Sum() > 0)
            {
                SetupFromScores(currentScores);
            }
        }

        private void SetupFromScores(int[] existingScore)
        {
            sortedScore = (int[])existingScore.Clone();
            Array.Sort<int>(sortedScore,
                new Comparison<int>(
                        (i1, i2) => i2.CompareTo(i1)
                ));

            playerScore = existingScore[0];

            int maxScore = existingScore.Max();
            int minScore = existingScore.Min();

            bool playerInFirst = playerScore == maxScore;
            bool playerInLast = playerScore == minScore;
            playerPlace = (playerInFirst ? 1 : playerInLast ? existingScore.Count() : Array.IndexOf(sortedScore, playerScore) + 1);
            lastPlayerPlace = playerPlace;
            lastPlayerScore = playerScore;

            SetFishPlaceFromNumber(PlayerFishInstance, playerPlace);
            PlayerFishInstance.TournamentFishProgress = GetGoalProgress(playerScore);
            UpdateFishPlaceMarkers(existingScore);
        }

        public void StartCelebration()
        {
            hasStartedCelebration = true;
            ThrowConfettiAnimation.Play();
        }
    }
}


text:
package com.amazonaws.services.ec2.model;

import java.io.Serializable;
import javax.annotation.Generated;

/**
 *

 * Describes an event in the history of an EC2 Fleet.
 *

 *
 * @see AWS API
 *      Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class HistoryRecordEntry implements Serializable, Cloneable {

    /**
     *

     * Information about the event.
     *

     */
    private EventInformation eventInformation;
    /**
     *

     * The event type.
     *

     */
    private String eventType;
    /**
     *

     * The date and time of the event, in UTC format (for example,
     * YYYY-MM-DDTHH:MM:SSZ).
     *

     */
    private java.util.Date timestamp;

    /**
     *

     * Information about the event.
     *

     *
     * @param eventInformation
     *        Information about the event.
     */

    public void setEventInformation(EventInformation eventInformation) {
        this.eventInformation = eventInformation;
    }

    /**
     *

     * Information about the event.
     *

     *
     * @return Information about the event.
     */

    public EventInformation getEventInformation() {
        return this.eventInformation;
    }

    /**
     *

     * Information about the event.
     *

     *
     * @param eventInformation
     *        Information about the event.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public HistoryRecordEntry withEventInformation(EventInformation eventInformation) {
        setEventInformation(eventInformation);
        return this;
    }

    /**
     *

     * The event type.
     *

     *
     * @param eventType
     *        The event type.
     * @see FleetEventType
     */

    public void setEventType(String eventType) {
        this.eventType = eventType;
    }

    /**
     *

     * The event type.
     *

     *
     * @return The event type.
     * @see FleetEventType
     */

    public String getEventType() {
        return this.eventType;
    }

    /**
     *

     * The event type.
     *

     *
     * @param eventType
     *        The event type.
     * @return Returns a reference to this object so that method calls can be chained together.
     * @see FleetEventType
     */

    public HistoryRecordEntry withEventType(String eventType) {
        setEventType(eventType);
        return this;
    }

    /**
     *

     * The event type.
     *

     *
     * @param eventType
     *        The event type.
     * @return Returns a reference to this object so that method calls can be chained together.
     * @see FleetEventType
     */

    public HistoryRecordEntry withEventType(FleetEventType eventType) {
        this.eventType = eventType.toString();
        return this;
    }

    /**
     *

     * The date and time of the event, in UTC format (for example,
     * YYYY-MM-DDTHH:MM:SSZ).
     *

     *
     * @param timestamp
     *        The date and time of the event, in UTC format (for example,
     *        YYYY-MM-DDTHH:MM:SSZ).
     */

    public void setTimestamp(java.util.Date timestamp) {
        this.timestamp = timestamp;
    }

    /**
     *

     * The date and time of the event, in UTC format (for example,
     * YYYY-MM-DDTHH:MM:SSZ).
     *

     *
     * @return The date and time of the event, in UTC format (for example,
     *         YYYY-MM-DDTHH:MM:SSZ).
     */

    public java.util.Date getTimestamp() {
        return this.timestamp;
    }

    /**
     *

     * The date and time of the event, in UTC format (for example,
     * YYYY-MM-DDTHH:MM:SSZ).
     *

     *
     * @param timestamp
     *        The date and time of the event, in UTC format (for example,
     *        YYYY-MM-DDTHH:MM:SSZ).
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public HistoryRecordEntry withTimestamp(java.util.Date timestamp) {
        setTimestamp(timestamp);
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getEventInformation() != null)
            sb.append("EventInformation: ").append(getEventInformation()).append(",");
        if (getEventType() != null)
            sb.append("EventType: ").append(getEventType()).append(",");
        if (getTimestamp() != null)
            sb.append("Timestamp: ").append(getTimestamp());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof HistoryRecordEntry == false)
            return false;
        HistoryRecordEntry other = (HistoryRecordEntry) obj;
        if (other.getEventInformation() == null ^ this.getEventInformation() == null)
            return false;
        if (other.getEventInformation() != null && other.getEventInformation().equals(this.getEventInformation()) == false)
            return false;
        if (other.getEventType() == null ^ this.getEventType() == null)
            return false;
        if (other.getEventType() != null && other.getEventType().equals(this.getEventType()) == false)
            return false;
        if (other.getTimestamp() == null ^ this.getTimestamp() == null)
            return false;
        if (other.getTimestamp() != null && other.getTimestamp().equals(this.getTimestamp()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getEventInformation() == null) ? 0 : getEventInformation().hashCode());
        hashCode = prime * hashCode + ((getEventType() == null) ? 0 : getEventType().hashCode());
        hashCode = prime * hashCode + ((getTimestamp() == null) ? 0 : getTimestamp().hashCode());
        return hashCode;
    }

    @Override
    public HistoryRecordEntry clone() {
        try {
            return (HistoryRecordEntry) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
        }
    }

}