text:
<?php

?>

@extends('Admin::layout.admin')

@section('title', ':: Admin Dashboard')

@section('content')

    {{-- @include('Admin::partials.default-page-header', ['pageHeader' => 'Admin Dashboard', 'quote' => false]) --}}

                @include('Admin::partials.admin-menu-sidebar')

User stats

                            <canvas id="userChart" width="135" height="135"></canvas>

                                    #
                                    Name
                                    E-Mail Address
                                    Created
                                    Last updated
                                    Last signed in

                                @foreach($users as $user)

                                    {{ $user->id }}
                                    {{ $user->name }}
                                    {{ $user->email }}
                                    {{ $user->created_at }}
                                    {{ $user->updated_at }}
                                     -

                                            <button type="button" class="btn btn-default">View</button>
                                            <button type="button" class="btn btn-success">Edit</button>
                                            <button type="button" class="btn btn-danger">Delete</button>

                                @endforeach

{!! $users->render() !!}

@endsection

@section('scripts')

    {{----}}

@endsection


text:
FOUNDATION_EXPORT double Pods_government_salariesVersionNumber;
FOUNDATION_EXPORT const unsigned char Pods_government_salariesVersionString[];

redpajama_set_name: RedPajamaGithub


text:
Colin's Simplifying Proposal
----------------------------

The blockchain contains two sets of records
    Host Record
        - Space Available (Unchecked)
        - Files Stored
        - Credit Balance
        - Address
    File Record
        - Lists money left
        - Lists proofs
        - States host
        - Storage metadata
    When a block is published it publishes the new set, as well as the signed
    updates

Update Types
    Balance Transfer
        - This transfers balances between arbitrary hosts
        - Must be signed by source host
    File Addition / Update
        - Has balance added (done by file source)
        - Lists where/how to get file (Done by file source)
        - Lists hosts where file is assigned (Done by block)
        - Has file puzzles (created by file source)
        - has payout rate (set by block)
        - Removes balance from hosts where file is
          stored for recreation bonus (Done by block)
    File Balance payout
        - Triggered by proof of storage from server (block signature)
    File Balance Update
        - Adds balance / replication rate
        - Must not lower eta
            - Adding balance always okay
            - Adding rate requires cur_balance/copies per additional copy
    File Shuffle
        - Describes files being moved, generally attached to a file addition
        - Lowers Host Balance
        - Adds Other Host Balance
    Host Addition
        - Adds a possible host storage

Trusted Curve
25, 519


text:
package org.multibit.hd.error_reporting.health;

/**
 *
HealthCheck to provide the following to application:

 *

 *
Provision of checks against a given Configuration property

 *

 *
 * @since 0.0.1
 *
 */

import com.yammer.metrics.core.HealthCheck;
import org.multibit.hd.error_reporting.core.email.Emails;

public class EmailHealthCheck extends HealthCheck {

  public EmailHealthCheck() {
    super("SMTP gateway health check");
  }

  @Override
  protected Result check() throws Exception {
    try {
      Emails.sendSupportEmail("Health check email (Error Reporting Service) - please delete");
    } catch (IllegalStateException e) {
      return Result.unhealthy("Verify environment variables: SMTP_PASSWORD for this user\n"+e.getMessage());
    }

    return Result.healthy();
  }
}


text:
package com.annimon.hotarufx.visual;

import java.util.Map;
import java.util.TreeMap;
import javafx.animation.Interpolator;
import javafx.beans.value.WritableValue;

public class PropertyTimeline<T> {

    private final WritableValue<T> property;
    private final Map<KeyFrame, KeyFrameValue<T>> keyFrames;

    public PropertyTimeline(WritableValue<T> property) {
        this.property = property;
        keyFrames = new TreeMap<>();
    }

    public WritableValue<T> getProperty() {
        return property;
    }

    public Map<KeyFrame, KeyFrameValue<T>> getKeyFrames() {
        return keyFrames;
    }

    public PropertyTimeline<T> add(KeyFrame keyFrame, T value) {
        keyFrames.put(keyFrame, new KeyFrameValue<>(value));
        return this;
    }

    public PropertyTimeline<T> add(KeyFrame keyFrame, T value, Interpolator interpolator) {
        keyFrames.put(keyFrame, new KeyFrameValue<>(value, interpolator));
        return this;
    }

    public PropertyTimeline<T> clear() {
        keyFrames.clear();
        return this;
    }
}


text: <!DOCTYPE html>


text:
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.

using System;
using osu.Framework.Platform;

namespace osu.Framework.Input
{
    public class GameWindowTextInput : ITextInputSource
    {
        private readonly IWindow window;

        private string pending = string.Empty;

        public GameWindowTextInput(IWindow window)
        {
            this.window = window;
        }

        protected virtual void HandleKeyPress(object sender, osuTK.KeyPressEventArgs e) => pending += e.KeyChar;

        protected virtual void HandleKeyTyped(char c) => pending += c;

        public bool ImeActive => false;

        public string GetPendingText()
        {
            try
            {
                return pending;
            }
            finally
            {
                pending = string.Empty;
            }
        }

        public void Deactivate(object sender)
        {
            if (window is DesktopWindow win)
                win.KeyTyped -= HandleKeyTyped;
            else
                window.KeyPress -= HandleKeyPress;
        }

        public void Activate(object sender)
        {
            if (window is DesktopWindow win)
                win.KeyTyped += HandleKeyTyped;
            else
                window.KeyPress += HandleKeyPress;
        }

        private void imeCompose()
        {
            //todo: implement
            OnNewImeComposition?.Invoke(string.Empty);
        }

        private void imeResult()
        {
            //todo: implement
            OnNewImeResult?.Invoke(string.Empty);
        }

        public event Action<string> OnNewImeComposition;
        public event Action<string> OnNewImeResult;
    }
}


text:
package broadcast

import (
	"context"

	"go-common/app/interface/main/app-resource/conf"
	broaddao "go-common/app/interface/main/app-resource/dao/broadcast"
	"go-common/app/interface/main/app-resource/model"
	"go-common/app/interface/main/app-resource/model/broadcast"
	warden "go-common/app/service/main/broadcast/api/grpc/v1"
	"go-common/library/log"
)

type Service struct {
	c   *conf.Config
	dao *broaddao.Dao
}

func New(c *conf.Config) (s *Service) {
	s = &Service{
		c:   c,
		dao: broaddao.New(c),
	}
	return
}

// ServerList warden server list
func (s *Service) ServerList(c context.Context, plat int8) (res *broadcast.ServerListReply, err error) {
	var (
		data     *warden.ServerListReply
		platform string
	)
	if model.IsIOS(plat) {
		platform = "ios"
	} else if model.IsAndroid(plat) {
		platform = "android"
	}
	if data, err = s.dao.ServerList(c, platform); err != nil {
		log.Error("ServerList s.dao.ServerList error(%v)", err)
		err = nil
		res = &broadcast.ServerListReply{
			Domain:       "broadcast.chat.bilibili.com",
			TCPPort:      7821,
			WsPort:       7822,
			WssPort:      7823,
			Heartbeat:    30,
			HeartbeatMax: 3,
			Nodes:        []string{"broadcast.chat.bilibili.com"},
			Backoff: &broadcast.Backoff{
				MaxDelay:  120,
				BaseDelay: 3,
				Factor:    1.6,
				Jitter:    0.2,
			},
		}
		return
	}
	res = &broadcast.ServerListReply{}
	res.ServerListChange(data)
	return
}


text:
package org.apereo.cas.authentication;

import org.apereo.cas.authentication.principal.Principal;
import org.apereo.cas.configuration.model.support.mfa.MultifactorAuthenticationProviderBypassProperties;
import org.apereo.cas.services.RegisteredService;
import org.apereo.cas.util.CollectionUtils;
import org.apereo.cas.util.RegexUtils;

import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.Ordered;

import javax.servlet.http.HttpServletRequest;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * This is {@link DefaultMultifactorAuthenticationProviderBypass}.
 *
 * @author Misagh Moayyed
 * @since 5.0.0
 */
@Slf4j
public class DefaultMultifactorAuthenticationProviderBypass implements MultifactorAuthenticationProviderBypass {

    private static final long serialVersionUID = 3720922341350004543L;

    private final MultifactorAuthenticationProviderBypassProperties bypassProperties;

    private final Pattern httpRequestRemoteAddressPattern;
    private final Set<Pattern> httpRequestHeaderPatterns;

    public DefaultMultifactorAuthenticationProviderBypass(final MultifactorAuthenticationProviderBypassProperties bypassProperties) {
        this.bypassProperties = bypassProperties;

        if (StringUtils.isNotBlank(bypassProperties.getHttpRequestRemoteAddress())) {
            this.httpRequestRemoteAddressPattern = RegexUtils.createPattern(bypassProperties.getHttpRequestRemoteAddress());
        } else {
            this.httpRequestRemoteAddressPattern = RegexUtils.MATCH_NOTHING_PATTERN;
        }

        val values = org.springframework.util.StringUtils.commaDelimitedListToSet(bypassProperties.getHttpRequestHeaders());
        this.httpRequestHeaderPatterns = values.stream().map(RegexUtils::createPattern).collect(Collectors.toSet());
    }

    @Override
    public boolean shouldMultifactorAuthenticationProviderExecute(final Authentication authentication,
                                                                  final RegisteredService registeredService,
                                                                  final MultifactorAuthenticationProvider provider,
                                                                  final HttpServletRequest request) {
        val principal = authentication.getPrincipal();
        LOGGER.debug("Evaluating multifactor authentication bypass properties for principal [{}], service [{}] and provider [{}]",
            principal.getId(), registeredService, provider);
        val bypassByPrincipal = locateMatchingAttributeBasedOnPrincipalAttributes(bypassProperties, principal);
        if (bypassByPrincipal) {
            LOGGER.debug("Bypass rules for principal [{}] indicate the request may be ignored", principal.getId());
            return false;
        }

        val bypassByAuthn = locateMatchingAttributeBasedOnAuthenticationAttributes(bypassProperties, authentication);
        if (bypassByAuthn) {
            LOGGER.debug("Bypass rules for authentication for principal [{}] indicate the request may be ignored", principal.getId());
            return false;
        }

        val bypassByAuthnMethod = locateMatchingAttributeValue(
            AuthenticationManager.AUTHENTICATION_METHOD_ATTRIBUTE,
            bypassProperties.getAuthenticationMethodName(),
            authentication.getAttributes(), false
        );
        if (bypassByAuthnMethod) {
            LOGGER.debug("Bypass rules for authentication method [{}] indicate the request may be ignored", bypassProperties.getAuthenticationMethodName());
            return false;
        }

        val bypassByHandlerName = locateMatchingAttributeValue(
            AuthenticationHandler.SUCCESSFUL_AUTHENTICATION_HANDLERS,
            bypassProperties.getAuthenticationHandlerName(),
            authentication.getAttributes(), false
        );
        if (bypassByHandlerName) {
            LOGGER.debug("Bypass rules for authentication handlers [{}] indicate the request may be ignored", bypassProperties.getAuthenticationHandlerName());
            return false;
        }

        val bypassByCredType = locateMatchingCredentialType(authentication, bypassProperties.getCredentialClassType());
        if (bypassByCredType) {
            LOGGER.debug("Bypass rules for credential types [{}] indicate the request may be ignored", bypassProperties.getCredentialClassType());
            return false;
        }

        val bypassByHttpRequest = locateMatchingHttpRequest(authentication, request);
        if (bypassByHttpRequest) {
            LOGGER.debug("Bypass rules for http request indicate the request may be ignored for [{}]", principal.getId());
            return false;
        }

        val bypassByService = locateMatchingRegisteredServiceForBypass(authentication, registeredService);
        if (bypassByService) {
            return false;
        }

        return true;
    }

