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.client;

import com.google.common.base.Splitter;
import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
import io.airlift.http.client.FullJsonResponseHandler;
import io.airlift.http.client.HttpClient;
import io.airlift.http.client.HttpClient.HttpResponseFuture;
import io.airlift.http.client.HttpStatus;
import io.airlift.http.client.Request;
import io.airlift.json.JsonCodec;
import io.airlift.units.Duration;

import javax.annotation.concurrent.ThreadSafe;

import java.io.Closeable;
import java.net.URI;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;

import static com.facebook.presto.client.PrestoHeaders.PRESTO_CLEAR_SESSION;
import static com.facebook.presto.client.PrestoHeaders.PRESTO_SET_SESSION;
import static com.google.common.base.MoreObjects.firstNonNull;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.net.HttpHeaders.USER_AGENT;
import static io.airlift.http.client.FullJsonResponseHandler.JsonResponse;
import static io.airlift.http.client.FullJsonResponseHandler.createFullJsonResponseHandler;
import static io.airlift.http.client.HttpStatus.Family;
import static io.airlift.http.client.HttpStatus.familyForStatusCode;
import static io.airlift.http.client.HttpUriBuilder.uriBuilderFrom;
import static io.airlift.http.client.Request.Builder.prepareDelete;
import static io.airlift.http.client.Request.Builder.prepareGet;
import static io.airlift.http.client.Request.Builder.preparePost;
import static io.airlift.http.client.StaticBodyGenerator.createStaticBodyGenerator;
import static io.airlift.http.client.StatusResponseHandler.StatusResponse;
import static io.airlift.http.client.StatusResponseHandler.createStatusResponseHandler;
import static java.lang.String.format;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.Objects.requireNonNull;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.MINUTES;

@ThreadSafe
public class StatementClient
        implements Closeable
{
    private static final Splitter SESSION_HEADER_SPLITTER = Splitter.on('=').limit(2).trimResults();
    private static final String USER_AGENT_VALUE = StatementClient.class.getSimpleName() +
            "/" +
            firstNonNull(StatementClient.class.getPackage().getImplementationVersion(), "unknown");

    private final HttpClient httpClient;
    private final FullJsonResponseHandler<QueryResults> responseHandler;
    private final boolean debug;
    private final String query;
    private final AtomicReference<QueryResults> currentResults = new AtomicReference<>();
    private final Map<String, String> setSessionProperties = new ConcurrentHashMap<>();
    private final Set<String> resetSessionProperties = Sets.newConcurrentHashSet();
    private final AtomicBoolean closed = new AtomicBoolean();
    private final AtomicBoolean gone = new AtomicBoolean();
    private final AtomicBoolean valid = new AtomicBoolean(true);
    private final String timeZoneId;

    public StatementClient(HttpClient httpClient, JsonCodec<QueryResults> queryResultsCodec, ClientSession session, String query)
    {
        requireNonNull(httpClient, "httpClient is null");
        requireNonNull(queryResultsCodec, "queryResultsCodec is null");
        requireNonNull(session, "session is null");
        requireNonNull(query, "query is null");

        this.httpClient = httpClient;
        this.responseHandler = createFullJsonResponseHandler(queryResultsCodec);
        this.debug = session.isDebug();
        this.timeZoneId = session.getTimeZoneId();
        this.query = query;

        Request request = buildQueryRequest(session, query);
        JsonResponse<QueryResults> response = httpClient.execute(request, responseHandler);

        if (response.getStatusCode() != HttpStatus.OK.code() || !response.hasValue()) {
            throw requestFailedException("starting query", request, response);
        }

        processResponse(response);
    }

    private static Request buildQueryRequest(ClientSession session, String query)
    {
        Request.Builder builder = preparePost()
                .setUri(uriBuilderFrom(session.getServer()).replacePath("/v1/statement").build())
                .setBodyGenerator(createStaticBodyGenerator(query, UTF_8));

        if (session.getUser() != null) {
            builder.setHeader(PrestoHeaders.PRESTO_USER, session.getUser());
        }
        if (session.getSource() != null) {
            builder.setHeader(PrestoHeaders.PRESTO_SOURCE, session.getSource());
        }
        if (session.getCatalog() != null) {
            builder.setHeader(PrestoHeaders.PRESTO_CATALOG, session.getCatalog());
        }
        if (session.getSchema() != null) {
            builder.setHeader(PrestoHeaders.PRESTO_SCHEMA, session.getSchema());
        }
        builder.setHeader(PrestoHeaders.PRESTO_TIME_ZONE, session.getTimeZoneId());
        builder.setHeader(PrestoHeaders.PRESTO_LANGUAGE, session.getLocale().toLanguageTag());
        builder.setHeader(USER_AGENT, USER_AGENT_VALUE);

        Map<String, String> property = session.getProperties();
        for (Entry<String, String> entry : property.entrySet()) {
            builder.addHeader(PrestoHeaders.PRESTO_SESSION, entry.getKey() + "=" + entry.getValue());
        }

        return builder.build();
    }

    public String getQuery()
    {
        return query;
    }

    public String getTimeZoneId()
    {
        return timeZoneId;
    }

    public boolean isDebug()
    {
        return debug;
    }

    public boolean isClosed()
    {
        return closed.get();
    }

    public boolean isGone()
    {
        return gone.get();
    }

    public boolean isFailed()
    {
        return currentResults.get().getError() != null;
    }

    public StatementStats getStats()
    {
        return currentResults.get().getStats();
    }

    public QueryResults current()
    {
        checkState(isValid(), "current position is not valid (cursor past end)");
        return currentResults.get();
    }

    public QueryResults finalResults()
    {
        checkState((!isValid()) || isFailed(), "current position is still valid");
        return currentResults.get();
    }

    public Map<String, String> getSetSessionProperties()
    {
        return ImmutableMap.copyOf(setSessionProperties);
    }

    public Set<String> getResetSessionProperties()
    {
        return ImmutableSet.copyOf(resetSessionProperties);
    }

    public boolean isValid()
    {
        return valid.get() && (!isGone()) && (!isClosed());
    }

    public boolean advance()
    {
        URI nextUri = current().getNextUri();
        if (isClosed() || (nextUri == null)) {
            valid.set(false);
            return false;
        }

        Request request = prepareGet()
                .setHeader(USER_AGENT, USER_AGENT_VALUE)
                .setUri(nextUri)
                .build();

        Exception cause = null;
        long start = System.nanoTime();
        long attempts = 0;

        do {
            // back-off on retry
            if (attempts > 0) {
                try {
                    MILLISECONDS.sleep(attempts * 100);
                }
                catch (InterruptedException e) {
                    try {
                        close();
                    }
                    finally {
                        Thread.currentThread().interrupt();
                    }
                    throw new RuntimeException("StatementClient thread was interrupted");
                }
            }
            attempts++;

            JsonResponse<QueryResults> response;
            try {
                response = httpClient.execute(request, responseHandler);
            }
            catch (RuntimeException e) {
                cause = e;
                continue;
            }

            if (response.getStatusCode() == HttpStatus.OK.code() && response.hasValue()) {
                processResponse(response);
                return true;
            }

            if (response.getStatusCode() != HttpStatus.SERVICE_UNAVAILABLE.code()) {
                throw requestFailedException("fetching next", request, response);
            }
        }
        while ((System.nanoTime() - start) < MINUTES.toNanos(2) && !isClosed());

        gone.set(true);
        throw new RuntimeException("Error fetching next", cause);
    }

    private void processResponse(JsonResponse<QueryResults> response)
    {
        for (String setSession : response.getHeaders().get(PRESTO_SET_SESSION)) {
            List<String> keyValue = SESSION_HEADER_SPLITTER.splitToList(setSession);
            if (keyValue.size() != 2) {
                continue;
            }
            setSessionProperties.put(keyValue.get(0), keyValue.size() > 1 ? keyValue.get(1) : "");
        }
        for (String clearSession : response.getHeaders().get(PRESTO_CLEAR_SESSION)) {
            resetSessionProperties.add(clearSession);
        }
        currentResults.set(response.getValue());
    }

    private RuntimeException requestFailedException(String task, Request request, JsonResponse<QueryResults> response)
    {
        gone.set(true);
        if (!response.hasValue()) {
            return new RuntimeException(format("Error %s at %s returned an invalid response: %s", task, request.getUri(), response), response.getException());
        }
        return new RuntimeException(format("Error %s at %s returned %s: %s", task, request.getUri(), response.getStatusCode(), response.getStatusMessage()));
    }

    public boolean cancelLeafStage(Duration timeout)
    {
        checkState(!isClosed(), "client is closed");

        URI uri = current().getPartialCancelUri();
        if (uri == null) {
            return false;
        }

        Request request = prepareDelete()
                .setHeader(USER_AGENT, USER_AGENT_VALUE)
                .setUri(uri)
                .build();

        HttpResponseFuture<StatusResponse> response = httpClient.executeAsync(request, createStatusResponseHandler());
        try {
            StatusResponse status = response.get(timeout.toMillis(), MILLISECONDS);
            return familyForStatusCode(status.getStatusCode()) == Family.SUCCESSFUL;
        }
        catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw Throwables.propagate(e);
        }
        catch (ExecutionException e) {
            throw Throwables.propagate(e.getCause());
        }
        catch (TimeoutException e) {
            return false;
        }
    }

    @Override
    public void close()
    {
        if (!closed.getAndSet(true)) {
            URI uri = currentResults.get().getNextUri();
            if (uri != null) {
                Request request = prepareDelete()
                        .setHeader(USER_AGENT, USER_AGENT_VALUE)
                        .setUri(uri)
                        .build();
                httpClient.executeAsync(request, createStatusResponseHandler());
            }
        }
    }
}


text:
#include "tensorflow/compiler/xla/client/lib/testing.h"

