text:
using Google.Apis.Json;
using Newtonsoft.Json;
using System;
using System.IO;
using System.Threading.Tasks;

namespace Google.Apis.Auth.OAuth2
{
    public partial class AwsExternalAccountCredential
    {
        /// <summary>
        /// Represents AWS security credentials which are used to sign
        /// the subject token.
        /// </summary>
        internal sealed class AwsSecurityCredentials
        {
            private const string AccessKeyIdEnvVar = "AWS_ACCESS_KEY_ID";
            private const string SecretAccessKeyEnvVar = "AWS_SECRET_ACCESS_KEY";
            private const string TokenEnvVar = "AWS_SESSION_TOKEN";

            /// <summary>
            /// The access key ID. Won't be null or empty.
            /// </summary>
            internal string AccessKeyId { get; }

            /// <summary>
            /// The secret access key. Won't be null or empty.
            /// </summary>
            internal string SecretAccessKey { get; }

            /// <summary>
            /// The credential token. May be null but won't be empty.
            /// </summary>
            internal string Token { get; }

            internal AwsSecurityCredentials(string accessKeyId, string secretAccessKey, string token)
            {
                AccessKeyId = accessKeyId;
                SecretAccessKey = secretAccessKey;
                Token = token;
            }

            /// <summary>
            /// Fetches the AWS security credentials as per https://google.aip.dev/auth/4117#determining-the-subject-token-in-aws.
            /// </summary>
            internal static async Task<AwsSecurityCredentials> FetchAsync(AwsMetadataServerClient metadataClient, string credentialUrl) =>
                MaybeFromEnvVars()
                ?? await MaybeFromMetadataAsync(metadataClient, credentialUrl).ConfigureAwait(false)
                ?? throw new InvalidOperationException($"Couldn't determine the AWS security credentials. " +
                    $"At least one of the following environment variables was not set: {AccessKeyIdEnvVar}, {SecretAccessKeyEnvVar}. " +
                    $"And the {nameof(SecurityCredentialsUrl)} was not specified in the credential configuration " +
                    "or no security credentials could be obtained from it.");

            /// <summary>
            /// Attempts to fetch the security credentials from environment variables.
            /// Returns null if the environment variables are not set.
            /// </summary>
            internal static AwsSecurityCredentials MaybeFromEnvVars()
            {
                if (GetNonEmptyEnvVarValue(AccessKeyIdEnvVar) is string accessKeyId
                    && GetNonEmptyEnvVarValue(SecretAccessKeyEnvVar) is string secretAccessKey)
                {
                    return new AwsSecurityCredentials(accessKeyId, secretAccessKey, GetNonEmptyEnvVarValue(TokenEnvVar));
                }

                return null;
            }

            /// <summary>
            /// Attempts to fetch the security credentials from the metadata server.
            /// Returns null if the credential URL is null or empty.
            /// </summary>
            internal static async Task<AwsSecurityCredentials> MaybeFromMetadataAsync(AwsMetadataServerClient metadataClient, string credentialUrl)
            {
                // https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html#instance-metadata-security-credentials
                if (!string.IsNullOrEmpty(credentialUrl)
                    // Build the actual credential endpoint.
                    && await BuildSecurityCredentialsEndpointAsync().ConfigureAwait(false) is string credentialEndpoint
                    // Fetch the credential JSON
                    && await metadataClient.FetchMetadataAsync(credentialEndpoint).ConfigureAwait(false) is string credentialJson
                    && credentialJson != "")
                {
                    // Deserialize the credentials
                    var deserializedCredentials = NewtonsoftJsonSerializer.Instance.Deserialize<AwsSecurityCredentialsResponse>(credentialJson);

                    if (deserializedCredentials.IsSuccess
                        && !string.IsNullOrEmpty(deserializedCredentials.AccessKeyId)
                        && !string.IsNullOrEmpty(deserializedCredentials.SecretAccessKey))
                    {
                        return new AwsSecurityCredentials(
                            deserializedCredentials.AccessKeyId, deserializedCredentials.SecretAccessKey,
                            deserializedCredentials.Token == "" ? null : deserializedCredentials.Token);
                    }

                    throw new InvalidOperationException(
                        $"The request to the metadata server security credentials endpoint {credentialEndpoint} was not successful. " +
                        $"The response was {credentialJson}");
                }

                return null;

                async Task<string> BuildSecurityCredentialsEndpointAsync()
                {
                    // https://github.com/aws/aws-sdk-java/blob/ccfd63c097874e3a1e9ffda7bf171769b6bd3b21/aws-java-sdk-core/src/main/java/com/amazonaws/auth/InstanceMetadataServiceCredentialsFetcher.java#L55
                    // Fetch the list of roles attached to the instance from the credential URL as given.
                    // Each role will be on a different line, and we keep the first one only.
                    if (await metadataClient.FetchMetadataAsync(credentialUrl).ConfigureAwait(false) is string metadataRoleList)
                    {
                        // Let's use StringReader so that we don't have to worry about which end of line charater(s) to use.
                        using var reader = new StringReader(metadataRoleList);
                        if (await reader.ReadLineAsync().ConfigureAwait(false) is string role && role != "")
                        {
                            // Attach the role to the given credential URL to fetch the actual credentials.
                            return credentialUrl.EndsWith("/") ? $"{credentialUrl}{role}" : $"{credentialUrl}/{role}";
                        }
                    }

                    return null;
                }
            }
            /// <summary>
            /// Partial representation of a metadata server security credentials response as defined by
            /// https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html#instance-metadata-security-credentials
            /// </summary>
            private struct AwsSecurityCredentialsResponse
            {
                internal const string SuccessStatusCode = "Success";

                [JsonIgnore]
                public bool IsSuccess => Code?.Equals(SuccessStatusCode, StringComparison.OrdinalIgnoreCase) == true;

                [JsonProperty("Code")]
                public string Code { get; set; }

                [JsonProperty("AccessKeyId")]
                public string AccessKeyId { get; set; }

                [JsonProperty("SecretAccessKey")]
                public string SecretAccessKey { get; set; }

                [JsonProperty("Token")]
                public string Token { get; set; }
            }
        }
    }
}


text:
#include <aws/glue/model/GetUnfilteredTableMetadataRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::Glue::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;

GetUnfilteredTableMetadataRequest::GetUnfilteredTableMetadataRequest() :
    m_catalogIdHasBeenSet(false),
    m_databaseNameHasBeenSet(false),
    m_nameHasBeenSet(false),
    m_auditContextHasBeenSet(false),
    m_supportedPermissionTypesHasBeenSet(false)
{
}

Aws::String GetUnfilteredTableMetadataRequest::SerializePayload() const
{
  JsonValue payload;

  if(m_catalogIdHasBeenSet)
  {
   payload.WithString("CatalogId", m_catalogId);

  }

  if(m_databaseNameHasBeenSet)
  {
   payload.WithString("DatabaseName", m_databaseName);

  }

  if(m_nameHasBeenSet)
  {
   payload.WithString("Name", m_name);

  }

  if(m_auditContextHasBeenSet)
  {
   payload.WithObject("AuditContext", m_auditContext.Jsonize());

  }

  if(m_supportedPermissionTypesHasBeenSet)
  {
   Aws::Utils::Array<JsonValue> supportedPermissionTypesJsonList(m_supportedPermissionTypes.size());
   for(unsigned supportedPermissionTypesIndex = 0; supportedPermissionTypesIndex < supportedPermissionTypesJsonList.GetLength(); ++supportedPermissionTypesIndex)
   {
     supportedPermissionTypesJsonList[supportedPermissionTypesIndex].AsString(PermissionTypeMapper::GetNameForPermissionType(m_supportedPermissionTypes[supportedPermissionTypesIndex]));
   }
   payload.WithArray("SupportedPermissionTypes", std::move(supportedPermissionTypesJsonList));

  }

  return payload.View().WriteReadable();
}

Aws::Http::HeaderValueCollection GetUnfilteredTableMetadataRequest::GetRequestSpecificHeaders() const
{
  Aws::Http::HeaderValueCollection headers;
  headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "AWSGlue.GetUnfilteredTableMetadata"));
  return headers;

}

redpajama_set_name: RedPajamaGithub


text:
#import "NSObject.h"

// Not exported
@interface TSDQuicklookPersistenceAdditions : NSObject
{
}

+ (id)imageFillFromColorFill:(id)arg1 objContext:(id)arg2;
+ (id)imageDataFromCGColor:(struct CGColor *)arg1 objContext:(id)arg2;
+ (struct CGSize)imageColorSize;