    /**
     * Locate matching registered service property boolean.
     *
     * @param authentication    the authentication
     * @param registeredService the registered service
     * @return true/false
     */
    protected boolean locateMatchingRegisteredServiceForBypass(final Authentication authentication,
                                                               final RegisteredService registeredService) {
        if (registeredService != null && registeredService.getMultifactorPolicy() != null) {
            return registeredService.getMultifactorPolicy().isBypassEnabled();
        }
        return false;
    }

    /**
     * Locate matching credential type boolean.
     *
     * @param authentication      the authentication
     * @param credentialClassType the credential class type
     * @return the boolean
     */
    protected boolean locateMatchingCredentialType(final Authentication authentication, final String credentialClassType) {
        return StringUtils.isNotBlank(credentialClassType) && authentication.getCredentials()
            .stream()
            .anyMatch(e -> e.getCredentialClass().getName().matches(credentialClassType));
    }

    /**
     * Skip bypass and support event based on authentication attributes.
     *
     * @param bypass the bypass settings for the provider.
     * @param authn  the authn
     * @return the boolean
     */
    protected boolean locateMatchingAttributeBasedOnAuthenticationAttributes(
        final MultifactorAuthenticationProviderBypassProperties bypass, final Authentication authn) {
        return locateMatchingAttributeValue(bypass.getAuthenticationAttributeName(),
            bypass.getAuthenticationAttributeValue(), authn.getAttributes());
    }

    /**
     * Skip bypass and support event based on principal attributes.
     *
     * @param bypass    the bypass properties
     * @param principal the principal
     * @return the boolean
     */
    protected boolean locateMatchingAttributeBasedOnPrincipalAttributes(
        final MultifactorAuthenticationProviderBypassProperties bypass, final Principal principal) {
        return locateMatchingAttributeValue(bypass.getPrincipalAttributeName(), bypass.getPrincipalAttributeValue(), principal.getAttributes());
    }

    /**
     * Locate matching attribute value boolean.
     *
     * @param attrName   the attr name
     * @param attrValue  the attr value
     * @param attributes the attributes
     * @return true/false
     */
    protected boolean locateMatchingAttributeValue(final String attrName, final String attrValue,
                                                   final Map<String, Object> attributes) {
        return locateMatchingAttributeValue(attrName, attrValue, attributes, true);
    }

    /**
     * Evaluate attribute rules for bypass.
     *
     * @param attrName               the attr name
     * @param attrValue              the attr value
     * @param attributes             the attributes
     * @param matchIfNoValueProvided the force match on value
     * @return true a matching attribute name/value is found
     */
    protected boolean locateMatchingAttributeValue(final String attrName, final String attrValue,
                                                   final Map<String, Object> attributes,
                                                   final boolean matchIfNoValueProvided) {
        LOGGER.debug("Locating matching attribute [{}] with value [{}] amongst the attribute collection [{}]", attrName, attrValue, attributes);
        if (StringUtils.isBlank(attrName)) {
            LOGGER.debug("Failed to match since attribute name is undefined");
            return false;
        }

        val names = attributes.entrySet()
            .stream()
            .filter(e -> {
                LOGGER.debug("Attempting to match [{}] against [{}]", attrName, e.getKey());
                return e.getKey().matches(attrName);
            })
            .collect(Collectors.toSet());

        LOGGER.debug("Found [{}] attributes relevant for multifactor authentication bypass", names.size());

        if (names.isEmpty()) {
            return false;
        }

        if (StringUtils.isBlank(attrValue)) {
            LOGGER.debug("No attribute value to match is provided; Match result is set to [{}]", matchIfNoValueProvided);
            return matchIfNoValueProvided;
        }

        val values = names
            .stream()
            .filter(e -> {
                val valuesCol = CollectionUtils.toCollection(e.getValue());
                LOGGER.debug("Matching attribute [{}] with values [{}] against [{}]", e.getKey(), valuesCol, attrValue);
                return valuesCol
                    .stream()
                    .anyMatch(v -> v.toString().matches(attrValue));
            }).collect(Collectors.toSet());

        LOGGER.debug("Matching attribute values remaining are [{}]", values);
        return !values.isEmpty();
    }

    /**
     * Locate matching http request and determine if bypass should be enabled.
     *
     * @param authentication the authentication
     * @param request        the request
     * @return true /false
     */
    protected boolean locateMatchingHttpRequest(final Authentication authentication, final HttpServletRequest request) {
        if (StringUtils.isNotBlank(bypassProperties.getHttpRequestRemoteAddress())) {
            if (httpRequestRemoteAddressPattern.matcher(request.getRemoteAddr()).find()) {
                LOGGER.debug("Http request remote address [{}] matches [{}]", bypassProperties.getHttpRequestRemoteAddress(), request.getRemoteAddr());
                return true;
            }
            if (httpRequestRemoteAddressPattern.matcher(request.getRemoteHost()).find()) {
                LOGGER.debug("Http request remote host [{}] matches [{}]", bypassProperties.getHttpRequestRemoteAddress(), request.getRemoteHost());
                return true;
            }
        }

        if (StringUtils.isNotBlank(bypassProperties.getHttpRequestHeaders())) {
            val headerNames = Collections.list(request.getHeaderNames());
            val matched = this.httpRequestHeaderPatterns.stream()
                .anyMatch(pattern -> headerNames.stream().anyMatch(name -> pattern.matcher(name).matches()));
            if (matched) {
                LOGGER.debug("Http request remote headers [{}] match [{}]", headerNames, bypassProperties.getHttpRequestHeaders());
                return true;
            }
        }

        return false;
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }
}


text:
using System;

public class Tourist_Information
{
    public static void Main()
    {
        var milesToKilometers = 1.6m;
        var inchesToCentimeters = 2.54m;
        var feetToCentimeters = 30m;
        var yardsToMeters = 0.91m;
        var gallonsToLiters = 3.8m;

        var imperialUnit = Console.ReadLine();
        var value = decimal.Parse(Console.ReadLine());

        var convertedValue = 0m;
        var metricUnit = string.Empty;

        switch (imperialUnit)
        {
            case "miles":
                convertedValue = value * milesToKilometers;
                metricUnit = "kilometers";
                break;

            case "inches":
                convertedValue = value * inchesToCentimeters;
                metricUnit = "centimeters";
                break;

            case "feet":
                convertedValue = value * feetToCentimeters;
                metricUnit = "centimeters";
                break;

            case "yards":
                convertedValue = value * yardsToMeters;
                metricUnit = "meters";
                break;

            case "gallons":
                convertedValue = value * gallonsToLiters;
                metricUnit = "liters";
                break;
        }

        Console.WriteLine($"{value} {imperialUnit} = {convertedValue:F2} {metricUnit}");
    }
}


text:
export * from './experimental/job-registry';
export * from './fs';
export * from './cli-logger';
export * from './host';
export { ModuleNotFoundException, ResolveOptions, resolve } from './resolve';


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.

using System.Runtime.CompilerServices;

[assembly: InternalsVisibleTo("Microsoft.MixedReality.Toolkit.Utilities.Gltf.Importers")]


text:
'use strict';

const TIME_OUT = 10000;

describe('angularjs homepage', function () {
    it('should greet the named user', function () {
        browser.get('http://www.angularjs.org');

        element(by.model('yourName')).sendKeys('Julie');

        let greeting = element(by.binding('yourName'));

        expect(greeting.getText()).toEqual('Hello Julie!');
    });

    describe('todo list', function () {
        let todoList;

        beforeEach(function () {
            browser.get('http://www.angularjs.org');

            todoList = element.all(by.repeater('todo in todoList.todos'));
        });

        it('should list todos', function () {
            expect(todoList.count()).toEqual(2);
            expect(todoList.get(1).getText()).toEqual('build an AngularJS app');
        });

        it('should add a todo', function () {
            let addTodo = element(by.model('todoList.todoText'));
            let addButton = element(by.css('[value="add"]'));

            addTodo.sendKeys('write a protractor test');
            addButton.click();

            expect(todoList.count()).toEqual(3);
            expect(todoList.get(2).getText()).toEqual('write a protractor test');
        });

        it('should wait until the video tags are shown', function () {
            browser.wait(protractor.ExpectedConditions.presenceOf(element(by.css('.video-img'))), TIME_OUT);

            let videos = element.all(by.css('.video-img'));
            expect(videos.count()).toEqual(2);
        });
    });
});


text:
<?php

class ImgInstaller extends CComponent
{
	/**
	 * @property ImgModule the image module.
	 */
	private $_module;
	/**
	 * @property string the image path.
	 */
	private $_imagePath;
	/**
	 * @property string the base path.
	 */
	private $_basePath;
	/**
	 * @var string the image database table name.
	 */
	private $_imageTable='Image';

	/**
	 * Initializes the component.
	 */
	public function init()
	{
		$this->_imagePath=Yii::app()->image->imagePath;
		$this->_basePath=realpath( Yii::app()->basePath.'/../' ).'/';
	}

	/**
	 * Runs the installer.
	 * @throws CException if an error occurs during the installation process.
	 */
	public function run()
	{
		$this->createDirectories();
		$this->executeSchema();

		// We only need to create the .htaccess file
		// if creating of images on-demand is enabled.
		if($this->_module->createOnDemand===true)
			$this->createHtaccessFile();
	}

	/**
	 * Creates the directories required by this module.
	 */
	public function createDirectories()
	{
		$path='';
		$directories=explode('/',trim($this->_imagePath,'/'));
		foreach($directories as $directory)
		{
			if(empty($path))
				$path=$this->_basePath;

			$path.='/'.$directory;
			if(!file_exists($path))
				mkdir($path);
		}

		$versionPath=$path.'/versions';
		if(!file_exists($versionPath))
			mkdir($versionPath);
	}

	/**
	 * Creates the .htaccess-file required for creating images on-demand.
	 * @throws CException if the template file cannot be read or the .htaccess created cannot be created.
	 */
	public function createHtaccessFile()
	{

		// Determine the URL for the rewrite.
		$urlManager=Yii::app()->getUrlManager();
		if($urlManager->getUrlFormat()===CUrlManager::PATH_FORMAT)
		{
			$targetUrl='';

			// Append the script name if necessary.
			if($urlManager->showScriptName===true)
				$targetUrl.='index.php/';

			$targetUrl.='image/default/create?id=$2&version=$1';
		}
		else
			$targetUrl='index.php?r=image/default/create&id=$2&version=$1';

		// Read the template file.
		if(($htaccess=file_get_contents(dirname(__FILE__).'/../files/htaccess'))===false)
			throw new CException(Img::t('error','Failed to create the access file! Template could not be read.'));

		// Replace the placeholders in the template file.
		$htaccess=strtr($htaccess,array(
			'{baseUrl}'=>Yii::app()->getRequest()->getBaseUrl().'/',
			'{sourceUrl}'=>'^versions/([a-zA-Z0-9]+)/([0-9]+)\.(gif|jpg|png)$',
			'{targetUrl}'=>$targetUrl,
		));

		// Create the .htaccess file.
		if((file_put_contents($this->_basePath.$this->_imagePath.$this->_module->accessFileName,$htaccess))===false)
			throw new CException(Img::t('error','Failed to create the access file! File could not be created.'));
	}

	/**
	 * Executes the database schema provided with this module.
	 * @throws CException if the schema cannot be read or if one of the queries fails.
	 */
	public function executeSchema()
	{
		$db=Yii::app()->getDb();

		// Read the schema file.
		if(($schema=file_get_contents(dirname(__FILE__).'/../data/schema.sql'))===false)
			throw new CException(Img::t('error','Failed to execute the database schema! File could not be read.'));

		// We need to append the table prefix if necessary.
		$schema=strtr($schema,array(
			$this->_imageTable=>$db->tablePrefix.$this->_imageTable,
		));

		// Split the schema into separate SQL-statements.
        $schema=preg_split("/;\s*/",trim($schema,';'));

        $trx=$db->beginTransaction();

        try
        {
            foreach($schema as $sql)
                $db->createCommand($sql)->execute();

	        // All statements executed successfully.
	        $trx->commit();
        }
        catch(CException $e)
        {
	        // Something went wrong.
	        $trx->rollback();
	        throw $e;
        }
	}