#include "tensorflow/compiler/xla/client/computation.h"
#include "tensorflow/compiler/xla/client/computation_builder.h"
#include "tensorflow/compiler/xla/execution_options_util.h"
#include "tensorflow/compiler/xla/literal_util.h"
#include "tensorflow/compiler/xla/shape_util.h"
#include "tensorflow/compiler/xla/statusor.h"
#include "tensorflow/compiler/xla/types.h"
#include "tensorflow/compiler/xla/util.h"
#include "tensorflow/core/lib/strings/strcat.h"
#include "tensorflow/core/platform/protobuf.h"
#include "tensorflow/core/platform/types.h"

namespace xla {

std::unique_ptr<GlobalData> MakeFakeDataOrDie(const Shape& shape,
                                              Client* client) {
  ComputationBuilder b(
      client,
      tensorflow::strings::StrCat("make_fake_", ShapeUtil::HumanString(shape)));
  // TODO(b/26811613): Replace this when RNG is supported on all backends.
  b.Broadcast(b.ConstantLiteral(Literal::One(shape.element_type())),
              AsInt64Slice(shape.dimensions()));
  Computation computation = b.Build().ConsumeValueOrDie();

  auto execution_options = CreateDefaultExecutionOptions();
  *execution_options.mutable_shape_with_output_layout() = shape;
  return client->Execute(computation, /*arguments=*/{}, &execution_options)
      .ConsumeValueOrDie();
}

std::vector<std::unique_ptr<GlobalData>> MakeFakeArgumentsOrDie(
    const Computation& computation, Client* client) {
  auto program_shape =
      client->GetComputationShape(computation).ConsumeValueOrDie();

  // For every (unbound) parameter that the computation wants, we manufacture
  // some arbitrary data so that we can invoke the computation.
  std::vector<std::unique_ptr<GlobalData>> fake_arguments;
  for (const Shape& parameter : program_shape->parameters()) {
    fake_arguments.push_back(MakeFakeDataOrDie(parameter, client));
  }

  return fake_arguments;
}

}  // namespace xla

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.Text;
using Alachisoft.NCache.Runtime.Exceptions;
using System.Runtime.Serialization;
using System.Security.Permissions;

namespace Alachisoft.NCache.Caching.Exceptions
{
    /// <summary>
    /// Thrown when an exception occurs during configuration. Likely causes are badly specified
    /// configuration strings.
    /// </summary>
    [Serializable]
    public class LicensingException : CacheException, ISerializable
    {
        /// <summary>
        /// default constructor.
        /// </summary>
        internal LicensingException() { }

        /// <summary>
        /// overloaded constructor, takes the reason as parameter.
        /// </summary>
        internal LicensingException(string reason)
            : base(reason)
        {
        }

        /// <summary>
        /// overloaded constructor.
        /// </summary>
        /// <param name="reason">reason for exception</param>
        /// <param name="inner">nested exception</param>
        internal LicensingException(string reason, Exception inner)
            : base(reason, inner)
        {
        }

        #region /                 --- ISerializable ---           /

        /// <summary>
        /// overloaded constructor, manual serialization.
        /// </summary>
        protected LicensingException(SerializationInfo info, StreamingContext context)
            : base(info, context)
        {
        }

        /// <summary>
        /// manual serialization
        /// </summary>
        /// <param name="info"></param>
        /// <param name="context"></param>
        [SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter = true)]
        void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
        {
            base.GetObjectData(info, context);
        }

        #endregion
    }
}


text:
package com.ctrip.xpipe.redis.console.service.meta.impl;

import com.ctrip.xpipe.redis.console.AbstractConsoleIntegrationTest;
import com.ctrip.xpipe.redis.console.migration.status.ClusterStatus;
import com.ctrip.xpipe.redis.console.model.ClusterTbl;
import com.ctrip.xpipe.redis.console.model.DcTbl;
import com.ctrip.xpipe.redis.console.model.MigrationClusterTbl;
import com.ctrip.xpipe.redis.console.service.migration.MigrationService;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;

import static org.mockito.Matchers.anyLong;
import static org.mockito.Mockito.when;

/**
 * @author wenchao.meng
 *
 * Mar 17, 2017
 */
public class ClusterMetaServiceImplTest extends AbstractConsoleIntegrationTest{

	@Autowired
	private ClusterMetaServiceImpl  clusterMetaServiceImpl;

	@Mock
	private MigrationService migrationService;

	@Before
	public void beforeClusterMetaServiceImplTest(){
		MockitoAnnotations.initMocks(this);
//		clusterMetaServiceImpl = new ClusterMetaServiceImpl();
		clusterMetaServiceImpl.setMigrationService(migrationService);
	}

	@Test
	public void testGetClusterMetaCurrentPrimaryDcMigrating(){

		long currentActiveDcId = randomInt();
		long clusterId = randomInt();
		long destinationDcId = currentActiveDcId + 1;
		long migrationEventId = randomInt();

		DcTbl dcTbl = new DcTbl();

		ClusterTbl clusterTbl = new ClusterTbl();
		clusterTbl.setId(clusterId);
		clusterTbl.setActivedcId(currentActiveDcId);
		clusterTbl.setStatus(ClusterStatus.Migrating.toString());
		clusterTbl.setMigrationEventId(migrationEventId);

		when(migrationService.findMigrationCluster(migrationEventId, clusterId)).thenReturn(new MigrationClusterTbl().setDestinationDcId(destinationDcId));

		dcTbl.setId(destinationDcId);
		Assert.assertEquals(destinationDcId, clusterMetaServiceImpl.getClusterMetaCurrentPrimaryDc(dcTbl, clusterTbl));

		dcTbl.setId(destinationDcId + 1);
		Assert.assertEquals(currentActiveDcId, clusterMetaServiceImpl.getClusterMetaCurrentPrimaryDc(dcTbl, clusterTbl));
		dcTbl.setId(currentActiveDcId);
		Assert.assertEquals(currentActiveDcId, clusterMetaServiceImpl.getClusterMetaCurrentPrimaryDc(dcTbl, clusterTbl));

	}

	@Test
	public void testGetClusterMetaCurrentPrimaryDcNotMigrating(){

		long currentActiveDcId = randomInt();
		long clusterId = randomInt();
		long destinationDcId = currentActiveDcId + 1;

		DcTbl dcTbl = new DcTbl();

		ClusterTbl clusterTbl = new ClusterTbl();
		clusterTbl.setId(clusterId);
		clusterTbl.setActivedcId(currentActiveDcId);

		when(migrationService.findMigrationCluster(anyLong(), anyLong())).thenReturn(new MigrationClusterTbl().setDestinationDcId(destinationDcId));

		dcTbl.setId(destinationDcId);
		for(ClusterStatus clusterStatus : ClusterStatus.values()){
			if(clusterStatus == ClusterStatus.Migrating){
				continue;
			}
			clusterTbl.setStatus(clusterStatus.toString());
			Assert.assertEquals(currentActiveDcId, clusterMetaServiceImpl.getClusterMetaCurrentPrimaryDc(dcTbl, clusterTbl));
		}
	}

	@Test
	public void testCurrentPrimaryDcPublish() {
		long currentActiveDcId = 1;
		long clusterId = randomInt();
		long destinationDcId = 2;
		long migrationEventId = randomInt();

		DcTbl dcTbl = new DcTbl();
		dcTbl.setId(destinationDcId);

		ClusterTbl clusterTbl = new ClusterTbl();
		clusterTbl.setId(clusterId);
		clusterTbl.setActivedcId(currentActiveDcId);
		clusterTbl.setStatus(ClusterStatus.Migrating.name());
		clusterTbl.setMigrationEventId(migrationEventId);

		when(migrationService.findMigrationCluster(migrationEventId, clusterId)).thenReturn(new MigrationClusterTbl().setDestinationDcId(destinationDcId));
		long target = clusterMetaServiceImpl.getClusterMetaCurrentPrimaryDc(dcTbl, clusterTbl);
		Assert.assertEquals(destinationDcId, target);
	}

}


text:
package net.tokensmith.hello.controller;

import io.netty.handler.codec.http.cookie.Cookie;
import net.tokensmith.jwt.config.JwtAppFactory;
import net.tokensmith.jwt.entity.jwt.JsonWebToken;
import net.tokensmith.jwt.serialization.JwtSerde;
import net.tokensmith.otter.controller.entity.StatusCode;
import net.tokensmith.otter.security.csrf.CsrfClaims;
import org.asynchttpclient.AsyncHttpClient;
import org.asynchttpclient.ListenableFuture;
import org.asynchttpclient.Param;
import org.asynchttpclient.Response;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import suite.IntegrationTestSuite;
import suite.ServletContainerTest;

import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.junit.Assert.assertThat;

@Category(ServletContainerTest.class)
public class LoginResourceTest {
    private static URI BASE_URI;

    @BeforeClass
    public static void beforeClass() {
        BASE_URI = IntegrationTestSuite.getServletContainerURI();
    }

    @Test
    public void getShouldReturn200() throws Exception {
        String loginURI = BASE_URI.toString() + "login";

        ListenableFuture<Response> f = IntegrationTestSuite.getHttpClient()
                .prepareGet(loginURI)
                .addHeader("Content-Type", "text/html")
                .execute();

        Response response = f.get();

        String errorMsg = "Attempted GET " + loginURI;
        assertThat(errorMsg, response.getStatusCode(), is(StatusCode.OK.getCode()));

        // there should be a csrf cookie
        Cookie csrfCookie = null;
        for(Cookie cookie: response.getCookies()){
            if("csrfToken".equals(cookie.name())) {
                csrfCookie = cookie;
                break;
            }
        }
        assertThat(csrfCookie, is(notNullValue()));

        // there should be a csrf challenge in the form
        String csrfInput =  "<input id=\"csrfToken\" type=\"hidden\" name=\"csrfToken\" value=\"";
        assertThat(response.getResponseBody().contains(csrfInput), is(true));

        // get the csrf value from the form.
        Pattern csrfPattern = Pattern.compile(".*\"csrfToken\" value=\"([^\"]*)\".*", Pattern.DOTALL);
        Matcher matcher = csrfPattern.matcher(response.getResponseBody());
        assertThat(matcher.matches(), is(true));
        String formCsrfValue = matcher.group(1);

        // cookie csrf value should match the form's value.
        JwtAppFactory jwtAppFactory = new JwtAppFactory();
        JwtSerde jwtSerializer = jwtAppFactory.jwtSerde();
        JsonWebToken<CsrfClaims> cookieJwt = jwtSerializer.stringToJwt(csrfCookie.value(), CsrfClaims.class);
        CsrfClaims cookieClaims = cookieJwt.getClaims();

        JsonWebToken<CsrfClaims> formJwt = jwtSerializer.stringToJwt(formCsrfValue, CsrfClaims.class);
        CsrfClaims formClaims = formJwt.getClaims();

        assertThat(cookieClaims.getChallengeToken(), is(formClaims.getChallengeToken()));
        assertThat(cookieClaims.getNoise(), is(not(formClaims.getNoise())));
    }