@end


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.3.0
// See https://javaee.github.io/jaxb-v2/
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2022.06.28 at 02:49:33 PM PDT
//

package com.intuit.ipp.data;

import java.io.Serializable;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
import org.jvnet.jaxb2_commons.lang.Equals2;
import org.jvnet.jaxb2_commons.lang.EqualsStrategy2;
import org.jvnet.jaxb2_commons.lang.HashCode2;
import org.jvnet.jaxb2_commons.lang.HashCodeStrategy2;
import org.jvnet.jaxb2_commons.lang.JAXBEqualsStrategy;
import org.jvnet.jaxb2_commons.lang.JAXBHashCodeStrategy;
import org.jvnet.jaxb2_commons.locator.ObjectLocator;
import org.jvnet.jaxb2_commons.locator.util.LocatorUtils;

/**
 * Financial Transaction information that pertains to
 * 				the entire Check.
 *
 *
Java class for CreditCardPurchase complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="CreditCardPurchase">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="AccountRef" type="{http://schema.intuit.com/finance/v3}ReferenceType" minOccurs="0"/>
 *         <element name="Credit" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "CreditCardPurchase", propOrder = {
    "accountRef",
    "credit"
})
public class CreditCardPurchase implements Serializable, Equals2, HashCode2
{

    private final static long serialVersionUID = 1L;
    @XmlElement(name = "AccountRef")
    protected ReferenceType accountRef;
    @XmlElement(name = "Credit")
    protected Boolean credit;

    /**
     * Gets the value of the accountRef property.
     *
     * @return
     *     possible object is
     *     {@link ReferenceType }
     *
     */
    public ReferenceType getAccountRef() {
        return accountRef;
    }

    /**
     * Sets the value of the accountRef property.
     *
     * @param value
     *     allowed object is
     *     {@link ReferenceType }
     *
     */
    public void setAccountRef(ReferenceType value) {
        this.accountRef = value;
    }

    /**
     * Gets the value of the credit property.
     *
     * @return
     *     possible object is
     *     {@link Boolean }
     *
     */
    public Boolean isCredit() {
        return credit;
    }

    /**
     * Sets the value of the credit property.
     *
     * @param value
     *     allowed object is
     *     {@link Boolean }
     *
     */
    public void setCredit(Boolean value) {
        this.credit = value;
    }

    public boolean equals(ObjectLocator thisLocator, ObjectLocator thatLocator, Object object, EqualsStrategy2 strategy) {
        if ((object == null)||(this.getClass()!= object.getClass())) {
            return false;
        }
        if (this == object) {
            return true;
        }
        final CreditCardPurchase that = ((CreditCardPurchase) object);
        {
            ReferenceType lhsAccountRef;
            lhsAccountRef = this.getAccountRef();
            ReferenceType rhsAccountRef;
            rhsAccountRef = that.getAccountRef();
            if (!strategy.equals(LocatorUtils.property(thisLocator, "accountRef", lhsAccountRef), LocatorUtils.property(thatLocator, "accountRef", rhsAccountRef), lhsAccountRef, rhsAccountRef, (this.accountRef!= null), (that.accountRef!= null))) {
                return false;
            }
        }
        {
            Boolean lhsCredit;
            lhsCredit = this.isCredit();
            Boolean rhsCredit;
            rhsCredit = that.isCredit();
            if (!strategy.equals(LocatorUtils.property(thisLocator, "credit", lhsCredit), LocatorUtils.property(thatLocator, "credit", rhsCredit), lhsCredit, rhsCredit, (this.credit!= null), (that.credit!= null))) {
                return false;
            }
        }
        return true;
    }

    public boolean equals(Object object) {
        final EqualsStrategy2 strategy = JAXBEqualsStrategy.INSTANCE;
        return equals(null, null, object, strategy);
    }

    public int hashCode(ObjectLocator locator, HashCodeStrategy2 strategy) {
        int currentHashCode = 1;
        {
            ReferenceType theAccountRef;
            theAccountRef = this.getAccountRef();
            currentHashCode = strategy.hashCode(LocatorUtils.property(locator, "accountRef", theAccountRef), currentHashCode, theAccountRef, (this.accountRef!= null));
        }
        {
            Boolean theCredit;
            theCredit = this.isCredit();
            currentHashCode = strategy.hashCode(LocatorUtils.property(locator, "credit", theCredit), currentHashCode, theCredit, (this.credit!= null));
        }
        return currentHashCode;
    }

    public int hashCode() {
        final HashCodeStrategy2 strategy = JAXBHashCodeStrategy.INSTANCE;
        return this.hashCode(null, strategy);
    }

}


text:
package com.baidubce.services.bec.model.vo;

import lombok.Data;

import java.util.ArrayList;
import java.util.List;

/**
 * Node information.
 */
@Data
public class NodeInfoVo {

    /**
     * Node information.
     */
    private List<RegionInfo> regionList = new ArrayList<RegionInfo>();

    /**
     * Get node sum.
     */
    public int getNodeSum() {
        int result = 0;
        for (RegionInfo regionInfo : regionList) {
            for (CityInfo cityInfo : regionInfo.getCityList()) {
                result += cityInfo.getServiceProviderList().size();
            }
        }
        return result;
    }

    /**
     * Region information.
     */
    @Data
    public static class RegionInfo {

        /**
         * The English name of the region to which the node belongs.
         */
        private String region;

        /**
         * The Chinese name of the region to which the node belongs.
         */
        private String name;

        /**
         * Information about the city where the node is located.
         */
        private List<CityInfo> cityList = new ArrayList<CityInfo>();

    }

    /**
     * City information.
     */
    @Data
    public static class CityInfo {

        /**
         * The English name of the city to which the node belongs.
         */
        private String city;

        /**
         * The Chinese name of the city to which the node belongs.
         */
        private String name;

        /**
         * Information of the operator where the node is located.
         */
        private List<ServiceProviderInfo> serviceProviderList = new ArrayList<ServiceProviderInfo>();

    }

    /**
     * Service provider information.
     */
    @Data
    public static class ServiceProviderInfo {

        /**
         * The English name of the service provider to which the node belongs.
         */
        private String serviceProvider;

        /**
         * The Chinese name of the service provider to which the node belongs.
         */
        private String name;

    }
}


text:
<?php

$name = 'Downtown Ophelialaan Aalsmeer 2019';
$markt_id = 18;
?>

    <meta charset="utf-8">

    <meta property="og:url"                content="http://app.directevents.nl/markt/downtown%20ophelialaan%20aalsmeer%202019">
    <meta property="og:type"               content="website">
    <meta property="og:title"              content="Downtown Ophelialaan Aalsmeer - Direct Events">
    <meta property="og:description"        content="Downtown Ophelialaan is op Zaterdag 22 juni van 12:00 tot 17:00 in Aalsmeer">
    <meta property="og:image"              content="http://app.directevents.nl/downtown%20ophelialaan%20aalsmeer%202019/mail.jpg">

    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="csrf-token" content="{{{ csrf_token() }}}">

    <title>Direct Events - {{ $name }}</title>

    <base href="http://{{ $_SERVER['HTTP_HOST'] }}/downtown ophelialaan aalsmeer 2019/">

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/fancyapps/fancybox@3.5.2/dist/jquery.fancybox.min.css" />
    <link href="https://fonts.googleapis.com/css?family=Roboto:300,400,700" rel="stylesheet">

    <link media="all" type="text/css" rel="stylesheet" href="style/style.css">

    <link rel="image_src" href="http://app.directevents.nl/downtown ophelialaan aalsmeer 2019/mail.jpg">

                Zaterdag

22 Juni

                10:00

                -

                17:00

            fashion | food | drinks | music | lifestyle

                Zaterdag

22 Juni

                10:00

                -

                17:00

            <button data-src="#aanmeldformulier" class="aanmelden btn _aanmeldformulieropenen">aanmelden</button>

            fashion | food | drinks | music | lifestyle

        <form id="aanmeld-formulier">