	/**
	 * Returns whether the image module is already installed.
	 * @return boolean whether the module is installed.
	 */
	public function getIsInstalled()
	{
		try
		{
			$sql="SELECT COUNT(*) FROM {$this->_imageTable}";
			Yii::app()->db->createCommand($sql)->queryScalar();
			return true;
		}
		catch(CDbException $e)
		{
			return false;
		}
	}

	/**
	 * Sets the image module.
	 * @param ImgModule $value the module.
	 */
	public function setModule($value)
	{
		$this->_module=$value;
	}
}


text:
<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Leonel Calendar Challenge</title>
  <link rel="stylesheet" href="css/bootstrap.min.css">
  <link rel="stylesheet" href="css/index.css"/>
  <link rel="stylesheet" href="css/bootstrap-datetimepicker.min.css" />
  <link rel="stylesheet" href="css/sweetalert.css">

Create calendar

                <form id="createTables">

                        Start Date

	                        <input type="text" id="date" class="form-control" required="required" pattern="\d{4}-\d{2}-\d{2}">

                        Number of Days
                        <input type="number" id="days" class="form-control" required="required" min="1">

                        Country Code
                        <input type="text" id="country" class="form-control"  pattern="[A-Z]{2}" required="required" title="Country code must be 2 uppercase chars">

                    <button type="submit" class="btn btn-primary"> Generate Calendars</button>
                </form>


text:
package org.jumaland;

import static com.lordofthejars.nosqlunit.mongodb.ManagedMongoDb.MongoServerRuleBuilder.newManagedMongoDbRule;
import static com.lordofthejars.nosqlunit.mongodb.MongoDbRule.MongoDbRuleBuilder.newMongoDbRule;
import static com.mongodb.client.model.Filters.eq;

import com.mongodb.MongoClient;
import org.bson.Document;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;

import com.lordofthejars.nosqlunit.annotation.ShouldMatchDataSet;
import com.lordofthejars.nosqlunit.annotation.UsingDataSet;

import static com.lordofthejars.nosqlunit.core.LoadStrategyEnum.CLEAN_INSERT;

import com.lordofthejars.nosqlunit.mongodb.ManagedMongoDb;
import com.lordofthejars.nosqlunit.mongodb.MongoDbRule;

import javax.inject.Inject;

public class BasicAPIUsingNoSQLUnitWithManagedServerTest extends AbstractBasicAPITest {

    @ClassRule
    public static final ManagedMongoDb DATABASE = newManagedMongoDbRule().mongodPath("/usr/local").build();

    @Rule
    public MongoDbRule rule = newMongoDbRule().defaultManagedMongoDb("test");

    @Inject
    private MongoClient client;

    @Override
    protected MongoClient client() throws Exception {
        return client;
    }

    @Test
    @UsingDataSet(locations = "initial-data.json", loadStrategy = CLEAN_INSERT)
    @ShouldMatchDataSet(location = "expected-data.json")
    @Override
    public void update() {
        client.getDatabase("test").getCollection("restaurant")
                .updateOne(eq("cuisine", "Italian"), new Document("$set", new Document("cuisine", "French")));
    }
}


text:
package org.apache.wicket.model;

import org.apache.wicket.WicketRuntimeException;
import org.apache.wicket.WicketTestCase;
import org.junit.Ignore;
import org.junit.Test;

/**
 * Test class for exercising the {@link PropertyModel}.
 *
 * @author dashorst
 */
public class PropertyModelTest extends WicketTestCase
{
	/**
	 * Interface for testing the property assignment with an null interface property.
	 */
	public static interface IAddress
	{
	}

	/**
	 * Abstract class for testing the property assignment with an null abstract class
	 * property.
	 */
	public static abstract class AbstractAddress implements IAddress
	{
		/** street field for assignment in property expressions. */
		public String street;
	}

	/**
	 * Concrete class for testing the property assignment with an null concrete class
	 * property.
	 */
	public static class ConcreteAddress extends AbstractAddress
	{
	}

	/**
	 * Person class for keeping the various different references for use in the test cases.
	 */
	public static class Person
	{
		/** tests a null interface property. */
		public IAddress interfaceAddress;
		/** tests a null abstract class property. */
		public AbstractAddress abstractAddress;
		/** tests a null concrete class property. */
		public ConcreteAddress concreteAddress;
		/** tests a null final concrete class property. */
		public final ConcreteAddress finalAddress = null;
	}

	/**
	 * Tests setting a value on a {@link PropertyModel} when a property is null and an
	 * interface type. This should end in an exception because Wicket can't decide what to
	 * instantiate on behalf of the program.
	 */
	@Test
	public void setWithNullPathInterface()
	{
		Person person = new Person();
		PropertyModel<String> model = new PropertyModel<String>(person, "interfaceAddress.street");
		try
		{
			model.setObject("foo");
			fail("Expected exception");
		}
		catch (WicketRuntimeException wre)
		{
			// ok
		}
	}

	/**
	 * Tests setting a value on a {@link PropertyModel} when a property is null and an
	 * abstract class type. This should end in an exception because Wicket can't decide what to
	 * instantiate on behalf of the program.
	 */
	@Test(expected = WicketRuntimeException.class)
	public void setWithNullPathAbstract()
	{
		Person person = new Person();
		PropertyModel<String> model = new PropertyModel<String>(person, "abstractAddress.street");
		model.setObject("foo");
	}

	/**
	 * Tests setting a value on a {@link PropertyModel} when a property is null and a
	 * concrete type. This should work because Wicket can decide what to instantiate on behalf of
	 * the program: the concrete class.
	 */
	@Test
	public void setWithNullPathConcrete()
	{
		Person person = new Person();
		PropertyModel<String> model = new PropertyModel<String>(person, "concreteAddress.street");
		model.setObject("foo");
		assertNotNull("concreteAddress", person.concreteAddress);
		assertTrue(person.concreteAddress instanceof ConcreteAddress);
		assertEquals("foo", person.concreteAddress.street);
	}

	/**
	 * Tests setting a value on a {@link PropertyModel} when a final (constant!) property is
	 * null and a concrete type. This should end in an exception because Wicket can't
	 * assign to the property, since it is final.
	 *
	 * This test has been disabled as it doesn't work on Mac OS X's 1.4 jdk (assignment doesn't
	 * fail).
	 */
	@Test(expected = WicketRuntimeException.class)
	@Ignore
	public void setWithNullPathFinalJdk14()
	{
		Person person = new Person();
		PropertyModel<String> model = new PropertyModel<String>(person, "finalAddress.street");
		model.setObject("foo");
		fail("Expected exception");
	}

	/**
	 * Tests setting a value on a null, final property using a {@link PropertyModel}. This test
	 * should pass when run using JDK 1.5 or newer.
	 */
	@Test
	public void setWithNullPathFinalJdk15()
	{
		Person person = new Person();
		PropertyModel<String> model = new PropertyModel<String>(person, "finalAddress.street");

		model.setObject("foo");
		assertNotNull("finalAddress", person.finalAddress);
		assertTrue(person.finalAddress instanceof ConcreteAddress);
		assertEquals("foo", person.finalAddress.street);
	}
}


text:
package org.springframework.cloud.function.task;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * @author Mark Fisher
 */
// @checkstyle:off
@SpringBootApplication(proxyBeanMethods = false)
public class TaskApplication {

	public static void main(String[] args) {
		SpringApplication.run(TaskApplication.class, args);
	}

}
// @checkstyle:on


text:
package com.orientechnologies.orient.test.java.serialization;

import com.orientechnologies.orient.core.serialization.serializer.OStringSerializerHelper;
import java.util.List;

public class OrientStringSplitSpeedTest {
  private static final String TEXT = "Ciao, questa, e, una, prova. Che ne pensi?";
  private static final int MAX = 10000000;

  public static void main(String[] iArgs) {
    List<String> pieces = OStringSerializerHelper.split(TEXT, ',');
    for (String s : pieces) System.out.println("String: " + s);

    System.out.println("Start testing cycle X " + MAX);

    long time = System.currentTimeMillis();
    for (int i = 0; i < MAX; ++i) {
      pieces = OStringSerializerHelper.split(TEXT, ',');
      if (i % (MAX / 10) == 0) System.out.print(".");
    }
    System.out.println("\nElapsed: " + (System.currentTimeMillis() - time));
  }
}


text:
<?php
// # Authorize Payment
// This sample code demonstrates how you can authorize a payment and get it's details.

$capture = require __DIR__ . '/../../safestore/create-finalize.php';
$captureId = $capture->getId();

use PayU\Api\Amount;
use PayU\Api\Transaction;
use PayU\Soap\ApiContext;

// ### Amount
// Lets you specify a payment amount.
// You can also specify additional details
// such as shipping, tax.
$amount = new Amount();
$amount->setCurrency("ZAR")
    ->setTotal(175.50);

// ### Transaction
// A transaction defines the contract of a
// payment - what is the payment for and who
// is fulfilling it.
$transaction = new Transaction();
$transaction->setAmount($amount);

$capture->setIntent(Transaction::TYPE_CREDIT)
    ->setTransaction($transaction);

// Setting integration will alter the way the API behaves.
$apiContext[0]->setAccountId('acct1')
    ->setIntegration(ApiContext::ENTERPRISE);

// For Sample Purposes Only.
$request = clone $capture;

// You can refund a payment amount by invoking the `refund` method
// with a valid ApiContext (See bootstrap.php for more on ApiContext).
try {
    $refund = $capture->refund($apiContext[0]);
} catch (Exception $ex) {
    // NOTE: PLEASE DO NOT USE RESULTPRINTER CLASS IN YOUR ORIGINAL CODE. FOR SAMPLE ONLY
    ResultPrinter::printError('Refund Captured/Finalized Payment', 'Refund', null, $request, $ex);
    exit(1);
}

// NOTE: PLEASE DO NOT USE RESULTPRINTER CLASS IN YOUR ORIGINAL CODE. FOR SAMPLE ONLY
ResultPrinter::printResult('Refund Captured/Finalized Payment', 'Refund', $captureId, $request, $refund);

return $refund;


text:
<?xml version="1.0" encoding="utf-8"?>
<plugin xmlns="http://www.phonegap.com/ns/plugins/1.0"
        id="com.scott.serviceDiscovery"
        version="0.2.0">

  <name>serviceDiscovery</name>

  <engines>
    <engine name="cordova" version=">=3.4.0"/>
  </engines>

  <asset src="www/serviceDiscovery.js" target="js/serviceDiscovery.js"/>

  <js-module src="www/serviceDiscovery.js" name="serviceDiscovery">
    <clobbers target="serviceDiscovery" />
  </js-module>

  <!-- android -->
  <platform name="android">

    <config-file target="res/xml/config.xml" parent="/*">
      <feature name="serviceDiscovery">
        <param name="android-package" value="com.scott.plugin.serviceDiscovery"/>
      </feature>
    </config-file>

    <source-file src="src/android/serviceDiscovery.java" target-dir="src/com/scott/plugin/"/>
    <source-file src="src/android/cordovaSSDP.java" target-dir="src/com/scott/plugin/"/>
    <!-- Requires 3rd party HTTP lib -->
    <framework src="com.loopj.android:android-async-http:1.4.9" />
  </platform>

  <!-- ios -->
  <platform name="ios">
    <config-file target="config.xml" parent="/*">
        <feature name="serviceDiscovery">
          <param name="ios-package" value="serviceDiscovery" onload="true" />
        </feature>
    </config-file>

    <header-file src="src/ios/serviceDiscovery.h" />
    <source-file src="src/ios/serviceDiscovery.m" />
  </platform>

