text:
namespace Microsoft.Azure.Management.Logic.Models
{

    /// <summary>
    /// Defines values for SkuName.
    /// </summary>
    public static class SkuName
    {
        public const string NotSpecified = "NotSpecified";
        public const string Free = "Free";
        public const string Shared = "Shared";
        public const string Basic = "Basic";
        public const string Standard = "Standard";
        public const string Premium = "Premium";
    }
}


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.facebook.presto.atop;

import com.facebook.presto.spi.PrestoException;
import com.facebook.presto.testing.QueryRunner;
import com.google.common.collect.ImmutableMap;
import com.google.common.io.Resources;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

import static com.facebook.presto.atop.AtopErrorCode.ATOP_READ_TIMEOUT;
import static com.facebook.presto.atop.LocalAtopQueryRunner.createQueryRunner;
import static com.google.common.io.Files.createTempDir;
import static com.google.common.io.Resources.toByteArray;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.fail;

public class TestAtopHang
{
    private QueryRunner queryRunner;

    @BeforeClass
    public void setUp()
            throws Exception
    {
        File tempPath = createTempDir();
        copyExecutable("hanging_atop.sh", tempPath);
        queryRunner = createQueryRunner(ImmutableMap.of("atop.executable-path", tempPath + "/hanging_atop.sh", "atop.executable-read-timeout", "1s"), AtopProcessFactory.class);
    }

    @AfterClass(alwaysRun = true)
    public void tearDown()
    {
        queryRunner.close();
        queryRunner = null;
    }

    @Test(timeOut = 60_000)
    public void testTimeout()
    {
        try {
            queryRunner.execute("SELECT * FROM disks");
            fail();
        }
        catch (PrestoException e) {
            assertEquals(e.getErrorCode(), ATOP_READ_TIMEOUT.toErrorCode(), e.getMessage());
        }
    }