Aanmelden

                    <input type="hidden" name="_token" value="{{{ csrf_token() }}}" />
                    <input type="hidden" name="markt_id" value="{{ $markt_id }}" />
                    <input style="display: none;" type="radio" name="foodNonfood" value="non-food" checked="checked">

                            Bedrijfs gegevens:

                                    Bedrijfsnaam: *
                                    <input type="text" class="form-control" id="bedrijfsnaam" name="bedrijfsnaam" placeholder="Uw bedrijfsnaam">

                                    Email: *
                                    <input type="email" class="form-control" id="email" name="email" placeholder="Uw email">

                                    Voornaam: *
                                    <input type="text" class="form-control" id="voornaam" name="voornaam" placeholder="Uw voornaam">

                                    Achternaam: *
                                    <input type="text" class="form-control" id="achternaam" name="achternaam" placeholder="Uw achternaam">

                                    Telefoon: *
                                    <input type="text" class="form-control" id="telefoon" name="telefoon" placeholder="Uw nummer">

                                    Website/facebook/etc: *
                                    <input type="text" class="form-control" id="website" name="website" placeholder="Uw website">

                            Adres gegevens:

                                    Woonplaats: *
                                    <input type="text" class="form-control" id="woonplaats" name="woonplaats" placeholder="Uw woonplaats">

                                    Postcode: *
                                    <input type="text" class="form-control" id="postcode" name="postcode" placeholder="Uw postcode">

                                    Straat: *
                                    <input type="text" class="form-control" id="straat" name="straat" placeholder="Uw straat">

                                    Huisnummer: *
                                    <input type="text" class="form-control" id="huisnummer" name="huisnummer" placeholder="Uw huisnummer">

                                    Toevoeging:
                                    <input type="text" class="form-control" id="toevoeging" name="toevoeging" placeholder="Uw toevoeging">

                            Markt gegevens:

                        <input type="hidden" name="dag[0]" checked="checked">

                                    Aantal kramen (€50,- excl. BTW): *
                                    <input type="text" class="form-control" id="kramen" name="kramen" placeholder="Aantal kramen">

                                    Grondplek per strekkende meter (€12,50 excl. BTW): *
                                    <input type="text" class="form-control" id="grondplek" name="grondplekken" placeholder="Aantal meters">

                                    Grote maten:
                                    <input type="checkbox" class="form-control" name="producten[0]" id="grote-maten" value="grote-maten">

                                    Dames kleding:
                                    <input type="checkbox" class="form-control" name="producten[1]" id="dames-kleding" value="dames-kleding">

                                    Herenkleding:
                                    <input type="checkbox" class="form-control" name="producten[2]" id="heren-kleding" value="heren-kleding">

                                    Kinderkleding:
                                    <input type="checkbox" class="form-control" name="producten[3]" id="kinder-kleding" value="kinder-kleding">

                                    Babykleding:
                                    <input type="checkbox" class="form-control" name="producten[4]" id="baby-kleding" value="baby-kleding">

                                    Kledingaccesoires:
                                    <input type="checkbox" class="form-control" name="producten[5]" id="fashion-accesoires" value="fashion-accesoires">

                                    Schoenen:
                                    <input type="checkbox" class="form-control" name="producten[6]" id="schoenen" value="schoenen">

                                    Lifestyle:
                                    <input type="checkbox" class="form-control" name="producten[7]" id="lifestyle" value="lifestyle">

                                    Woonaccessoires:
                                    <input type="checkbox" class="form-control" name="producten[8]" id="woon-accessoires" value="woon-accessoires">

                                    Kunst:
                                    <input type="checkbox" class="form-control" name="producten[9]" id="kunst" value="kunst">

                                    Sieraden:
                                    <input type="checkbox" class="form-control" name="producten[10]" id="sieraden" value="sieraden">

                                    Tassen:
                                    <input type="checkbox" class="form-control" name="producten[11]" id="tassen" value="tassen">

                                    Brocante:
                                    <input type="checkbox" class="form-control" name="producten[12]" id="brocante" value="brocante">

                                    Dierenspullen:
                                    <input type="checkbox" class="form-control" name="producten[13]" id="dierenspullen" value="dierenspullen">

                                    Anders:
                                    <input type="checkbox" class="form-control" name="producten[14]" id="anders" value="anders">

                <button class="btn btn-default aanmelden">

                    Aanmelden
                </button>

        </form>


text:
namespace Tn.DeviceManager.Measurements
{
    using System;
    using System.Collections.Generic;

    public class QueryResult
    {
        public QueryResult(string name, ICollection<Point> points)
        {
            if (string.IsNullOrEmpty(name))
                throw new ArgumentNullException(nameof(name));

            Name = name;
            Points = points ?? Array.Empty<Point>();
        }

        public string Name { get; }
        public ICollection<Point> Points { get; }
    }
}


text:
#ifndef _NFI_ITEM_MODULE_H_
#define _NFI_ITEM_MODULE_H_

#include <iostream>
#include "NFILogicModule.h"

class NFIItemModule
    : public NFILogicModule
{

public:

};

#endif


text:
#include "tensorflow_serving/core/test_util/fake_loader_source_adapter.h"

#include <memory>

#include "tensorflow/core/lib/strings/strcat.h"
#include "tensorflow/core/platform/types.h"
#include "tensorflow_serving/core/loader.h"
#include "tensorflow_serving/core/source_adapter.h"

namespace tensorflow {
namespace serving {
namespace test_util {

FakeLoaderSourceAdapter::FakeLoaderSourceAdapter(
    const string& suffix, std::function<void(const string&)> call_on_destruct)
    : SimpleLoaderSourceAdapter(
          [this](const StoragePath& path,
                 std::unique_ptr<string>* servable_ptr) {
            const string servable = suffix_.length() > 0
                                        ? strings::StrCat(path, "/", suffix_)
                                        : path;
            servable_ptr->reset(new string(servable));
            return Status::OK();
          },
          SimpleLoaderSourceAdapter<StoragePath,
                                    string>::EstimateNoResources()),
      suffix_(suffix),
      call_on_destruct_(call_on_destruct) {}

FakeLoaderSourceAdapter::~FakeLoaderSourceAdapter() {
  Detach();
  if (call_on_destruct_) {
    call_on_destruct_(suffix_);
  }
}

// Register the source adapter.
class FakeLoaderSourceAdapterCreator {
 public:
  static Status Create(
      const FakeLoaderSourceAdapterConfig& config,
      std::unique_ptr<SourceAdapter<StoragePath, std::unique_ptr<Loader>>>*
          adapter) {
    adapter->reset(new FakeLoaderSourceAdapter(config.suffix()));
    return Status::OK();
  }
};
REGISTER_STORAGE_PATH_SOURCE_ADAPTER(FakeLoaderSourceAdapterCreator,
                                     FakeLoaderSourceAdapterConfig);

}  // namespace test_util
}  // namespace serving
}  // namespace tensorflow


text:
package org.wso2.appcloud.core.docker;

import io.fabric8.docker.api.model.AuthConfig;
import io.fabric8.docker.client.Config;
import io.fabric8.docker.client.ConfigBuilder;
import io.fabric8.docker.client.DefaultDockerClient;
import io.fabric8.docker.dsl.EventListener;
import io.fabric8.docker.dsl.OutputHandle;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.appcloud.common.AppCloudException;
import org.wso2.appcloud.common.util.AppCloudUtil;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.concurrent.CountDownLatch;

/**
 * Java client for docker operations.
 */
public class DockerClient {

    private static Log log = LogFactory.getLog(DockerClient.class);

    io.fabric8.docker.client.DockerClient dockerClient;
    OutputHandle handle;

    final CountDownLatch buildDone = new CountDownLatch(1);
    final CountDownLatch pushDone = new CountDownLatch(1);
    final CountDownLatch pullDone = new CountDownLatch(1);

    final String TAG_LATEST = "latest";

    public DockerClient() {
        Config config = new ConfigBuilder()
                .withDockerUrl(DockerClientConstants.DEFAULT_DOCKER_URL)
                .build();
        dockerClient = new DefaultDockerClient(config);
    }

    public DockerClient(String uri) {
        // if docker registry is secured, set auth configuration
        Map<String, AuthConfig> authConfigMap = new HashMap<>();
        String securedDockerRegistryServer = AppCloudUtil.getPropertyValue(DockerClientConstants.DOCKER_REGISTRY_SERVER);
        if (StringUtils.isNotEmpty(securedDockerRegistryServer)) {
            AuthConfig authConfig = new AuthConfig();
            authConfig.setUsername(AppCloudUtil.getPropertyValue(DockerClientConstants.DOCKER_REGISTRY_USERNAME));
            authConfig.setPassword(new String(Base64.decodeBase64(
                    AppCloudUtil.getPropertyValue(DockerClientConstants.DOCKER_REGISTRY_PASSWORD))));
            authConfig.setServeraddress(securedDockerRegistryServer);

            authConfigMap.put(authConfig.getServeraddress(), authConfig);
            log.debug("Auth configuration is successfully set for registry:" + securedDockerRegistryServer);
        }

        Config config = new ConfigBuilder()
                .withDockerUrl(uri)
                .withConnectionTimeout(Integer.parseInt(AppCloudUtil.getPropertyValue(DockerClientConstants
                        .DOCKER_CONNECTION_TIMEOUT)))
                .withRequestTimeout(Integer.parseInt(AppCloudUtil.getPropertyValue(DockerClientConstants
                        .DOCKER_REQUEST_TIMEOUT)))
                .withImagePushTimeout(Integer.parseInt(AppCloudUtil.getPropertyValue(DockerClientConstants
                        .DOCKER_PUSH_TIMEOUT)))
                .withImageBuildTimeout(Integer.parseInt(AppCloudUtil.getPropertyValue(DockerClientConstants
                        .DOCKER_BUILLD_TIMEOUT)))
                .withImageSearchTimeout(Integer.parseInt(AppCloudUtil.getPropertyValue(DockerClientConstants
                        .DOCKER_SEARCH_TIMEOUT)))
                .withAuthConfigs(authConfigMap)
                .build();
        dockerClient = new DefaultDockerClient(config);
    }