</plugin>


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Suite" verbose="5">
	<test name="Test">
		<parameter name="browser" value="firefox" />
		<parameter name="testdatapath"
			value="/Users/kishorevarman/deepthi/workspace/Testproject/Testdata.xlsx" />
		<parameter name="sheet" value="input" />
		<parameter name="Validation_statement" value="Please Select an Travel Date" />
		<classes>
			<class name="projectAutomation.NewTest_testng" />
		</classes>
	</test> <!-- Test -->
</suite> <!-- Suite -->


text:
package alluxio.server.ft.journal.raft;

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

import alluxio.AlluxioURI;
import alluxio.ConfigurationRule;
import alluxio.Constants;
import alluxio.conf.PropertyKey;
import alluxio.client.file.FileSystem;
import alluxio.conf.ServerConfiguration;
import alluxio.exception.FileAlreadyExistsException;
import alluxio.exception.FileDoesNotExistException;
import alluxio.grpc.NetAddress;
import alluxio.grpc.QuorumServerInfo;
import alluxio.grpc.QuorumServerState;
import alluxio.master.journal.JournalType;
import alluxio.multi.process.MultiProcessCluster;
import alluxio.multi.process.PortCoordination;
import alluxio.testutils.BaseIntegrationTest;
import alluxio.util.CommonUtils;
import alluxio.util.WaitForOptions;

import org.junit.After;
import org.junit.Rule;
import org.junit.Test;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;

/**
 * Integration tests for the embedded journal.
 */
public final class EmbeddedJournalIntegrationTest extends BaseIntegrationTest {
  private static final int NUM_MASTERS = 3;
  private static final int RESTART_TIMEOUT_MS = 2 * Constants.MINUTE_MS;

  @Rule
  public ConfigurationRule mConf =
      new ConfigurationRule(PropertyKey.USER_METRICS_COLLECTION_ENABLED, "false",
          ServerConfiguration.global());

  public MultiProcessCluster mCluster;

  @After
  public void after() throws Exception {
    if (mCluster != null) {
      mCluster.destroy();
    }
  }

  @Test
  public void failover() throws Exception {
    mCluster = MultiProcessCluster.newBuilder(PortCoordination.EMBEDDED_JOURNAL_FAILOVER)
        .setClusterName("EmbeddedJournalFailover")
        .setNumMasters(NUM_MASTERS)
        .setNumWorkers(0)
        .addProperty(PropertyKey.MASTER_JOURNAL_TYPE, JournalType.EMBEDDED.toString())
        .addProperty(PropertyKey.MASTER_JOURNAL_FLUSH_TIMEOUT_MS, "5min")
        // To make the test run faster.
        .addProperty(PropertyKey.MASTER_EMBEDDED_JOURNAL_ELECTION_TIMEOUT, "750ms")
        .addProperty(PropertyKey.MASTER_EMBEDDED_JOURNAL_HEARTBEAT_INTERVAL, "250ms")
        .build();
    mCluster.start();

    AlluxioURI testDir = new AlluxioURI("/dir");
    FileSystem fs = mCluster.getFileSystemClient();
    fs.createDirectory(testDir);
    mCluster.waitForAndKillPrimaryMaster(RESTART_TIMEOUT_MS);
    assertTrue(fs.exists(testDir));
    mCluster.notifySuccess();
  }

  @Test
  public void resizeCluster() throws Exception {
    mCluster = MultiProcessCluster.newBuilder(PortCoordination.EMBEDDED_JOURNAL_RESIZE)
        .setClusterName("EmbeddedJournalResizing").setNumMasters(5).setNumWorkers(0)
        .addProperty(PropertyKey.MASTER_JOURNAL_TYPE, JournalType.EMBEDDED.toString())
        .addProperty(PropertyKey.MASTER_JOURNAL_FLUSH_TIMEOUT_MS, "5min")
        // To make the test run faster.
        .addProperty(PropertyKey.MASTER_EMBEDDED_JOURNAL_ELECTION_TIMEOUT, "750ms")
        .addProperty(PropertyKey.MASTER_EMBEDDED_JOURNAL_HEARTBEAT_INTERVAL, "250ms").build();
    mCluster.start();

    assertEquals(5,
        mCluster.getJournalMasterClientForMaster().getQuorumInfo().getServerInfoList().size());

    AlluxioURI testDir = new AlluxioURI("/dir");
    FileSystem fs = mCluster.getFileSystemClient();
    fs.createDirectory(testDir);
    assertTrue(fs.exists(testDir));

    // Stop 2 masters. Now cluster can't tolerate any loss.
    mCluster.stopMaster(0);
    mCluster.stopMaster(1);
    // Verify cluster is still serving requests.
    assertTrue(fs.exists(testDir));

    CommonUtils.waitFor("Quorum noticing master unavailability", () -> {
      try {
        int unavailableCount = 0;
        for (QuorumServerInfo serverState : mCluster.getJournalMasterClientForMaster()
            .getQuorumInfo().getServerInfoList()) {
          if (serverState.getServerState().equals(QuorumServerState.UNAVAILABLE)) {
            unavailableCount++;
          }
        }
        return unavailableCount >= 2;
      } catch (Exception exc) {
        throw new RuntimeException(exc);
      }
    });

    // Get and verify list of unavailable masters.
    List<NetAddress> unavailableMasters = new LinkedList<>();
    for (QuorumServerInfo serverState : mCluster.getJournalMasterClientForMaster().getQuorumInfo()
        .getServerInfoList()) {
      if (serverState.getServerState().equals(QuorumServerState.UNAVAILABLE)) {
        unavailableMasters.add(serverState.getServerAddress());
      }
    }
    assertEquals(2, unavailableMasters.size());

    // Remove unavailable masters from quorum.
    for (NetAddress unavailableMasterAddress : unavailableMasters) {
      mCluster.getJournalMasterClientForMaster().removeQuorumServer(unavailableMasterAddress);
    }
    // Verify quorum is down to 3 masters.
    assertEquals(3,
        mCluster.getJournalMasterClientForMaster().getQuorumInfo().getServerInfoList().size());

    // Validate that cluster can tolerate one more master failure after resizing.
    mCluster.stopMaster(2);
    assertTrue(fs.exists(testDir));
    mCluster.notifySuccess();
  }

  @Test
  public void restart() throws Exception {
    mCluster = MultiProcessCluster.newBuilder(PortCoordination.EMBEDDED_JOURNAL_RESTART)
        .setClusterName("EmbeddedJournalRestart")
        .setNumMasters(NUM_MASTERS)
        .setNumWorkers(0)
        .addProperty(PropertyKey.MASTER_JOURNAL_TYPE, JournalType.EMBEDDED.toString())
        .addProperty(PropertyKey.MASTER_JOURNAL_FLUSH_TIMEOUT_MS, "5min")
        // To make the test run faster.
        .addProperty(PropertyKey.MASTER_EMBEDDED_JOURNAL_ELECTION_TIMEOUT, "750ms")
        .addProperty(PropertyKey.MASTER_EMBEDDED_JOURNAL_HEARTBEAT_INTERVAL, "250ms")
        .build();
    mCluster.start();

    AlluxioURI testDir = new AlluxioURI("/dir");
    FileSystem fs = mCluster.getFileSystemClient();
    fs.createDirectory(testDir);
    restartMasters();
    assertTrue(fs.exists(testDir));
    restartMasters();
    assertTrue(fs.exists(testDir));
    restartMasters();
    assertTrue(fs.exists(testDir));
    mCluster.notifySuccess();
  }

  @Test
  public void restartStress() throws Throwable {
    mCluster = MultiProcessCluster.newBuilder(PortCoordination.EMBEDDED_JOURNAL_RESTART_STRESS)
        .setClusterName("EmbeddedJournalRestartStress")
        .setNumMasters(NUM_MASTERS)
        .setNumWorkers(0)
        .addProperty(PropertyKey.MASTER_JOURNAL_TYPE, JournalType.EMBEDDED.toString())
        .addProperty(PropertyKey.MASTER_JOURNAL_FLUSH_TIMEOUT_MS, "5min")
        // To make the test run faster.
        .addProperty(PropertyKey.MASTER_EMBEDDED_JOURNAL_ELECTION_TIMEOUT, "750ms")
        .addProperty(PropertyKey.MASTER_EMBEDDED_JOURNAL_HEARTBEAT_INTERVAL, "250ms")
        .build();
    mCluster.start();

    // Run and verify operations while restarting the cluster multiple times.
    AtomicReference<Throwable> failure = new AtomicReference<>();
    AtomicInteger successes = new AtomicInteger(0);
    FileSystem fs = mCluster.getFileSystemClient();
    List<OperationThread> threads = new ArrayList<>();
    try {
      for (int i = 0; i < 10; i++) {
        OperationThread t = new OperationThread(fs, i, failure, successes);
        t.start();
        threads.add(t);
      }
      for (int i = 0; i < 2; i++) {
        restartMasters();
        System.out.printf("---------- Iteration %s ----------\n", i);
        successes.set(0);
        CommonUtils.waitFor("11 successes", () -> successes.get() >= 11,
            WaitForOptions.defaults().setTimeoutMs(RESTART_TIMEOUT_MS));
        if (failure.get() != null) {
          throw failure.get();
        }
      }
    } finally {
      threads.forEach(t -> t.interrupt());
      for (Thread t : threads) {
        t.join();
      }
    }
    mCluster.notifySuccess();
  }

  private void restartMasters() throws Exception {
    for (int i = 0; i < NUM_MASTERS; i++) {
      mCluster.stopMaster(i);
    }
    for (int i = 0; i < NUM_MASTERS; i++) {
      mCluster.startMaster(i);
    }
  }

  private static class OperationThread extends Thread {
    private final FileSystem mFs;
    private final int mThreadNum;
    private final AtomicReference<Throwable> mFailure;
    private final AtomicInteger mSuccessCounter;

    public OperationThread(FileSystem fs, int threadNum, AtomicReference<Throwable> failure,
        AtomicInteger successCounter) {
      super("operation-test-thread-" + threadNum);
      mFs = fs;
      mThreadNum = threadNum;
      mFailure = failure;
      mSuccessCounter = successCounter;
    }

    public void run() {
      try {
        runInternal();
      } catch (Exception e) {
        e.printStackTrace();
        mFailure.set(e);
      }
    }

    public void runInternal() throws Exception {
      while (!Thread.interrupted()) {
        for (int i = 0; i < 100; i++) {
          AlluxioURI dir = formatDirName(i);
          try {
            mFs.createDirectory(dir);
          } catch (FileAlreadyExistsException e) {
            // This could happen if the operation was retried but actually succeeded server-side on
            // the first attempt. Alluxio does not de-duplicate retried operations.
            continue;
          }
          if (!mFs.exists(dir)) {
            mFailure.set(new RuntimeException(String.format("Directory %s does not exist", dir)));
            return;
          }
        }
        for (int i = 0; i < 100; i++) {
          AlluxioURI dir = formatDirName(i);
          try {
            mFs.delete(dir);
          } catch (FileDoesNotExistException e) {
            // This could happen if the operation was retried but actually succeeded server-side on
            // the first attempt. Alluxio does not de-duplicate retried operations.
            continue;
          }
          if (mFs.exists(dir)) {
            mFailure.set(new RuntimeException(String.format("Directory %s still exists", dir)));
            return;
          }
        }
        System.out.println("Success counter: " + mSuccessCounter.incrementAndGet());
      }
    }