    @Test
    public void postShouldReturn200() throws Exception {
        String loginURI = BASE_URI.toString() + "login";

        AsyncHttpClient httpClient = IntegrationTestSuite.getHttpClient();

        // this is the GET request to get the csrf cookie & form value
        ListenableFuture<Response> f = httpClient
                .prepareGet(loginURI)
                .addHeader("Content-Type", "text/html")
                .execute();

        Response getResponse = f.get();

        String errorMsg = "Attempted GET " + loginURI;
        assertThat(errorMsg, getResponse.getStatusCode(), is(StatusCode.OK.getCode()));

        // get the csrf value from the form.
        Pattern csrfPattern = Pattern.compile(".*\"csrfToken\" value=\"([^\"]*)\".*", Pattern.DOTALL);
        Matcher matcher = csrfPattern.matcher(getResponse.getResponseBody());
        assertThat(matcher.matches(), is(true));
        String formCsrfValue = matcher.group(1);

        List<Param> formData = new ArrayList<>();
        formData.add(new Param("email", "obi-wan@tokensmith.net"));
        formData.add(new Param("password", "foo"));
        formData.add(new Param("csrfToken", formCsrfValue));

        // this is the POST request
        f = httpClient
                .preparePost(loginURI)
                .addHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8;")
                .setFormParams(formData)
                .setCookies(getResponse.getCookies())
                .execute();

        Response postResponse = f.get();

        errorMsg = "Attempted POST " + loginURI;
        assertThat(errorMsg, postResponse.getStatusCode(), is(StatusCode.OK.getCode()));
    }

    @Test
    public void postWhenNoCSRFCookieShouldReturn403() throws Exception {
        String loginURI = BASE_URI.toString() + "login";

        List<Param> formData = new ArrayList<>();
        formData.add(new Param("email", "obi-wan@tokensmith.net"));
        formData.add(new Param("password", "foo"));
        formData.add(new Param("csrfToken", "foo"));

        AsyncHttpClient httpClient = IntegrationTestSuite.getHttpClient();

        // this is the POST request
        ListenableFuture<Response> f = httpClient
                .preparePost(loginURI)
                .addHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8;")
                .setFormParams(formData)
                .execute();

        Response postResponse = f.get();

        String errorMsg = "Attempted POST " + loginURI;
        assertThat(errorMsg, postResponse.getStatusCode(), is(StatusCode.FORBIDDEN.getCode()));
    }
}


text:
(function () {
 'use strict';

  angular.module('horizon.framework.util', [
    'horizon.framework.util.bind-scope',
    'horizon.framework.util.filters',
    'horizon.framework.util.form',
    'horizon.framework.util.i18n',
    'horizon.framework.util.workflow',
    'horizon.framework.util.validators'
  ])
    .constant('horizon.framework.util.basePath', '/static/framework/util/');

})();


text:
if [ "x$1" == "x" ]; then
  echo "Specify the name of the module you want to generate."
  read -p "Use author-module format, ie: example42-apache: " fullmodule