    /**
     * Create a docker file according to given details. This will get docker template file and replace the parameters
     * with the given customized values in the dockerFilePropertyMap
     * @param dockerFilePath
     * @param runtimeId - application runtime id
     * @param dockerTemplateFilePath
     * @param dockerFileCategory - app creation method eg : svn, url, default
     * @param dockerFilePropertyMap
     * @param customDockerFileProperties
     * @throws IOException
     * @throws AppCloudException
     */
    public void createDockerFile(String dockerFilePath, String runtimeId, String dockerTemplateFilePath,
            String dockerFileCategory, Map<String, String> dockerFilePropertyMap,
            Map<String, String> customDockerFileProperties) throws  AppCloudException {

        // customDockerFileProperties will be null when creating docker files for custom docker security
        if(customDockerFileProperties != null) {
            customDockerFileProperties.keySet().removeAll(dockerFilePropertyMap.keySet());
            dockerFilePropertyMap.putAll(customDockerFileProperties);
        }
        String dockerFileTemplatePath;
        // runtime id will be null when creating docker files for custom docker security
        if(runtimeId != null && dockerFileCategory != null) {
            // Get docker template file
            // A sample docker file can be found at
            // https://github.com/wso2/app-cloud/blob/master/modules/resources/dockerfiles/wso2as/default/Dockerfile.wso2as.6.0.0-m1
            dockerFileTemplatePath = DockerUtil
                    .getDockerFileTemplatePath(runtimeId, dockerTemplateFilePath, dockerFileCategory);
        } else {
            dockerFileTemplatePath = dockerTemplateFilePath;
        }
        List<String> dockerFileConfigs = new ArrayList<>();

        try {
            for (String line : FileUtils.readLines(new File(dockerFileTemplatePath))) {
                StringTokenizer stringTokenizer = new StringTokenizer(line);
                //Search if line contains keyword to replace with the value
                while (stringTokenizer.hasMoreElements()) {
                    String element = stringTokenizer.nextElement().toString().trim();
                    if (dockerFilePropertyMap.containsKey(element)) {
                        if (log.isDebugEnabled()) {
                            log.debug("Dockerfile placeholder : " + element);
                        }
                        String value = dockerFilePropertyMap.get(element);
                        line = line.replace(element, value);
                    }
                }
                dockerFileConfigs.add(line);
            }
        } catch (IOException e) {
            String msg = "Error occurred while reading docker template file " + dockerFileTemplatePath;
            throw new AppCloudException(msg,e);
        }
        try {
            FileUtils.writeLines(new File(dockerFilePath), dockerFileConfigs);
        } catch (IOException e) {
            String msg = "Error occurred while writing to docker file " + dockerFilePath;
            throw new AppCloudException(msg,e);
        }
    }

    /**
     * Build created docker images
     * @param repoUrl - docker registry url
     * @param imageName - application runtime name
     * @param tag - tag name
     * @param dockerFileUrl - absolute file upload path
     * @throws InterruptedException
     * @throws IOException
     * @throws AppCloudException
     */
    public void buildDockerImage(String repoUrl, String imageName, String tag, String dockerFileUrl)
            throws AppCloudException {

        String dockerImage = repoUrl + "/" + imageName + ":" + tag;
        final boolean[] dockerStatusCheck = new boolean[1];
	    dockerStatusCheck[0] = false; //this is to check docker build status, whether it was successful or failed
        try {
            handle = dockerClient.image().build()
                                 .withRepositoryName(dockerImage)
                                 .withNoCache()
                                 .usingListener(new EventListener() {
                                     @Override
                                     public void onSuccess(String message) {
                                         log.info("Build Success:" + message);
                                         buildDone.countDown();
                                         dockerStatusCheck[0] = true;
                                     }

                                     @Override
                                     public void onError(String message) {
                                         // log as a warning because docker build operation is retried by jaggery client
                                         log.warn("Build Failure:" + message);
                                         buildDone.countDown();
                                     }

                                     @Override
                                     public void onEvent(String event) {
                                         log.info(event);
                                     }
                                 })
                                 .fromFolder(dockerFileUrl);
            buildDone.await();
        } catch (InterruptedException e) {
            String msg = "Error occurred while building docker image " + imageName + " with tag : " + tag + " of " +
                         "docker file : " + dockerFileUrl;
            throw new AppCloudException(msg, e);
        } finally {
            try {
                handle.close();
            } catch (IOException e) {
                log.warn("Error occurred while closing output handle after building docker image " + imageName +
                         " with tag : " + tag + " of docker file : " + dockerFileUrl);

            }
        }

        if (!dockerStatusCheck[0]) {
            log.error("Docker image building failed: " + imageName + " repo: " + repoUrl + " docker file: "
                    + dockerFileUrl + " tag: " + tag);
            throw new AppCloudException(
                    "Docker image building failed: " + imageName + " repo: " + repoUrl + " docker file: "
                            + dockerFileUrl + " tag: " + tag);
        }
    }

    /**
     * Push docker images
     *
     * @param imageName - application runtime name
     * @param tag       - tag name
     * @throws InterruptedException
     * @throws IOException
     * @throws AppCloudException
     */
    public void pushDockerImage(String imageName, String tag)
            throws AppCloudException {

        final boolean[] dockerStatusCheck = new boolean[1];
        dockerStatusCheck[0] = false;
        try {
            handle = dockerClient.image().withName(imageName).push()
                                 .usingListener(new EventListener() {
                                     @Override
                                     public void onSuccess(String message) {
                                         log.info("Push Success:" + message);
                                         pushDone.countDown();
                                         dockerStatusCheck[0] = true;
                                     }

                                     @Override
                                     public void onError(String message) {
                                         // log as warning because docker push operation is retried by jaggery client
                                         log.warn("Push Failure:" + message);
                                         pushDone.countDown();
                                     }

                                     @Override
                                     public void onEvent(String event) {
                                         log.info(event);
                                     }
                                 }).withTag(tag).toRegistry();
            pushDone.await();

        } catch (InterruptedException e) {

            String msg = "Error occurred while pushing docker image " + imageName + " with tag : " + tag + " to " +
                         "docker registry. ";
            log.error(e);
            throw new AppCloudException(msg, e);
        } finally {
            try {
                handle.close();
            } catch (IOException e) {
                log.warn("Error occurred while closing output handle after pushing docker image " + imageName +
                         " with tag : " + tag + " to docker registry. " );
            }
        }

        if (!dockerStatusCheck[0]) {
            log.error("Docker image push failed: " + imageName + " tag: " + tag);
            throw new AppCloudException(
                    "Docker image push failed: " + imageName  + " tag: " + tag);
        }
    }

    public void pullDockerImage(String imageRepoUrl, String imageTag) throws AppCloudException {

        if (log.isDebugEnabled()) {
            log.debug("Docker image pull triggered for repo : " + imageRepoUrl + " with tag : " + imageTag);
        }

        final boolean[] dockerStatusCheck = new boolean[1];
        dockerStatusCheck[0] = false;
        try {
            handle = dockerClient.image().withName(imageRepoUrl).pull()
                                 .usingListener(new EventListener() {
                                     @Override
                                     public void onSuccess(String message) {
                                         log.info("Pull Success:" + message);
                                         pullDone.countDown();
                                         dockerStatusCheck[0] = true;

                                     }

                                     @Override
                                     public void onError(String message) {
                                         log.error("Pull Failure:" + message);
                                         pullDone.countDown();
                                     }

                                     @Override
                                     public void onEvent(String event) {
                                         log.info(event);
                                     }
                                 }).withTag(imageTag).fromRegistry();
            pullDone.await();

        } catch (InterruptedException e) {

            String msg = "Error occurred while pulling docker image " + imageRepoUrl + " with tag : " + imageTag;
            throw new AppCloudException(msg, e);
        } finally {
            try {
                handle.close();
            } catch (IOException e) {
                log.warn("Error occurred while closing output handle after pulling docker image " + imageRepoUrl +
                         " with tag : " + imageTag);
            }
        }

        if (!dockerStatusCheck[0]) {
            log.error("Docker image pull failed : " + imageRepoUrl + " with tag : " + imageTag);
            throw new AppCloudException("Docker image pull failed: " + imageRepoUrl + " with tag : " + imageTag);
        }
    }