    private AlluxioURI formatDirName(int dirNum) {
      return new AlluxioURI(String.format("/dir-%d-%d", mThreadNum, dirNum));
    }
  }
}


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

namespace Algo.Trees
{
    public class TreeTraversal
    {
        public IEnumerable<BinaryTreeNode> LevelOrder(BinaryTreeNode root)
        {
            Queue<BinaryTreeNode> nodes = new Queue<BinaryTreeNode>();
            nodes.Enqueue(root);

            while (nodes.Count > 0)
            {
                BinaryTreeNode node = nodes.Dequeue();

                if (node.Left != null)
                {
                    nodes.Enqueue(node.Left);
                }

                if (node.Right != null)
                {
                    nodes.Enqueue(node.Right);
                }

                yield return node;
            }
        }

        public IEnumerable<BinaryTreeNode> InOrder(BinaryTreeNode node)
        {
            //if (node == null) { return Enumerable.Empty<BinaryTreeNode>(); }
            //return InOrder(node.Left)
            //    .Union(new[] { node })
            //    .Union(InOrder(node.Right));

            // non-recursive
            Stack<BinaryTreeNode> nodes = new Stack<BinaryTreeNode>();

            BinaryTreeNode current = node;

            while (current != null || nodes.Count > 0)
            {
                while (current != null)
                {
                    nodes.Push(current);
                    current = current.Left;
                }

                current = nodes.Pop();
                yield return current;

                current = current.Right;
            }
        }

        public IEnumerable<BinaryTreeNode> PreOrder(BinaryTreeNode node)
        {
            if (node == null) { return Enumerable.Empty<BinaryTreeNode>(); }

            return new[] { node }
                .Union(PreOrder(node.Left))
                .Union(PreOrder(node.Right));

            // non-recursive
            //Stack<BinaryTreeNode> nodes = new Stack<BinaryTreeNode>();
            //nodes.Push(node);
            //while (nodes.Count > 0)
            //{
            //    BinaryTreeNode current = nodes.Pop();
            //    yield return current;
            //    if (current.Right != null)
            //    {
            //        nodes.Push(current.Right);
            //    }

            //    if (current.Left != null)
            //    {
            //        nodes.Push(current.Left);
            //    }
            //}
        }

        public IEnumerable<BinaryTreeNode> PostOrder(BinaryTreeNode node)
        {
            //if (node == null) { return Enumerable.Empty<BinaryTreeNode>(); }

            //return PostOrder(node.Left).Union(PostOrder(node.Right)).Union(new[] { node });

            // non-recursive
            Stack<BinaryTreeNode> nodes = new Stack<BinaryTreeNode>();
            Stack<BinaryTreeNode> reverse = new Stack<BinaryTreeNode>();
            nodes.Push(node);
            while (nodes.Count > 0)
            {
                BinaryTreeNode current = nodes.Pop();
                if (current.Left != null)
                {
                    nodes.Push(current.Left);
                }

                if (current.Right != null)
                {
                    nodes.Push(current.Right);
                }

                reverse.Push(current);
            }

            return reverse;
        }

        public bool SameFringe(BinaryTreeNode a, BinaryTreeNode b)
        {
            return Fringe(a).SequenceEqual(Fringe(b));
        }

        private IEnumerable<string> Fringe(BinaryTreeNode n)
        {
            if (n.Left == null && n.Right == null)
            {
                return new[] { n.Value };
            }
            else
            {
                IEnumerable<string> result = Enumerable.Empty<string>();
                if (n.Left != null)
                {
                    result = result.Union(Fringe(n.Left));
                }

                if (n.Right != null)
                {
                    result = result.Union(Fringe(n.Right));
                }

                return result;
            }
        }

        public List<List<BinaryTreeNode>> AllRootToLeafPaths(BinaryTreeNode root)
        {
            List<BinaryTreeNode> list = new List<BinaryTreeNode>();
            List<List<BinaryTreeNode>> results = new List<List<BinaryTreeNode>>();

            AllRootToLeafPaths(root, list, results);

            return results;
        }

        private void AllRootToLeafPaths(BinaryTreeNode node, List<BinaryTreeNode> current, List<List<BinaryTreeNode>> paths)
        {
            // add node
            current.Add(node);

            // leaf
            if (node.Left == null && node.Right == null)
            {
                paths.Add(current.ToList());
            }

            // recurse left
            if (node.Left != null)
            {
                AllRootToLeafPaths(node.Left, current, paths);
            }

            // recurse right
            if (node.Right != null)
            {
                AllRootToLeafPaths(node.Right, current, paths);
            }

            // remove node
            current.Remove(node);
        }
    }
}


text:
package com.deleidos.rtws.webapp.register.worker;

import java.util.List;

import net.sf.json.JSONObject;

import org.apache.commons.logging.Log;
import org.apache.log4j.Logger;
import org.eclipse.jetty.util.ajax.JSON;

import com.deleidos.rtws.commons.cloud.platform.ServiceInterface;
import com.deleidos.rtws.commons.cloud.platform.StorageInterface;
import com.deleidos.rtws.commons.cloud.platform.aws.AWSEndpoint;
import com.deleidos.rtws.commons.cloud.platform.aws.SimpleAwsServiceImpl;
import com.deleidos.rtws.commons.cloud.platform.jetset.JetSetConnectionFactory;
import com.deleidos.rtws.commons.cloud.platform.jetset.JetSetStorageService;
import com.deleidos.rtws.commons.cloud.platform.jetset.JetSetThreadedStorageService;
import com.deleidos.rtws.commons.config.UserDataProperties;
import com.deleidos.rtws.commons.ldap.InfoAttributeModel;
import com.deleidos.rtws.commons.util.env.SystemEnvUtil;
import com.deleidos.rtws.webapp.register.client.DbApiRestClient;
import com.deleidos.rtws.webapp.register.client.LdapApiRestClient;
import com.deleidos.rtws.webapp.register.client.RestClientManager;
import com.deleidos.rtws.webapp.register.client.TenantApiRestClient;
import com.deleidos.rtws.webapp.register.form.AccountForm;
import com.deleidos.rtws.webapp.register.form.NetworkType;
import com.deleidos.rtws.webapp.register.form.RegistrationForm;
import com.deleidos.rtws.webapp.register.model.StatusEnum;
import com.deleidos.rtws.webapp.register.service.cloud.AwsConnectionFactory;
import com.deleidos.rtws.webapp.register.service.cloud.AwsServiceInterface;
import com.deleidos.rtws.webapp.register.service.gateway.AbstractNetworkService;
import com.deleidos.rtws.webapp.register.service.gateway.GatewayServiceException;
import com.deleidos.rtws.webapp.register.service.gateway.RegistrationService;
import com.deleidos.rtws.webapp.register.servlet.RegistrationException;

public class RegistrationWorker implements Runnable {

	private Logger log = Logger.getLogger(getClass());

	private RegistrationForm form;

	private String executionId;

	private String vpcId;

	RegistrationService regService;

	public RegistrationWorker(RegistrationForm f) {
		form = f;
		this.executionId = f.getExecutionId();
	}

	public void run() {

		AWSEndpoint endpoint = AWSEndpoint.getEndpointByName(form.getRegion());
		form.setEndpoints(endpoint);

		if (tenantExists(form.getTenantId())) {
			// account name already exists. Throw exception back to form to
			// handle error
			setStatus(StatusEnum.ERROR,form.getTenantId(),form.getEmailAddress(),"ERROR: Account name is already in use");
			// early return for error case
			return;
		}

		setStatus(StatusEnum.REGISTER_TMS,form.getTenantId(),form.getEmailAddress(),"Creating TMS accounts...");
		try {

			determineAvZone();

			regService = RegistrationService.newInstance(form, this);
			try{
				createAndLinkAccounts();
			}catch(Exception e){
				setStatus(StatusEnum.ERROR,form.getTenantId(),form.getEmailAddress(),"Error creating accounts.  Contact Digital Edge Support.  Error was: "+e.getMessage());
				log.error("Exception creating account for tenant "+form.getTenantId()+".  Error was "+e.getMessage(),e);
				return;
			}
			setStatus(StatusEnum.REGISTER_TMS,form.getTenantId(),form.getEmailAddress(),"TMS accounts created.  Creating VPC networks if applicable...");

			if (form.getNetworkType()==NetworkType.VPC) {
				regService.createVPCNetworks();
			}

			setStatus(StatusEnum.REGISTER_TMS,form.getTenantId(),form.getEmailAddress(),"VPC networks created (If applicable).  Creating base security group rules...");
			try{
				regService.createBaseSecurityGroup();
			}catch(Exception e){
				setStatus(StatusEnum.ERROR,form.getTenantId(),form.getEmailAddress(),"Error creating Security group rules.");
				log.error("Error creating security group rules for tenant "+form.getTenantId()+".  Error was "+e.getMessage(),e);
				return;
			}
			setStatus(StatusEnum.REGISTER_TMS,form.getTenantId(),form.getEmailAddress(),"Security group rules created.  Creating AMI...");

			try {
				Thread.sleep(10000);
			} catch (InterruptedException ignore) {}

			if (!SystemEnvUtil.isMarketPlaceLaunched()) {
				String amiId = regService.createAMI();

				setStatus(StatusEnum.CREATE_AMI,form.getTenantId(),form.getEmailAddress(),"AMI created.  Launching gateway with created AMI..,.");

				regService.launchGateway(amiId);
			}

		} catch (RegistrationException e) {
			setStatus(StatusEnum.ERROR,form.getTenantId(),form.getEmailAddress(),"An exception occured while creating account.  Contact Digital Edge Support.  Error was: "+e.getMessage());
			log.error("Exception creating account for tenant "+form.getTenantId()+".  Error was "+e.getMessage(),e);
			return;
		}
	}

	private void determineAvZone() {
		AwsConnectionFactory factory = new AwsConnectionFactory(form.getAccessKey(), form.getSecretKey());
		factory.setServiceEndpoint(form.getEndpoints().getEC2Endpoint());

		AwsServiceInterface serviceInterface = new AwsServiceInterface();
		serviceInterface.setConnectionFactory(factory);

		List<String> avZones = serviceInterface.listAvailabilityZones();
		form.setAvailabilityZone(avZones.get(0));//use first one

		// TODO Auto-generated method stub

	}

	public void setVpcId(String vpcId){
		this.vpcId=vpcId;
	}

	private boolean tenantExists(String tenantName) {
		return RestClientManager.getDBApiClient()
				.doesTenantExistInAccountAccessTable(tenantName);
	}