    private void copyExecutable(String name, File target)
            throws IOException
    {
        byte[] bytes = toByteArray(Resources.getResource(getClass(), name));
        Path path = target.toPath().resolve(new File(name).getName());
        Files.write(path, bytes);
        if (!path.toFile().setExecutable(true)) {
            throw new IOException("failed to make executable: " + path);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
layout: pattern
title: Adapter
categories: Structural

---

**Also known as:** Wrapper

**Intent:** Convert the interface of a class into another interface the clients
expect. Adapter lets classes work together that couldn't otherwise because of
incompatible interfaces.

![alt text](./etc/adapter.png "Adapter")

**Applicability:** Use the Adapter pattern when

* you want to use an existing class, and its interface does not match the one you need
* you want to create a reusable class that cooperates with unrelated or unforeseen classes, that is, classes that don't necessarily have compatible interfaces
* you need to use several existing subclasses, but it's impractical to adapt their interface by subclassing every one. An object adapter can adapt the interface of its parent class.

**Real world examples:**

* [java.util.Arrays#asList()](http://docs.oracle.com/javase/8/docs/api/java/util/Arrays.html#asList%28T...%29)

**Credits**
* [oodesign](http://www.oodesign.com/adapter-pattern.html)
* [iluwatar](https://github.com/iluwatar/java-design-patterns/tree/master/adapter)


text:
#include <SCTProvider.h>
#include <secconv_security_context_token.h>
#include <map>

using namespace std;
using namespace wso2wsf;

typedef map<string, void*> MapSCT_t;

class TokenProvider: public SCTProvider
{
public:
    WSF_CALL TokenProvider();
    WSF_CALL ~TokenProvider();

    virtual void* WSF_CALL getToken(string& sct_id, MessageContext* msgctx);
    virtual bool WSF_CALL storeToken(string& sct_id, MessageContext* msgctx, void* sct);
    virtual bool WSF_CALL removeToken(string& sct_id, MessageContext* msgctx);
    virtual bool WSF_CALL validateToken(OMNode* sct_node, MessageContext* msgctx);

private:
    MapSCT_t* getSCTMap(MessageContext* msgctx);
};

WSF_SCT_PROVIDER_INIT(TokenProvider);

TokenProvider::TokenProvider()
{
    //you can write any construction logic
}

TokenProvider::~TokenProvider()
{
    //you can write any destruction logic
}

void* TokenProvider::getToken(string& sct_id, MessageContext* msgctx)
{
    MapSCT_t* pmapSCT = getSCTMap(msgctx);
    MapSCT_t::iterator ite = pmapSCT->find(sct_id);
    if(ite != pmapSCT->end())
    {
        return ite->second;
    }
	else
	{
		const axutil_env_t* env = Environment::getEnv();
		Environment::switchToGlobalPool();
		security_context_token_t *sct = security_context_token_create(env);
        if(sct)
        {
            oxs_buffer_t* key_buffer = oxs_buffer_create(env);
            oxs_buffer_populate(
                key_buffer, env, (unsigned char*)"01234567012345670123456701234567", 32);
            security_context_token_set_secret(sct, env, key_buffer);
            if(sct_id == "")
            {
				axis2_char_t* sctid = oxs_util_generate_id(env,"urn:uuid:");
                sct_id = (const char*)sctid;
                AXIS2_FREE(env->allocator, sctid);

            }
            security_context_token_set_global_identifier(sct, env, (axis2_char_t*)axutil_strdup(env, sct_id.c_str()));
            security_context_token_set_local_identifier(
                sct, env, (axis2_char_t*)axutil_strdup(env, "#sctId-29530019"));
            security_context_token_set_is_sc10(sct, env, AXIS2_TRUE);

		}
		Environment::switchToLocalPool();
		return sct;
	}
}

bool TokenProvider::storeToken(string& sct_id, MessageContext* msgctx, void* sct)
{
    MapSCT_t* pmapSCT = getSCTMap(msgctx);
    pmapSCT->insert(std::make_pair(sct_id, sct));
    return true;
}

bool TokenProvider::removeToken(string& sct_id, MessageContext* msgctx)
{
    MapSCT_t* pmapSCT = getSCTMap(msgctx);
    pmapSCT->erase(sct_id);
    return true;
}

bool TokenProvider::validateToken(OMNode* sct_node, MessageContext* msgctx)
{
    return true;
}

MapSCT_t* TokenProvider::getSCTMap(MessageContext* msgctx)
{
    string propertyName = "SCTContainerMap";
    MapSCT_t* pmapSCT = (MapSCT_t*)msgctx->getPropertyValue(propertyName);
    if(!pmapSCT)
    {
       //The property is not created yet. So we have to create it and store it in conf context
        pmapSCT = new MapSCT_t;
        const axutil_env_t* env = Environment::getEnv();
        axis2_conf_ctx_t *conf_ctx = axis2_msg_ctx_get_conf_ctx(
            msgctx->getAxis2MessageContext(), env);
        axutil_property_t* sct_map_prop = axutil_property_create_with_args(
            env, AXIS2_SCOPE_APPLICATION, AXIS2_TRUE, NULL, pmapSCT);
        axis2_conf_ctx_set_property(conf_ctx, env, propertyName.c_str(), sct_map_prop);
    }

    return pmapSCT;
}


text:
var Nasty = require('./nasty');

class NastySpawner {

  constructor(game, player, roomManager, navMesh, zDepth, x, y) {
    this.game = game;
    this.player = player;
    this.roomManager = roomManager;
    this.navMesh = navMesh;
    this.zDepth = zDepth;
    this.x = x;
    this.y = y;

    this.hasTriggered = false;
  }

  trigger() {
    if (this.hasTriggered) {
      return;
    }
    this.hasTriggered = true;

    this.zDepth.sprite.add(
      new Nasty(this.game, this.player, this.roomManager, this.navMesh, this.x, this.y));
  }
}

module.exports = NastySpawner;


text:
package fixture

import (
	"time"

	"$GITHUB_URI/probe/docker"
	"$GITHUB_URI/probe/endpoint"
	"$GITHUB_URI/probe/host"
	"$GITHUB_URI/probe/kubernetes"
	"$GITHUB_URI/probe/process"
	"$GITHUB_URI/render/detailed"
	"$GITHUB_URI/report"
)

// This is an example Report:
//   2 hosts with probes installed - client & server.
var (
	Now = time.Now()

	ClientHostID  = "client.hostname.com"
	ServerHostID  = "server.hostname.com"
	UnknownHostID = ""

	ClientIP         = "10.10.10.20"
	ServerIP         = "192.168.1.1"
	UnknownClient1IP = "10.10.10.10"
	UnknownClient2IP = "10.10.10.10"
	UnknownClient3IP = "10.10.10.11"
	RandomClientIP   = "51.52.53.54"
	GoogleIP         = "8.8.8.8"

	ClientPort54001        = "54001"
	ClientPort54002        = "54002"
	ServerPort             = "80"
	UnknownClient1Port     = "54010"
	UnknownClient2Port     = "54020"
	UnknownClient3Port     = "54020"
	RandomClientPort       = "12345"
	GooglePort             = "80"
	NonContainerClientPort = "46789"

	ClientHostName = ClientHostID
	ServerHostName = ServerHostID

	Client1PID      = "10001"
	Client2PID      = "30020"
	ServerPID       = "215"
	NonContainerPID = "1234"

	Client1Name      = "/usr/bin/curl"
	Client2Name      = "/usr/bin/curl"
	ServerName       = "apache"
	NonContainerName = "bash"

	True = "true"

	ClientHostNodeID = report.MakeHostNodeID(ClientHostID)
	ServerHostNodeID = report.MakeHostNodeID(ServerHostID)

	Client54001NodeID    = report.MakeEndpointNodeID(ClientHostID, ClientIP, ClientPort54001)            // curl (1)
	Client54002NodeID    = report.MakeEndpointNodeID(ClientHostID, ClientIP, ClientPort54002)            // curl (2)
	Server80NodeID       = report.MakeEndpointNodeID(ServerHostID, ServerIP, ServerPort)                 // apache
	UnknownClient1NodeID = report.MakeEndpointNodeID(ServerHostID, UnknownClient1IP, UnknownClient1Port) // we want to ensure two unknown clients, connnected
	UnknownClient2NodeID = report.MakeEndpointNodeID(ServerHostID, UnknownClient2IP, UnknownClient2Port) // to the same server, are deduped.
	UnknownClient3NodeID = report.MakeEndpointNodeID(ServerHostID, UnknownClient3IP, UnknownClient3Port) // Check this one isn't deduped
	RandomClientNodeID   = report.MakeEndpointNodeID(ServerHostID, RandomClientIP, RandomClientPort)     // this should become an internet node
	NonContainerNodeID   = report.MakeEndpointNodeID(ServerHostID, ServerIP, NonContainerClientPort)
	GoogleEndpointNodeID = report.MakeEndpointNodeID(ServerHostID, GoogleIP, GooglePort)

	ClientProcess1NodeID      = report.MakeProcessNodeID(ClientHostID, Client1PID)
	ClientProcess2NodeID      = report.MakeProcessNodeID(ClientHostID, Client2PID)
	ServerProcessNodeID       = report.MakeProcessNodeID(ServerHostID, ServerPID)
	NonContainerProcessNodeID = report.MakeProcessNodeID(ServerHostID, NonContainerPID)

	ClientContainerID     = "a1b2c3d4e5"
	ClientContainerName   = "client"
	ServerContainerID     = "5e4d3c2b1a"
	ServerContainerName   = "task-name-5-server-aceb93e2f2b797caba01"
	ClientContainerNodeID = report.MakeContainerNodeID(ClientContainerID)
	ServerContainerNodeID = report.MakeContainerNodeID(ServerContainerID)

	ClientContainerHostname = ClientContainerName + ".hostname.com"
	ServerContainerHostname = ServerContainerName + ".hostname.com"

	ClientContainerImageID     = "imageid123"
	ServerContainerImageID     = "imageid456"
	ClientContainerImageNodeID = report.MakeContainerImageNodeID(ClientContainerImageID)
	ServerContainerImageNodeID = report.MakeContainerImageNodeID(ServerContainerImageID)
	ClientContainerImageName   = "image/client"
	ServerContainerImageName   = "image/server"

	KubernetesNamespace = "ping"
	ClientPodID         = "ping/pong-a"
	ServerPodID         = "ping/pong-b"
	ClientPodUID        = "5d4c3b2a1"
	ServerPodUID        = "i9h8g7f6e"
	ClientPodNodeID     = report.MakePodNodeID(ClientPodUID)
	ServerPodNodeID     = report.MakePodNodeID(ServerPodUID)
	ServiceName         = "pongservice"
	ServiceID           = "ping/pongservice"
	ServiceUID          = "service1234"
	ServiceNodeID       = report.MakeServiceNodeID(ServiceUID)

	ClientProcess1CPUMetric    = report.MakeMetric().Add(Now, 0.01).WithFirst(Now.Add(-1 * time.Second))
	ClientProcess1MemoryMetric = report.MakeMetric().Add(Now, 0.02).WithFirst(Now.Add(-2 * time.Second))

	ClientContainerCPUMetric    = report.MakeMetric().Add(Now, 0.03).WithFirst(Now.Add(-3 * time.Second))
	ClientContainerMemoryMetric = report.MakeMetric().Add(Now, 0.04).WithFirst(Now.Add(-4 * time.Second))

	ServerContainerCPUMetric    = report.MakeMetric().Add(Now, 0.05).WithFirst(Now.Add(-5 * time.Second))
	ServerContainerMemoryMetric = report.MakeMetric().Add(Now, 0.06).WithFirst(Now.Add(-6 * time.Second))

	ClientHostCPUMetric    = report.MakeMetric().Add(Now, 0.07).WithFirst(Now.Add(-7 * time.Second))
	ClientHostMemoryMetric = report.MakeMetric().Add(Now, 0.08).WithFirst(Now.Add(-8 * time.Second))
	ClientHostLoad1Metric  = report.MakeMetric().Add(Now, 0.09).WithFirst(Now.Add(-9 * time.Second))

	ServerHostCPUMetric    = report.MakeMetric().Add(Now, 0.12).WithFirst(Now.Add(-12 * time.Second))
	ServerHostMemoryMetric = report.MakeMetric().Add(Now, 0.13).WithFirst(Now.Add(-13 * time.Second))
	ServerHostLoad1Metric  = report.MakeMetric().Add(Now, 0.14).WithFirst(Now.Add(-14 * time.Second))

	Report = report.Report{
		ID: "test-report",
		Endpoint: report.Topology{
			Nodes: report.Nodes{
				// Node is arbitrary. We're free to put only precisely what we
				// care to test into the fixture. Just be sure to include the bits
				// that the mapping funcs extract :)
				Client54001NodeID: report.MakeNode(Client54001NodeID).WithTopology(report.Endpoint).WithLatests(map[string]string{
					endpoint.Addr:      ClientIP,
					endpoint.Port:      ClientPort54001,
					process.PID:        Client1PID,
					report.HostNodeID:  ClientHostNodeID,
					endpoint.Procspied: True,
				}).WithEdge(Server80NodeID, report.EdgeMetadata{
					EgressPacketCount: newu64(10),
					EgressByteCount:   newu64(100),
				}),

				Client54002NodeID: report.MakeNode(Client54002NodeID).WithTopology(report.Endpoint).WithLatests(map[string]string{
					endpoint.Addr:      ClientIP,
					endpoint.Port:      ClientPort54002,
					process.PID:        Client2PID,
					report.HostNodeID:  ClientHostNodeID,
					endpoint.Procspied: True,
				}).WithEdge(Server80NodeID, report.EdgeMetadata{
					EgressPacketCount: newu64(20),
					EgressByteCount:   newu64(200),
				}),

				Server80NodeID: report.MakeNode(Server80NodeID).WithTopology(report.Endpoint).WithLatests(map[string]string{
					endpoint.Addr:      ServerIP,
					endpoint.Port:      ServerPort,
					process.PID:        ServerPID,
					report.HostNodeID:  ServerHostNodeID,
					endpoint.Procspied: True,
				}),

				NonContainerNodeID: report.MakeNode(NonContainerNodeID).WithTopology(report.Endpoint).WithLatests(map[string]string{
					endpoint.Addr:      ServerIP,
					endpoint.Port:      NonContainerClientPort,
					process.PID:        NonContainerPID,
					report.HostNodeID:  ServerHostNodeID,
					endpoint.Procspied: True,
				}).WithAdjacent(GoogleEndpointNodeID),

				// Probe pseudo nodes
				UnknownClient1NodeID: report.MakeNode(UnknownClient1NodeID).WithTopology(report.Endpoint).WithLatests(map[string]string{
					endpoint.Addr:      UnknownClient1IP,
					endpoint.Port:      UnknownClient1Port,
					endpoint.Procspied: True,
				}).WithEdge(Server80NodeID, report.EdgeMetadata{
					EgressPacketCount: newu64(30),
					EgressByteCount:   newu64(300),
				}),

				UnknownClient2NodeID: report.MakeNode(UnknownClient2NodeID).WithTopology(report.Endpoint).WithLatests(map[string]string{
					endpoint.Addr:      UnknownClient2IP,
					endpoint.Port:      UnknownClient2Port,
					endpoint.Procspied: True,
				}).WithEdge(Server80NodeID, report.EdgeMetadata{
					EgressPacketCount: newu64(40),
					EgressByteCount:   newu64(400),
				}),

				UnknownClient3NodeID: report.MakeNode(UnknownClient3NodeID).WithTopology(report.Endpoint).WithLatests(map[string]string{
					endpoint.Addr:      UnknownClient3IP,
					endpoint.Port:      UnknownClient3Port,
					endpoint.Procspied: True,
				}).WithEdge(Server80NodeID, report.EdgeMetadata{
					EgressPacketCount: newu64(50),
					EgressByteCount:   newu64(500),
				}),

				RandomClientNodeID: report.MakeNode(RandomClientNodeID).WithTopology(report.Endpoint).WithLatests(map[string]string{
					endpoint.Addr:      RandomClientIP,
					endpoint.Port:      RandomClientPort,
					endpoint.Procspied: True,
				}).WithEdge(Server80NodeID, report.EdgeMetadata{
					EgressPacketCount: newu64(60),
					EgressByteCount:   newu64(600),
				}),

				GoogleEndpointNodeID: report.MakeNode(GoogleEndpointNodeID).WithTopology(report.Endpoint).WithLatests(map[string]string{
					endpoint.Addr:      GoogleIP,
					endpoint.Port:      GooglePort,
					endpoint.Procspied: True,
				}),
			},
		},
		Process: report.Topology{
			Nodes: report.Nodes{
				ClientProcess1NodeID: report.MakeNodeWith(ClientProcess1NodeID, map[string]string{
					process.PID:        Client1PID,
					process.Name:       Client1Name,
					docker.ContainerID: ClientContainerID,
					report.HostNodeID:  ClientHostNodeID,
				}).
					WithTopology(report.Process).WithParents(report.EmptySets.
					Add("host", report.MakeStringSet(ClientHostNodeID)).
					Add("container", report.MakeStringSet(ClientContainerNodeID)).
					Add("container_image", report.MakeStringSet(ClientContainerImageNodeID)),
				).WithMetrics(report.Metrics{
					process.CPUUsage:    ClientProcess1CPUMetric,
					process.MemoryUsage: ClientProcess1MemoryMetric,
				}),
				ClientProcess2NodeID: report.MakeNodeWith(ClientProcess2NodeID, map[string]string{
					process.PID:        Client2PID,
					process.Name:       Client2Name,
					docker.ContainerID: ClientContainerID,
					report.HostNodeID:  ClientHostNodeID,
				}).
					WithTopology(report.Process).WithParents(report.EmptySets.
					Add("host", report.MakeStringSet(ClientHostNodeID)).
					Add("container", report.MakeStringSet(ClientContainerNodeID)).
					Add("container_image", report.MakeStringSet(ClientContainerImageNodeID)),
				),
				ServerProcessNodeID: report.MakeNodeWith(ServerProcessNodeID, map[string]string{
					process.PID:        ServerPID,
					process.Name:       ServerName,
					docker.ContainerID: ServerContainerID,
					report.HostNodeID:  ServerHostNodeID,
				}).
					WithTopology(report.Process).WithParents(report.EmptySets.
					Add("host", report.MakeStringSet(ServerHostNodeID)).
					Add("container", report.MakeStringSet(ServerContainerNodeID)).
					Add("container_image", report.MakeStringSet(ServerContainerImageNodeID)),
				),
				NonContainerProcessNodeID: report.MakeNodeWith(NonContainerProcessNodeID, map[string]string{
					process.PID:       NonContainerPID,
					process.Name:      NonContainerName,
					report.HostNodeID: ServerHostNodeID,
				}).
					WithTopology(report.Process).WithParents(report.EmptySets.
					Add("host", report.MakeStringSet(ServerHostNodeID)),
				),
			},
			MetadataTemplates: process.MetadataTemplates,
			MetricTemplates:   process.MetricTemplates,
		}.WithShape(report.Square).WithLabel("process", "processes"),
		Container: report.Topology{
			Nodes: report.Nodes{
				ClientContainerNodeID: report.MakeNodeWith(

					ClientContainerNodeID, map[string]string{
						docker.ContainerID:                           ClientContainerID,
						docker.ContainerName:                         ClientContainerName,
						docker.ContainerHostname:                     ClientContainerHostname,
						docker.ImageID:                               ClientContainerImageID,
						report.HostNodeID:                            ClientHostNodeID,
						docker.LabelPrefix + "io.kubernetes.pod.uid": ClientPodUID,
						kubernetes.Namespace:                         KubernetesNamespace,
						docker.ContainerState:                        docker.StateRunning,
						docker.ContainerStateHuman:                   docker.StateRunning,
					}).
					WithTopology(report.Container).WithParents(report.EmptySets.
					Add("host", report.MakeStringSet(ClientHostNodeID)).
					Add("container_image", report.MakeStringSet(ClientContainerImageNodeID)).
					Add("pod", report.MakeStringSet(ClientPodNodeID)),
				).WithMetrics(report.Metrics{
					docker.CPUTotalUsage: ClientContainerCPUMetric,
					docker.MemoryUsage:   ClientContainerMemoryMetric,
				}),
				ServerContainerNodeID: report.MakeNodeWith(

					ServerContainerNodeID, map[string]string{
						docker.ContainerID:                                        ServerContainerID,
						docker.ContainerName:                                      ServerContainerName,
						docker.ContainerHostname:                                  ServerContainerHostname,
						docker.ContainerState:                                     docker.StateRunning,
						docker.ContainerStateHuman:                                docker.StateRunning,
						docker.ImageID:                                            ServerContainerImageID,
						report.HostNodeID:                                         ServerHostNodeID,
						docker.LabelPrefix + detailed.AmazonECSContainerNameLabel: "server",
						docker.LabelPrefix + "foo1":                               "bar1",
						docker.LabelPrefix + "foo2":                               "bar2",
						docker.LabelPrefix + "io.kubernetes.pod.uid":              ServerPodUID,
						kubernetes.Namespace:                                      KubernetesNamespace,
					}).
					WithTopology(report.Container).WithParents(report.EmptySets.
					Add("host", report.MakeStringSet(ServerHostNodeID)).
					Add("container_image", report.MakeStringSet(ServerContainerImageNodeID)).
					Add("pod", report.MakeStringSet(ServerPodNodeID)),
				).WithMetrics(report.Metrics{
					docker.CPUTotalUsage: ServerContainerCPUMetric,
					docker.MemoryUsage:   ServerContainerMemoryMetric,
				}),
			},
			MetadataTemplates: docker.ContainerMetadataTemplates,
			MetricTemplates:   docker.ContainerMetricTemplates,
		}.WithShape(report.Hexagon).WithLabel("container", "containers"),
		ContainerImage: report.Topology{
			Nodes: report.Nodes{
				ClientContainerImageNodeID: report.MakeNodeWith(ClientContainerImageNodeID, map[string]string{
					docker.ImageID:    ClientContainerImageID,
					docker.ImageName:  ClientContainerImageName,
					report.HostNodeID: ClientHostNodeID,
				}).
					WithParents(report.EmptySets.
						Add("host", report.MakeStringSet(ClientHostNodeID)),
					).WithTopology(report.ContainerImage),
				ServerContainerImageNodeID: report.MakeNodeWith(ServerContainerImageNodeID, map[string]string{
					docker.ImageID:              ServerContainerImageID,
					docker.ImageName:            ServerContainerImageName,
					report.HostNodeID:           ServerHostNodeID,
					docker.LabelPrefix + "foo1": "bar1",
					docker.LabelPrefix + "foo2": "bar2",
				}).
					WithParents(report.EmptySets.
						Add("host", report.MakeStringSet(ServerHostNodeID)),
					).WithTopology(report.ContainerImage),
			},
			MetadataTemplates: docker.ContainerImageMetadataTemplates,
		}.WithShape(report.Hexagon).WithLabel("image", "images"),
		Host: report.Topology{
			Nodes: report.Nodes{
				ClientHostNodeID: report.MakeNodeWith(

					ClientHostNodeID, map[string]string{
						"host_name":       ClientHostName,
						"os":              "Linux",
						report.HostNodeID: ClientHostNodeID,
					}).
					WithTopology(report.Host).WithSets(report.EmptySets.
					Add(host.LocalNetworks, report.MakeStringSet("10.10.10.0/24")),
				).WithMetrics(report.Metrics{
					host.CPUUsage:    ClientHostCPUMetric,
					host.MemoryUsage: ClientHostMemoryMetric,
					host.Load1:       ClientHostLoad1Metric,
				}),
				ServerHostNodeID: report.MakeNodeWith(

					ServerHostNodeID, map[string]string{
						"host_name":       ServerHostName,
						"os":              "Linux",
						report.HostNodeID: ServerHostNodeID,
					}).
					WithTopology(report.Host).WithSets(report.EmptySets.
					Add(host.LocalNetworks, report.MakeStringSet("10.10.10.0/24")),
				).WithMetrics(report.Metrics{
					host.CPUUsage:    ServerHostCPUMetric,
					host.MemoryUsage: ServerHostMemoryMetric,
					host.Load1:       ServerHostLoad1Metric,
				}),
			},
			MetadataTemplates: host.MetadataTemplates,
			MetricTemplates:   host.MetricTemplates,
		}.WithShape(report.Circle).WithLabel("host", "hosts"),
		Pod: report.Topology{
			Nodes: report.Nodes{
				ClientPodNodeID: report.MakeNodeWith(
					ClientPodNodeID, map[string]string{
						kubernetes.ID:        ClientPodID,
						kubernetes.Name:      "pong-a",
						kubernetes.Namespace: KubernetesNamespace,
						report.HostNodeID:    ClientHostNodeID,
					}).
					WithTopology(report.Pod).WithParents(report.EmptySets.
					Add("host", report.MakeStringSet(ClientHostNodeID)).
					Add("service", report.MakeStringSet(ServiceNodeID)),
				),
				ServerPodNodeID: report.MakeNodeWith(
					ServerPodNodeID, map[string]string{
						kubernetes.ID:        ServerPodID,
						kubernetes.Name:      "pong-b",
						kubernetes.Namespace: KubernetesNamespace,
						kubernetes.State:     "running",
						report.HostNodeID:    ServerHostNodeID,
					}).
					WithTopology(report.Pod).WithParents(report.EmptySets.
					Add("host", report.MakeStringSet(ServerHostNodeID)).
					Add("service", report.MakeStringSet(ServiceNodeID)),
				),
			},
			MetadataTemplates: kubernetes.PodMetadataTemplates,
		}.WithShape(report.Heptagon).WithLabel("pod", "pods"),
		Service: report.Topology{
			Nodes: report.Nodes{
				ServiceNodeID: report.MakeNodeWith(

					ServiceNodeID, map[string]string{
						kubernetes.ID:        ServiceID,
						kubernetes.Name:      "pongservice",
						kubernetes.Namespace: "ping",
					}).
					WithTopology(report.Service),
			},
		}.WithShape(report.Heptagon).WithLabel("service", "services"),
		Sampling: report.Sampling{
			Count: 1024,
			Total: 4096,
		},
		Window: 2 * time.Second,
	}
)

func init() {
	if err := Report.Validate(); err != nil {
		panic(err)
	}
}

func newu64(value uint64) *uint64 { return &value }


text:
package etri.sdn.controller.protocol;

import org.projectfloodlight.openflow.protocol.OFDescStatsReply;
import org.projectfloodlight.openflow.protocol.OFFeaturesReply;

public class SwitchInfo {
	private OFDescStatsReply	descStatsReply = null;
	private OFFeaturesReply	featuresReply = null;

	public SwitchInfo() {
		// does nothing
	}

	public void setDescStatsReply(OFDescStatsReply r) {
		this.descStatsReply = r;
	}

	public OFDescStatsReply getDescStatsReply() {
		return this.descStatsReply;
	}

	public void setFeaturesReply(OFFeaturesReply r) {
		this.featuresReply = r;
	}

	public OFFeaturesReply getFeaturesReply() {
		return this.featuresReply;
	}

	/*
	 * convenient functions
	 */

	public long getBuffers() {
		if ( this.featuresReply != null ) {
			this.featuresReply.getNBuffers();
		}
		return 0;
	}
}


text:
package onpremise

import (
	"context"
	"net/http"
)

// ResolutionService handles resolutions for the Jira instance / API.
//
// Jira API docs: https://developer.atlassian.com/cloud/jira/platform/rest/#api-Resolution
type ResolutionService service

// Resolution represents a resolution of a Jira issue.
// Typical types are "Fixed", "Suspended", "Won't Fix", ...
type Resolution struct {
	Self        string `json:"self" structs:"self"`
	ID          string `json:"id" structs:"id"`
	Description string `json:"description" structs:"description"`
	Name        string `json:"name" structs:"name"`
}

// GetList gets all resolutions from Jira
//
// Jira API docs: https://developer.atlassian.com/cloud/jira/platform/rest/#api-api-2-resolution-get
//
// TODO Double check this method if this works as expected, is using the latest API and the response is complete
// This double check effort is done for v2 - Remove this two lines if this is completed.
func (s *ResolutionService) GetList(ctx context.Context) ([]Resolution, *Response, error) {
	apiEndpoint := "rest/api/2/resolution"
	req, err := s.client.NewRequest(ctx, http.MethodGet, apiEndpoint, nil)
	if err != nil {
		return nil, nil, err
	}

	resolutionList := []Resolution{}
	resp, err := s.client.Do(req, &resolutionList)
	if err != nil {
		return nil, resp, NewJiraError(resp, err)
	}
	return resolutionList, resp, nil
}


text:
import getProp from '../src/getProp';

const parser = require('babylon');

function parse(code) {
  return parser.parse(code, {
    plugins: ['jsx', 'functionBind', 'estree'],
  });
}

export function getOpeningElement(code) {
  return parse(code).program.body[0].expression.openingElement;
}

export function extractProp(code, prop = 'foo') {
  const node = getOpeningElement(code);
  const { attributes: props } = node;
  return getProp(props, prop);
}


text:
package com.netflix.spinnaker.clouddriver.kubernetes.v2.op.deployer;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.netflix.spinnaker.clouddriver.deploy.DeploymentResult;
import com.netflix.spinnaker.clouddriver.kubernetes.v2.artifact.ArtifactReplacer;
import com.netflix.spinnaker.clouddriver.kubernetes.v2.caching.Keys;
import com.netflix.spinnaker.clouddriver.kubernetes.v2.caching.agent.KubernetesV2CachingAgent;
import com.netflix.spinnaker.clouddriver.kubernetes.v2.caching.view.provider.KubernetesCacheUtils;
import com.netflix.spinnaker.clouddriver.kubernetes.v2.description.KubernetesSpinnakerKindMap.SpinnakerKind;
import com.netflix.spinnaker.clouddriver.kubernetes.v2.description.manifest.KubernetesKind;
import com.netflix.spinnaker.clouddriver.kubernetes.v2.description.manifest.KubernetesManifest;
import com.netflix.spinnaker.clouddriver.kubernetes.v2.op.job.KubectlJobExecutor;
import com.netflix.spinnaker.clouddriver.kubernetes.v2.security.KubernetesV2Credentials;
import com.netflix.spinnaker.clouddriver.model.Manifest.Status;
import com.netflix.spinnaker.kork.artifacts.model.Artifact;
import lombok.Getter;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

public abstract class KubernetesHandler {
  @Autowired
  protected ObjectMapper objectMapper;

  @Getter
  @Autowired
  protected KubectlJobExecutor jobExecutor;

  private ArtifactReplacer artifactReplacer = new ArtifactReplacer();

  protected void registerReplacer(ArtifactReplacer.Replacer replacer) {
    artifactReplacer.addReplacer(replacer);
  }

  public KubernetesManifest replaceArtifacts(KubernetesManifest manifest, List<Artifact> artifacts) {
    return artifactReplacer.replaceAll(manifest, artifacts);
  }

  public Set<Artifact> listArtifacts(KubernetesManifest manifest) {
    return artifactReplacer.findAll(manifest);
  }

  public DeploymentResult deployAugmentedManifest(KubernetesV2Credentials credentials, KubernetesManifest manifest) {
    deploy(credentials, manifest);

    DeploymentResult result = new DeploymentResult();
    result.setDeployedNames(new ArrayList<>(Collections.singleton(manifest.getNamespace() + ":" + manifest.getFullResourceName())));
    result.setDeployedNamesByLocation(new HashMap<>(Collections.singletonMap(manifest.getNamespace(), Collections.singletonList(manifest.getFullResourceName()))));

    return result;
  }

  abstract public KubernetesKind kind();
  abstract public boolean versioned();
  abstract public SpinnakerKind spinnakerKind();
  abstract public Status status(KubernetesManifest manifest);
  abstract public Class<? extends KubernetesV2CachingAgent> cachingAgentClass();

  protected void deploy(KubernetesV2Credentials credentials, KubernetesManifest manifest) {
    credentials.deploy(manifest);
  }

  public Map<String, Object> hydrateSearchResult(Keys.InfrastructureCacheKey key, KubernetesCacheUtils cacheUtils) {
    Map<String, Object> result = objectMapper.convertValue(key, new TypeReference<Map<String, Object>>() {});
    result.put("region", key.getNamespace());
    result.put("name", KubernetesManifest.getFullResourceName(key.getKubernetesKind(), key.getName()));
    return result;
  }
}


text:
@class MenuItem;

typedef void(^DidSelctedItemCompletedBlock)(MenuItem *menuItem);

@interface MenuButton : UIView

@property (nonatomic, copy) DidSelctedItemCompletedBlock didSelctedItemCompleted;

- (instancetype)initWithFrame:(CGRect)frame
                     menuItem:(MenuItem *)menuItem;

@end


text:
'use strict';

angular
.module('report-editor')
.config(function ($stateProvider) {
    $stateProvider
        .state('report.taxonomy.concepts.recompile', {
            url: '/recompile',
            templateUrl: '/report/taxonomy/concepts/recompile/recompile.html',
            controller: 'RecompileCtrl'
        });
})
;


text:
//*********************************************************//
//    Copyright (c) Microsoft. All rights reserved.
//
//    Apache 2.0 License
//
//    You may obtain a copy of the License at
//    http://www.apache.org/licenses/LICENSE-2.0
//
//    Unless required by applicable law or agreed to in writing, software
//    distributed under the License is distributed on an "AS IS" BASIS,
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
//    implied. See the License for the specific language governing
//    permissions and limitations under the License.
//
//*********************************************************//

namespace TestUtilities.Nodejs {
    public class NodejsTestData {
        const string DataSourcePath = @"Nodejs\Tests\TestData";

        public static void Deploy(bool includeTestData = true) {
            TestData.Deploy(DataSourcePath, includeTestData);
        }
    }
}


text:
FROM vovimayhem/app:node-for-c-ish
MAINTAINER Roberto Quintanilla <roberto.quintanilla@gmail.com>

################################################################################
# 1: Building ruby
# - Taken almost entirely from https://github.com/docker-library/ruby
#
# Some of ruby's build scripts are written in ruby. We'll purge this later in
# this RUN command to make sure our final image uses what we just built.
#
# Please note that unlike the official ruby image, we're:
#  - Compiling ruby with DTrace enabled.
#  - Installing bundler as a system gem as part of the build step.
#  - Setting the '/app/vendor/bundle' as the GEM_HOME variable
#  - Adding '/app/bin' and '/app/vendor/bundle/bin' to the PATH variable
RUN RUBY_MAJOR=2.1 RUBY_VERSION=2.1.7 RUBYGEMS_VERSION=2.4.8 \
	RUBY_DOWNLOAD_SHA256=f59c1596ac39cc7e60126e7d3698c19f482f04060674fdfe0124e1752ba6dd81 \
	&& apt-get update \
	&& apt-get install -y bison libgdbm-dev ruby \
	&& rm -rf /var/lib/apt/lists/* \
	&& mkdir -p /usr/src/ruby \
	&& curl -fSL -o ruby.tar.gz "http://cache.ruby-lang.org/pub/ruby/$RUBY_MAJOR/ruby-$RUBY_VERSION.tar.gz" \
	&& echo "$RUBY_DOWNLOAD_SHA256 *ruby.tar.gz" | sha256sum -c - \
	&& tar -xzf ruby.tar.gz -C /usr/src/ruby --strip-components=1 \
	&& rm ruby.tar.gz \
	&& cd /usr/src/ruby \
	&& autoconf \
	&& ./configure --disable-install-doc \
	&& make -j"$(nproc)" \
	&& make install \
	&& apt-get purge -y --auto-remove bison libgdbm-dev ruby \
	&& gem update --system $RUBYGEMS_VERSION \
	&& cd / && rm -r /usr/src/ruby \
	&& gem install bundler --no-rdoc --no-ri \
	&& bundle config --global frozen 1

################################################################################
# Persisted Environment Variables:
#  1: Set the GEM_HOME to the app's /app/vendor/bundle path. (It will preserve
#     the original gem paths - check it with 'gem env')
#  2: The path to the directory where bundler will store the local configuration.
#  3: Prepend the following paths to $PATH:
#      - The app's vendored gem binaries
#      - The app's binaries
ENV GEM_HOME=/app/vendor/bundle \
	BUNDLE_APP_CONFIG=/app/vendor/bundle \
	PATH=/app/bin:/app/vendor/bundle/bin:$PATH

# Set the image user as the unprivileged 'app' user:
USER app

# Set the image's working directory to the '/app' folder, which is the 'app'
# user's home:
WORKDIR /app

# Run bundle install on build:
ONBUILD RUN bundle install --deployment --without development test

CMD ["irb"]


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.authorization.fluent.models;

import com.azure.core.util.ExpandableStringEnum;
import com.fasterxml.jackson.annotation.JsonCreator;
import java.util.Collection;

/** chatMessagePolicyViolationUserActionTypes. */
public final class MicrosoftGraphChatMessagePolicyViolationUserActionTypes
    extends ExpandableStringEnum<MicrosoftGraphChatMessagePolicyViolationUserActionTypes> {
    /** Static value none for MicrosoftGraphChatMessagePolicyViolationUserActionTypes. */
    public static final MicrosoftGraphChatMessagePolicyViolationUserActionTypes NONE = fromString("none");

    /** Static value override for MicrosoftGraphChatMessagePolicyViolationUserActionTypes. */
    public static final MicrosoftGraphChatMessagePolicyViolationUserActionTypes OVERRIDE = fromString("override");

    /** Static value reportFalsePositive for MicrosoftGraphChatMessagePolicyViolationUserActionTypes. */
    public static final MicrosoftGraphChatMessagePolicyViolationUserActionTypes REPORT_FALSE_POSITIVE =
        fromString("reportFalsePositive");

    /**
     * Creates or finds a MicrosoftGraphChatMessagePolicyViolationUserActionTypes from its string representation.
     *
     * @param name a name to look for.
     * @return the corresponding MicrosoftGraphChatMessagePolicyViolationUserActionTypes.
     */
    @JsonCreator
    public static MicrosoftGraphChatMessagePolicyViolationUserActionTypes fromString(String name) {
        return fromString(name, MicrosoftGraphChatMessagePolicyViolationUserActionTypes.class);
    }

    /**
     * Gets known MicrosoftGraphChatMessagePolicyViolationUserActionTypes values.
     *
     * @return known MicrosoftGraphChatMessagePolicyViolationUserActionTypes values.
     */
    public static Collection<MicrosoftGraphChatMessagePolicyViolationUserActionTypes> values() {
        return values(MicrosoftGraphChatMessagePolicyViolationUserActionTypes.class);
    }
}


text:
sap.ui.define([
	"sap/ui/core/mvc/Controller",
	"sap/m/MessageToast"
], function(Controller, MessageToast) {
	"use strict";

	return Controller.extend("sap.m.sample.buttonShortcut.Controller", {
		onSave: function () {
			MessageToast.show("CTRL+S: save triggered on controller");
		},

		onDelete: function () {
			MessageToast.show("CTRL+D: delete triggered on controller");
		}
	});
});


text:
<?php

namespace Gamma\ProductBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class GammaProductBundle extends Bundle
{
}


text:
package auth

import (
	"encoding/xml"

	"github.com/fgrid/iso20022"
)

type Document01500101 struct {
	XMLName xml.Name                                            `xml:"urn:iso:std:iso:20022:tech:xsd:auth.015.001.01 Document"`
	Message *MoneyMarketOvernightIndexSwapsStatisticalReportV01 `xml:"MnyMktOvrnghtIndxSwpsSttstclRpt"`
}

func (d *Document01500101) AddMessage() *MoneyMarketOvernightIndexSwapsStatisticalReportV01 {
	d.Message = new(MoneyMarketOvernightIndexSwapsStatisticalReportV01)
	return d.Message
}

// The MoneyMarketOvernightIndexSwapsStatisticalReport message is sent by the reporting agents to the relevant competent authority, to report the daily overnight index swaps (OIS) transactions.
type MoneyMarketOvernightIndexSwapsStatisticalReportV01 struct {

	// Provides the elements specific to the report.
	ReportHeader *iso20022.MoneyMarketReportHeader1 `xml:"RptHdr"`

	// Provides the reason why no activity is reported or the required list of transactions for the overnight index swaps segment.
	OvernightIndexSwapsReport *iso20022.OvernightIndexSwap3Choice `xml:"OvrnghtIndxSwpsRpt"`

	// Additional information that can not be captured in the structured fields and/or any other specific block.
	SupplementaryData []*iso20022.SupplementaryData1 `xml:"SplmtryData,omitempty"`
}

func (m *MoneyMarketOvernightIndexSwapsStatisticalReportV01) AddReportHeader() *iso20022.MoneyMarketReportHeader1 {
	m.ReportHeader = new(iso20022.MoneyMarketReportHeader1)
	return m.ReportHeader
}

func (m *MoneyMarketOvernightIndexSwapsStatisticalReportV01) AddOvernightIndexSwapsReport() *iso20022.OvernightIndexSwap3Choice {
	m.OvernightIndexSwapsReport = new(iso20022.OvernightIndexSwap3Choice)
	return m.OvernightIndexSwapsReport
}

func (m *MoneyMarketOvernightIndexSwapsStatisticalReportV01) AddSupplementaryData() *iso20022.SupplementaryData1 {
	newValue := new(iso20022.SupplementaryData1)
	m.SupplementaryData = append(m.SupplementaryData, newValue)
	return newValue
}


text:
using System;

using System.Collections.Generic;

using System.Text;

using System.IO.Ports;

using System.Globalization;

namespace MDIMonitor_CS

{

    public class UserSerialPort

    {

        SerialPort _serialPort = null;

        //定义委托

        public delegate void SerialPortDataReceiveEventArgs(object sender, SerialDataReceivedEventArgs e, byte[] bits);

        //定义接收数据事件

        public event SerialPortDataReceiveEventArgs DataReceived;

        //定义接收错误事件

        //public event SerialErrorReceivedEventHandler Error;

        //接收事件是否有效 false表示有效

        public bool ReceiveEventFlag = false;

        #region 获取串口名

        private string protName;

        public string PortName

        {

            get { return _serialPort.PortName; }

            set

            {

                _serialPort.PortName = value;

                protName = value;

            }

        }

        #endregion

        #region 获取比特率

        private int baudRate;

        public int BaudRate

        {

            get { return _serialPort.BaudRate; }

            set

            {

                _serialPort.BaudRate = value;

                baudRate = value;

            }

        }

        #endregion

        #region 默认构造函数

        /// <summary>

        /// 默认构造函数,操作COM1,速度为9600,没有奇偶校验,8位字节,停止位为1 "COM1", 9600, Parity.None, 8, StopBits.One

        /// </summary>

        public UserSerialPort()

        {

            _serialPort = new SerialPort();

        }

        #endregion

        #region 构造函数

        /// <summary>

        /// 构造函数,

        /// </summary>

        /// <param name="comPortName"></param>

        public UserSerialPort(string comPortName)

        {

            _serialPort = new SerialPort(comPortName);

            _serialPort.BaudRate = 9600;

            _serialPort.Parity = Parity.Even;

            _serialPort.DataBits = 8;

            _serialPort.StopBits = StopBits.One;

            _serialPort.Handshake = Handshake.None;

            _serialPort.RtsEnable = true;

            _serialPort.ReadTimeout = 2000;

            setSerialPort();

        }

        #endregion

        #region 构造函数,可以自定义串口的初始化参数

        /// <summary>

        /// 构造函数,可以自定义串口的初始化参数

        /// </summary>

        /// <param name="comPortName">需要操作的COM口名称</param>

        /// <param name="baudRate">COM的速度</param>

        /// <param name="parity">奇偶校验位</param>

        /// <param name="dataBits">数据长度</param>

        /// <param name="stopBits">停止位</param>

        public UserSerialPort(string comPortName, int baudRate, Parity parity, int dataBits, StopBits stopBits)

        {

            _serialPort = new SerialPort(comPortName, baudRate, parity, dataBits, stopBits);

            _serialPort.RtsEnable = true;  //自动请求

            _serialPort.ReadTimeout = 3000;//超时

            setSerialPort();

        }

        #endregion

        #region 析构函数

        /// <summary>

        /// 析构函数,关闭串口

        /// </summary>

        ~UserSerialPort()

       {

           if (_serialPort.IsOpen)

               _serialPort.Close();

       }

        #endregion

        #region 设置串口参数

        /// <summary>

        /// 设置串口参数

        /// </summary>

        /// <param name="comPortName">需要操作的COM口名称</param>

        /// <param name="baudRate">COM的速度</param>

        /// <param name="dataBits">数据长度</param>

        /// <param name="stopBits">停止位</param>

        public void setSerialPort(string comPortName, int baudRate, int dataBits, int stopBits )

        {

            if (_serialPort.IsOpen)

                _serialPort.Close();

            _serialPort.PortName = comPortName;

            _serialPort.BaudRate = baudRate;

            _serialPort.Parity = Parity.None;

            _serialPort.DataBits = dataBits;

            _serialPort.StopBits = (StopBits)stopBits;

            _serialPort.Handshake = Handshake.None;

            _serialPort.RtsEnable = false;

            _serialPort.ReadTimeout = 3000;

            _serialPort.NewLine = "/r/n";

            setSerialPort();

        }

        #endregion

        #region 设置接收函数

        /// <summary>

        /// 设置串口资源,还需重载多个设置串口的函数

        /// </summary>

        void setSerialPort()

        {

            if (_serialPort != null)

            {

                //设置触发DataReceived事件的字节数为1

                _serialPort.ReceivedBytesThreshold = 1;

                //接收到一个字节时,也会触发DataReceived事件

                _serialPort.DataReceived += new SerialDataReceivedEventHandler(_serialPort_DataReceived);

                //接收数据出错,触发事件

                _serialPort.ErrorReceived += new SerialErrorReceivedEventHandler(_serialPort_ErrorReceived);

                //打开串口

                //openPort();

            }

        }

        #endregion

        #region 打开串口资源

        /// <summary>

        /// 打开串口资源

        /// <returns>返回bool类型</returns>

        /// </summary>

        public bool openPort()

        {

            bool ok = false;

            //如果串口是打开的,先关闭

            if (_serialPort.IsOpen)

                _serialPort.Close();

            try

            {

                //打开串口

                _serialPort.Open();

                ok = true;

            }

            catch (Exception Ex)

            {

                throw Ex;

            }

            return ok;

        }

        #endregion

        #region 关闭串口

        /// <summary>

        /// 关闭串口资源,操作完成后,一定要关闭串口

        /// </summary>

        public void closePort()

        {

            //如果串口处于打开状态,则关闭

            if (_serialPort.IsOpen)

                _serialPort.Close();

        }

        #endregion

        #region 接收串口数据事件

        /// <summary>

        /// 接收串口数据事件

        /// </summary>

        /// <param name="sender"></param>

        /// <param name="e"></param>

        void _serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)

        {

            //禁止接收事件时直接退出

            if (ReceiveEventFlag)

            {

                return;

            }

            try

            {

                    System.Threading.Thread.Sleep(20);

                    byte[] _data = new byte[_serialPort.BytesToRead];

                    _serialPort.Read(_data, 0, _data.Length);

                    if (_data.Length == 0) { return; }

                    if (DataReceived != null)

                    {

                        DataReceived(sender, e, _data);

                    }

                    //_serialPort.DiscardInBuffer();  //清空接收缓冲区

            }

            catch (Exception ex)

            {

                throw ex;

            }

        }

        #endregion

        #region 接收数据出错事件

        /// <summary>

        /// 接收数据出错事件

        /// </summary>

        /// <param name="sender"></param>

        /// <param name="e"></param>

        void _serialPort_ErrorReceived(object sender, SerialErrorReceivedEventArgs e)

        {

        }

        #endregion

        #region 发送数据string类型

        public void SendData(string data)

        {

            //发送数据

            //禁止接收事件时直接退出

            if (ReceiveEventFlag)

            {

                return;

            }

            if (_serialPort.IsOpen)

            {

                _serialPort.Write(data);

            }

        }

        #endregion

        #region 发送数据byte类型

        /// <summary>

        /// 数据发送

        /// </summary>

        /// <param name="data">要发送的数据字节</param>

        public void SendData(byte[] data, int offset, int count)

        {

            //禁止接收事件时直接退出

            if (ReceiveEventFlag)

            {

                return;

            }

            try

            {

                if (_serialPort.IsOpen)

                {

                    //_serialPort.DiscardInBuffer();//清空接收缓冲区

                    _serialPort.Write(data, offset, count);

                }

            }

            catch (Exception ex)

            {

                throw ex;

            }

        }

        #endregion

        #region 发送命令

        /// <summary>

        /// 发送命令

        /// </summary>

        /// <param name="SendData">发送数据</param>

        /// <param name="ReceiveData">接收数据</param>

        /// <param name="Overtime">超时时间</param>

        /// <returns></returns>

        public int SendCommand(byte[] SendData, ref  byte[] ReceiveData, int Overtime)

        {

            if (_serialPort.IsOpen)

            {

                try

                {

                    ReceiveEventFlag = true;        //关闭接收事件

                    _serialPort.DiscardInBuffer();  //清空接收缓冲区

                    _serialPort.Write(SendData, 0, SendData.Length);

                    int num = 0, ret = 0;

                    System.Threading.Thread.Sleep(10);

                    ReceiveEventFlag = false;      //打开事件

                    while (num++ < Overtime)

                    {

                        if (_serialPort.BytesToRead >= ReceiveData.Length)

                            break;

                        System.Threading.Thread.Sleep(10);

                    }

                    if (_serialPort.BytesToRead >= ReceiveData.Length)

                    {

                        ret = _serialPort.Read(ReceiveData, 0, ReceiveData.Length);

                    }

                    else

                    {

                        ret = _serialPort.Read(ReceiveData, 0, _serialPort.BytesToRead);

                    }

                    ReceiveEventFlag = false;      //打开事件

                    return ret;

                }

                catch (Exception ex)

                {

                    ReceiveEventFlag = false;

                    throw ex;

                }

            }

            return -1;

        }

        #endregion

        #region 获取串口

        /// <summary>

        /// 获取所有已连接短信猫设备的串口

        /// </summary>

        /// <returns></returns>

        public string[] serialsIsConnected()

        {

            List<string> lists = new List<string>();

            string[] seriallist = getSerials();

            foreach (string s in seriallist)

            {

            }

            return lists.ToArray();

        }

        #endregion

        #region 获取当前全部串口资源

        /// <summary>

        /// 获得当前电脑上的所有串口资源

        /// </summary>

        /// <returns></returns>

        public string[] getSerials()

        {

            return SerialPort.GetPortNames();

        }

        #endregion

        #region 字节型转换16

        /// <summary>

        /// 把字节型转换成十六进制字符串

        /// </summary>

        /// <param name="InBytes"></param>

        /// <returns></returns>

        public static string ByteToString(byte[] InBytes)

        {

            string StringOut = "";

            foreach (byte InByte in InBytes)

            {

                StringOut = StringOut + String.Format("{0:X2} ", InByte);

            }

            return StringOut;

        }

        #endregion

        #region 十六进制字符串转字节型

        /// <summary>

        /// 把十六进制字符串转换成字节型(方法1)

        /// </summary>

        /// <param name="InString"></param>

        /// <returns></returns>

        public static byte[] StringToByte(string InString)

        {

            string[] ByteStrings;

            ByteStrings = InString.Split(" ".ToCharArray());

            byte[] ByteOut;

            ByteOut = new byte[ByteStrings.Length];

            for (int i = 0; i <= ByteStrings.Length-1 ; i++)

            {

                //ByteOut[i] = System.Text.Encoding.ASCII.GetBytes(ByteStrings[i]);

                ByteOut[i] = Byte.Parse(ByteStrings[i], System.Globalization.NumberStyles.HexNumber);

                //ByteOut[i] =Convert.ToByte("0x" + ByteStrings[i]);

            }

            return ByteOut;

        }

        #endregion

        #region 十六进制字符串转字节型

        /// <summary>

        /// 字符串转16进制字节数组(方法2)

        /// </summary>

        /// <param name="hexString"></param>

        /// <returns></returns>

        public static byte[] strToToHexByte(string hexString)

        {

            hexString = hexString.Replace(" ", "");

            if ((hexString.Length % 2) != 0)

                hexString += " ";

            byte[] returnBytes = new byte[hexString.Length / 2];

            for (int i = 0; i < returnBytes.Length; i++)

                returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);

            return returnBytes;

        }

        #endregion

        #region 字节型转十六进制字符串

        /// <summary>

        /// 字节数组转16进制字符串

        /// </summary>

        /// <param name="bytes"></param>

        /// <returns></returns>

        public static string byteToHexStr(byte[] bytes)

        {

            string returnStr = "";

            if (bytes != null)

            {

                for (int i = 0; i < bytes.Length; i++)

                {

                    returnStr += bytes[i].ToString("X2");

                }

            }

            return returnStr;

        }

        #endregion

    }

}


text:
package org.gradle.internal.resource.transport.gcp.gcs;

import com.google.common.base.Optional;
import com.google.common.collect.Sets;
import org.apache.commons.lang.StringUtils;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.Set;

import static java.lang.System.getProperty;

@SuppressWarnings("Duplicates") // re-use not possible across modules currently
public final class GcsConnectionProperties {

    public static final String GCS_ENDPOINT_PROPERTY = "org.gradle.gcs.endpoint";
    public static final String GCS_SERVICE_PATH_PROPERTY = "org.gradle.gcs.servicePath";
    // Controls when to disable reading default authentication credentials, should be used in tests only
    public static final String GCS_DISABLE_AUTH_PROPERTY = "org.gradle.gcs.disableAuthentication";

    private static final Set<String> SUPPORTED_SCHEMES = Sets.newHashSet("HTTP", "HTTPS");

    private final URI endpoint;
    private final String servicePath;
    private final boolean disableAuthentication;

    GcsConnectionProperties() {
        this(getProperty(GCS_ENDPOINT_PROPERTY),
            getProperty(GCS_SERVICE_PATH_PROPERTY),
            getProperty(GCS_DISABLE_AUTH_PROPERTY));
    }

    GcsConnectionProperties(String endpoint, String servicePath, String disableAuthentication) {
        this(configureEndpoint(endpoint),
            configureServicePath(servicePath),
            configureDisableAuthentication(disableAuthentication));
    }

    private GcsConnectionProperties(URI endpoint, String servicePath, boolean disableAuthentication) {
        this.endpoint = endpoint;
        this.servicePath = servicePath;
        this.disableAuthentication = disableAuthentication;
    }

    Optional<URI> getEndpoint() {
        return Optional.fromNullable(endpoint);
    }

    Optional<String> getServicePath() {
        return Optional.fromNullable(servicePath);
    }

    boolean requiresAuthentication() {
        return !disableAuthentication;
    }

    private static URI configureEndpoint(String property) {
        URI uri = null;
        if (StringUtils.isNotBlank(property)) {
            try {
                uri = new URI(property);
                if (StringUtils.isBlank(uri.getScheme()) || !SUPPORTED_SCHEMES.contains(uri.getScheme().toUpperCase())) {
                    throw new IllegalArgumentException("System property [" + GCS_ENDPOINT_PROPERTY + "=" + property + "] must have a scheme of 'http' or 'https'");
                }
            } catch (URISyntaxException e) {
                throw new IllegalArgumentException("System property [" + GCS_ENDPOINT_PROPERTY + "=" + property + "]  must be a valid URI");
            }
        }
        return uri;
    }

    private static String configureServicePath(String property) {
        if (StringUtils.isNotBlank(property)) {
           return property;
        } else {
            return null;
        }
    }

    private static boolean configureDisableAuthentication(String property) {
        return StringUtils.isNotBlank(property) && Boolean.parseBoolean(property);
    }
}


text:
<?php

use InMemoryList\Command\StatisticsCommand;
use InMemoryList\Tests\BaseTestCase;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Tester\CommandTester;

class StatisticsCommandTest extends BaseTestCase
{
    /**
     * @var Application
     */
    private $app;

    public function setUp()
    {
        parent::setUp(); // TODO: Change the autogenerated stub

        $this->app = new Application();
        $this->app->add(new StatisticsCommand());
    }

    /**
     * @test
     */
    public function it_displays_correctly_apcu_statistics()
    {
        $this->app->add(new StatisticsCommand('apcu'));
        $command = $this->app->find('iml:cache:statistics');

        $commandTester = new CommandTester($command);
        $commandTester->execute([
            'command' => $command->getName(),
        ]);

        $output = $commandTester->getDisplay();

        $this->assertContains('num_slots', $output);
        $this->assertContains('ttl', $output);
        $this->assertContains('num_hits', $output);
        $this->assertContains('num_misses', $output);
        $this->assertContains('num_inserts', $output);
        $this->assertContains('num_entries', $output);
        $this->assertContains('expunges', $output);
        $this->assertContains('start_time', $output);
        $this->assertContains('start_time', $output);
        $this->assertContains('mem_size', $output);
        $this->assertContains('memory_type', $output);
        $this->assertContains('deleted_list', $output);
        $this->assertContains('slot_distribution', $output);
    }

    /**
     * @test
     */
    public function it_displays_correctly_memcached_statistics()
    {
        $this->app->add(new StatisticsCommand('memcached', $this->memcached_parameters));
        $command = $this->app->find('iml:cache:statistics');

        $commandTester = new CommandTester($command);
        $commandTester->execute([
            'command' => $command->getName(),
        ]);

        $output = $commandTester->getDisplay();

        // if $this->memcached_parameters is a monodimensional array convert to multidimensional
        if (!isset($this->memcached_parameters[0])) {
            $this->memcached_parameters = [$this->memcached_parameters];
        }

        $this->assertContains($this->memcached_parameters[0]['host'], $output);
        $this->assertContains($this->memcached_parameters[0]['port'], $output);
    }

    /**
     * @test
     */
    public function it_displays_correctly_redis_statistics()
    {
        $this->app->add(new StatisticsCommand('redis', $this->redis_parameters));
        $command = $this->app->find('iml:cache:statistics');

        $commandTester = new CommandTester($command);
        $commandTester->execute([
            'command' => $command->getName(),
        ]);

        $output = $commandTester->getDisplay();

        $this->assertContains('Clients', $output);
        $this->assertContains('CPU', $output);
        $this->assertContains('Memory', $output);
        $this->assertContains('Persistence', $output);
        $this->assertContains('Replication', $output);
        $this->assertContains('Server', $output);
        $this->assertContains('Stats', $output);
    }
}


text:
<?php

namespace Illuminate\Routing;

use Illuminate\Container\Container;

class ControllerDispatcher
{
    use RouteDependencyResolverTrait;

    /**
     * The container instance.
     *
     * @var \Illuminate\Container\Container
     */
    protected $container;

    /**
     * Create a new controller dispatcher instance.
     *
     * @param  \Illuminate\Container\Container  $container
     * @return void
     */
    public function __construct(Container $container)
    {
        $this->container = $container;
    }

    /**
     * Dispatch a request to a given controller and method.
     *
     * @param  \Illuminate\Routing\Route  $route
     * @param  mixed  $controller
     * @param  string  $method
     * @return mixed
     */
    public function dispatch(Route $route, $controller, $method)
    {
        $parameters = $this->resolveClassMethodDependencies(
            $route->parametersWithoutNulls(), $controller, $method
        );

        if (method_exists($controller, 'callAction')) {
            return $controller->callAction($method, $parameters);
        }

        return call_user_func_array([$controller, $method], $parameters);
    }

    /**
     * Get the middleware for the controller instance.
     *
     * @param  \Illuminate\Routing\Controller  $controller
     * @param  string  $method
     * @return array
     */
    public static function getMiddleware($controller, $method)
    {
        if (! method_exists($controller, 'getMiddleware')) {
            return [];
        }

        return collect($controller->getMiddleware())->reject(function ($options, $name) use ($method) {
            return static::methodExcludedByOptions($method, $options);
        })->keys()->all();
    }

    /**
     * Determine if the given options exclude a particular method.
     *
     * @param  string  $method
     * @param  array  $options
     * @return bool
     */
    protected static function methodExcludedByOptions($method, array $options)
    {
        return (isset($options['only']) && ! in_array($method, (array) $options['only'])) ||
            (! empty($options['except']) && in_array($method, (array) $options['except']));
    }
}


text:
<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateMyDishesTable extends Migration {

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
		Schema::create('my_dishes', function(Blueprint $table)
		{
			$table->increments('id');
			$table->timestamps();
		});
	}

	/**
	 * Reverse the migrations.
	 *
	 * @return void
	 */
	public function down()
	{
		Schema::drop('my_dishes');
	}

}


text:
<?php
class Product_model extends CI_Model {
        public function __construct()
        {
                $this->load->database();
				date_default_timezone_set('Australia/Sydney');
        }

		public function get_product($product_id = FALSE)
		{
	        if ($product_id !== FALSE)
	        {
	        	$query = $this->db->get_where('os_product', array('os_product_id' => $product_id));
	        	return $query->row_array();
	        }
	        $this->db->order_by("product_name", "asc");
	        $query = $this->db->get('os_product');
			return $query->result_array();

		}
		public function get_product_by_name($product_name = "")
		{
	        if ($product_name !== FALSE)
	        {
				$product_name = $this->input->get('term');

				$myquery = "select op.product_name label, op.os_product_id id, op.product_name value, op.chemist_price, op.source_type from os_product op where UPPER(op.product_name) like UPPER('%".$product_name."%')";

				$query = $this->db->query($myquery);
	        	return $query->result_array();
	        }

		}

		public function get_product_list($offset = 1,$per_page = 50,$is_total = FALSE)
		{
			$product_name = $this->input->get('product_name');
			$product_name = str_replace('\'','\'\'',$product_name);
			$barcode = $this->input->get('barcode');
			$brand_id = $this->input->get('brand_id');
			$category_id = $this->input->get('category_id');
			$stock = $this->input->get('stock');
			$location = $this->input->get('location');

			//$myquery = 'select * from os_product as pro,os_brand as bra,os_category as cat where pro.brand_id = bra.brand_id and cat.category_id = pro.category_id ';

			$myquery = 'select * from os_product as pro where 1=1 ';
			if ($product_name != '')
			{
				$myquery = $myquery.' and pro.product_name like \'%'.$product_name.'%\'';
			}
			if ($barcode != '')
			{
				$myquery = $myquery.' and pro.barcode like \'%'.$barcode.'%\'';
			}
			// if ($brand_id != '' && $brand_id !=0 )
			// {
			// 	$myquery = $myquery.' and pro.brand_id = '.$brand_id;
			// }
			// if ($category_id != '' && $category_id !=0 )
			// {
			// 	$myquery = $myquery.' and pro.category_id = '.$category_id;
			// }
			if ($stock === '1')
			{
				$myquery = $myquery.' and pro.stock <= purchase_line';
			}
			if ($stock === '2')
			{
				$myquery = $myquery.' and pro.stock <= reserve_line';
			}

			if ($location !='' AND $location !='all') {
				$myquery = $myquery.' and pro.wh_loc = \''.$location.'\'';
			}

			if ($is_total == TRUE)
			{
				//echo $myquery;
				$query = $this->db->query($myquery);
				return $query->num_rows();
			}
			else
			{

				$myquery = $myquery.' order by pro.entry_time desc limit '.$offset.', '.$per_page;
				//echo $myquery;
				$query = $this->db->query($myquery);
				// $data=$this->db->from('os_product as pro')
				// ->join('os_brand as bra', 'pro.brand_id = bra.brand_id')
				// ->join('os_category as cat', 'cat.category_id = pro.category_id')
				// ->get()->result_array();
	            return $query->result_array();
            }
		}

		public function save_fetch_product()
		{

        	// chemist product list json string
			echo "this is model-save_fetch_product()";
			echo "

";
			$product_obj = json_decode($this->input->post('product'),true);
			print_r($product_obj);
			echo "

";

			$this->db->trans_begin();

			//empty the table
			$this->db->query('delete from os_chemist_product_fetch');

			//insert fetch product data into temp table
			$this->db->insert_batch('os_chemist_product_fetch', $product_obj);

			//insert fetch product data into table os_chemist_product, if product is exits ,update it .or else insert
			$this->db->query('insert into os_chemist_product
				(chemist_product_id,product_name,small_img_src,big_img_src,chemist_price, entry_time)
								select of.chemist_product_id,
									of.product_name,
									of.small_img_src,
									of.big_img_src,
									of.chemist_price,
									CURRENT_TIMESTAMP entry_time
								from
								os_chemist_product_fetch of left join
								os_chemist_product OP on
								of.chemist_product_id = op.chemist_product_id
								where op.chemist_product_id is null ');
			$this->db->query('insert into os_product
				(chemist_product_id,product_name,small_img_src,big_img_src,chemist_price,source_type, entry_time)
								select of.chemist_product_id,
									of.product_name,
									of.small_img_src,
									of.big_img_src,
									of.chemist_price,
									"chemist warehouse" source_type,
									CURRENT_TIMESTAMP entry_time
								from
								os_chemist_product_fetch of left join
								os_product op on
								of.chemist_product_id = op.chemist_product_id
								where op.chemist_product_id is null ');

			//$this->db->set($product_obj);
			$this->db->update_batch('os_chemist_product', $product_obj, 'chemist_product_id');
			$this->db->update_batch('os_product', $product_obj, 'chemist_product_id');

			$this->db->query('update os_chemist_product
								 set update_time = CURRENT_TIMESTAMP
								where chemist_product_id in
									(select of.chemist_product_id from os_chemist_product_fetch of ) ');
			$this->db->query('update os_product
								 set update_time = CURRENT_TIMESTAMP, source_type = "chemist warehouse"
								where chemist_product_id in
									(select of.chemist_product_id from os_chemist_product_fetch of ) ');
			//$this->db->insert_batch('os_chemist_product', $product_obj);

			if ($this->db->trans_status() === FALSE)
			{
			    $this->db->trans_rollback();
				echo "error";
			}
			else
			{
			    $this->db->trans_commit();
				echo "success";
			}

		}

		public function set_product()
		{
			$today = date("Y-m-d H:i:s");
		    $data = array(
		        //'chemist_product_id' => '999999999',
		        'product_name' => $this->input->post('product_name'),
		        'small_img_src' => $this->input->post('small_img_src'),
		        'big_img_src' => $this->input->post('big_img_src'),
		        'chemist_price' => $this->input->post('chemist_price'),
		        'source_type' => 'manmade',
		        'remark' => $this->input->post('remark'),
		        'entry_time' => $today,
		        'update_time' => $today
		    );
 			return $this->db->insert('os_product', $data);
		}

		public function update_product($os_product_id = FALSE)
		{
			$today = date("Y-m-d H:i:s");
			if ($os_product_id !== FALSE)
			{
			    $data = array(
		        'product_name' => $this->input->post('product_name'),
		        'small_img_src' => $this->input->post('small_img_src'),
		        'big_img_src' => $this->input->post('big_img_src'),
		        'chemist_price' => $this->input->post('chemist_price'),
		        'remark' => $this->input->post('remark'),
		        'update_time' => $today
			    );

			    $this->db->where('os_product_id', $os_product_id);
			    $this->db->update('os_product', $data);
		    }
		}

		public function delete_product($product_id = FALSE)
		{
			if ($product_id !== FALSE)
			{
			    $this->db->where('os_product_id', $product_id);
			    $this->db->delete('os_product');
		    }
		}
}


text:
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta content="history" name="save" />
    <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5" />
    <title>Scale Operators</title>
    <xml>
    </xml>
    <link rel="stylesheet" type="text/css" href="MSDN.css" />

            A MIDI Library for .NET

Scale Operators

The operators of the Scale class are listed below. For a complete list of Scale class members, see the Scale Members topic.

Public Static Operators

Equality Operator	 Equality operator does value equality because Scale is immutable.

Inequality Operator	 Inequality operator does value inequality because Chord is immutable.

See Also

        Scale Class | Scale Members | Midi Namespace

          Copyright © 2009 Tom Lokovic

Generated from assembly Midi [1.1.0.0] by NDoc3


text:
"""
    Kubernetes

    No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)

    OpenAPI spec version: v1.8.2

    Generated by: https://github.com/swagger-api/swagger-codegen.git
"""

from __future__ import absolute_import

import sys
import os
import re

# python 2 and python 3 compatibility library
from six import iteritems

from ..api_client import ApiClient

class ApiregistrationApi(object):
    """
    NOTE: This class is auto generated by the swagger code generator program.
    Do not edit the class manually.
    Ref: https://github.com/swagger-api/swagger-codegen
    """

    def __init__(self, api_client=None):
        if api_client is None:
            api_client = ApiClient()
        self.api_client = api_client

    def get_api_group(self, **kwargs):
        """
        get information of a group
        This method makes a synchronous HTTP request by default. To make an
        asynchronous HTTP request, please pass async=True
        >>> thread = api.get_api_group(async=True)
        >>> result = thread.get()

        :param async bool
        :return: V1APIGroup
                 If the method is called asynchronously,
                 returns the request thread.
        """
        kwargs['_return_http_data_only'] = True
        if kwargs.get('async'):
            return self.get_api_group_with_http_info(**kwargs)
        else:
            (data) = self.get_api_group_with_http_info(**kwargs)
            return data

    def get_api_group_with_http_info(self, **kwargs):
        """
        get information of a group
        This method makes a synchronous HTTP request by default. To make an
        asynchronous HTTP request, please pass async=True
        >>> thread = api.get_api_group_with_http_info(async=True)
        >>> result = thread.get()

        :param async bool
        :return: V1APIGroup
                 If the method is called asynchronously,
                 returns the request thread.
        """

        all_params = []
        all_params.append('async')
        all_params.append('_return_http_data_only')
        all_params.append('_preload_content')
        all_params.append('_request_timeout')

        params = locals()
        for key, val in iteritems(params['kwargs']):
            if key not in all_params:
                raise TypeError(
                    "Got an unexpected keyword argument '%s'"
                    " to method get_api_group" % key
                )
            params[key] = val
        del params['kwargs']

        collection_formats = {}

        path_params = {}

        query_params = []

        header_params = {}

        form_params = []
        local_var_files = {}

        body_params = None
        # HTTP header `Accept`
        header_params['Accept'] = self.api_client.\
            select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf'])

        # HTTP header `Content-Type`
        header_params['Content-Type'] = self.api_client.\
            select_header_content_type(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf'])

        # Authentication setting
        auth_settings = ['BearerToken']

        return self.api_client.call_api('/apis/apiregistration.k8s.io/', 'GET',
                                        path_params,
                                        query_params,
                                        header_params,
                                        body=body_params,
                                        post_params=form_params,
                                        files=local_var_files,
                                        response_type='V1APIGroup',
                                        auth_settings=auth_settings,
                                        async=params.get('async'),
                                        _return_http_data_only=params.get('_return_http_data_only'),
                                        _preload_content=params.get('_preload_content', True),
                                        _request_timeout=params.get('_request_timeout'),
                                        collection_formats=collection_formats)


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

import com.datastax.driver.core.ResultSet;
import com.datastax.driver.core.Row;
import com.datastax.driver.core.Session;
import com.datastax.driver.core.Statement;
import com.datastax.driver.core.querybuilder.Insert;
import com.datastax.driver.core.querybuilder.QueryBuilder;
import static com.datastax.driver.core.querybuilder.QueryBuilder.eq;
import java.util.ArrayList;
import java.util.UUID;

/**
 *
 * @author akhfa
 */
public class TimeLine {
    private String username;
    private UUID time;
    private UUID tweet_id;

    public TimeLine(String _username, UUID _time, UUID _tweet_id)
    {
        this.username = _username;
        this.time = _time;
        this.tweet_id = _tweet_id;
    }

    public void save()
    {
        Session session = Connection.getSession();

        Insert insert = QueryBuilder.insertInto(Connection.getKeySpace(), "timeline")
                                .value("username", username)
                                .value("time", time)
                                .value("tweet_id", tweet_id);
        ResultSet result = session.execute(insert.toString());
        Connection.close();
    }

    public static ArrayList<TweetContainer> getAllTweetFrom(String _username)
    {
        // ambil tweet id dari username
        ArrayList<TweetContainer> tweets = new ArrayList<>();
        Session session = Connection.getSession();

        Statement statement = QueryBuilder.select("tweet_id")
                                            .from(Connection.getKeySpace(), "timeline")
                                            .where(eq("username", _username));
        ResultSet results = session.execute(statement);

        for (Row row : results) {
            Statement statement2 = QueryBuilder.select().all()
                                            .from(Connection.getKeySpace(), "tweets")
                                            .where(eq("tweet_id", row.getUUID("tweet_id")));
            ResultSet results2 = session.execute(statement2);

            Row tweet = results2.one();
            if(tweet != null)
            {
                String username = tweet.getString("username");
                String body = tweet.getString("body");
                TweetContainer container = new TweetContainer(username, body);
                tweets.add(container);
            }
        }

        return tweets;
    }
}


text:
template <typename ReturnType>
ActorTaskCaller<ReturnType> Task(ActorFunc0<ActorType, ReturnType> actor_func);
// 1 arg
template <typename ReturnType, typename Arg1Type>
ActorTaskCaller<ReturnType> Task(ActorFunc1<ActorType, ReturnType, Arg1Type> actor_func,
                                 Arg1Type arg1);

template <typename ReturnType, typename Arg1Type>
ActorTaskCaller<ReturnType> Task(ActorFunc1<ActorType, ReturnType, Arg1Type> actor_func,
                                 ObjectRef<Arg1Type> &arg1);

// 2 args
template <typename ReturnType, typename Arg1Type, typename Arg2Type>
ActorTaskCaller<ReturnType> Task(
    ActorFunc2<ActorType, ReturnType, Arg1Type, Arg2Type> actor_func, Arg1Type arg1,
    Arg2Type arg2);

template <typename ReturnType, typename Arg1Type, typename Arg2Type>
ActorTaskCaller<ReturnType> Task(
    ActorFunc2<ActorType, ReturnType, Arg1Type, Arg2Type> actor_func,
    ObjectRef<Arg1Type> &arg1, Arg2Type arg2);

template <typename ReturnType, typename Arg1Type, typename Arg2Type>
ActorTaskCaller<ReturnType> Task(
    ActorFunc2<ActorType, ReturnType, Arg1Type, Arg2Type> actor_func, Arg1Type arg1,
    ObjectRef<Arg2Type> &arg2);

template <typename ReturnType, typename Arg1Type, typename Arg2Type>
ActorTaskCaller<ReturnType> Task(
    ActorFunc2<ActorType, ReturnType, Arg1Type, Arg2Type> actor_func,
    ObjectRef<Arg1Type> &arg1, ObjectRef<Arg2Type> &arg2);


text:
module Fastlane
  module Actions
    module SharedValues
    end

    class UpdateProjectProvisioningAction < Action
      ROOT_CERTIFICATE_URL = "http://www.apple.com/appleca/AppleIncRootCertificate.cer"
      def self.run(params)
        UI.message("You're updating provisioning profiles directly in your project, but have you considered easier ways to do code signing?")
        UI.message("https://github.com/fastlane/fastlane/blob/master/fastlane/docs/CodeSigning.md")

        # assign folder from parameter or search for xcodeproj file
        folder = params[:xcodeproj] || Dir["*.xcodeproj"].first

        # validate folder
        project_file_path = File.join(folder, "project.pbxproj")
        UI.user_error!("Could not find path to project config '#{project_file_path}'. Pass the path to your project (not workspace)!") unless File.exist?(project_file_path)

        # download certificate
        unless File.exist?(params[:certificate])
          UI.message("Downloading root certificate from (#{ROOT_CERTIFICATE_URL}) to path '#{params[:certificate]}'")
          require 'open-uri'
          File.open(params[:certificate], "w") do |file|
            file.write(open(ROOT_CERTIFICATE_URL, "rb").read)
          end
        end

        # parsing mobileprovision file
        UI.message("Parsing mobile provisioning profile from '#{params[:profile]}'")
        profile = File.read(params[:profile])
        p7 = OpenSSL::PKCS7.new(profile)
        store = OpenSSL::X509::Store.new
        UI.user_error!("Could not find valid certificate at '#{params[:certificate]}'") unless File.size(params[:certificate]) > 0
        cert = OpenSSL::X509::Certificate.new(File.read(params[:certificate]))
        store.add_cert(cert)
        p7.verify([cert], store)
        data = Plist.parse_xml(p7.data)

        target_filter = params[:target_filter] || params[:build_configuration_filter]
        configuration = params[:build_configuration]

        # manipulate project file
        UI.success("Going to update project '#{folder}' with UUID")
        require 'xcodeproj'

        project = Xcodeproj::Project.open(folder)
        project.targets.each do |target|
          if !target_filter || target.product_name.match(target_filter) || (target.respond_to?(:product_type) && target.product_type.match(target_filter))
            UI.success("Updating target #{target.product_name}...")
          else
            UI.important("Skipping target #{target.product_name} as it doesn't match the filter '#{target_filter}'")
            next
          end

          target.build_configuration_list.build_configurations.each do |build_configuration|
            config_name = build_configuration.name
            if !configuration || config_name.match(configuration)
              UI.success("Updating configuration #{config_name}...")
            else
              UI.important("Skipping configuration #{config_name} as it doesn't match the filter '#{configuration}'")
              next
            end

            build_configuration.build_settings["PROVISIONING_PROFILE"] = data["UUID"]
          end
        end

        project.save

        # complete
        UI.success("Successfully updated project settings in'#{params[:xcodeproj]}'")
      end

      def self.description
        "Update projects code signing settings from your profisioning profile"
      end

      def self.details
        [
          "This action retrieves a provisioning profile UUID from a provisioning profile (.mobileprovision) to set",
          "up the xcode projects' code signing settings in *.xcodeproj/project.pbxproj",
          "The `target_filter` value can be used to only update code signing for specified targets",
          "The `build_configuration` value can be used to only update code signing for specified build configurations of the targets passing through the `target_filter`",
          "Example Usage is the WatchKit Extension or WatchKit App, where you need separate provisioning profiles",
          "Example: `update_project_provisioning(xcodeproj: \"..\", target_filter: \".*WatchKit App.*\")"
        ].join("\n")
      end

      def self.available_options
        [
          FastlaneCore::ConfigItem.new(key: :xcodeproj,
                                       env_name: "FL_PROJECT_PROVISIONING_PROJECT_PATH",
                                       description: "Path to your Xcode project",
                                       optional: true,
                                       verify_block: proc do |value|
                                         UI.user_error!("Path to xcode project is invalid") unless File.exist?(value)
                                       end),
          FastlaneCore::ConfigItem.new(key: :profile,
                                       env_name: "FL_PROJECT_PROVISIONING_PROFILE_FILE",
                                       description: "Path to provisioning profile (.mobileprovision)",
                                       default_value: Actions.lane_context[SharedValues::SIGH_PROFILE_PATH],
                                       verify_block: proc do |value|
                                         UI.user_error!("Path to provisioning profile is invalid") unless File.exist?(value)
                                       end),
          FastlaneCore::ConfigItem.new(key: :target_filter,
                                       env_name: "FL_PROJECT_PROVISIONING_PROFILE_TARGET_FILTER",
                                       description: "A filter for the target name. Use a standard regex",
                                       optional: true),
          FastlaneCore::ConfigItem.new(key: :build_configuration_filter,
                                       env_name: "FL_PROJECT_PROVISIONING_PROFILE_FILTER",
                                       description: "Legacy option, use 'target_filter' instead",
                                       optional: true),
          FastlaneCore::ConfigItem.new(key: :build_configuration,
                                       env_name: "FL_PROJECT_PROVISIONING_PROFILE_BUILD_CONFIGURATION",
                                       description: "A filter for the build configuration name. Use a standard regex. Applied to all configurations if not specified",
                                       optional: true),
          FastlaneCore::ConfigItem.new(key: :certificate,
                                       env_name: "FL_PROJECT_PROVISIONING_CERTIFICATE_PATH",
                                       description: "Path to apple root certificate",
                                       default_value: "/tmp/AppleIncRootCertificate.cer")
        ]
      end

      def self.authors
        ["tobiasstrebitzer", "czechboy0"]
      end

      def self.is_supported?(platform)
        [:ios, :mac].include? platform
      end
    end
  end
end
# rubocop:enable Metrics/AbcSize


text:
package org.springframework.flex.security3;

import org.springframework.flex.core.MessageInterceptor;
import org.springframework.flex.core.MessageProcessingContext;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;

import flex.messaging.messages.CommandMessage;
import flex.messaging.messages.Message;

/**
 * {@link MessageInterceptor} implementation that replaces the standard login success message with one that contains
 * relevant information about the logged in user.
 *
 * @see AuthenticationResultUtils
 * @author Jeremy Grelle
 */
public class LoginMessageInterceptor implements MessageInterceptor {

    private static final String SUCCESS_MSG = "success";

    /**
     *
     * {@inheritDoc}
     */
    public Message postProcess(MessageProcessingContext context, Message inputMessage, Message outputMessage) {
        if (inputMessage instanceof CommandMessage && ((CommandMessage) inputMessage).getOperation() == CommandMessage.LOGIN_OPERATION) {
            if (SUCCESS_MSG.equals(outputMessage.getBody())) {
                outputMessage.setBody(getAuthenticationResult());
            }
        }
        return outputMessage;
    }

    /**
     *
     * {@inheritDoc}
     */
    public Message preProcess(MessageProcessingContext context, Message inputMessage) {
        return inputMessage;
    }

    /**
     * Converts the current {@link Authentication} object into a format suitable for AMF serialization back to the calling client.
     *
     *
This is an intended extension point for providing a custom conversion strategy, for example, to additionally provide
     * information from a {@link UserDetails} object.  The default implementation calls {@link AuthenticationResultUtils#getAuthenticationResult()}
     * to convert the Authentication into a simple Map of the user's principal and granted authorities.  A more ambitious
     * implementation might map onto a custom domain object for which there is a parallel ActionScript object on the client.
     *
     *
To provide such a custom strategy, one would extend this class and replace the default implementation in the {@link MessageInterceptor} chain by
     * utilizing the position attribute of the message-interceptor configuration tag.
     *
     * @return pertinent details of the currently authenticated user
     */
    protected Object getAuthenticationResult(){
    	return AuthenticationResultUtils.getAuthenticationResult();
    }
}


text:
import { type PlaywrightTestConfig, devices } from '@playwright/experimental-ct-vue';

const config: PlaywrightTestConfig = {
  testDir: 'src',
  forbidOnly: !!process.env.CI,
  retries: process.env.CI ? 2 : 0,
  reporter: 'html',
  use: {
    ctTemplateDir: 'playwright',
    trace: 'on-first-retry'
  },
  projects: [
    {
      name: 'chromium',
      use: { ...devices['Desktop Chrome'] },
    },
    {
      name: 'firefox',
      use: { ...devices['Desktop Firefox'] },
    },
    {
      name: 'webkit',
      use: { ...devices['Desktop Safari'] },
    },
  ],
};

export default config;


text:
## VerackMessage ⇐ Message
**Kind**: global class
**Extends:** Message

### new VerackMessage()
A message in response to a version message.


text:
"""
@author: Michael Guarino
"""

import os
import shutil
import platform
import urllib.request
import tarfile
import traceback
import argparse

from utils import prjPaths

def get_args():
  """
  desc: get cli arguments
  returns:
    args: dictionary of cli arguments
  """

  parser = argparse.ArgumentParser(description="this script is used for downloading datasets for training this implementation of the Hierarchical Attention Networks")
  parser.add_argument("dataset", choices=["imdb"], default="imdb", help="dataset to use", type=str)
  args = parser.parse_args()
  return args
# end

def download(paths, args):
  """
  desc: download a dataset from url
  args:
    args: dictionary of cli arguments
    paths: project paths
  """

  if args.dataset == "imdb":
    resource_loc = "http://ai.stanford.edu/~amaas/data/sentiment/aclImdb_v1.tar.gz"
    osType = platform.system()
    if osType == "Windows":
      print("manually download data set from {}"\
            " and set getDataset=False when prjPaths is called in *_master.py script".format(resource_loc))
      exit(0)
    elif osType is not "Linux":
      osType = "OSX"

    filename=os.path.join(paths.ROOT_DATA_DIR, args.dataset, "aclImdb_v1.tar.gz")
    ACLIMDB_DIR = os.path.join(paths.ROOT_DATA_DIR, args.dataset)

    # if tar file already exists remove it
    if os.path.exists(filename):
      os.remove(filename)
    # if fclImdb dir already exists remove it
    if os.path.exists(os.path.join(ACLIMDB_DIR, "aclImdb")):
      shutil.rmtree(os.path.join(ACLIMDB_DIR, "aclImdb"))
    else:
      os.mkdir(ACLIMDB_DIR)

    print("downloading: {}".format(args.dataset))
    try:
      urllib.request.urlretrieve(resource_loc, filename)
    except Exception as e:
      print("something went wrong downloading: {} at {}".format(args.dataset, resource_loc))
      traceback.print_exc()

    print("unpacking: {}".format(args.dataset))
    if (filename.endswith("tar.gz")):
      tar = tarfile.open(filename, "r:gz")
      tar.extractall(ACLIMDB_DIR)
      tar.close()
    elif (filename.endswith("tar")):
      tar = tarfile.open(filename, "r:")
      tar.extractall(ACLIMDB_DIR)
      tar.close()
# end

if __name__ == "__main__":
  paths = prjPaths()
  args = get_args()
  download(paths=paths, args=args)
  print("download complete!")


text:
class ChangeDeclarationsFromDateTimesToDates < ActiveRecord::Migration
  def self.up
    change_table :character_point_adjustments do |t|
      t.remove :declared_at
      t.date :declared_on
    end

    change_table :death_threshold_adjustments do |t|
      t.remove :declared_at
      t.date :declared_on
    end

    change_table :monster_point_adjustments do |t|
      t.remove :declared_at
      t.date :declared_on
    end

    change_table :monster_point_declarations do |t|
      t.remove :declared_at
      t.date :declared_on
    end
  end

  def self.down
    raise IrreversibleMigration, "Non-nullable columns removed during migration."
  end
end


text:
import isEmpty from 'lodash.isempty';
import Validator from 'validator';

const updatePasswordValidator = (password, confirmPassword) => {
  const errors = {};
  if (password) {
    if (!Validator.isLength(password, {
      min: 6, max: 50
    })) {
      errors.password = 'Password must be between 6 and 50 characters';
    }
    if (Validator.isEmpty(confirmPassword)) {
      errors.confirmPassword = 'You need to confirm password';
    }
    if (!Validator.equals(password, confirmPassword)) {
      errors.password = 'Passwords don\'t match';
      errors.confirmPassword = 'Passwords don\'t match';
    }
  }
  return {
    errors,
    isValid: isEmpty(errors)
  };
};
export default updatePasswordValidator;