    public void tagDockerImage(String oldImage, String oldTag, String newImageName, String newTag)
            throws AppCloudException {

        if (log.isDebugEnabled()) {
            log.debug("Docker image tagging triggered for image : " + oldImage + " with old tag : " + oldTag + " to new " +
                      "tag : " + newImageName);
        }

        boolean dockerStatusCheck = dockerClient.image().withName(oldImage + ":" + oldTag).tag()
                                                .inRepository(newImageName).withTagName(newTag);
        if (!dockerStatusCheck) {
            log.error("Docker custom image tag failed: " + oldImage);
            throw new AppCloudException("Docker custom image tag failed: " + oldImage);
        }
    }

    public void clientClose() throws IOException {
        dockerClient.close();
    }
}


text:
from __future__ import unicode_literals

import frappe, json, os
import frappe.permissions
from frappe.utils.csvutils import UnicodeWriter
from frappe.utils import cstr, cint, flt

from frappe.core.page.data_import_tool.data_import_tool import data_keys

@frappe.whitelist()
def get_template(doctype=None, parent_doctype=None, all_doctypes="No", with_data="No"):
	all_doctypes = all_doctypes=="Yes"
	if not parent_doctype:
		parent_doctype = doctype

	column_start_end = {}

	if all_doctypes:
		doctype_parentfield = {}
		child_doctypes = []
		for df in frappe.get_meta(doctype).get_table_fields():
			child_doctypes.append(df.options)
			doctype_parentfield[df.options] = df.fieldname

	def add_main_header():
		w.writerow(['Data Import Template'])
		w.writerow([data_keys.main_table, doctype])

		if parent_doctype != doctype:
			w.writerow([data_keys.parent_table, parent_doctype])
		else:
			w.writerow([''])

		w.writerow([''])
		w.writerow(['Notes:'])
		w.writerow(['Please do not change the template headings.'])
		w.writerow(['First data column must be blank.'])
		w.writerow(['If you are uploading new records, leave the "name" (ID) column blank.'])
		w.writerow(['If you are uploading new records, "Naming Series" becomes mandatory, if present.'])
		w.writerow(['Only mandatory fields are necessary for new records. You can delete non-mandatory columns if you wish.'])
		w.writerow(['For updating, you can update only selective columns.'])
		w.writerow(['You can only upload upto 5000 records in one go. (may be less in some cases)'])
		if key == "parent":
			w.writerow(['"Parent" signifies the parent table in which this row must be added'])
			w.writerow(['If you are updating, please select "Overwrite" else existing rows will not be deleted.'])

	def build_field_columns(dt):
		meta = frappe.get_meta(dt)

		tablecolumns = filter(None,
			[(meta.get_field(f[0]) or None) for f in frappe.db.sql('desc `tab%s`' % dt)])

		tablecolumns.sort(lambda a, b: a.idx - b.idx)

		if dt==doctype:
			column_start_end[dt] = frappe._dict({"start": 0})
		else:
			column_start_end[dt] = frappe._dict({"start": len(columns)})

			append_field_column(frappe._dict({
				"fieldname": "name",
				"label": "ID",
				"fieldtype": "Data",
				"reqd": 1,
				"idx": 0,
				"info": "Leave blank for new records"
			}), True)

		for docfield in tablecolumns:
			append_field_column(docfield, True)

		# all non mandatory fields
		for docfield in tablecolumns:
			append_field_column(docfield, False)

		# append DocType name
		tablerow[column_start_end[dt].start + 1] = dt
		if dt!=doctype:
			tablerow[column_start_end[dt].start + 2] = doctype_parentfield[dt]

		column_start_end[dt].end = len(columns) + 1

	def append_field_column(docfield, mandatory):
		if docfield and ((mandatory and docfield.reqd) or not (mandatory or docfield.reqd)) \
			and (docfield.fieldname not in ('parenttype', 'trash_reason')) and not docfield.hidden:
			tablerow.append("")
			fieldrow.append(docfield.fieldname)
			labelrow.append(docfield.label)
			mandatoryrow.append(docfield.reqd and 'Yes' or 'No')
			typerow.append(docfield.fieldtype)
			inforow.append(getinforow(docfield))
			columns.append(docfield.fieldname)

	def append_empty_field_column():
		tablerow.append("~")
		fieldrow.append("~")
		labelrow.append("")
		mandatoryrow.append("")
		typerow.append("")
		inforow.append("")
		columns.append("")

	def getinforow(docfield):
		"""make info comment for options, links etc."""
		if docfield.fieldtype == 'Select':
			if not docfield.options:
				return ''
			else:
				return 'One of: %s' % ', '.join(filter(None, docfield.options.split('\n')))
		elif docfield.fieldtype == 'Link':
			return 'Valid %s' % docfield.options
		elif docfield.fieldtype == 'Int':
			return 'Integer'
		elif docfield.fieldtype == "Check":
			return "0 or 1"
		elif hasattr(docfield, "info"):
			return docfield.info
		else:
			return ''

	def add_field_headings():
		w.writerow(tablerow)
		w.writerow(labelrow)
		w.writerow(fieldrow)
		w.writerow(mandatoryrow)
		w.writerow(typerow)
		w.writerow(inforow)
		w.writerow([data_keys.data_separator])

	def add_data():
		def add_data_row(row_group, dt, doc, rowidx):
			d = doc.copy()
			if all_doctypes:
				d.name = '"'+ d.name+'"'

			if len(row_group) < rowidx + 1:
				row_group.append([""] * (len(columns) + 1))
			row = row_group[rowidx]
			for i, c in enumerate(columns[column_start_end[dt].start:column_start_end[dt].end]):
				row[column_start_end[dt].start + i + 1] = d.get(c, "")

		if with_data=='Yes':
			frappe.permissions.can_export(parent_doctype, raise_exception=True)

			# get permitted data only
			data = frappe.get_list(doctype, fields=["*"], limit_page_length=None)
			for doc in data:
				# add main table
				row_group = []

				add_data_row(row_group, doctype, doc, 0)

				if all_doctypes:
					# add child tables
					for child_doctype in child_doctypes:
						for ci, child in enumerate(frappe.db.sql("""select * from `tab%s`
							where parent=%s order by idx""" % (child_doctype, "%s"), doc.name, as_dict=1)):
							add_data_row(row_group, child_doctype, child, ci)

				for row in row_group:
					w.writerow(row)

	w = UnicodeWriter()
	key = 'parent' if parent_doctype != doctype else 'name'

	add_main_header()

	w.writerow([''])
	tablerow = [data_keys.doctype, ""]
	labelrow = ["Column Labels:", "ID"]
	fieldrow = [data_keys.columns, key]
	mandatoryrow = ['Mandatory:', 'Yes']
	typerow = ['Type:', 'Data (text)']
	inforow = ['Info:', '']
	columns = [key]

	build_field_columns(doctype)
	if all_doctypes:
		for d in child_doctypes:
			append_empty_field_column()
			build_field_columns(d)

	add_field_headings()
	add_data()

	# write out response as a type csv
	frappe.response['result'] = cstr(w.getvalue())
	frappe.response['type'] = 'csv'
	frappe.response['doctype'] = doctype


text:
/*global $, window */