	private void createAndLinkAccounts() throws RegistrationException {

		DbApiRestClient dbClient = RestClientManager.getDBApiClient();
		TenantApiRestClient tenantClient = RestClientManager
				.getTenantApiClient();
		LdapApiRestClient ldapClient = RestClientManager.getLdapApiClient();

		try {
			regService.setDomainSuffix();
		} catch (GatewayServiceException e1) {
			throw new RegistrationException(e1);
		}

		try {
			tenantClient.addTenant(form);

			try {
				Thread.sleep(30 * 1000);
			} catch (Exception drop) {
			}

			form.setAccountId(dbClient.getAccountIDfromAccountName(form
					.getTenantId()));
		} catch (Exception e) {
			throw new RegistrationException("Error creating accounts.", e);
		}

		try{
			InfoAttributeModel model = new InfoAttributeModel();
			for(int i=0;i<form.getSecurityAnswers().length;i++){
				model.addSecurityQuestion(form.getSecurityQuestions()[i], form.getSecurityAnswers()[i]);
			}
			ldapClient.addUser(form.getTenantId(), form.getPassword(), form.getDescription(), form.getTenantId(), form.getTenantId(), form.getEmailAddress(), model.toJsonString());
		}catch(Exception e){
			throw new RegistrationException(e);
		}

		//long accountId = dbClient.nextSequenceValue("IAAS_ACCOUNT_ID_SEQ");
		//form.setAccountId(accountId);
		/*
		try {
			dbClient.addTenantToIAASAccountsTable(form);
		} catch (Exception e) {
			throw new RegistrationException(
					"Error adding tenant to iaas accounts table.", e);
		}
		setStatus("Added tenant to iaas accounts Table.");

		try {
			dbClient.addTenantToAccountAccessTable(form.getTenantId(),
					accountId);
		} catch (Exception e) {
			throw new RegistrationException(
					"Error adding tenant to account access table.", e);
		}
		setStatus("Added tenant to Account Access Table.");

		try {
			dbClient.addTenantRDBMSConnection(form.getTenantId(),
					form.getAccountId());
		} catch (Exception e) {
			throw new RegistrationException(
					"Error adding RDBMS connections entry.", e);
		}
		setStatus("Tenant RDBMS connections table entry created");

		try{
			dbClient.addTenantToGatewayTable(form);
		}catch (Exception e){
			throw new RegistrationException("Error adding GatewayAccounts table entry.",e);
		}
		setStatus("Tenant GatewayAccount table entry created.");

		// TODO: add to LDAP and link LDAP to database account
*/
	}

	// shortcut method
	public void setStatus(StatusEnum enumStatus, String tenantId, String email, String stringStatus) {
		try {
			JSONObject json = new JSONObject();
			json.put("STATUS", stringStatus);
			json.put("EMAIL", email);
			json.put("ID",tenantId);
			json.put("STEP", enumStatus);

			RegistrationStatus.INSTANCE.setStatus(executionId, json);
			RestClientManager.getDBApiClient().updateRegistrationStatusEntry(
					executionId, json.toString());
			log.debug("STATUS: {"+executionId+"}: "+json);
		} catch (Exception e) {
			log.debug("ERROR SETTING STATUS: {"+executionId+"}: "+stringStatus);
		}
	}

	public void setExecutionId(String executionId) {
		this.executionId = executionId;
	}

}


text:
{% load bootstrap3 %}

{% bootstrap_css %}
{% bootstrap_javascript %}

	<form class="form-signin" id="login_form" method="post" action="/login/">

Simple QA

Sign In

		<input type="text" class="form-control" placeholder="Username" type="text" name="username" required="" autofocus="">
		<input type="password" class="form-control" placeholder="Password" type="password" name="password" required="">
        {% csrf_token %}
		<button class="btn btn-lg btn-primary btn-block" type="submit">
			Sign In
		</button>
	</form>

or

    New User? Sign Up


text:
$(document).ready(function () {
    $('#reg').click(function (e) {
        if ($('#TOS').not(':checked').length) {
            e.preventDefault();
            alert('You must agree with terms of service');
        }

    })
});


text:
export declare class XmlEntities {
    encode(str: string): string;
    static encode(str: string): string;
    decode(str: string): string;
    static decode(str: string): string;
    encodeNonUTF(str: string): string;
    static encodeNonUTF(str: string): string;
    encodeNonASCII(str: string): string;
    static encodeNonASCII(str: string): string;
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="Site de monitoramento dos resultados das votações no Senado">
    <meta name="keywords" content="legislativo, senador, senadores, Senado, Senado Federal, votação, PEC, PL, MP, medida provisória, política, Michel Temer, presidente, governo, eleição, reforma, open data, transparency, government, social participation, democracy, visualization, Congress, politics, Brasil, Brazil, Brasília, brazilian, election, Planalto, Câmara, Câmara dos Deputados, Renan Calheiros, Eunício Oliveira, Aécio Neves, PMDB, PSDB, PT, Rede, PSB, PSD, PPS, PCdoB, PDT, PTC, DEM, Lava Jato, Sérgio Moro">
    <meta name="author" content="Gabriela Caesar">

    <title>plenário</title>

	<link rel="shortcut icon" type="image/ico" href="imagens/faviconGeneratorOrg.ico"/>

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

    <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

		<button id="hamburgerMenu" aria-label="menu">

		</button>

Home

Senadores

Proposições

Sobre

Home

Senadores

Proposições

Sobre

sobre

a criação do plenário

O plenário é uma ferramenta open source para o controle social. Esta versão inicial apresenta os dados de votações do Senado.

O site de monitoramento online procura unir interesse público, transparência e visualização de dados.

O projeto foi desenvolvido como trabalho final para o curso bootcamp {reprograma}, com apoio do Senai de Santa Cecília, unidade localizada em São Paulo.

Se você gostou e quer ajudar a tornar o projeto sustentável, eis uma forma de colaborar:

				<form action="https://pagseguro.uol.com.br/checkout/v2/donation.html" method="post" class="flex pagseguro">

				<input type="hidden" name="currency" value="BRL" />
				<input type="hidden" name="receiverEmail" value="caesar.gabriela@gmail.com" />
				<input type="hidden" name="iot" value="button" />
				<input type="image" src="https://stc.pagseguro.uol.com.br/public/img/botoes/doacoes/120x53-doar-cinza.gif" name="submit" alt="Pague com PagSeguro - é rápido, grátis e seguro!" />
				</form>

				<form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_top" class="flex paypal">
				<input type="hidden" name="cmd" value="_s-xclick">
				<input type="hidden" name="hosted_button_id" value="QFC4V6RBF3FT2">
				<input type="image" src="https://www.paypalobjects.com/pt_BR/BR/i/btn/btn_donateCC_LG.gif" border="0" name="submit" alt="PayPal - A maneira fácil e segura de enviar pagamentos online!">

				</form>

Para Gabriela Caesar, a ferramenta amplia o leque de mecanismos para fortalecer a participação social.

Gabriela é jornalista e programadora front-end, com passagens em redações de São Paulo e Brasília.

Fale comigo em caesar.gabriela@gmail.com

Ou pelas mídias sociais:

Desenvolvido com  por Gabriela Caesar


text:
package com.codinghabit.java8.book.ch2;

import com.codinghabit.java8.book.Apple;
import com.codinghabit.java8.book.ApplePredicate;
import java.util.List;

/**
 * Created by msavoury on 8/10/15.
 */
public class ApplePrint {

    public static void main(String args[]) {
        ApplePredicate printName = new ApplePredicate() {
            @Override
            public boolean test(Apple a) {
                System.out.println("Apple Name is " + a.getName());
                return false;
            }
        };

        ApplePredicate printColor = new ApplePredicate() {
            @Override
            public boolean test(Apple a) {
                System.out.println("Apple Color is " + a.getColor());
                return false;
            }
        };

        List<Apple> myApples = Apple.getAppleList();

        prettyPrintApple(myApples, printName);

        prettyPrintApple(myApples, printColor);
    }