else
  fullmodule=$1
  template=${2:-https://github.com/puppetlabs/pdk-templates}
fi
# author=$(echo $fullmodule | cut -d '-' -f 1)
module=$(echo $fullmodule | cut -d '-' -f 2)

echo "Generating new module with pdk"
pdk new module $module --template-url=$template


text:
package io.cdap.directives.date;

import io.cdap.cdap.api.annotation.Description;
import io.cdap.cdap.api.annotation.Name;
import io.cdap.cdap.api.annotation.Plugin;
import io.cdap.wrangler.api.Arguments;
import io.cdap.wrangler.api.Directive;
import io.cdap.wrangler.api.DirectiveExecutionException;
import io.cdap.wrangler.api.DirectiveParseException;
import io.cdap.wrangler.api.ExecutorContext;
import io.cdap.wrangler.api.Row;
import io.cdap.wrangler.api.annotations.Categories;
import io.cdap.wrangler.api.parser.ColumnName;
import io.cdap.wrangler.api.parser.Text;
import io.cdap.wrangler.api.parser.TokenType;
import io.cdap.wrangler.api.parser.UsageDefinition;

import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/**
 * A directive for managing date formats.
 */
@Plugin(type = Directive.TYPE)
@Name("format-date")
@Categories(categories = {"date", "format"})
@Description("Formats a column using a date-time format. Use 'parse-as-date` beforehand.")
public class FormatDate implements Directive {
  public static final String NAME = "format-date";
  private String format;
  private String column;
  private DateTimeFormatter destinationFmt;

  @Override
  public UsageDefinition define() {
    UsageDefinition.Builder builder = UsageDefinition.builder(NAME);
    builder.define("column", TokenType.COLUMN_NAME);
    builder.define("format", TokenType.TEXT);
    return builder.build();
  }

  @Override
  public void initialize(Arguments args) throws DirectiveParseException {
    this.column = ((ColumnName) args.value("column")).value();
    this.format = ((Text) args.value("format")).value();
    this.destinationFmt = DateTimeFormatter.ofPattern(this.format);
  }

  @Override
  public void destroy() {
    // no-op
  }

  @Override
  public List<Row> execute(List<Row> rows, ExecutorContext context) throws DirectiveExecutionException {
    List<Row> results = new ArrayList<>();
    for (Row row : rows) {
      Row dt = new Row(row);
      int idx = dt.find(column);

      if (idx == -1) {
        throw new DirectiveExecutionException(toString() + " : '" + column + "' column is not defined in the row. " +
                                                "Please check the wrangling step."
        );
      }

      Object object = row.getValue(idx);

      if (object != null) {
        ZonedDateTime zonedDateTime;
        if (object instanceof LocalDate) {
          zonedDateTime = ((LocalDate) object).atStartOfDay(ZoneId.ofOffset("UTC", ZoneOffset.UTC));
        } else if (object instanceof ZonedDateTime) {
          zonedDateTime = (ZonedDateTime) object;
        } else {
          throw new DirectiveExecutionException(
            String.format("%s : Invalid type '%s' of column '%s'. Apply 'parse-as-date' directive first.", toString(),
                          object.getClass().getName(), column)
          );
        }

        dt.setValue(idx, destinationFmt.format(zonedDateTime));
      }

      results.add(dt);
    }
    return results;
  }
}


text:
/**
 * Spring Boot developer tools.
 */
package org.springframework.boot.devtools;


text:
PLEASE NOTE: This document applies to the HEAD of the source tree

If you are using a released version of Kubernetes, you should
refer to the docs that go with that version.

Documentation for other releases can be found at
[releases.k8s.io](http://releases.k8s.io).

--

**Stop. This guide has been superseded by [Minikube](https://github.com/kubernetes/minikube) which is the recommended method of running Kubernetes on your local machine.**

### Requirements

#### Linux

Not running Linux? Consider running Linux in a local virtual machine with [vagrant](https://www.vagrantup.com/), or on a cloud provider like Google Compute Engine

#### Docker

At least [Docker](https://docs.docker.com/installation/#installation)
1.8.3+. Ensure the Docker daemon is running and can be contacted (try `docker
ps`).  Some of the Kubernetes components need to run as root, which normally
works fine with docker.

#### etcd

You need an [etcd](https://github.com/coreos/etcd/releases) in your path, please make sure it is installed and in your ``$PATH``.

#### go

You need [go](https://golang.org/doc/install) at least 1.4+ in your path, please make sure it is installed and in your ``$PATH``.

### Starting the cluster

First, you need to [download Kubernetes](http://kubernetes.io/docs/getting-started-guides/binary_release/). Then open a separate tab of your terminal
and run the following (since one needs sudo access to start/stop Kubernetes daemons, it is easier to run the entire script as root):

```shell
cd kubernetes
hack/local-up-cluster.sh
```

This will build and start a lightweight local cluster, consisting of a master
and a single node. Type Control-C to shut it down.

You can use the cluster/kubectl.sh script to interact with the local cluster. hack/local-up-cluster.sh will
print the commands to run to point kubectl at the local cluster.

### Running a container

Your cluster is running, and you want to start running containers!

You can now use any of the cluster/kubectl.sh commands to interact with your local setup.

```shell
export KUBERNETES_PROVIDER=local
cluster/kubectl.sh get pods
cluster/kubectl.sh get services
cluster/kubectl.sh get deployments
cluster/kubectl.sh run my-nginx --image=nginx --replicas=2 --port=80

## begin wait for provision to complete, you can monitor the docker pull by opening a new terminal
  sudo docker images
  ## you should see it pulling the nginx image, once the above command returns it
  sudo docker ps
  ## you should see your container running!
  exit
## end wait

## create a service for nginx, which serves on port 80
cluster/kubectl.sh expose deployment my-nginx --port=80 --name=my-nginx

## introspect Kubernetes!
cluster/kubectl.sh get pods
cluster/kubectl.sh get services
cluster/kubectl.sh get deployments

## Test the nginx service with the IP/port from "get services" command
curl http://10.X.X.X:80/
```

### Running a user defined pod

Note the difference between a [container](http://kubernetes.io/docs/user-guide/containers/)
and a [pod](http://kubernetes.io/docs/user-guide/pods/). Since you only asked for the former, Kubernetes will create a wrapper pod for you.
However you cannot view the nginx start page on localhost. To verify that nginx is running you need to run `curl` within the docker container (try `docker exec`).

You can control the specifications of a pod via a user defined manifest, and reach nginx through your browser on the port specified therein:

```shell
cluster/kubectl.sh create -f docs/user-guide/pod.yaml
```

Congratulations!

### FAQs

#### I cannot reach service IPs on the network.

Some firewall software that uses iptables may not interact well with
kubernetes.  If you have trouble around networking, try disabling any
firewall or other iptables-using systems, first.  Also, you can check
if SELinux is blocking anything by running a command such as `journalctl --since yesterday | grep avc`.

By default the IP range for service cluster IPs is 10.0.*.* - depending on your
docker installation, this may conflict with IPs for containers.  If you find
containers running with IPs in this range, edit hack/local-cluster-up.sh and
change the service-cluster-ip-range flag to something else.

#### I changed Kubernetes code, how do I run it?

```shell
cd kubernetes
hack/build-go.sh
hack/local-up-cluster.sh
```

#### kubectl claims to start a container but `get pods` and `docker ps` don't show it.

One or more of the Kubernetes daemons might've crashed. Tail the [logs](http://kubernetes.io/docs/admin/cluster-troubleshooting/#looking-at-logs) of each in /tmp.

```shell
$ ls /tmp/kube*.log
$ tail -f /tmp/kube-apiserver.log
```

#### The pods fail to connect to the services by host names

The local-up-cluster.sh script doesn't start a DNS service. Similar situation can be found [here](http://issue.k8s.io/6667). You can start a manually.

[![Analytics](https://kubernetes-site.appspot.com/UA-36037335-10/GitHub/docs/devel/local-cluster/local.md?pixel)]()


text:
EXTERNC int cbor_version_major()
{
    return LIBRARY_VERSION_MAJOR;
}

EXTERNC int cbor_version_minor()
{
    return LIBRARY_VERSION_MINOR;
}

EXTERNC int cbor_version_patch()
{
    return LIBRARY_VERSION_PATCH;
}


text:
module Frontify
  module ApplicationHelper
  end
end


text:
module Graphics.Vty.Widgets.Builder.Handlers.Fixed
    ( handlers
    )
where

import Control.Applicative ((<$>), (<*>))
import Graphics.Vty.Widgets.Builder.Types
import Graphics.Vty.Widgets.Builder.GenLib
import qualified Graphics.Vty.Widgets.Builder.Validation as V
import qualified Graphics.Vty.Widgets.Builder.SrcHelpers as S
import qualified Language.Haskell.Exts as Hs

handlers :: [WidgetElementHandler]
handlers = [ handleVFixed
           , handleHFixed
           , handleBoxFixed
           ]

handleVFixed :: WidgetElementHandler
handleVFixed =
    WidgetElementHandler genSrc doValidate "vFixed"
        where
          doValidate s = (,)
                         <$> V.requiredInt s "height"
                         <*> V.firstChildWidget s

          genSrc nam (height, ch) = do
            chNam <- newEntry (widgetLikeName ch)
            gen ch chNam
            chType <- getWidgetStateType chNam

            append $ S.bind nam "vFixed" [S.mkInt height, S.expr chNam]
            return $ declareWidget nam $
                   S.parseType $ "VFixed (" ++ Hs.prettyPrint chType ++ ")"

handleHFixed :: WidgetElementHandler
handleHFixed =
    WidgetElementHandler genSrc doValidate "hFixed"
        where
          doValidate s = (,)
                         <$> V.requiredInt s "width"
                         <*> V.firstChildWidget s

          genSrc nam (width, ch) = do
            chNam <- newEntry (widgetLikeName ch)
            gen ch chNam
            chType <- getWidgetStateType chNam

            append $ S.bind nam "hFixed" [S.mkInt width, S.expr chNam]
            return $ declareWidget nam $
                   S.parseType $ "HFixed (" ++ Hs.prettyPrint chType ++ ")"

handleBoxFixed :: WidgetElementHandler
handleBoxFixed =
    WidgetElementHandler genSrc doValidate "boxFixed"
        where
          doValidate s = (,,)
                         <$> V.requiredInt s "width"
                         <*> V.requiredInt s "height"
                         <*> V.firstChildWidget s

          genSrc nam (width, height, ch) = do
            chNam <- newEntry (widgetLikeName ch)
            gen ch chNam
            chType <- getWidgetStateType chNam

            append $ S.bind nam "boxFixed" [S.mkInt width, S.mkInt height, S.expr chNam]
            return $ declareWidget nam $
                   S.parseType $ "VFixed (HFixed (" ++ Hs.prettyPrint chType ++ "))"


text:
module BencodeSpec
  ( main
  , spec
  ) where

import BType
import Bencode
import Test.Hspec

import Data.ByteString.Char8 (pack)

-- `main` is here so that this module can be run from GHCi on its own. It
-- is not needed for automatic spec discovery.
main :: IO ()
main = hspec spec

spec :: Spec
spec = do
  describe "Integer encoding and decoding" $ do
    it "should encode and decode integers" $ do
      let expected = pack "i3e"
      let bin = BInteger 3
      encode bin `shouldBe` expected
      decode expected `shouldBe` Right bin
    it "should encode and decode negative integers" $ do
      let expected = pack "i-3e"
          bin = BInteger (-3)
      encode bin `shouldBe` expected
      decode expected `shouldBe` Right bin
    it "should not pad integers with 0s" $ do
      let expected = pack "i3e"
          bin = BInteger 0003
      encode bin `shouldBe` expected
      decode expected `shouldBe` Right bin
  describe "String encoding and decoding" $ do
    it "should encode and decode strings" $ do
      let expected = pack "4:spam"
          bin = BString $ pack "spam"
      encode bin `shouldBe` expected
      decode expected `shouldBe` Right bin
    it "should encode and decode the empty string" $ do
      let expected = pack "0:"
          bin = BString $ pack ""
      encode bin `shouldBe` expected
      decode expected `shouldBe` Right bin
  describe "List encoding and decoding" $ do
    it "should encode and decode lists of one type" $ do
      let expected = pack "li3ei4ei5ee"
          bin = BList [BInteger 3, BInteger 4, BInteger 5]
      encode bin `shouldBe` expected
      decode expected `shouldBe` Right bin
    it "should encode and decode lists of mixed type" $ do
      let expected = pack "l4:spami3e4:eggse"
          bin = BList [BString $ pack "spam", BInteger 3, BString $ pack "eggs"]
      encode bin `shouldBe` expected
      decode expected `shouldBe` Right bin
    it "should encode and decode an empty list" $ do
      let expected = pack "le"
          bin = BList []
      encode bin `shouldBe` expected
      decode expected `shouldBe` Right bin
    it "should encode and decode a list of lists" $ do
      let expected = pack "l4:spamli3ei4eee"
          bin = BList [BString $ pack "spam", BList [BInteger 3, BInteger 4]]
      encode bin `shouldBe` expected
      decode expected `shouldBe` Right bin
    it "should encode and decode a list of dictionaries" $ do
      let expected = pack "ld3:cow3:mooed3:cow3:mooee"
          bin =
            BList
              [ BDict [(pack "cow", BString $ pack "moo")]
              , BDict [(pack "cow", BString $ pack "moo")]
              ]
      encode bin `shouldBe` expected
      decode expected `shouldBe` Right bin
  describe "Dictionary encoding and decoding" $ do
    it "should encode and decode a dictionary with an integer value" $ do
      let expected = pack "d3:fooi3ee"
          bin = BDict [(pack "foo", BInteger 3)]
      encode bin `shouldBe` expected
      decode expected `shouldBe` Right bin
    it "should encode and decode a dictionary with a string value" $ do
      let expected = pack "d3:foo3:bare"
          bin = BDict [(pack "foo", BString $ pack "bar")]
      encode bin `shouldBe` expected
      decode expected `shouldBe` Right bin
    it "should encode and decode a dictionary with a list value" $ do
      let expected = pack "d3:fooli3eee"
          bin = BDict [(pack "foo", BList [BInteger 3])]
      encode bin `shouldBe` expected
      decode expected `shouldBe` Right bin
    it "should encode and decode a dictionary with a dictionary value" $ do
      let expected = pack "d3:food3:bari3eee"
          bin = BDict [(pack "foo", BDict [(pack "bar", BInteger 3)])]
      encode bin `shouldBe` expected
      decode expected `shouldBe` Right bin
    it "should encode and decode an empty dictionary" $ do
      let expected = pack "de"
          bin = BDict []
      encode bin `shouldBe` expected
      decode expected `shouldBe` Right bin


text:
Web portal for managing grades and registration for students and teachers of IIT Mandi( Not in production)

#####################################Instruction for installing the game#######################################

Step 1. Install xampp server on your machine
Step 2. Copy folder cyber into the root directory of your xampp server i.e. for windows C:\\xampp\htdocs\
	for linux \opt\lampp\htdocs
	or in some linux \var\www\html\
Step 3.( In case of Linux)
	give folder the root permission by doing chmod 777 -R /opt/lampp/htdocs/cyber/
	(In case of windows )
	No such thing required
Step 4. Install the database in the xampp server
	start xampp server with apache and mysq service
	Go to browser open localhost/phpmyadmin
	Create a database named "project" or any name of your choice
	Open the Sql prompt on the same page for "project" database
	paste the content of database file final.sql provided in database folder outside of this directory
	Enter Go.
Step 5. Change the credentials in configuration file
	open final/connect.php
	change the following according to your setting of the server and database(If you have changed them)
	$db_host		= 'localhost';
	$db_user		= 'root';
	$db_pass		= '';
	$db_database	= 'project';
Step 7. Now you are ready with the deployment
Step 8. There is no custom way defined in this web app to register user.
For this purpose you need to go in the database user table and create one for yourself or you can see existing users as well there and use them.

#### For any problem and query contact 1308js@gmail.com.


text:
/****************************************************************************
** Meta object code from reading C++ file 'addstationdlg.h'
**
** Created by: The Qt Meta Object Compiler version 67 (Qt 5.7.0)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/

#include "../addstationdlg.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'addstationdlg.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.7.0. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif

QT_BEGIN_MOC_NAMESPACE
struct qt_meta_stringdata_AddStationDlg_t {
    QByteArrayData data[5];
    char stringdata0[53];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
    Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
    qptrdiff(offsetof(qt_meta_stringdata_AddStationDlg_t, stringdata0) + ofs \
        - idx * sizeof(QByteArrayData)) \
    )
static const qt_meta_stringdata_AddStationDlg_t qt_meta_stringdata_AddStationDlg = {
    {
QT_MOC_LITERAL(0, 0, 13), // "AddStationDlg"
QT_MOC_LITERAL(1, 14, 13), // "getTrainnum_2"
QT_MOC_LITERAL(2, 28, 0), // ""
QT_MOC_LITERAL(3, 29, 1), // "s"
QT_MOC_LITERAL(4, 31, 21) // "on_pushButton_clicked"

    },
    "AddStationDlg\0getTrainnum_2\0\0s\0"
    "on_pushButton_clicked"
};
#undef QT_MOC_LITERAL

static const uint qt_meta_data_AddStationDlg[] = {

 // content:
       7,       // revision
       0,       // classname
       0,    0, // classinfo
       2,   14, // methods
       0,    0, // properties
       0,    0, // enums/sets
       0,    0, // constructors
       0,       // flags
       0,       // signalCount

 // slots: name, argc, parameters, tag, flags
       1,    1,   24,    2, 0x0a /* Public */,
       4,    0,   27,    2, 0x08 /* Private */,

 // slots: parameters
    QMetaType::Void, QMetaType::QString,    3,
    QMetaType::Void,

       0        // eod
};

void AddStationDlg::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
    if (_c == QMetaObject::InvokeMetaMethod) {
        AddStationDlg *_t = static_cast<AddStationDlg *>(_o);
        Q_UNUSED(_t)
        switch (_id) {
        case 0: _t->getTrainnum_2((*reinterpret_cast< QString(*)>(_a[1]))); break;
        case 1: _t->on_pushButton_clicked(); break;
        default: ;
        }
    }
}

const QMetaObject AddStationDlg::staticMetaObject = {
    { &QDialog::staticMetaObject, qt_meta_stringdata_AddStationDlg.data,
      qt_meta_data_AddStationDlg,  qt_static_metacall, Q_NULLPTR, Q_NULLPTR}
};

const QMetaObject *AddStationDlg::metaObject() const
{
    return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}

void *AddStationDlg::qt_metacast(const char *_clname)
{
    if (!_clname) return Q_NULLPTR;
    if (!strcmp(_clname, qt_meta_stringdata_AddStationDlg.stringdata0))
        return static_cast<void*>(const_cast< AddStationDlg*>(this));
    return QDialog::qt_metacast(_clname);
}

int AddStationDlg::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
    _id = QDialog::qt_metacall(_c, _id, _a);
    if (_id < 0)
        return _id;
    if (_c == QMetaObject::InvokeMetaMethod) {
        if (_id < 2)
            qt_static_metacall(this, _c, _id, _a);
        _id -= 2;
    } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
        if (_id < 2)
            *reinterpret_cast<int*>(_a[0]) = -1;
        _id -= 2;
    }
    return _id;
}
QT_END_MOC_NAMESPACE


text:
package com.atypon.wayf.facade.impl;

import com.atypon.wayf.data.device.Device;
import com.atypon.wayf.data.identity.IdentityProvider;
import com.atypon.wayf.data.identity.IdentityProviderQuery;
import com.atypon.wayf.data.identity.external.IdPExternalId;
import com.atypon.wayf.facade.IdentityProviderFacade;
import io.reactivex.Completable;
import io.reactivex.Observable;
import io.reactivex.Single;

import java.util.Collection;
import java.util.LinkedList;
import java.util.List;

public class IdentityProviderFacadeMockImpl implements IdentityProviderFacade {
    @Override
    public Single<IdentityProvider> create(IdentityProvider identityProvider) {
        return null;
    }

    @Override
    public Single<IdentityProvider> read(Long id) {
        return null;
    }

    @Override
    public Observable<IdentityProvider> filter(IdentityProviderQuery filter) {
        Long[] idpIds = filter.getIds();
        List<IdentityProvider> idps = new LinkedList<>();
        for (Long idpId : idpIds) {
            IdentityProvider idp = new IdentityProvider();
            idp.setId(idpId);
            idps.add(idp);
        }
        return Observable.fromIterable(idps);
    }

    @Override
    public Single<IdentityProvider> resolve(IdentityProvider identityProvider) {
        return null;
    }

    @Override
    public Completable blockIdentityProviderForLocalId(String localId, Long idpId) {
        return null;
    }

    @Override
    public Completable blockIdentityProviderForGlobalId(String globalId, Long idpId) {
        return null;
    }

    @Override
    public Single<IdentityProvider> recordIdentityProviderUse(String localId, IdentityProvider identityProvider) {
        return null;
    }

    @Override
    public Single<IdentityProvider> resolveIdpExternalIds(IdentityProvider identityProvider, List<IdPExternalId> externalIds) {
        return null;
    }

    @Override
    public Completable blockIdentityProviderForDevice(Device device, Long idpId) {
        return null;
    }
}


text:
//
//  TinyHTTPServerForUnity.cs
//
//  github:
//    https://github.com/yoggy/unity_test/test57_httpserver/Assets/Scripts/TinyWebSocketServerForUnity.cs
//
//  libraries:
//    WebSocketSharp https://github.com/sta/websocket-sharp
//
//  license:
//    Copyright(c) 2019 yoggy<yoggy0@gmail.com>
//    Released under the MIT license
//    http://opensource.org/licenses/mit-license.php;
//
using System;
using System.Collections;
using System.Threading;
using UnityEngine;
using UnityEngine.Events;

using WebSocketSharp;
using WebSocketSharp.Net;
using WebSocketSharp.Server;

[System.Serializable]
public class OnMessage : UnityEvent<string> { }

[DisallowMultipleComponent]
public class TinyWebSocketServerForUnity : SingletonMonoBehaviour<TinyWebSocketServerForUnity>
{
    public int port = 10081;
    public OnLoggingEvent on_logging_event;
    public OnMessage on_message;

    WebSocketServer websocket_server;
    bool loop_flag = true;

    SynchronizationContext serialization_context;

    void Start()
    {
        serialization_context = SynchronizationContext.Current;

        websocket_server = new WebSocketServer(port);
        websocket_server.AddWebSocketService<TinyWebSocketClient>("/");
        websocket_server.Start();
        Debug.Log("websocket_server.Start()");
    }

    void OnDestroy()
    {
        websocket_server.Stop();
        Debug.Log("websocket_server.Stop()");
    }

    public static void Log(string msg)
    {
        var websocketserver = TinyWebSocketServerForUnity.Instance;
        websocketserver.serialization_context.Post(__ =>
        {
            Debug.Log(msg);
            websocketserver.on_logging_event.Invoke("ws", msg);
        }, null);
    }

    public static void OnMessage(string msg)
    {
        var websocketserver = TinyWebSocketServerForUnity.Instance;
        websocketserver.serialization_context.Post(__ =>
        {
            Debug.Log(msg);
            websocketserver.on_message.Invoke(msg);
        }, null);
    }

    public void BroadcastMessage(string msg)
    {
        serialization_context.Post(__ =>
        {
            Debug.Log("TinyWebSocketServerForUnity.BroadcastMessage msg=" + msg);
            websocket_server.WebSocketServices.Broadcast(msg);
        }, null);
    }
}

public class TinyWebSocketClient : WebSocketBehavior
{
    protected override void OnOpen()
    {
        TinyWebSocketServerForUnity.Log("TinyWebSocketClient.OnOpen() uri=" + Context.RequestUri);
    }

    protected override void OnMessage(MessageEventArgs evt)
    {
        TinyWebSocketServerForUnity.Log("TinyWebSocketClient.OnMessage : evt.Data=" + evt.Data);
        TinyWebSocketServerForUnity.OnMessage(evt.Data);
    }

    protected override void OnClose(CloseEventArgs evt)
    {
        TinyWebSocketServerForUnity.Log("TinyWebSocketClient.OnClose : evt=" + evt);
    }

    protected override void OnError(ErrorEventArgs evt)
    {
        TinyWebSocketServerForUnity.Log("TinyWebSocketClient.OnError : evt=" + evt);
    }
}


text:
package com.rotterdam.service;

import com.rotterdam.dto.SettingsDto;
import com.rotterdam.model.dao.PeriodDao;
import com.rotterdam.model.dao.WeekDao;
import com.rotterdam.model.entity.Period;
import com.rotterdam.model.entity.Week;
import com.rotterdam.tools.DateTools;
import org.springframework.transaction.annotation.Transactional;

import javax.inject.Inject;
import javax.inject.Named;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by root on 03.02.15.
 */
@Named
public class SettingsService {

    @Inject
    private WeekDao weekDao;

    @Inject
    private PeriodDao periodDao;

    @Transactional
    public void save(SettingsDto settingsDto, long userId){
        //check date
        settingsDto.currentDate = DateTools.getDateOfPrevMonday(settingsDto.currentDate);

        Week week = weekDao.selectByStartDateAndUser(settingsDto.currentDate, userId);

        if(week == null){
            //need to create new week
            week = new Week();
            week = settingsDto.copyDaysOfWeekAndCheckBoxesToWeek(week);
            //we need to find corresponding period
            Period period = periodDao.selectByDateBetweenAndUser(settingsDto.currentDate, userId);
            if(period == null){
                //logic error
                return;
            }
            week.setPeriod(period);
            week.setStartDate(settingsDto.currentDate);
            week.setEndDate(DateTools.getDateOf7DayAfter(settingsDto.currentDate));

            //now save to db
            weekDao.insert(week);
        } else {
            week = settingsDto.copyDaysOfWeekAndCheckBoxesToWeek(week);
            weekDao.update(week);
        }
    }

    @Transactional
    public SettingsDto getSettings(Date date, long userId){
        date = DateTools.getDateOfPrevMonday(date);

        SettingsDto settingsDto = new SettingsDto();

        Period period = periodDao.selectByDateBetweenAndUser(date, userId);

        if(period != null) {
            settingsDto.startDate = period.getStartDate();
            settingsDto.endDate = period.getEndDate();
        }

        Week week = weekDao.selectByStartDateAndUser(date, userId);

        settingsDto.active = isActive(date, userId);

        if(week == null) {
            return settingsDto;
        }

        settingsDto = settingsDto.copyDaysOfWeekToSettingsDto(week);

        settingsDto.paymentDate = week.getPeriod().getUser().getLastPaymentDate();

        return settingsDto;
    }

    private boolean isActive(Date date, long userId){
        Period weekPeriod = periodDao.selectByDateBetweenAndUser(date, userId);
        Period currentPeriod = periodDao.selectByDateBetweenAndUser(new Date(), userId);
        if(weekPeriod == null || currentPeriod == null) return false;
        return weekPeriod.getStartDate().equals(currentPeriod.getStartDate());
    }

    public List<SettingsDto.DateWrapper> generateFakeHours() {
        List<SettingsDto.DateWrapper> hours = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            hours.add(new SettingsDto.DateWrapper(null));
        }
        return hours;
    }
}


text:
@interface PBImagePickerCoordinator : NSObject

- (UIImagePickerController *)cameraVC;

@end


text:
package org.apache.camel.component.aws.translate;

import com.amazonaws.Protocol;
import com.amazonaws.services.translate.AmazonTranslate;
import org.apache.camel.RuntimeCamelException;
import org.apache.camel.spi.Metadata;
import org.apache.camel.spi.UriParam;
import org.apache.camel.spi.UriParams;
import org.apache.camel.spi.UriPath;

@UriParams
public class TranslateConfiguration implements Cloneable {

    @UriPath(description = "Logical name")
    @Metadata(required = true)
    private String label;
    @UriParam(label = "producer")
    private AmazonTranslate translateClient;
    @UriParam(label = "producer", secret = true)
    private String accessKey;
    @UriParam(label = "producer", secret = true)
    private String secretKey;
    @UriParam(label = "producer")
    @Metadata(required = true, defaultValue = "translateText")
    private TranslateOperations operation = TranslateOperations.translateText;
    @UriParam(enums = "HTTP,HTTPS", defaultValue = "HTTPS")
    private Protocol proxyProtocol = Protocol.HTTPS;
    @UriParam(label = "producer")
    private String proxyHost;
    @UriParam(label = "producer")
    private String sourceLanguage;
    @UriParam(label = "producer")
    private String targetLanguage;
    @UriParam(label = "producer")
    private Integer proxyPort;
    @UriParam
    private String region;
    @UriParam(label = "producer", defaultValue = "false")
    private boolean autodetectSourceLanguage;
    @UriParam(label = "common", defaultValue = "true")
    private boolean autoDiscoverClient = true;

    public AmazonTranslate getTranslateClient() {
        return translateClient;
    }

    /**
     * To use a existing configured AWS Translate as client
     */
    public void setTranslateClient(AmazonTranslate translateClient) {
        this.translateClient = translateClient;
    }

    public String getAccessKey() {
        return accessKey;
    }

    /**
     * Amazon AWS Access Key
     */
    public void setAccessKey(String accessKey) {
        this.accessKey = accessKey;
    }

    public String getSecretKey() {
        return secretKey;
    }

    /**
     * Amazon AWS Secret Key
     */
    public void setSecretKey(String secretKey) {
        this.secretKey = secretKey;
    }

    public TranslateOperations getOperation() {
        return operation;
    }

    /**
     * The operation to perform
     */
    public void setOperation(TranslateOperations operation) {
        this.operation = operation;
    }

    public Protocol getProxyProtocol() {
        return proxyProtocol;
    }

    /**
     * To define a proxy protocol when instantiating the Translate client
     */
    public void setProxyProtocol(Protocol proxyProtocol) {
        this.proxyProtocol = proxyProtocol;
    }

    public String getProxyHost() {
        return proxyHost;
    }

    /**
     * To define a proxy host when instantiating the Translate client
     */
    public void setProxyHost(String proxyHost) {
        this.proxyHost = proxyHost;
    }

    public Integer getProxyPort() {
        return proxyPort;
    }

    /**
     * To define a proxy port when instantiating the Translate client
     */
    public void setProxyPort(Integer proxyPort) {
        this.proxyPort = proxyPort;
    }

    public String getRegion() {
        return region;
    }

    /**
     * The region in which Translate client needs to work. When using this parameter, the configuration will expect the
     * capitalized name of the region (for example AP_EAST_1) You'll need to use the name Regions.EU_WEST_1.name()
     */
    public void setRegion(String region) {
        this.region = region;
    }

    public boolean isAutodetectSourceLanguage() {
        return autodetectSourceLanguage;
    }

    /**
     * Being able to autodetect the source language
     */
    public void setAutodetectSourceLanguage(boolean autodetectSourceLanguage) {
        this.autodetectSourceLanguage = autodetectSourceLanguage;
    }

    public String getSourceLanguage() {
        return sourceLanguage;
    }

    /**
     * Source language to use
     */
    public void setSourceLanguage(String sourceLanguage) {
        this.sourceLanguage = sourceLanguage;
    }

    public String getTargetLanguage() {
        return targetLanguage;
    }

    /**
     * Target language to use
     */
    public void setTargetLanguage(String targetLanguage) {
        this.targetLanguage = targetLanguage;
    }

    public boolean isAutoDiscoverClient() {
        return autoDiscoverClient;
    }

    /**
     * Setting the autoDiscoverClient mechanism, if true, the component will look for a client instance in the registry
     * automatically otherwise it will skip that checking.
     */
    public void setAutoDiscoverClient(boolean autoDiscoverClient) {
        this.autoDiscoverClient = autoDiscoverClient;
    }

    // *************************************************
    //
    // *************************************************

    public TranslateConfiguration copy() {
        try {
            return (TranslateConfiguration) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new RuntimeCamelException(e);
        }
    }
}


text:
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
    for (var p in m) if (p !== "default" && !exports.hasOwnProperty(p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.tsParticles = exports.pJSDom = exports.particlesJS = void 0;
var index_slim_1 = require("./index.slim");
Object.defineProperty(exports, "particlesJS", { enumerable: true, get: function () { return index_slim_1.particlesJS; } });
Object.defineProperty(exports, "pJSDom", { enumerable: true, get: function () { return index_slim_1.pJSDom; } });
Object.defineProperty(exports, "tsParticles", { enumerable: true, get: function () { return index_slim_1.tsParticles; } });
require("./Plugins/Absorbers/AbsorbersPlugin");
require("./Plugins/Emitters/EmittersPlugin");
require("./Plugins/PolygonMask/PolygonMaskPlugin");
__exportStar(require("./Enums"), exports);


text:
<?php
/**
 * Created by PhpStorm.
 * User: sergey
 * Date: 10.01.17
 * Time: 22:34
 */

namespace common\models\ar;

use common\models\ZnakiZodiaka as BaseZnakiZodiaka;
use yii\behaviors\TimestampBehavior;

class ZnakiZodiaka extends BaseZnakiZodiaka
{
    const TYPE_COMMON = 'common';
    const TYPE_MAN = 'man';
    const TYPE_WOMAN = 'woman';
    const TYPE_CHILD = 'child';
    const TYPE_CAREER = 'career';
    const TYPE_HEALTH = 'health';
    const TYPE_SEX = 'sex';

    public function behaviors()
    {
        return [
            'timestamp' => [
                'class' => TimestampBehavior::className(),
            ],
        ];
    }
}


text:
class CDevObjDoc;
class CRunView;
class CGroupObj;

_COM_SMARTPTR_TYPEDEF(ICxExtendedObject, _uuidof(ICxExtendedObject));

interface IDynamicSet;

#define OBJMISC_EVENTSINK  0x00000001L

#define ABSOLUTEVALUE(a) ((a) < 0 ? (-a) : (a))

//¸ù¾ÝÁ½¸öµãÇóÏà¶Ô½Ç¶È
int CalculateAngle(POINT ptOrigin, POINT ptCal);
float CalculateAngle(POINTF ptOrigin, POINTF ptCal);
POINTF CalculateRotatePoint(POINTF ptOrgin, POINTF ptCal, float fAngle);

typedef struct tagLINKINFO
{
	DISPID dispid;
	ICxDynamicObject* pDynamicObject;
} LINKINFO;

typedef struct tagEVENTINFO
{
	DISPID dispid;
	CString strMethod;
} EVENTINFO;

class CDevObj : public CCmdTarget
{
	DECLARE_SERIAL(CDevObj)

//ÔDynamicSet×é¼þº¯Êý
public:
	HRESULT HasDynamic(DISPID dispid, VARIANT_BOOL *pConnected);
	HRESULT GetDynamic(DISPID dispid, IUnknown** ppUnknown);
	HRESULT RemoveDynamic(DISPID dispid);
	HRESULT AddDynamic(DISPID dispid, IUnknown* pUnknown);
	//ÐÂÔö
	BOOL HaveDynamic() { return m_arLinkInfo.GetSize() > 0; }
	virtual BOOL OnMouseInput(LPCSTR szPropName, BOOL bProcess);

protected:
	CArray<LINKINFO, LINKINFO&> m_arLinkInfo;

	BOOL m_bInitEventInfo;
	IID m_iidEventInterface;
	CArray<EVENTINFO, EVENTINFO&> m_arrEventInfo;

	DWORD m_dwEventCookie;
	IConnectionPointPtr m_pEventCP;

public:
	CDevObj(CDevObjDoc* pContainer = NULL);
	virtual ~CDevObj();

// Attributes
public:
	DWORD m_dwVer;

	CDC* m_pDC;

	CRectF m_position;
	int m_nLayer;
	BOOL m_bLocked;
	BOOL m_bVisible;
	CString m_strToolTip; //ÌáʾÎı¾
	int m_nPrivilege; //°²È«Çø
	CString m_strDescription;

// Operations
public:
	BOOL GetEnventSinkStatus() { return (m_dwMiscStatus	& OBJMISC_EVENTSINK != 0); }

	virtual void OnDynamicChange();
	virtual BOOL OnWindowMessage(const MSG* pMessage, BOOL bSubObj = FALSE){ return FALSE; }
	virtual BOOL TranslateAccelerator(const MSG* pMessage) { return FALSE; }

	virtual void Active(CRunView* pView){}
	virtual void Deactive(){}

	virtual void Draw(CDC* pDC){}
	virtual void Print(CDC* pDC) { Draw(pDC); }
	virtual void DrawBackToFront(CDC* pDC){}
	virtual void DrawFrontToBack(CDC* pDC){}
	virtual BOOL HitTest(CPoint point, const CRunView* pView);
	virtual void MoveTo(const CRectF& position, BOOL bUniformScale, CRunView* pView = NULL);

	virtual void RotateAt(CPointF point, float fAngle, CRunView* pView = NULL);
	virtual void ScaleAt(CPointF point, float fHorScale, float fVerScale, CRunView* pView = NULL);

	virtual CString GetDisplayName(){ return m_strDisplayName; }
	virtual void PutDisplayName(LPCSTR strDisplayName){ m_strDisplayName = strDisplayName; };

	virtual CString GetClassName();
	virtual IDispatch* GetObjectDispatch(){ return NULL; }
	virtual LPUNKNOWN GetObjectUnknown(){ return NULL; }

	virtual HRESULT PutProperty(DISPID dwDispID, VARIANT* pVar);

	virtual CRect GetBoundingRect(){ return CRect(m_position.GetRECT()); }
	virtual CRectF GetPositionRect(){ return m_position; }
	virtual void Invalidate(CRunView* pView = NULL);
	virtual void Release();

	virtual void InitRun();

	virtual void FakeParseDynamic();
	virtual void ParseDynamic();
	virtual void OnTimer() {}
	virtual void OnMouseLeave() {}

	virtual BOOL IsDefaultMousePointer() { return FALSE; }

	virtual void Serialize(CArchive& ar);   // for Native data
	virtual void SaveProperty(CArchive& ar);   // ±£´æÊôÐÔ
	virtual void RestoreProperty(CArchive& ar);   // »¹ÔÊôÐÔ

	void InitEventInfo();
	BOOL GetEventByDispid(DISPID dispid, CString& strEvent);

	void AdviseEnventSink();

	IUnknown* GetInterfaceHook(const void* pv);

	DWORD m_dwMiscStatus;

	WORD m_wAreaMask[8];

// Implementation
public:
	CDevObjDoc* m_pDocument;
	CGroupObj* m_pGroupObj;	//ËùÔÚ×éºÏ¶ÔÏó

	DWORD m_dwSubObjNum; // ¶ÔÏó´æÔÚÓÚÒ»¸ö×éºÏ¶ÔÏóÖÐʱµÄ±àºÅ

	DWORD m_dwObjectNumber;
	LPSTORAGE m_lpStorage;
	BYTE m_bNeedCommit;     // TRUE if need CommitItem

	LPSTORAGE m_lpNewStorage;

	DWORD GetNewObjectNumber();
	void GetObjectName(LPTSTR lpszItemName) const;

	//¶¯Ì¬ÊôÐÔÊôÐÔ
	HRESULT LoadDynamicProperty(IStream *pStream);
	HRESULT SaveDynamicProperty(IStream *pStream);
	void SerializeDynamicProperty(CArchive& ar);

protected:
	BEGIN_INTERFACE_PART(ScriptEngineSite, ICxScriptEngineSite)
		STDMETHOD(EvaluateExpression)(BSTR bstrSource, VARIANT* pvaValidObjects);
		STDMETHOD(Execute)(BSTR bstrStatement);
		STDMETHOD(PreTreatExpression)(BSTR bstrSource, BSTR* pbstrSource);
		STDMETHOD(PreTreatExpressionEx)(BSTR bstrSource, BSTR* pbstrSource, VARIANT* pvaMin, VARIANT* pvaMax);
	END_INTERFACE_PART(ScriptEngineSite)

	BEGIN_INTERFACE_PART(EventHandler, IDispatch)
		STDMETHOD(GetIDsOfNames)(REFIID iid, LPOLESTR* ppszNames, UINT nNames, LCID lcid, DISPID* pDispIDs);
		STDMETHOD(GetTypeInfo)(UINT iTypeInfo, LCID lcid,	ITypeInfo** ppTypeInfo);
		STDMETHOD(GetTypeInfoCount)(UINT* pnInfoCount);
		STDMETHOD(Invoke)(DISPID dispidMember, REFIID iid, LCID lcid,
			WORD wFlags, DISPPARAMS* pdpParams, VARIANT* pvarResult, EXCEPINFO* pExceptionInfo, UINT* piArgError);
	END_INTERFACE_PART(EventHandler)

	DECLARE_INTERFACE_MAP()

protected:
	BOOL m_bExtendedObject;
	CString m_strDisplayName;
	CString m_strClassName;

	ICxExtendedObjectPtr m_pExtendedObject;

	friend class CExtendedControl;

};

typedef CTypedPtrList<CObList, CDevObj*> CDevObjList;
typedef CTypedPtrArray<CObArray, CDevObj*> CDevObjArray;
typedef CTypedPtrMap<CMapStringToPtr, CString, CDevObj*> CNamedDevobjMap;

/////////////////////////////////////////////////////////////////////////////

//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.

#endif // __DEVITEM_H__


text:
<?php

/* SonataAdminBundle:CRUD:show_html.html.twig */
class __TwigTemplate_54d9da32e42d750969f3a97d3a55d0cf47d0eaf8cd04ba90d47326920fa91174 extends Twig_Template
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        // line 1
        $this->parent = $this->loadTemplate("SonataAdminBundle:CRUD:base_show_field.html.twig", "SonataAdminBundle:CRUD:show_html.html.twig", 1);
        $this->blocks = array(
            'field' => array($this, 'block_field'),
        );
    }

    protected function doGetParent(array $context)
    {
        return "SonataAdminBundle:CRUD:base_show_field.html.twig";
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        $this->parent->display($context, array_merge($this->blocks, $blocks));
    }

    // line 3
    public function block_field($context, array $blocks = array())
    {
        // line 4
        if (twig_test_empty((isset($context["value"]) ? $context["value"] : $this->getContext($context, "value")))) {
            // line 5
            echo "
    ";
        } else {
            // line 7
            if ($this->getAttribute($this->getAttribute((isset($context["field_description"]) ? $context["field_description"] : null), "options", array(), "any", false, true), "truncate", array(), "any", true, true)) {
                // line 8
                $context["truncate"] = $this->getAttribute($this->getAttribute((isset($context["field_description"]) ? $context["field_description"] : $this->getContext($context, "field_description")), "options", array()), "truncate", array());
                // line 9
                echo "            ";
                $context["length"] = (($this->getAttribute((isset($context["truncate"]) ? $context["truncate"] : null), "length", array(), "any", true, true)) ? (_twig_default_filter($this->getAttribute((isset($context["truncate"]) ? $context["truncate"] : null), "length", array()), 30)) : (30));
                // line 10
                echo "            ";
                $context["preserve"] = (($this->getAttribute((isset($context["truncate"]) ? $context["truncate"] : null), "preserve", array(), "any", true, true)) ? (_twig_default_filter($this->getAttribute((isset($context["truncate"]) ? $context["truncate"] : null), "preserve", array()), false)) : (false));
                // line 11
                echo "            ";
                $context["separator"] = (($this->getAttribute((isset($context["truncate"]) ? $context["truncate"] : null), "separator", array(), "any", true, true)) ? (_twig_default_filter($this->getAttribute((isset($context["truncate"]) ? $context["truncate"] : null), "separator", array()), "...")) : ("..."));
                // line 12
                echo "            ";
                echo twig_truncate_filter($this->env, strip_tags((isset($context["value"]) ? $context["value"] : $this->getContext($context, "value"))), (isset($context["length"]) ? $context["length"] : $this->getContext($context, "length")), (isset($context["preserve"]) ? $context["preserve"] : $this->getContext($context, "preserve")), (isset($context["separator"]) ? $context["separator"] : $this->getContext($context, "separator")));
            } else {
                // line 14
                if ($this->getAttribute($this->getAttribute((isset($context["field_description"]) ? $context["field_description"] : null), "options", array(), "any", false, true), "strip", array(), "any", true, true)) {
                    // line 15
                    $context["value"] = strip_tags((isset($context["value"]) ? $context["value"] : $this->getContext($context, "value")));
                }
                // line 17
                echo (isset($context["value"]) ? $context["value"] : $this->getContext($context, "value"));
                echo "
        ";
            }
            // line 19
            echo "    ";
        }
    }

    public function getTemplateName()
    {
        return "SonataAdminBundle:CRUD:show_html.html.twig";
    }

    public function isTraitable()
    {
        return false;
    }

    public function getDebugInfo()
    {
        return array (  64 => 19,  59 => 17,  56 => 15,  54 => 14,  50 => 12,  47 => 11,  44 => 10,  41 => 9,  39 => 8,  37 => 7,  33 => 5,  31 => 4,  28 => 3,  11 => 1,);
    }
}


text:
title: Go 1.18 is released!
date: 2022-03-15
by:
- The Go Team
summary: Go 1.18 adds generics, native fuzzing, workspace mode, performance improvements, and more.
---

Today the Go team is thrilled to release Go 1.18,
which you can get by visiting the [download page](/dl/).

Go 1.18 is a massive release that includes new features,
performance improvements, and our biggest change ever to the language.
It isn't a stretch to say that the design for parts of Go 1.18
started over a decade ago when we first released Go.

## Generics

In Go 1.18, we're introducing new support for
[generic code using parameterized types](/blog/why-generics).
Supporting generics has been Go's most often requested feature,
and we're proud to deliver the generic support that the majority of users need today.
Subsequent releases will provide additional support for some of
the more complicated generic use cases.
We encourage you to get to know this new feature using our
[generics tutorial](/doc/tutorial/generics),
and to explore the best ways to use generics to optimize and simplify your code today.
The [release notes](/doc/go1.18) have more details about using generics in Go 1.18.

## Fuzzing

With Go 1.18, Go is the first major language with fuzzing
fully integrated into its standard toolchain.
Like generics, fuzzing has been in design for a long time,
and we're delighted to share it with the Go ecosystem with this release.
Please check out our
[fuzzing tutorial](/doc/tutorial/fuzz)
to help you get started with this new feature.

## Workspaces

Go modules have been almost universally adopted,
and Go users have reported very high satisfaction scores in our annual surveys.
In our 2021 user survey, the most common challenge
users identified with modules
was working across multiple modules.
In Go 1.18, we've addressed this with a new
[Go workspace mode](/doc/tutorial/workspaces),
which makes it simple to work with multiple modules.

## 20% Performance Improvements

Apple M1, ARM64, and PowerPC64 users rejoice!
Go 1.18 includes CPU performance improvements of up to 20%
due to the expansion of Go 1.17's register ABI calling convention to these architectures.
Just to underscore how big this release is, a 20% performance improvement
is the fourth most important headline!

For a more detailed description of everything that's in 1.18,
please consult the [release notes](/doc/go1.18).

Go 1.18 is a huge milestone for the entire Go community.
We want to thank every Go user who filed a bug, sent in a change, wrote a tutorial,
or helped in any way to make Go 1.18 a reality.
We couldn't do it without you.
Thank you.

Enjoy Go 1.18!


text:
package deployments

//All these functions require api access specific to the version of the app

import (
	"context"
	"fmt"
	"strconv"

	"github.com/golang/glog"

	"kube-monkey/internal/pkg/config"
	"kube-monkey/internal/pkg/victims"

	kube "k8s.io/client-go/kubernetes"

	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

// EligibleDeployments gets all eligible deployments that opted in (filtered by config.EnabledLabel)
func EligibleDeployments(clientset kube.Interface, namespace string, filter *metav1.ListOptions) (eligVictims []victims.Victim, err error) {
	enabledVictims, err := clientset.AppsV1().Deployments(namespace).List(context.TODO(), *filter)
	if err != nil {
		return nil, err
	}

	for _, vic := range enabledVictims.Items {
		victim, err := New(&vic)
		if err != nil {
			glog.Warningf("Skipping eligible %T %s because of error: %s", vic, vic.Name, err.Error())
			continue
		}

		// TODO: After generating whitelisting ns list, this will move to factory.
		// IsBlacklisted will change to something like IsAllowedNamespace
		// and will only be used to verify at time of scheduled execution
		if victim.IsBlacklisted() {
			continue
		}

		eligVictims = append(eligVictims, victim)
	}

	return
}

/* Below methods are used to verify the victim's attributes have not changed at the scheduled time of termination */

// IsEnrolled checks if the deployment is currently enrolled in kube-monkey
func (d *Deployment) IsEnrolled(clientset kube.Interface) (bool, error) {
	deployment, err := clientset.AppsV1().Deployments(d.Namespace()).Get(context.TODO(), d.Name(), metav1.GetOptions{})
	if err != nil {
		return false, err
	}
	return deployment.Labels[config.EnabledLabelKey] == config.EnabledLabelValue, nil
}

// KillType returns current killtype config label for update
func (d *Deployment) KillType(clientset kube.Interface) (string, error) {
	deployment, err := clientset.AppsV1().Deployments(d.Namespace()).Get(context.TODO(), d.Name(), metav1.GetOptions{})
	if err != nil {
		return "", err
	}

	killType, ok := deployment.Labels[config.KillTypeLabelKey]
	if !ok {
		return "", fmt.Errorf("%s %s does not have %s label", d.Kind(), d.Name(), config.KillTypeLabelKey)
	}

	return killType, nil
}

// KillValue returns current killvalue config label for update
func (d *Deployment) KillValue(clientset kube.Interface) (int, error) {
	deployment, err := clientset.AppsV1().Deployments(d.Namespace()).Get(context.TODO(), d.Name(), metav1.GetOptions{})
	if err != nil {
		return -1, err
	}

	killMode, ok := deployment.Labels[config.KillValueLabelKey]
	if !ok {
		return -1, fmt.Errorf("%s %s does not have %s label", d.Kind(), d.Name(), config.KillValueLabelKey)
	}

	killModeInt, err := strconv.Atoi(killMode)
	if err != nil || !(killModeInt > 0) {
		return -1, fmt.Errorf("Invalid value for label %s: %d", config.KillValueLabelKey, killModeInt)
	}

	return killModeInt, nil
}


text:
module StructParser::Containers
  class Sheet < StructParser::Container
    # Together forms children
    attr_accessor :rows, :cols

    def dup(parent=nil)
      sheet = self.class.new parent: parent
      sheet.name = name
      sheet.load_matrix to_matrix
    end

    def header_row
      rows[0]
    end

    def op_squad=(squad)
      squad = { after_children: squad } unless squad.is_a? Hash
      @op_squad = squad
    end

    def run
      begin
        super
      rescue StandardError
        raise $!, "#{$!}, Sheet name: `#{name}`", $!.backtrace
      end
    end

    def name
      context[:name]
    end

    def name=(val)
      context[:name] = val
    end

    def get_cell(r, c)
      rows[r].children[c]
    end

    def initialize(options={})
      super options
      self.rows = []
      self.cols = []
    end

    def assign_cell_squad(squad)
      # Default action is before_children
      squad = { before_children: squad } unless squad.is_a? Hash
      squad = StructParser::Utils.flatten_val squad
      rows.each do |row|
        row.children.each do |cell|
          cell.op_squad = squad
        end
      end
      self
    end

    def assign_row_squad(squad)
      squad = { after_children: squad } unless squad.is_a? Hash
      squad = StructParser::Utils.flatten_val squad
      rows.each do |row|
        row.op_squad = squad
      end
      self
    end

    def assign_col_squad(squad)
      squad = { after_children: squad } unless squad.is_a? Hash
      squad = StructParser::Utils.flatten_val squad
      cols.each do |col|
        col.op_squad = squad
      end
      self
    end

    ##
    # Create a sub sheet
    def slice(xs, x, ys, y)
      m = []
      (xs..x).each do |i|
        srow = []
        m << srow
        (ys..y).each do |j|
          srow << rows[i].children[j].raw
        end
      end
      self.class.new.load_matrix m
    end

    def to_matrix
      rows.map do |r|
        r.children.map &:raw
      end
    end

    def load_matrix(m)
      col_count = 0
      m.each do |row|
        col_count = row.size if col_count < row.size
      end
      # Populate rows
      m.each_with_index do |srow, row_idx|
        row = Row.new parent: self, idx: row_idx, context: { val: {} }
        rows << row
        srow.each do |val|
          val = val.nil? ? nil : val.strip
          val = val.blank? ? nil : val
          Cell.new parent: row, context: { raw: val,
                                           val: val}, row: row
        end
        # Pad row to max width with nil values
        if srow.count < col_count
          (0...col_count - srow.count).each do
            Cell.new parent: row, context: { raw: nil }
          end
        end
      end
      # Populate cols
      (0...col_count).each do |i|
        col = Column.new parent: self, idx: i
        cols << col
        rows.each do |row|
          cell = row.children[i]
          cell.col = col
          col.children << cell
        end
      end
      self
    end

    ##
    # Drop columns without header
    def drop_no_header
      idx = -1
      # Means no value in header column
      while (idx+=1) < header_row.children.size && header_row.children[idx].raw.blank?
        drop_column idx
        idx -= 1
      end
    end

    def drop_column(idx)
      # Remove cols
      cols.delete_at idx
      # Remove each row's column
      rows.each do |row|
        row.delete_at idx
      end
      # Remove row in children's column
      children.select { |c| c.class == Row }.each do |row|
        row.delete_at idx
      end
    end

    def to_category!(options)
      anchor = options[:anchor]
      namer = options[:namer]
      cell_squad = anchor &
          -> (c) {
            # Create sheet
            self.val ||= {}
            cat = val[:cat] ||= Category.new
            # Probe for dimension
            dim = naive_probe_dimension c
            # Assign sheet name
            sub_sheet = slice *dim
             if namer.respond_to? :call
               sub_sheet.name = namer.call c
             else
               sub_sheet.name = name
             end
            cat.children << sub_sheet
          }
      assign_cell_squad cell_squad
      run
      # Return partitioned category
      val[:cat]
    end

    def naive_probe_dimension(cell)
      # Read until empty column or end of row for header
      x = xs = cell.row.idx
      y = ys = cell.col.idx
      # Get row
      cells = cell.row.children
      (ys...cells.size).each do |idx|
        c = cells[idx]
        break if c.raw.blank?
        y = idx
      end
      # col is a bit more tricky, we need to scan rows downwards
      # until one row is entirely empty in col range
      rows = cell.sheet.rows
      (xs...rows.size).each do |idx|
        row = rows[idx]
        break if row.children[ys..y].map(&:raw).map(&:blank?).all?
        x = idx
      end
      # Return tuple
      [xs, x, ys, y]
    end

  end
end


text:
function() {
  console.log("this is not a bug");
}