require(["jquery","sakai/sakai.api.core"], function($, sakai) {
    sakai_global.admin_widgets = function(tuid, showSettings){

        // CSS IDs
        var adminWidgets = "admin_widgets";
        var adminWidgetsID = "#admin_widgets";
        var adminWidgetsClass = ".admin_widgets";

        var adminWidgetsDialog = adminWidgetsClass + "_dialog";
        var adminWidgetsWidget = adminWidgetsClass + "_widget_";
        var adminWidgetsWidgetName = adminWidgetsWidget + "name_";
        var adminWidgetsButton = adminWidgetsClass + "_button";
        var adminWidgetsButtonDisable = adminWidgetsButton + "_disable";
        var adminWidgetsButtonEnable = adminWidgetsButton + "_enable";
        var adminWidgetsButtonDelete = adminWidgetsButton + "_delete";
        var adminWidgetsButtonDisableConfirm = adminWidgetsButtonDisable + "_confirm";
        var adminWidgetsButtonEnableConfirm = adminWidgetsButtonEnable + "_confirm";
        var adminWidgetsButtonDeleteConfirm = adminWidgetsButtonDelete + "_confirm";

        var adminWidgetsDisable = adminWidgetsID + "_disable_";
        var adminWidgetsEnable = adminWidgetsID + "_enable_";
        var adminWidgetsDelete = adminWidgetsID + "_delete_";
        var adminWidgetsNofication = adminWidgetsID + "_notication";
        var adminWidgetsNoficationDisableSuccess = adminWidgetsNofication + "_disable_success";
        var adminWidgetsNoficationDisableError = adminWidgetsNofication + "_disable_error";
        var adminWidgetsNoficationEnableSuccess = adminWidgetsNofication + "_enable_success";
        var adminWidgetsNoficationEnableError = adminWidgetsNofication + "_enable_error";
        var adminWidgetsNoficationDeleteSuccess = adminWidgetsNofication + "_delete_success";
        var adminWidgetsNoficationDeleteError = adminWidgetsNofication + "_delete_error";
        var adminWidgetsNoficationInstallSuccess = adminWidgetsNofication + "_install_success";
        var adminWidgetsNoficationInstallError = adminWidgetsNofication + "_install_error";
        var adminWidgetsDisableDialog = adminWidgetsDisable + "dialog";
        var adminWidgetsEnableDialog = adminWidgetsEnable + "dialog";
        var adminWidgetsDeleteDialog = adminWidgetsDelete + "dialog";
        var adminWidgetsDisableConfirmWidgetTitle = adminWidgetsDisable + "confirm_widget_title";
        var adminWidgetsEnableConfirmWidgetTitle = adminWidgetsEnable + "confirm_widget_title";
        var adminWidgetsDeleteConfirmWidgetTitle = adminWidgetsDelete + "confirm_widget_title";
        var adminWidgetsInstallUrl = adminWidgetsID + "_install_url";
        var adminWidgetsInstallUrlSubmit = adminWidgetsInstallUrl + "_submit";

        // Containers
        var coreWidgetsTemplateContainer = adminWidgetsID + "_core_template_container";
        var sakaiWidgetsTemplateContainer = adminWidgetsID + "_sakai_template_container";
        var contribWidgetsTemplateContainer = adminWidgetsID + "_contrib_template_container";

        // Templates
        var coreWidgetsTemplate = "#admin_widgets_core_template";
        var sakaiWidgetsTemplate = "#admin_widgets_sakai_template";
        var contribWidgetsTemplate = "#admin_widgets_contrib_template";

        /**
         * Callback function to sort widgets
         */
        var sortWidgets = function(a, b){
            if (a.name && b.name) {
                return a.name > b.name ? 1 : -1;
            } else if (a.id && b.name) {
                return a.id > b.name ? 1 : -1;
            } else if (a.name && b.id) {
                return a.name > b.id ? 1 : -1;
            }
            return a.id > b.id ? 1 : -1;
        };

        /**
         * Render the widgets on the page
         */
        var renderCurrentWidgets = function(){
            // Vars for the different widget types
            var coreWidgets = {}; coreWidgets.items = [];
            var sakaiWidgets = {}; sakaiWidgets.items = [];
            var contribWidgets = {}; contribWidgets.items = [];

            // Fill in the widget types
            for (var i in sakai.widgets){
                if (sakai.widgets.hasOwnProperty(i) && i) {
                    var widget = sakai.widgets[i];
                    if (widget.type && widget.type.toLowerCase() === "core") {
                        coreWidgets.items.push(widget);
                    } else if (widget.type && widget.type.toLowerCase() === "sakai") {
                        sakaiWidgets.items.push(widget);
                    } else {
                        contribWidgets.items.push(widget);
                    }
                }
            }

            // Sort widgets alphabetically
            coreWidgets.items.sort(sortWidgets);
            sakaiWidgets.items.sort(sortWidgets);
            contribWidgets.items.sort(sortWidgets);

            $(coreWidgetsTemplateContainer).html(sakai.api.Util.TemplateRenderer(coreWidgetsTemplate, coreWidgets));
            $(sakaiWidgetsTemplateContainer).html(sakai.api.Util.TemplateRenderer(sakaiWidgetsTemplate, sakaiWidgets));
            $(contribWidgetsTemplateContainer).html(sakai.api.Util.TemplateRenderer(contribWidgetsTemplate, contribWidgets));
        };

        /**
         * Disable the specified widget
         * @param {String} widgetId - the widget ID to disable
         */
        var disableWidget = function(widgetId){
            var disableButtonId = adminWidgetsDisable + widgetId;
            var enableButtonId = adminWidgetsEnable + widgetId;

            // ajax call to service

            // on success
            $(disableButtonId).hide();
            $(enableButtonId).show();
            $(adminWidgetsDisableDialog).jqmHide();
                    sakai.api.Util.notification.show($(adminWidgetsNofication).html(),
                                                     """ + widgetId + "" " + $(adminWidgetsNoficationDisableSuccess).html(),
                                                     sakai.api.Util.notification.type.INFORMATION);

            // on error
            /*        $(adminWidgetsDisableDialog).jqmHide();
                        sakai.api.Util.notification.show($(adminWidgetsNofication).html(),
                                                     $(adminWidgetsNoficationDisableError).html() + " - " + widgetId,
                                                     sakai.api.Util.notification.type.ERROR);*/
        };

        /**
         * Enable the specified widget
         * @param {String} widgetId - the widget ID to enable
         */
        var enableWidget = function(widgetId){
            var disableButtonId = adminWidgetsDisable + widgetId;
            var enableButtonId = adminWidgetsEnable + widgetId;

            // ajax call to service

            // on success
            $(enableButtonId).hide();
            $(disableButtonId).show();
            $(adminWidgetsEnableDialog).jqmHide();
                    sakai.api.Util.notification.show($(adminWidgetsNofication).html(),
                                                     """ + widgetId + "" " + $(adminWidgetsNoficationEnableSuccess).html(),
                                                     sakai.api.Util.notification.type.INFORMATION);

            // on error
            /*        $(adminWidgetsEnableDialog).jqmHide();
                        sakai.api.Util.notification.show($(adminWidgetsNofication).html(),
                                                     $(adminWidgetsNoficationEnableError).html() + " - " + widgetId,
                                                     sakai.api.Util.notification.type.ERROR);*/
        };

        /**
         * Delete the specified widget
         * @param {String} widgetId - the widget ID to delete
         */
        var deleteWidget = function(widgetId){
            var widgetSection = adminWidgetsWidget + widgetId;

            // ajax call to service

            // on success
            $(adminWidgetsDeleteDialog).jqmHide();
            $(widgetSection).hide();
            sakai.api.Util.notification.show($(adminWidgetsNofication).html(),
                                                     """ + widgetId + "" " + $(adminWidgetsNoficationDeleteSuccess).html(),
                                                     sakai.api.Util.notification.type.INFORMATION);

            // on error
            /*        $(adminWidgetsDeleteDialog).jqmHide();
                        sakai.api.Util.notification.show($(adminWidgetsNofication).html(),
                                                     $(adminWidgetsNoficationDeleteError).html() + " - " + widgetId,
                                                     sakai.api.Util.notification.type.ERROR);*/
        };

        /**
         * Positions the dialog box at the users scroll position
         */
        var installFromUrl = function(){
            var widgetUrl = $(adminWidgetsInstallUrl).val();
            $(adminWidgetsInstallUrl).attr("disabled", "disabled");
            $(adminWidgetsInstallUrlSubmit).attr("disabled", "disabled");

            // ajax call to service

            // on success
            var widgetId = "widgetId";
            $(adminWidgetsInstallUrl).removeAttr("disabled");
            $(adminWidgetsInstallUrlSubmit).removeAttr("disabled");
            sakai.api.Util.notification.show($(adminWidgetsNofication).html(),
                                                     """ + widgetId + "" " + $(adminWidgetsNoficationInstallSuccess).html(),
                                                     sakai.api.Util.notification.type.INFORMATION);

            // on error
            /*        $(adminWidgetsInstallUrl).removeAttr("disabled");
                    $(adminWidgetsInstallUrlSubmit).removeAttr("disabled");
                    sakai.api.Util.notification.show($(adminWidgetsNofication).html(),
                                                     $(adminWidgetsNoficationInstallError).html(),
                                                     sakai.api.Util.notification.type.ERROR);*/
        };

        /**
         * Positions the dialog box at the users scroll position
         */
        var positionDialog = function(){
            // position dialog box at users scroll position
            var htmlScrollPos = $("html").scrollTop();
            var docScrollPos = $(document).scrollTop();
            if (htmlScrollPos > 0) {
                $(adminWidgetsDialog).css({"top": htmlScrollPos + 130 + "px"});
            } else if (docScrollPos > 0) {
                $(adminWidgetsDialog).css({"top": docScrollPos + 130 + "px"});
            }
        };

        // Init disable dialog
        $(adminWidgetsDisableDialog).jqm({
            modal: true,
            trigger: $('.admin_widgets_disable_dialog'),
            overlay: 20,
            toTop: true
        });

        // Init enable dialog
        $(adminWidgetsEnableDialog).jqm({
            modal: true,
            trigger: $('.admin_widgets_enable_dialog'),
            overlay: 20,
            toTop: true
        });

        // Init delete dialog
        $(adminWidgetsDeleteDialog).jqm({
            modal: true,
            trigger: $('.admin_widgets_delete_dialog'),
            overlay: 20,
            toTop: true
        });

        ///////////////////////
        // BINDING FUNCTIONS //
        ///////////////////////

        /**
         * Add binding to the page elements
         */
        var addBinding = function(){
            // Clicking to upload widget
            $("#admin_widgets_upload_link").click(function(ev) {
                // will need to mod fileupload to take a config object or use something else
                $(window).trigger("init.fileupload.sakai");
            });

            // Listen for complete.fileupload.sakai event (from the fileupload widget)
            // to refresh widget listing
            $(window).bind("complete.fileupload.sakai", function() {
                // re render contrib widgets list
                // notification of success or error
            });

            // Bind the disable buttons
            $(adminWidgetsButtonDisable).live("click", function(){
                var widgetId = this.id.substring(adminWidgetsDisable.length - 1);
                $(adminWidgetsButtonDisableConfirm).attr("id", widgetId);
                $(adminWidgetsDisableConfirmWidgetTitle).html(""" + $(adminWidgetsWidgetName + widgetId).html() + """);
                positionDialog();
                $(adminWidgetsDisableDialog).jqmShow();
            });

            // Bind the confirm disable button
            $(adminWidgetsButtonDisableConfirm).live("click", function(){
                var widgetId = this.id;
                disableWidget(widgetId);
            });

            // Bind the enable buttons
            $(adminWidgetsButtonEnable).live("click", function(){
                var widgetId = this.id.substring(adminWidgetsEnable.length - 1);
                $(adminWidgetsButtonEnableConfirm).attr("id", widgetId);
                $(adminWidgetsEnableConfirmWidgetTitle).html(""" + $(adminWidgetsWidgetName + widgetId).html() + """);
                positionDialog();
                $(adminWidgetsEnableDialog).jqmShow();
            });

            // Bind the confirm enable button
            $(adminWidgetsButtonEnableConfirm).live("click", function(){
                var widgetId = this.id;
                enableWidget(widgetId);
            });

            // Bind the delete buttons
            $(adminWidgetsButtonDelete).live("click", function(){
                var widgetId = this.id.substring(adminWidgetsDelete.length - 1);
                $(adminWidgetsButtonDeleteConfirm).attr("id", widgetId);
                $(adminWidgetsDeleteConfirmWidgetTitle).html(""" + $(adminWidgetsWidgetName + widgetId).html() + """);
                positionDialog();
                $(adminWidgetsDeleteDialog).jqmShow();
            });

            // Bind the confirm delete button
            $(adminWidgetsButtonDeleteConfirm).live("click", function(){
                var widgetId = this.id;
                deleteWidget(widgetId);
            });

            // Bind the install from url button
            $(adminWidgetsInstallUrlSubmit).live("click", function(){
                installFromUrl();
            });
        };

        /**
         * Initialize page functionality
         */
        var doInit = function(){
            // redirect to 500 error page if not admin
            if (sakai.data.me.user.userid !== "admin") {
                document.location = "/500";
            } else {
                renderCurrentWidgets();
                addBinding();
            }
        };

        doInit();
    };

    sakai.api.Widgets.Container.registerForLoad("sakai.admin_widgets");
});