    public static void prettyPrintApple(List<Apple> inventory, ApplePredicate aP) {
        for(Apple app : inventory) {
            aP.test(app);
        }
    }
}


text:
'use strict'

const chai = require('chai');
const Connection = require('../src/connection');

chai.use(require('chai-as-promised'));
chai.use(require('chai-string'));
chai.use(require('sinon-chai'));
chai.should();

const Sinon = require('sinon');
const fakeTLS = {
    addListener: Sinon.stub(),
    write: Sinon.stub()
};

describe('Connection', () => {
        var opts = {
            server: 'irc.darkmyst.org',
            port: '6697',
            nick: 'aNickName'
        };

    let sandbox, con;

    beforeEach(function() {
        sandbox = Sinon.sandbox.create();
        con = new Connection(opts);
        sandbox.stub(con, "emit");
        sandbox.stub(require('tls'), "connect").yields();
        con.data.con = fakeTLS;
    });

    afterEach(function() {
        sandbox.restore();
        fakeTLS.write.reset();
        fakeTLS.addListener.reset();
    });

    it('exists', () => {
        con.should.be.ok;
    });

    describe('connect', () => {

        beforeEach(function() {
            sandbox.stub(require('net'), 'connect').yields();
        });

        it('connects to servers', () => {
            return con.connect().should.resolve;
        });

        it('calls phase2', () => {
            sandbox.spy(con, '_phase2');
            return con.connect().then(() => {
               con._phase2.should.have.been.called;
            });
        });

    });

    describe('phase2', () => {

        it('sends a NICK', () => {
            const fakeResolve = Sinon.stub();
            con._phase2(fakeResolve);
            fakeTLS.write.should.have.been.calledWith('NICK aNickName\r\n');
            fakeResolve.should.have.been.called;
        });

        it('sends a USER', () => {
            const fakeResolve = Sinon.stub();
            con._phase2(fakeResolve);
            fakeTLS.write.should.have.been.calledWith(Sinon.match('USER'));
            fakeResolve.should.have.been.called;
        });
    });

    describe('replyPing', () => {
        it('should reply "PONG"', () => {
            con.replyPing({args: '12345'});
            return fakeTLS.write.should.have.been.calledWith('PONG 12345\r\n');
        });
    });

    describe('handleData', () => {
        beforeEach(function() {
            sandbox.stub(con, 'parseData');
        });

        it('should parse a line', () => {
            con.handleData(new Buffer('This is a line\r\n'));
            return con.parseData.should.have.been.calledWith('This is a line');
        });

        it('shouldn\'t barf on nulls', () => {
            con.handleData(null);
            return con.should.be.ok;
        });

        it('should parse two lines', () => {
            con.handleData(new Buffer('This is a line\r\nThis is another line\r\n'));
            con.parseData.should.have.been.calledWith('This is a line');
            con.parseData.should.have.been.calledWith('This is another line');
        });

        it('should parse a line split into two chunks', () => {
            con.handleData(new Buffer('This is a line'));
            con.handleData(new Buffer(' that is extra long\r\n'));
            con.parseData.should.have.been.calledWith('This is a line that is extra long');
        });

        it('should parse a linebreak across chunks', () => {
            con.handleData(new Buffer('This is a line with half a linebreak\r'));
            con.handleData(new Buffer('\n'));
            con.parseData.should.have.been.calledWith('This is a line with half a linebreak');
        });

        it('should parse a character across chunks', () => {
            con.handleData(new Buffer([0xC2]));
            con.handleData(new Buffer([0xA2]));
            con.handleData(Buffer.from('\r\n'));
            con.parseData.should.have.been.calledWith('¢');
        });
    });

    describe('parseData', () => {
        beforeEach(function() {
            sandbox.stub(con, 'parseNotice');
            sandbox.stub(con, 'replyPing');
            sandbox.stub(con, 'autoJoin');
        });

        it('should parse a valid line', () => {
            con.parseData(":prometheus.no.eu.darkmyst.org NOTICE * :*** Looking up your hostname...");
            return con.emit.should.have.been.calledWith('data');
        });

        it('should parse two lines', () => {
            con.parseData(":prometheus.no.eu.darkmyst.org NOTICE * :*** Looking up your hostname...");
            con.parseData(":flame.de.eu.darkmyst.org NOTICE * :*** Found your hostname");
            return con.emit.should.have.been.calledTwice;
        });

        it('should parse a NOTICE from the server', () => {
            con.parseData(":prometheus.no.eu.darkmyst.org NOTICE * :*** Looking up your hostname...");
            return con.parseNotice.should.have.been.called;
        });

        it('should parse a PING', () => {
            con.parseData("PING :FFFFFFFFC76EDFCA");
            return con.replyPing.should.have.been.called;
        });

        it('should join when Welcome is sent', () => {
            con.parseData(":flame.de.eu.darkmyst.org 001 yamibot :Welcome to the DarkMyst Internet Relay Chat Network yamibot +109ms");
            return con.autoJoin.should.have.been.called;
        });
    });

    describe('parseArgs', () => {
        it('should separate on spaces', () => con.parseArgs('some args').should.deep.equal(['some', 'args']));
        it('should stop at 15', () => con.parseArgs('1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18')
            .should.deep.equal(['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15 16 17 18']));
        it('should treat : special', () => con.parseArgs('one two :colon and then some words').should.deep.equal(['one', 'two', ':colon and then some words']));
    });

    describe('parseNotice', () => {
        it('should parse a valid notice', () => {
            con.parseNotice({"prefix":"maple.on.ca.darkmyst.org","command":"NOTICE","args":"* :*** Looking up your hostname..."});
            return con.emit.should.have.been.calledWith('NOTICE');
        });

        it('should reject a non-notice', () => {
            con.parseNotice({"prefix":"maple.on.ca.darkmyst.org","command":"NOTICE","args":"aaaaaaaaaaaaaaaa"});
            return con.emit.should.not.have.been.calledWith('NOTICE');
        });
    });
});


text:
var express = require("express");
var app = express();

// load static content before routing takes place
app.use(express["static"](__dirname + "/fixtures"));

// load liveReload script
app.use(require('../index.js')());

app.get("/default-test", function (req, res) {
  var html = '
default test
';
  res.send(html);
});

// start the server
if (!module.parent) {
  var port = settings.webserver.port || 3000;
  app.listen(port);
  console.log("Express app started on port " + port);
}

// run the tests
var request = require('supertest');
var assert = require('assert');

function hasScript(html) {
  return (~html.indexOf('livereload.js?snipver=1'));
}

describe('GET /default-test', function () {
  it('respond with inserted script', function (done) {
    request(app)
      .get('/default-test')
      .set('Accept', 'text/html')
      .expect(200)
      .end(function (err, res) {
        assert(hasScript(res.text));
        if (err) return done(err);
        done()
      });
  })
});

describe('GET /client.js', function () {
  it('respond without script', function (done) {
    request(app)
      .get('/client.js')
      .set('Accept', 'text/html')
      .expect(200)
      .end(function (err, res) {
        assert(!hasScript(res.text));
        if (err) return done(err);
        done()
      });
  })
});

describe('GET /static.html', function () {
  it('respond without script', function (done) {
    request(app)
      .get('/static.html')
      .set('Accept', 'text/html')
      .expect(200)
      .end(function (err, res) {
        assert(!hasScript(res.text));
        if (err) return done(err);
        done()
      });
  })
});

describe('GET /large-file', function () {
  it('respond with inserted script', function (done) {
    request(app)
      .get('/large-file.html')
      .set('Accept', 'text/html')
      .expect(200)
      .end(function (err, res) {
        assert(!hasScript(res.text));
        if (err) return done(err);
        done()
      });
  })
});


text:
copyright:
  years: 2017
lastupdated: "2017-03-17"

---
{:new_window: target="_blank"}
{:shortdesc: .shortdesc}
{:screen: .screen}
{:codeblock: .codeblock}
{:pre: .pre}

# Plugin SDK Generator
{: #sdk-cli}

Il plug-in {{site.data.keyword.IBM}} SDK Generator può essere installato nella CLI [{{site.data.keyword.Bluemix_notm}} ![Icona link esterno](../icons/launch-glyph.svg "Icona link esterno")](/docs/cli/reference/bluemix_cli/index.html).

In qualità di sviluppatore in {{site.data.keyword.Bluemix_notm}}, puoi utilizzare questo plug-in per generare gli SDK dalla tua definizione API REST conforme alla [Specifica Open API ![Icona link esterno](../icons/launch-glyph.svg "Icona link esterno")](https://www.openapis.org/). Quando apporti modifiche alla tua definizione API REST, puoi utilizzare il plug-in per rigenerare solo l'SDK anziché rigenerare l'intero progetto.

Puoi anche vedere se le tue applicazioni Cloud Foundry in un determinato spazio hanno definizioni API REST valide per la generazione dell'SDK. Infine, puoi utilizzare il plug-in {{site.data.keyword.IBM_notm}} SDK Generator per convalidare qualsiasi definizione API REST al fine di garantire che siano conformi ai requisiti del generatore SDK.

Questo plug-in {{site.data.keyword.IBM_notm}} SDK Generator ti consente di integrare facilmente i tuoi servizi di backend alla tua applicazione con un SDK generato. Quando viene apportata una modifica a un'API REST, puoi rigenerare l'SDK e sostituire quello vecchio per un aggiornamento SDK senza interruzioni. Puoi anche integrare la CLI in una pipeline DevOps e garantire che l'SDK sia sempre conforme alla specifica API ogni volta che l'applicazione viene creata.

La definizione API REST deve essere valida e deve essere ospitata su un endpoint server live o in un file locale sul tuo sistema. Se la definizione API REST è ospitata, l'URL relativo deve essere definito nella variabile di ambiente `OPENAPI_SPEC`.

## Requisiti
{: #prereqs}

Assicurati di soddisfare i seguenti requisiti.

* Disponi di un account [{{site.data.keyword.Bluemix_notm}} ![Icona link esterno](../icons/launch-glyph.svg "Icona link esterno")](http://bluemix.net)
* Hai una definizione API valida conforme alla specifica [Open API ![Icona link esterno](../icons/launch-glyph.svg "Icona link esterno")](https://www.openapis.org/)

## Installazione
{: #installation}

1. [Installa la CLI {{site.data.keyword.Bluemix}} ![Icona link esterno](../icons/launch-glyph.svg "Icona link esterno")](http://clis.ng.bluemix.net/ui/home.html).

2. [Installa il plug-in ![Icona link esterno](../icons/launch-glyph.svg "Icona link esterno")](/docs/cli/reference/bluemix_cli/index.html#install_plug-in).

	```
	bx plugin install sdk-gen -r Bluemix
	```
	{: codeblock}

## Comandi
{: #commands}

Utilizza i seguenti comandi per generare un SDK, per convalidare i file di definizione Open API o per elencare le applicazioni Cloud Foundry.

### Generazione di un SDK
{: #gen}

Use `bluemix sdk generate [arguments...][command options]`.

#### Argomenti
{: #gen-args}

* `APP_NAME` - il nome dell'applicazione Cloud Foundry nel tuo spazio corrente
* `OPENAPI_DOC_LOCATION` - un URL o percorso file relativo al JSON o Yaml della definizione API REST non elaborata
* `GENERATED_SDK_NAME` (facoltativo) - il nome dell'SDK generato

#### Opzioni
{: #gen-options}

* `PLATFORM` (obbligatorio)
   * `--android` - genera un SDK Android
   * `--ios` - genera un SDK iOS Swift
   * `--swift` - genera un SDK server Swift
* `--output "YOUR_RELATIVE_PATH"` (facoltativo) - inserisce l'SDK generato nella directory specificata da `YOUR_RELATIVE_PATH` (sovrascrive l'SDK esistente, se presente)
* `--unzip` (facoltativo) - estrae l'SDK generato (sovrascrive le risorse SDK esistenti, se presenti)

#### Utilizzo
{: #gen-usage}

Per generare un SDK da un'applicazione Cloud Foundry in esecuzione in {{site.data.keyword.Bluemix_notm}}, puoi utilizzare il nome dell'applicazione come parametro nella CLI. Il seguente comando utilizza il nome dell'applicazione come `SDK_Name`.

```
bluemix sdk generate [APP_NAME] [PLATFORM]
```
{: codeblock}

Per generare un SDK da un URL di un file di definizione Open API o un file JSON o Yaml locale, utilizza il seguente comando.

```
bluemix sdk generate [OPENAPI_DOC_LOCATION] [SDK_Name] [Platform]
```
{: codeblock}

### Convalida delle definizioni API Open
{: #validating}

Utilizza `bluemix sdk validate [argument]`.

#### Argomenti
{: #val-args}

* `APP_NAME` - il nome dell'applicazione Cloud Foundry nel tuo spazio corrente
* `OPENAPI_DOC_LOCATION` - un URL o percorso file relativo al JSON o Yaml della definizione API REST non elaborata

#### Utilizzo
{: #val-usage}

Per convalidare la specifica API di un'applicazione Cloud Foundry in esecuzione in {{site.data.keyword.Bluemix_notm}}, puoi utilizzare il nome dell'applicazione come parametro nella CLI.

```
bluemix sdk validate [APP_NAME]
```
{: codeblock}

Per convalidare un SDK dall'URL di un documento di specifiche API o un file JSON o Yaml locale, utilizza il seguente comando.

```
bluemix sdk validate [OPENAPI_DOC_LOCATION]
```
{: codeblock}

### Elenca applicazioni (Cloud Foundry)
{: #list-apps}

Utilizza `bluemix sdk list [argument][option]` per elencare le applicazioni e convalidare le specifiche API. Devi impostare la variabile di ambiente `OPENAPI_SPEC` sul percorso URL relativo che ospita la tua specifica.

#### Argomenti
{: #list-args}

* `SPACE_NAME` (facoltativo) - il nome dello spazio Cloud Foundry all'interno della tua organizzazione in cui ricercare le applicazioni. Se non viene fornito, la ricerca avviene nello spazio corrente.

#### Opzioni
{: #list-options}

* `--url` (facoltativo) - visualizza un URL completamente formato della definizione Open API per ogni applicazione nell'elenco

#### Utilizzo
{: #list-usage}

Per elencare le applicazioni nello spazio corrente, utilizza il seguente comando.

```
bluemix sdk list
```
{: codeblock}

Per elencare le applicazioni nello spazio corrente e visualizzare l'URL della specifica API, utilizza il seguente comando.

```
bluemix sdk list --url
```
{: codeblock}

Per elencare le applicazioni in uno specifico spazio, utilizza il seguente comando.

```
bluemix sdk list [SPACE_NAME]
```
{: codeblock}

Per elencare le applicazioni in uno specifico spazio e visualizzare l'URL della specifica API, utilizza il seguente comando.

```
bluemix sdk list [SPACE_NAME] --url
```
{: codeblock}


text:
"""Paths to different API modules, used to decouple domain from the base"""

PATHS = {
    'mgmt': 'api/v2.0',
    'reports': 'reporting/v1/std',
    'uniques': 'uniques/v1',
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.12"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>Parallel PopGen Package: File List</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="navtree.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

Parallel PopGen Package

File List

Here is a list of all documented files with brief descriptions:

[detail level 123]

 ▼ 3P

 ▼ _internal

 go_fish_impl.cu

 go_fish_impl.cuh

 inline_go_fish_data_struct.hpp

 shared.cu

 shared.cuh

 spectrum.cu

 template_inline_simulation_functors.cuh

 go_fish.cuh	GO Fish Simulation API (contains namespaces GO_Fish and Sim_Model)

 go_fish_data_struct.h	Subset of go_fish.cuh (the GO_Fish data structures)

 spectrum.h	Proto-API for building site frequency spectra (contains the titular namespace Spectrum)

Generated by

     1.8.12


text:
package org.apache.drill.exec.store.dfs;

import java.io.IOException;
import java.net.URI;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;

import com.google.common.base.Stopwatch;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.drill.exec.store.parquet.Metadata.ParquetTableMetadata_v1;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.Path;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.google.common.collect.Lists;

/**
 * Jackson serializable description of a file selection. Maintains an internal set of file statuses. However, also
 * serializes out as a list of Strings. All accessing methods first regenerate the FileStatus objects if they are not
 * available.  This allows internal movement of FileStatus and the ability to serialize if need be.
 */
public class FileSelection {
  static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(FileSelection.class);

  @JsonIgnore
  private List<FileStatus> statuses;

  public List<String> files;
  public String selectionRoot;

  // this is a temporary location for the reference to Parquet metadata
  // TODO: ideally this should be in a Parquet specific derived class.
  private ParquetTableMetadata_v1 parquetMeta = null;

  public FileSelection() {
  }

  public FileSelection(List<String> files, String selectionRoot, boolean dummy) {
    this.files = files;
    this.selectionRoot = selectionRoot;
  }

  public FileSelection(List<String> files, boolean dummy) {
    this.files = files;
  }

  public FileSelection(List<FileStatus> statuses) {
    this(statuses, null);
  }

  public FileSelection(List<String> files, String selectionRoot,
      ParquetTableMetadata_v1 meta) {
    this.files = files;
    this.selectionRoot = selectionRoot;
    this.parquetMeta = meta;
  }

  public FileSelection(List<FileStatus> statuses, String selectionRoot) {
    this.statuses = statuses;
    this.files = Lists.newArrayList();
    for (FileStatus f : statuses) {
      files.add(f.getPath().toString());
    }
    this.selectionRoot = selectionRoot;
  }

  public FileSelection(List<String> files, String selectionRoot,
                       ParquetTableMetadata_v1 meta, List<FileStatus> statuses) {
    this.files = files;
    this.selectionRoot = selectionRoot;
    this.parquetMeta = meta;
    this.statuses = statuses;
  }

  public boolean containsDirectories(DrillFileSystem fs) throws IOException {
    init(fs);
    for (FileStatus p : statuses) {
      if (p.isDirectory()) {
        return true;
      }
    }
    return false;
  }

  public FileSelection minusDirectories(DrillFileSystem fs) throws IOException {
    Stopwatch timer = new Stopwatch();
    timer.start();
    init(fs);
    List<FileStatus> newList = Lists.newArrayList();
    for (FileStatus p : statuses) {
      if (p.isDirectory()) {
        List<FileStatus> statuses = fs.list(true, p.getPath());
        for (FileStatus s : statuses) {
          newList.add(s);
        }
      } else {
        newList.add(p);
      }
    }
    logger.info("FileSelection.minusDirectories() took {} ms, numFiles: {}",
        timer.elapsed(TimeUnit.MILLISECONDS), newList.size());
    return new FileSelection(newList, selectionRoot);
  }

  public FileStatus getFirstPath(DrillFileSystem fs) throws IOException {
    init(fs);
    return statuses.get(0);
  }

  public List<String> getAsFiles() {
    if (!files.isEmpty()) {
      return files;
    }
    if (statuses == null) {
      return Collections.emptyList();
    }
    List<String> files = Lists.newArrayList();
    for (FileStatus s : statuses) {
      files.add(s.getPath().toString());
    }
    return files;
  }

  private void init(DrillFileSystem fs) throws IOException {
    Stopwatch timer = new Stopwatch();
    timer.start();
    if (files != null && statuses == null) {
      statuses = Lists.newArrayList();
      for (String p : files) {
        statuses.add(fs.getFileStatus(new Path(p)));
      }
    }
    logger.info("FileSelection.init() took {} ms, numFiles: {}",
        timer.elapsed(TimeUnit.MILLISECONDS), statuses == null ? 0 : statuses.size());
  }

  public List<FileStatus> getFileStatusList(DrillFileSystem fs) throws IOException {
    init(fs);
    return statuses;
  }

  /**
   * Return the parquet table metadata that may have been read
   * from a metadata cache file during creation of this file selection.
   * It will always be null for non-parquet files and null for cases
   * where no metadata cache was created.
   */
  public ParquetTableMetadata_v1 getParquetMetadata() {
    return parquetMeta;
  }

  private static String commonPath(FileStatus... paths) {
    String commonPath = "";
    String[][] folders = new String[paths.length][];
    for (int i = 0; i < paths.length; i++) {
      folders[i] = Path.getPathWithoutSchemeAndAuthority(paths[i].getPath()).toString().split("/");
    }
    for (int j = 0; j < folders[0].length; j++) {
      String thisFolder = folders[0][j];
      boolean allMatched = true;
      for (int i = 1; i < folders.length && allMatched; i++) {
        if (folders[i].length < j) {
          allMatched = false;
          break;
        }
        allMatched &= folders[i][j].equals(thisFolder);
      }
      if (allMatched) {
        commonPath += thisFolder + "/";
      } else {
        break;
      }
    }
    URI oneURI = paths[0].getPath().toUri();
    return new Path(oneURI.getScheme(), oneURI.getAuthority(), commonPath).toString();
  }

  public static FileSelection create(DrillFileSystem fs, String parent, String path) throws IOException {
    Path p = new Path(parent,removeLeadingSlash(path));
    FileStatus[] status = fs.globStatus(p);
    if (status == null || status.length == 0) {
      return null;
    }
    if (status.length == 1) {
      URI oneURI = status[0].getPath().toUri();
      String selectionRoot = new Path(oneURI.getScheme(), oneURI.getAuthority(), p.toUri().getPath()).toString();
      return new FileSelection(Collections.singletonList(status[0]), selectionRoot);
    }
    return new FileSelection(Lists.newArrayList(status), commonPath(status));
  }

  private static String removeLeadingSlash(String path) {
    if (path.charAt(0) == '/') {
      String newPath = path.substring(1);
      return removeLeadingSlash(newPath);
    } else {
      return path;
    }
  }

}


text:
@interface FSHTheme : GTLObject

@property (assign) NSInteger identifier;
@property (copy) NSString *displayName;

@end


text:
void* smalloc( size_t bytes );
void* srealloc( void* old, size_t bytes );
int file_exists( const char* filename );

#endif


text:
use opcode::Opcodes;
use Const;

/// Describes how an Upvalue is referenced
#[derive(PartialEq, Eq, Clone, Copy, Debug, RustcEncodable, RustcDecodable)]
pub enum UpvalDesc {
    /// Upvalue is the parent's local with the given id
    ///
    /// This is emitted by the resolver and converted to `Stack` by the emitter
    Local(usize),
    /// Upvalue is local variable of the parent in the given stack slot
    Stack(u8),
    /// Upvalue is the parent's Upvalue with the given ID
    Upval(usize),
}

/// Function representation output by the compiler. Later converted to a `FunctionProto`. This owns
/// all child functions (as `FnData`) and can be serialized.
#[derive(Debug, RustcEncodable, RustcDecodable)]
pub struct FnData {
    /// Size of the variable stack. This is also used as the next slot allocated for a value.
    pub stacksize: u8,
    pub params: u8,
    pub varargs: bool,
    pub opcodes: Opcodes,
    pub consts: Vec<Const>,
    pub upvals: Vec<UpvalDesc>,
    pub lines: Vec<usize>,
    pub source_name: String,
    pub child_protos: Vec<Box<FnData>>,
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:baselineAligned="false"
    android:gravity="center_vertical"
    android:padding="8dp">

    <TextView
        android:id="@+id/title"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:gravity="center_vertical"
        android:lines="2"
        android:textSize="18sp"
        android:textStyle="bold" />

    <Space
        android:layout_width="10dp"
        android:layout_height="wrap_content" />

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:gravity="end"
        android:orientation="vertical">

        <TextView
            android:id="@+id/startTime"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="14sp"
            android:textStyle="bold" />

        <TextView
            android:id="@+id/register"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="14sp"
            android:textStyle="bold" />
    </LinearLayout>

    <ImageView
        android:id="@+id/action_ImageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="8dp"
        android:background="@drawable/button_selector"
        android:src="@drawable/ic_action_overflow" />

</LinearLayout>


text:
package org.apache.mahout.cf.taste.example.kddcup.track2;

import java.util.regex.Pattern;

import org.apache.mahout.cf.taste.impl.common.FastIDSet;

final class TrackData {

  private static final Pattern PIPE = Pattern.compile("\\|");
  private static final String NO_VALUE = "None";
  static final long NO_VALUE_ID = Long.MIN_VALUE;
  private static final FastIDSet NO_GENRES = new FastIDSet();

  private final long trackID;
  private final long albumID;
  private final long artistID;
  private final FastIDSet genreIDs;

  TrackData(CharSequence line) {
    String[] tokens = PIPE.split(line);
    trackID = Long.parseLong(tokens[0]);
    albumID = parse(tokens[1]);
    artistID = parse(tokens[2]);
    if (tokens.length > 3) {
      genreIDs = new FastIDSet(tokens.length - 3);
      for (int i = 3; i < tokens.length; i++) {
        genreIDs.add(Long.parseLong(tokens[i]));
      }
    } else {
      genreIDs = NO_GENRES;
    }
  }

  private static long parse(String value) {
    return NO_VALUE.equals(value) ? NO_VALUE_ID : Long.parseLong(value);
  }

  public long getTrackID() {
    return trackID;
  }

  public long getAlbumID() {
    return albumID;
  }

  public long getArtistID() {
    return artistID;
  }

  public FastIDSet getGenreIDs() {
    return genreIDs;
  }

}


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Service_types extends CI_Controller {

	function __construct() {
		parent::__construct();
		$this->load->model('service_types_model');
	}

	public function index()
	{
		//Load the symptoms page. Header and Footer seperated to load common files on to any view
		$data['form_data'] = $this->service_types_model->get_form_data();
		$this->load->view('include/header');
		$this->load->view('service_types_view', $data);
		$this->load->view('include/footer');
	}

	public function submit() {
		//Function triggered to register user
		$result = $this->service_types_model->submit();
		$this->index();
	}

}


text:
using System;
using System.Globalization;
using Xunit;

namespace System.Globalization.Tests
{
    public class NumberStylesFloat
    {
        // PosTest1: Verify value of NumberStyles.Float
        [Fact]
        public void TestFloat()
        {
            int AllowLeadingWhite = 0x00000001,
                AllowTrailingWhite = 0x00000002,
                AllowLeadingSign = 0x00000004,
                AllowDecimalPoint = 0x00000020,
                AllowExponent = 0x00000080;

            int expected = AllowLeadingWhite | AllowTrailingWhite | AllowLeadingSign |
                           AllowDecimalPoint | AllowExponent;

            int actual = (int)NumberStyles.Float;
            Assert.Equal(expected, actual);
        }
    }
}


text:
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

namespace report_search\output;

defined('MOODLE_INTERNAL') || die();

require_once("$CFG->libdir/formslib.php");

/**
 * Search report form.
 *
 * @package    report_search
 * @copyright  Prateek Sachan {@link http://prateeksachan.com}
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
class form extends \moodleform {

    /**
     * Form definition.
     *
     * @return void
     */
    public function definition() {

        $mform = $this->_form;

        $checkboxarray = array();
        $checkboxarray[] =& $mform->createElement('checkbox', 'reindex', '', get_string('indexsite', 'report_search'));
        $mform->addGroup($checkboxarray, 'reindexcheckbox', '', array(''), false);
        $mform->closeHeaderBefore('reindexcheckbox');

        $checkboxarray = array();
        $checkboxarray[] =& $mform->createElement('checkbox', 'delete', '', get_string('delete', 'report_search'));
        $mform->addGroup($checkboxarray, 'deletecheckbox', '', array(''), false);
        $mform->closeHeaderBefore('deletecheckbox');

        // Only available if delete checked.
        $areacheckboxarray = array();
        $areacheckboxarray[] =& $mform->createElement('advcheckbox', 'all', '', get_string('entireindex', 'report_search'),
            array('group' => 1));
        $mform->setDefault('all', true);

        foreach ($this->_customdata['searchareas'] as $key => $searcharea) {
            $areacheckboxarray[] =& $mform->createElement('advcheckbox', $key, '',
                $searcharea->get_visible_name(), array('group' => 2));
        }
        $mform->addGroup($areacheckboxarray, 'areasadvcheckbox', '', array(' '), false);
        $mform->closeHeaderBefore('areasadvcheckbox');
        $mform->disabledIf('areasadvcheckbox', 'delete', 'notchecked');

        $this->add_action_buttons(false, get_string('execute', 'report_search'));
    }
}