text:
dark_money_predictions
======================

This is predictive modeling using 2014 and 2014 advertising data for Grand Rapids, Michigan to measure influence of Dark Money on political outcomes.

To see the base ipython notebook for my 2012 data on NBViewer, click here: http://nbviewer.ipython.org/github/aglorios/dark_money_predictions/blob/master/Kalamazoo2-Copy0-Copy0-Copy0.ipynb.


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System.ComponentModel;
using System.Numerics.Hashing;

namespace System.Drawing
{
    /**
     * Represents a dimension in 2D coordinate space
     */
    /// <summary>
    ///    <para>
    ///       Represents the size of a rectangular region
    ///       with an ordered pair of width and height.
    ///    </para>
    /// </summary>
    [Serializable]
    [System.Runtime.CompilerServices.TypeForwardedFrom("System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
    public struct SizeF : IEquatable<SizeF>
    {
        /// <summary>
        ///    Initializes a new instance of the <see cref='System.Drawing.SizeF'/> class.
        /// </summary>
        public static readonly SizeF Empty = new SizeF();
        private float width; // Do not rename (binary serialization)
        private float height; // Do not rename (binary serialization)

        /**
         * Create a new SizeF object from another size object
         */
        /// <summary>
        ///    Initializes a new instance of the <see cref='System.Drawing.SizeF'/> class
        ///    from the specified existing <see cref='System.Drawing.SizeF'/>.
        /// </summary>
        public SizeF(SizeF size)
        {
            width = size.width;
            height = size.height;
        }

        /**
         * Create a new SizeF object from a point
         */
        /// <summary>
        ///    <para>
        ///       Initializes a new instance of the <see cref='System.Drawing.SizeF'/> class from
        ///       the specified <see cref='System.Drawing.PointF'/>.
        ///    </para>
        /// </summary>
        public SizeF(PointF pt)
        {
            width = pt.X;
            height = pt.Y;
        }

        /**
         * Create a new SizeF object of the specified dimension
         */
        /// <summary>
        ///    <para>
        ///       Initializes a new instance of the <see cref='System.Drawing.SizeF'/> class from
        ///       the specified dimensions.
        ///    </para>
        /// </summary>
        public SizeF(float width, float height)
        {
            this.width = width;
            this.height = height;
        }

        /// <summary>
        ///    <para>
        ///       Performs vector addition of two <see cref='System.Drawing.SizeF'/> objects.
        ///    </para>
        /// </summary>
        public static SizeF operator +(SizeF sz1, SizeF sz2) => Add(sz1, sz2);

        /// <summary>
        ///    <para>
        ///       Contracts a <see cref='System.Drawing.SizeF'/> by another <see cref='System.Drawing.SizeF'/>
        ///    </para>
        /// </summary>
        public static SizeF operator -(SizeF sz1, SizeF sz2) => Subtract(sz1, sz2);

        /// <summary>
        /// Multiplies <see cref="SizeF"/> by a <see cref="float"/> producing <see cref="SizeF"/>.
        /// </summary>
        /// <param name="left">Multiplier of type <see cref="float"/>.</param>
        /// <param name="right">Multiplicand of type <see cref="SizeF"/>.</param>
        /// <returns>Product of type <see cref="SizeF"/>.</returns>
        public static SizeF operator *(float left, SizeF right) => Multiply(right, left);

        /// <summary>
        /// Multiplies <see cref="SizeF"/> by a <see cref="float"/> producing <see cref="SizeF"/>.
        /// </summary>
        /// <param name="left">Multiplicand of type <see cref="SizeF"/>.</param>
        /// <param name="right">Multiplier of type <see cref="float"/>.</param>
        /// <returns>Product of type <see cref="SizeF"/>.</returns>
        public static SizeF operator *(SizeF left, float right) => Multiply(left, right);

        /// <summary>
        /// Divides <see cref="SizeF"/> by a <see cref="float"/> producing <see cref="SizeF"/>.
        /// </summary>
        /// <param name="left">Dividend of type <see cref="SizeF"/>.</param>
        /// <param name="right">Divisor of type <see cref="int"/>.</param>
        /// <returns>Result of type <see cref="SizeF"/>.</returns>
        public static SizeF operator /(SizeF left, float right)
            => new SizeF(left.width / right, left.height / right);

        /// <summary>
        ///    Tests whether two <see cref='System.Drawing.SizeF'/> objects
        ///    are identical.
        /// </summary>
        public static bool operator ==(SizeF sz1, SizeF sz2) => sz1.Width == sz2.Width && sz1.Height == sz2.Height;

        /// <summary>
        ///    <para>
        ///       Tests whether two <see cref='System.Drawing.SizeF'/> objects are different.
        ///    </para>
        /// </summary>
        public static bool operator !=(SizeF sz1, SizeF sz2) => !(sz1 == sz2);

        /// <summary>
        ///    <para>
        ///       Converts the specified <see cref='System.Drawing.SizeF'/> to a
        ///    <see cref='System.Drawing.PointF'/>.
        ///    </para>
        /// </summary>
        public static explicit operator PointF(SizeF size) => new PointF(size.Width, size.Height);

        /// <summary>
        ///    <para>
        ///       Tests whether this <see cref='System.Drawing.SizeF'/> has zero
        ///       width and height.
        ///    </para>
        /// </summary>
        [Browsable(false)]
        public bool IsEmpty => width == 0 && height == 0;

        /**
         * Horizontal dimension
         */

        /// <summary>
        ///    <para>
        ///       Represents the horizontal component of this
        ///    <see cref='System.Drawing.SizeF'/>.
        ///    </para>
        /// </summary>
        public float Width
        {
            get { return width; }
            set { width = value; }
        }

        /**
         * Vertical dimension
         */

        /// <summary>
        ///    <para>
        ///       Represents the vertical component of this
        ///    <see cref='System.Drawing.SizeF'/>.
        ///    </para>
        /// </summary>
        public float Height
        {
            get { return height; }
            set { height = value; }
        }

        /// <summary>
        ///    <para>
        ///       Performs vector addition of two <see cref='System.Drawing.SizeF'/> objects.
        ///    </para>
        /// </summary>
        public static SizeF Add(SizeF sz1, SizeF sz2) => new SizeF(sz1.Width + sz2.Width, sz1.Height + sz2.Height);

        /// <summary>
        ///    <para>
        ///       Contracts a <see cref='System.Drawing.SizeF'/> by another <see cref='System.Drawing.SizeF'/>
        ///       .
        ///    </para>
        /// </summary>
        public static SizeF Subtract(SizeF sz1, SizeF sz2) => new SizeF(sz1.Width - sz2.Width, sz1.Height - sz2.Height);

        /// <summary>
        ///    <para>
        ///       Tests to see whether the specified object is a
        ///    <see cref='System.Drawing.SizeF'/>
        ///    with the same dimensions as this <see cref='System.Drawing.SizeF'/>.
        /// </para>
        /// </summary>
        public override bool Equals(object obj) => obj is SizeF && Equals((SizeF)obj);

        public bool Equals(SizeF other) => this == other;

        public override int GetHashCode() => HashHelpers.Combine(Width.GetHashCode(), Height.GetHashCode());

        public PointF ToPointF() => (PointF)this;

        public Size ToSize() => Size.Truncate(this);

        /// <summary>
        ///    <para>
        ///       Creates a human-readable string that represents this
        ///    <see cref='System.Drawing.SizeF'/>.
        ///    </para>
        /// </summary>
        public override string ToString() => "{Width=" + width.ToString() + ", Height=" + height.ToString() + "}";

        /// <summary>
        /// Multiplies <see cref="SizeF"/> by a <see cref="float"/> producing <see cref="SizeF"/>.
        /// </summary>
        /// <param name="size">Multiplicand of type <see cref="SizeF"/>.</param>
        /// <param name="multiplier">Multiplier of type <see cref="float"/>.</param>
        /// <returns>Product of type SizeF.</returns>
        private static SizeF Multiply(SizeF size, float multiplier) =>
            new SizeF(size.width * multiplier, size.height * multiplier);
    }
}


text:
#ifndef _INCREMENTAL_QUICK_SELECT_H_
#define _INCREMENTAL_QUICK_SELECT_H_

#include <vector>
#include <stack>
#include "global.h"

namespace similarity {

template <typename T>
class IncrementalQuickSelect {
 public:
  explicit IncrementalQuickSelect(std::vector<T>& x)
      : x_(x), n_(static_cast<int>(x.size())), idx_(0) {
    stk_.push(n_);
  }

  ~IncrementalQuickSelect() {}

  T GetNext() {
    CHECK(idx_ <= stk_.top());
    if (stk_.top() == idx_) {
      stk_.pop();
      return x_[idx_];
    } else {
      int pivot_idx = idx_;     // OR random[idx, stk.top() - 1]
      int pivot_idx_final = Partition(pivot_idx, idx_, stk_.top() - 1);
      stk_.push(pivot_idx_final);
      return GetNext();
    }
  }

  inline bool Next() {
    ++idx_;
    return idx_ < n_;
  }

 private:

  int Partition(int pivot_idx, int left, int right) {
    T pivot = x_[pivot_idx];
    for (;;) {
      while (x_[left] < pivot) ++left;
      while (x_[right] > pivot) --right;

      if (left >= right) {
        break;
      } else if (x_[left] == x_[right]) {
        ++left;
      } else if (left < right) {
        std::swap(x_[left], x_[right]);
      }
    }
    return right;
  }

  std::vector<T>& x_;
  const int n_;
  int idx_;
  std::stack<int> stk_;

  // disable copy and assign
  DISABLE_COPY_AND_ASSIGN(IncrementalQuickSelect);
};

}  // namespace similarity

#endif     //  _INCREMENTAL_QUICK_SELECT_H_


text:
package com.asksunny.agent;

import org.hyperic.sigar.ProcCpu;
import org.hyperic.sigar.Sigar;

public class HardwareProfiler {

	private final Sigar sigar;
    private final int cpuCount = 1;
    private ProcCpu prevPc = null;
    private double load = 0.0;

	public HardwareProfiler() {
		this.sigar = new Sigar();
	}

	protected void gatherSystemInfo() throws Exception
	{

		System.out.println(sigar.getCpuPerc().getSys());
		System.out.println(sigar.getCpuPerc().getUser());
		System.out.println(sigar.getCpuPerc().getIdle());

	}

	public static void main(String[] args) throws Exception
	{
		HardwareProfiler profiler = new HardwareProfiler();
		profiler.gatherSystemInfo();

	}

}


text:
<!DOCTYPE html>

	<meta charset="UTF-8">
	<title>Cloud Services · Nice To Know IT</title>
    <link rel="stylesheet" href="https://nicetoknow.github.io/IT/css.css" type="text/css" >

    Nice To KnowIT WebCloud Services

    	Infrastructure aaS

    	Amazon Web Services

    	EC2

    	Elastic Beanstalk

    	Lamda

    	Google Cloud Engine

    	IBM Cloud

    	Microsoft Azure

    	OpenStack

    	Platform aaS

    	DEIS

    	OpenShift

    	Software aaS

(http://reinvent-hripps.rhcloud.com/#/6)


text:
using UnityEngine;
using System.Collections;
public class Portal : PT_MonoBehaviour
{
    public string toRoom;
    public bool justArrived = false;
    // ^ true if _Mage has just teleported here
    void OnTriggerEnter(Collider other)
    {
        if (justArrived) return;
        // ^ Since the Mage has just arrived, don't teleport her back
        // Get the GameObject of the collider
        GameObject go = other.gameObject;
        // Search up for a tagged parent
        GameObject goP = Utils.FindTaggedParent(go);
        if (goP != null) go = goP;
        // If this isn't the _Mage, return
        if (go.tag != "Mage") return;
        // Go ahead and build the next room
        LayoutTiles.S.BuildRoom(toRoom);
    }
    void OnTriggerExit(Collider other)
    {
        // Once the Mage leaves this Portal, set justArrived to false
        if (other.gameObject.tag == "Mage")
        {
            justArrived = false;
        }
    }
}


text:
var common     = require('../../common');
var connection = common.createConnection();
var assert     = require('assert');

var rows = undefined;
var rows1 = undefined;
var fields = undefined;
var fields1 = undefined;

var buf = Buffer([0x80, 0x90, 1, 2, 3, 4, 5, 6, 7, 8, 9, 100, 100, 255, 255]);
connection.execute('SELECT HEX(?) as buf', [buf], function(err, _rows, _fields) {
  if (err) throw err;
  rows = _rows;
  fields = _fields;
});

connection.query('SELECT HEX(?) as buf', [buf], function(err, _rows, _fields) {
  if (err) throw err;
  rows1 = _rows;
  fields1 = _fields;
});

connection.end();

process.on('exit', function() {
  assert.deepEqual(rows, [{buf: buf.toString('hex').toUpperCase()}]);
  assert.deepEqual(rows1, [{buf: buf.toString('hex').toUpperCase()}]);
});