text:
/*
 * This file is part of Nucleus, licensed under the MIT License (MIT). See the LICENSE.txt file
 * at the root of this project for more details.
 */
package io.github.nucleuspowered.nucleus.modules.home.commands;

import io.github.nucleuspowered.nucleus.Nucleus;
import io.github.nucleuspowered.nucleus.Util;
import io.github.nucleuspowered.nucleus.api.nucleusdata.Home;
import io.github.nucleuspowered.nucleus.api.nucleusdata.NamedLocation;
import io.github.nucleuspowered.nucleus.internal.annotations.RunAsync;
import io.github.nucleuspowered.nucleus.internal.annotations.command.NoModifiers;
import io.github.nucleuspowered.nucleus.internal.annotations.command.Permissions;
import io.github.nucleuspowered.nucleus.internal.annotations.command.RegisterCommand;
import io.github.nucleuspowered.nucleus.internal.command.AbstractCommand;
import io.github.nucleuspowered.nucleus.internal.command.NucleusParameters;
import io.github.nucleuspowered.nucleus.internal.command.ReturnMessageException;
import io.github.nucleuspowered.nucleus.internal.interfaces.Reloadable;
import io.github.nucleuspowered.nucleus.internal.permissions.PermissionInformation;
import io.github.nucleuspowered.nucleus.internal.permissions.SuggestedLevel;
import io.github.nucleuspowered.nucleus.modules.home.config.HomeConfig;
import io.github.nucleuspowered.nucleus.modules.home.config.HomeConfigAdapter;
import io.github.nucleuspowered.nucleus.modules.home.services.HomeHandler;
import org.spongepowered.api.command.CommandResult;
import org.spongepowered.api.command.CommandSource;
import org.spongepowered.api.command.args.CommandContext;
import org.spongepowered.api.command.args.CommandElement;
import org.spongepowered.api.command.args.GenericArguments;
import org.spongepowered.api.entity.living.player.Player;
import org.spongepowered.api.entity.living.player.User;
import org.spongepowered.api.event.cause.Cause;
import org.spongepowered.api.service.pagination.PaginationList;
import org.spongepowered.api.text.Text;
import org.spongepowered.api.text.action.TextActions;
import org.spongepowered.api.text.format.TextColors;
import org.spongepowered.api.text.format.TextStyles;
import org.spongepowered.api.util.annotation.NonnullByDefault;
import org.spongepowered.api.world.Location;
import org.spongepowered.api.world.World;

import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

@Permissions(prefix = "home", mainOverride = "list", suggestedLevel = SuggestedLevel.USER)
@RunAsync
@NoModifiers
@NonnullByDefault
@RegisterCommand(value = "list", subcommandOf = HomeCommand.class, rootAliasRegister = {"listhomes", "homes"})
public class ListHomeCommand extends AbstractCommand<CommandSource> implements Reloadable {

    private final String exemptOther = Nucleus.getNucleus().getPermissionRegistry().getPermissionsForNucleusCommand(HomeOtherCommand.class)
                                              .getPermissionWithSuffix(HomeOtherCommand.OTHER_EXEMPT_PERM_SUFFIX);
    private final String exemptSameDimension = Nucleus.getNucleus().getPermissionRegistry().getPermissionsForNucleusCommand(HomeCommand.class)
                                                      .getPermissionWithSuffix(HomeCommand.EXEMPT_SAMEDIMENSION_SUFFIX);

    private final HomeHandler homeHandler = getServiceUnchecked(HomeHandler.class);

    private boolean isOnlySameDimension = false;

    @Override
    public Map<String, PermissionInformation> permissionSuffixesToRegister() {
        Map<String, PermissionInformation> m = new HashMap<>();
        m.put("others", PermissionInformation.getWithTranslation("permission.others", SuggestedLevel.ADMIN));
        // m.put("exempt.samedimension", PermissionInformation.getWithTranslation("permission.home.exempt.samedimension", SuggestedLevel.ADMIN));
        return m;
    }

    @Override
    public CommandElement[] getArguments() {
        return new CommandElement[] {
                GenericArguments.optional(requirePermissionArg(
                        NucleusParameters.ONE_USER, this.permissions.getPermissionWithSuffix("others")))
        };
    }

    @Override
    public CommandResult executeCommand(CommandSource src, CommandContext args, Cause cause) throws Exception {
        User user = this.getUserFromArgs(User.class, src, NucleusParameters.Keys.USER, args);
        Text header;

        boolean other = src instanceof User && !((User) src).getUniqueId().equals(user.getUniqueId());
        if (other && hasPermission(user, this.exemptOther)) {
            throw new ReturnMessageException(Nucleus.getNucleus().getMessageProvider().getTextMessageWithFormat("command.listhome.exempt"));
        }

        List<Home> msw = this.homeHandler.getHomes(user);
        if (msw.isEmpty()) {
            src.sendMessage(Nucleus.getNucleus().getMessageProvider().getTextMessageWithFormat("command.home.nohomes"));
            return CommandResult.empty();
        }

        if (other) {
            header = Nucleus.getNucleus().getMessageProvider().getTextMessageWithFormat("home.title.name", user.getName());
        } else {
            header = Nucleus.getNucleus().getMessageProvider().getTextMessageWithFormat("home.title.normal");
        }

        List<Text> lt = msw.stream().sorted(Comparator.comparing(NamedLocation::getName)).map(x -> {
            Optional<Location<World>> olw = x.getLocation();
            if (!olw.isPresent()) {
                return Text.builder().append(
                                Text.builder(x.getName()).color(TextColors.RED)
                                        .onHover(TextActions.showText(
                                                Nucleus.getNucleus().getMessageProvider().getTextMessageWithFormat("home.warphoverinvalid", x.getName())))
                                        .build())
                        .build();
            } else {
                final Location<World> lw = olw.get();
                final Text textMessage = Nucleus.getNucleus().getMessageProvider().getTextMessageWithFormat("home.location",
                                                 lw.getExtent().getName(), String.valueOf(lw.getBlockX()), String.valueOf(lw.getBlockY()), String.valueOf(lw.getBlockZ()));

                if (this.isOnlySameDimension && src instanceof Player && !other) {
                    if (!lw.getExtent().getUniqueId().equals(((Player) src).getLocation().getExtent().getUniqueId())) {
                        if (!hasPermission(user, this.exemptSameDimension)) {
                            return Text.builder()
                                       .append(Text.builder(x.getName())
                                                   .color(TextColors.LIGHT_PURPLE)
                                                   .onHover(TextActions.showText(
                                                           Nucleus.getNucleus().getMessageProvider().getTextMessageWithFormat("home.warphoverotherdimension", x.getName())))
                                                   .build())
                                       .append(textMessage)
                                       .build();
                        }
                    }
                }

                return Text.builder()
                           .append(
                                Text.builder(x.getName())
                                    .color(TextColors.GREEN).style(TextStyles.UNDERLINE)
                                    .onHover(TextActions.showText(
                                            Nucleus.getNucleus().getMessageProvider().getTextMessageWithFormat("home.warphover", x.getName())))
                                    .onClick(TextActions.runCommand(other ? "/homeother " + user.getName() + " " + x.getName()
                                                                          : "/home " + x.getName()))
                                    .build())
                           .append(textMessage)
                           .build();
            }
        }).collect(Collectors.toList());

        PaginationList.Builder pb =
            Util.getPaginationBuilder(src).title(Text.of(TextColors.YELLOW, header)).padding(Text.of(TextColors.GREEN, "-")).contents(lt);

        pb.sendTo(src);
        return CommandResult.success();
    }

    @Override
    public void onReload() {
        HomeConfig hc = Nucleus.getNucleus().getInternalServiceManager().getServiceUnchecked(HomeConfigAdapter.class).getNodeOrDefault();
        this.isOnlySameDimension = hc.isOnlySameDimension();
    }
}


text:
/*
 * This code was generated by
 * ___ _ _ _ _ _    _ ____    ____ ____ _    ____ ____ _  _ ____ ____ ____ ___ __   __
 *  |  | | | | |    | |  | __ |  | |__| | __ | __ |___ |\ | |___ |__/ |__|  | |  | |__/
 *  |  |_|_| | |___ | |__|    |__| |  | |    |__] |___ | \| |___ |  \ |  |  | |__| |  \
 *
 * Twilio - Trusthub
 * This is the public Twilio REST API.
 *
 * NOTE: This class is auto generated by OpenAPI Generator.
 * https://openapi-generator.tech
 * Do not edit the class manually.
 */

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using Twilio.Base;
using Twilio.Clients;
using Twilio.Converters;
using Twilio.Exceptions;
using Twilio.Http;

namespace Twilio.Rest.Trusthub.V1
{
    public class SupportingDocumentTypeResource : Resource
    {

        private static Request BuildFetchRequest(FetchSupportingDocumentTypeOptions options, ITwilioRestClient client)
        {

            string path = "/v1/SupportingDocumentTypes/{Sid}";

            string PathSid = options.PathSid;
            path = path.Replace("{"+"Sid"+"}", PathSid);

            return new Request(
                HttpMethod.Get,
                Rest.Domain.Trusthub,
                path,
                queryParams: options.GetParams(),
                headerParams: null
            );
        }

        /// <summary> Fetch a specific Supporting Document Type Instance. </summary>
        /// <param name="options"> Fetch SupportingDocumentType parameters </param>
        /// <param name="client"> Client to make requests to Twilio </param>
        /// <returns> A single instance of SupportingDocumentType </returns>
        public static SupportingDocumentTypeResource Fetch(FetchSupportingDocumentTypeOptions options, ITwilioRestClient client = null)
        {
            client = client ?? TwilioClient.GetRestClient();
            var response = client.Request(BuildFetchRequest(options, client));
            return FromJson(response.Content);
        }

        #if !NET35
        /// <summary> Fetch a specific Supporting Document Type Instance. </summary>
        /// <param name="options"> Fetch SupportingDocumentType parameters </param>
        /// <param name="client"> Client to make requests to Twilio </param>
        /// <returns> Task that resolves to A single instance of SupportingDocumentType </returns>
        public static async System.Threading.Tasks.Task<SupportingDocumentTypeResource> FetchAsync(FetchSupportingDocumentTypeOptions options,
                                                                                ITwilioRestClient client = null)
        {
            client = client ?? TwilioClient.GetRestClient();
            var response = await client.RequestAsync(BuildFetchRequest(options, client));
            return FromJson(response.Content);
        }
        #endif
        /// <summary> Fetch a specific Supporting Document Type Instance. </summary>
        /// <param name="pathSid"> The unique string that identifies the Supporting Document Type resource. </param>
        /// <param name="client"> Client to make requests to Twilio </param>
        /// <returns> A single instance of SupportingDocumentType </returns>
        public static SupportingDocumentTypeResource Fetch(
                                         string pathSid,
                                         ITwilioRestClient client = null)
        {
            var options = new FetchSupportingDocumentTypeOptions(pathSid){  };
            return Fetch(options, client);
        }

        #if !NET35
        /// <summary> Fetch a specific Supporting Document Type Instance. </summary>
        /// <param name="pathSid"> The unique string that identifies the Supporting Document Type resource. </param>
        /// <param name="client"> Client to make requests to Twilio </param>
        /// <returns> Task that resolves to A single instance of SupportingDocumentType </returns>
        public static async System.Threading.Tasks.Task<SupportingDocumentTypeResource> FetchAsync(string pathSid, ITwilioRestClient client = null)
        {
            var options = new FetchSupportingDocumentTypeOptions(pathSid){  };
            return await FetchAsync(options, client);
        }
        #endif

        private static Request BuildReadRequest(ReadSupportingDocumentTypeOptions options, ITwilioRestClient client)
        {

            string path = "/v1/SupportingDocumentTypes";

            return new Request(
                HttpMethod.Get,
                Rest.Domain.Trusthub,
                path,
                queryParams: options.GetParams(),
                headerParams: null
            );
        }
        /// <summary> Retrieve a list of all Supporting Document Types. </summary>
        /// <param name="options"> Read SupportingDocumentType parameters </param>
        /// <param name="client"> Client to make requests to Twilio </param>
        /// <returns> A single instance of SupportingDocumentType </returns>
        public static ResourceSet<SupportingDocumentTypeResource> Read(ReadSupportingDocumentTypeOptions options, ITwilioRestClient client = null)
        {
            client = client ?? TwilioClient.GetRestClient();
            var response = client.Request(BuildReadRequest(options, client));
            var page = Page<SupportingDocumentTypeResource>.FromJson("supporting_document_types", response.Content);
            return new ResourceSet<SupportingDocumentTypeResource>(page, options, client);
        }

        #if !NET35
        /// <summary> Retrieve a list of all Supporting Document Types. </summary>
        /// <param name="options"> Read SupportingDocumentType parameters </param>
        /// <param name="client"> Client to make requests to Twilio </param>
        /// <returns> Task that resolves to A single instance of SupportingDocumentType </returns>
        public static async System.Threading.Tasks.Task<ResourceSet<SupportingDocumentTypeResource>> ReadAsync(ReadSupportingDocumentTypeOptions options,
                                                                                ITwilioRestClient client = null)
        {
            client = client ?? TwilioClient.GetRestClient();
            var response = await client.RequestAsync(BuildReadRequest(options, client));

            var page = Page<SupportingDocumentTypeResource>.FromJson("supporting_document_types", response.Content);
            return new ResourceSet<SupportingDocumentTypeResource>(page, options, client);
        }
        #endif
        /// <summary> Retrieve a list of all Supporting Document Types. </summary>
        /// <param name="pageSize"> How many resources to return in each list page. The default is 50, and the maximum is 1000. </param>
        /// <param name="client"> Client to make requests to Twilio </param>
        /// <param name="limit"> Record limit </param>
        /// <returns> A single instance of SupportingDocumentType </returns>
        public static ResourceSet<SupportingDocumentTypeResource> Read(
                                                     int? pageSize = null,
                                                     long? limit = null,
                                                     ITwilioRestClient client = null)
        {
            var options = new ReadSupportingDocumentTypeOptions(){ PageSize = pageSize, Limit = limit};
            return Read(options, client);
        }

        #if !NET35
        /// <summary> Retrieve a list of all Supporting Document Types. </summary>
        /// <param name="pageSize"> How many resources to return in each list page. The default is 50, and the maximum is 1000. </param>
        /// <param name="client"> Client to make requests to Twilio </param>
        /// <param name="limit"> Record limit </param>
        /// <returns> Task that resolves to A single instance of SupportingDocumentType </returns>
        public static async System.Threading.Tasks.Task<ResourceSet<SupportingDocumentTypeResource>> ReadAsync(
                                                                                int? pageSize = null,
                                                                                long? limit = null,
                                                                                ITwilioRestClient client = null)
        {
            var options = new ReadSupportingDocumentTypeOptions(){ PageSize = pageSize, Limit = limit};
            return await ReadAsync(options, client);
        }
        #endif

        /// <summary> Fetch the target page of records </summary>
        /// <param name="targetUrl"> API-generated URL for the requested results page </param>
        /// <param name="client"> Client to make requests to Twilio </param>
        /// <returns> The target page of records </returns>
        public static Page<SupportingDocumentTypeResource> GetPage(string targetUrl, ITwilioRestClient client)
        {
            client = client ?? TwilioClient.GetRestClient();

            var request = new Request(
                HttpMethod.Get,
                targetUrl
            );

            var response = client.Request(request);
            return Page<SupportingDocumentTypeResource>.FromJson("supporting_document_types", response.Content);
        }

        /// <summary> Fetch the next page of records </summary>
        /// <param name="page"> current page of records </param>
        /// <param name="client"> Client to make requests to Twilio </param>
        /// <returns> The next page of records </returns>
        public static Page<SupportingDocumentTypeResource> NextPage(Page<SupportingDocumentTypeResource> page, ITwilioRestClient client)
        {
            var request = new Request(
                HttpMethod.Get,
                page.GetNextPageUrl(Rest.Domain.Api)
            );

            var response = client.Request(request);
            return Page<SupportingDocumentTypeResource>.FromJson("supporting_document_types", response.Content);
        }

        /// <summary> Fetch the previous page of records </summary>
        /// <param name="page"> current page of records </param>
        /// <param name="client"> Client to make requests to Twilio </param>
        /// <returns> The previous page of records </returns>
        public static Page<SupportingDocumentTypeResource> PreviousPage(Page<SupportingDocumentTypeResource> page, ITwilioRestClient client)
        {
            var request = new Request(
                HttpMethod.Get,
                page.GetPreviousPageUrl(Rest.Domain.Api)
            );

            var response = client.Request(request);
            return Page<SupportingDocumentTypeResource>.FromJson("supporting_document_types", response.Content);
        }

        /// <summary>
        /// Converts a JSON string into a SupportingDocumentTypeResource object
        /// </summary>
        /// <param name="json"> Raw JSON string </param>
        /// <returns> SupportingDocumentTypeResource object represented by the provided JSON </returns>
        public static SupportingDocumentTypeResource FromJson(string json)
        {
            try
            {
                return JsonConvert.DeserializeObject<SupportingDocumentTypeResource>(json);
            }
            catch (JsonException e)
            {
                throw new ApiException(e.Message, e);
            }
        }

        ///<summary> The unique string that identifies the Supporting Document Type resource </summary>
        [JsonProperty("sid")]
        public string Sid { get; private set; }

        ///<summary> A human-readable description of the Supporting Document Type resource </summary>
        [JsonProperty("friendly_name")]
        public string FriendlyName { get; private set; }

        ///<summary> The machine-readable description of the Supporting Document Type resource </summary>
        [JsonProperty("machine_name")]
        public string MachineName { get; private set; }

        ///<summary> The required information for creating a Supporting Document </summary>
        [JsonProperty("fields")]
        public List<object> Fields { get; private set; }

        ///<summary> The absolute URL of the Supporting Document Type resource </summary>
        [JsonProperty("url")]
        public Uri Url { get; private set; }

        private SupportingDocumentTypeResource() {

        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.lowtuna.dropwizard.extras.view.handlebars;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import com.codahale.metrics.MetricRegistry;
import com.google.common.collect.ImmutableList;
import com.sun.jersey.api.client.UniformInterfaceException;
import com.sun.jersey.api.core.DefaultResourceConfig;
import com.sun.jersey.test.framework.AppDescriptor;
import com.sun.jersey.test.framework.JerseyTest;
import com.sun.jersey.test.framework.LowLevelAppDescriptor;
import io.dropwizard.logging.LoggingFactory;
import io.dropwizard.views.ViewMessageBodyWriter;
import io.dropwizard.views.ViewRenderer;
import org.junit.Test;

import static org.fest.assertions.api.Assertions.assertThat;

public class HandlebarsViewRendererTest extends JerseyTest {
    static {
        LoggingFactory.bootstrap();
    }

    @Path("/test/")
    @Produces(MediaType.TEXT_HTML)
    public static class ExampleResource {
        @GET
        @Path("/absolute")
        public AbsoluteView showAbsolute() {
            return new AbsoluteView("yay");
        }

        @GET
        @Path("/relative")
        public RelativeView showRelative() {
            return new RelativeView();
        }

        @GET
        @Path("/bad")
        public BadView showBad() {
            return new BadView();
        }
    }

    @Override
    protected AppDescriptor configure() {
        DefaultResourceConfig config = new DefaultResourceConfig();
        ViewRenderer renderer = new HandlebarsViewRenderer();
        config.getSingletons().add(new ViewMessageBodyWriter(new MetricRegistry(), ImmutableList.of(renderer)));
        config.getSingletons().add(new ExampleResource());
        return new LowLevelAppDescriptor.Builder(config).build();
    }

    @Test
    public void rendersViewsWithAbsoluteTemplatePaths() throws Exception {
        String response = client().resource(getBaseURI() + "test/absolute").get(String.class);
        assertThat(response).isEqualTo("Woop woop. yay\n");
    }

    @Test
    public void rendersViewsWithRelativeTemplatePaths() throws Exception {
        String response = client().resource(getBaseURI() + "test/relative").get(String.class);
        assertThat(response).isEqualTo("Ok.\n");
    }

    @Test
    public void returnsA500ForViewsWithBadTemplatePaths() throws Exception {
        try {
            client().resource(getBaseURI() + "test/bad").get(String.class);
        } catch (UniformInterfaceException e) {
            assertThat(e.getResponse().getStatus()).isEqualTo(500);

            assertThat(e.getResponse().getEntity(String.class))
                    .isEqualTo("<title>Missing Template</title>
Missing Template

/woo-oo-ahh.txt.hbs
");
        }
    }

}


text:
	<label for="filter_search_<?php echo $attribute_def->code; ?>"><?php _e($attribute_def->frontend_label, 'wpshop'); ?>

		<select id="filter_search_<?php echo $attribute_def->code; ?>" name="filter_search_<?php echo $attribute_def->code; ?>" class="filter_search_element" >
			<option value="all_attribute_values"><?php _e('Display all', 'wpshop'); ?></option>
			<?php echo $list_values; ?>
		</select>


text:
package org.openecard.ifd.scio;

import iso.std.iso_iec._24727.tech.schema.Connect;
import iso.std.iso_iec._24727.tech.schema.ControlIFD;
import iso.std.iso_iec._24727.tech.schema.ControlIFDResponse;
import iso.std.iso_iec._24727.tech.schema.EstablishChannel;
import iso.std.iso_iec._24727.tech.schema.EstablishChannelResponse;
import iso.std.iso_iec._24727.tech.schema.EstablishContext;
import iso.std.iso_iec._24727.tech.schema.InputUnitType;
import iso.std.iso_iec._24727.tech.schema.ListIFDs;
import iso.std.iso_iec._24727.tech.schema.PasswordAttributesType;
import iso.std.iso_iec._24727.tech.schema.PasswordTypeType;
import iso.std.iso_iec._24727.tech.schema.PinInputType;
import iso.std.iso_iec._24727.tech.schema.VerifyUser;
import iso.std.iso_iec._24727.tech.schema.VerifyUserResponse;
import java.math.BigInteger;
import jakarta.activation.UnsupportedDataTypeException;
import jakarta.xml.bind.JAXBException;
import org.openecard.common.ECardConstants;
import org.openecard.common.util.ByteUtils;
import org.openecard.common.util.PINUtils;
import org.openecard.common.util.StringUtils;
import org.openecard.common.util.UtilException;
import org.openecard.gui.swing.SwingDialogWrapper;
import org.openecard.gui.swing.SwingUserConsent;
import org.openecard.ifd.scio.reader.PCSCFeatures;
import org.openecard.ifd.scio.reader.PCSCPinModify;
import org.openecard.ifd.scio.reader.PCSCPinVerify;
import org.openecard.ws.marshal.WSMarshaller;
import org.openecard.ws.marshal.WSMarshallerException;
import org.openecard.ws.marshal.WSMarshallerFactory;
import org.testng.annotations.Test;
import org.xml.sax.SAXException;
import static iso.std.iso_iec._24727.tech.schema.PasswordTypeType.*;
import java.util.Locale;
import org.openecard.common.ClientEnv;
import static org.testng.Assert.*;

/**
 *
 * @author Tobias Wich
 */
public class PINTest {

    private static PasswordAttributesType create(boolean needsPadding, PasswordTypeType pwdType, int minLen, int storedLen, int maxLen) {
	PasswordAttributesType r = create(needsPadding, pwdType, minLen, storedLen);
	r.setMaxLength(BigInteger.valueOf(maxLen));
	return r;
    }
    private static PasswordAttributesType create(boolean needsPadding, PasswordTypeType pwdType, int minLen, int storedLen) {
	PasswordAttributesType r = new PasswordAttributesType();
	r.setMinLength(BigInteger.valueOf(minLen));
	r.setStoredLength(BigInteger.valueOf(storedLen));
	r.setPwdType(pwdType);
	if (needsPadding) {
	    r.getPwdFlags().add("needs-padding");
	}
	return r;
    }

    @Test
    public void testISO() throws UtilException {
	PasswordAttributesType pwdAttr = create(true, ISO_9564_1, 4, 8, 12);

	byte[] pinMask = PINUtils.createPinMask(pwdAttr);
	assertEquals(new byte[] {0x20,(byte)0xFF,(byte)0xFF,(byte)0xFF,(byte)0xFF,(byte)0xFF,(byte)0xFF,(byte)0xFF}, pinMask);

	byte[] pinResult = PINUtils.encodePin("123456789".toCharArray(), pwdAttr);
	assertEquals(new byte[] {0x29,0x12,0x34,0x56,0x78,(byte)0x9F,(byte)0xFF,(byte)0xFF}, pinResult);
    }

    @Test
    public void testBCD() throws UtilException {
	PasswordAttributesType pwdAttr = create(true, BCD, 4, 3, 6);
	pwdAttr.setPadChar(new byte[]{(byte)0xFF});

	byte[] pinMask = PINUtils.createPinMask(pwdAttr);
	assertEquals(new byte[] {(byte)0xFF,(byte)0xFF,(byte)0xFF}, pinMask);

	byte[] pinResult = PINUtils.encodePin("12345".toCharArray(), pwdAttr);
	assertEquals(new byte[] {(byte)0x12,(byte)0x34,(byte)0x5F}, pinResult);
    }

    @Test
    public void testASCII() throws UtilException {
	PasswordAttributesType pwdAttr = create(false, ASCII_NUMERIC, 6, 6);

	byte[] pinResult = PINUtils.encodePin("123456".toCharArray(), pwdAttr);
	assertEquals(new byte[] {0x31,0x32,0x33,0x34,0x35,0x36}, pinResult);

	try {
	    pwdAttr = create(true, ASCII_NUMERIC, 6, 6);
	    PINUtils.encodePin("123456".toCharArray(), pwdAttr);
	    fail(); // padding needed, but no char given
	} catch (UtilException ex) {
	}
//	try {
//	    pwdAttr = create(false, ASCII_NUMERIC, 6, 7);
//	    PINUtils.encodePin("123456", pwdAttr);
//	    fail(); // padding inferred, but no char given
//	} catch (UtilException ex) {
//	}
    }

    @Test
    public void testHalfNibble() throws UtilException {
	PasswordAttributesType pwdAttr = create(false, HALF_NIBBLE_BCD, 6, 6);

	byte[] pinResult = PINUtils.encodePin("123456".toCharArray(), pwdAttr);
	assertEquals(new byte[] {(byte)0xF1,(byte)0xF2,(byte)0xF3,(byte)0xF4,(byte)0xF5,(byte)0xF6}, pinResult);

	pwdAttr = create(true, HALF_NIBBLE_BCD, 6, 7);
	pwdAttr.setPadChar(new byte[]{(byte)0xFF});

	pinResult = PINUtils.encodePin("123456".toCharArray(), pwdAttr);
	assertEquals(new byte[] {(byte)0xF1,(byte)0xF2,(byte)0xF3,(byte)0xF4,(byte)0xF5,(byte)0xF6,(byte)0xFF}, pinResult);
    }

    @Test
    public void verifyISO() throws IFDException {
	PasswordAttributesType pwdAttr = create(true, ISO_9564_1, 4, 8);
	PCSCPinVerify ctrlStruct = new PCSCPinVerify(pwdAttr, StringUtils.toByteArray("00200001"));
	ctrlStruct.setLang(Locale.GERMANY);
	byte[] structData = ctrlStruct.toBytes();
	String pinStr = "00 20 00 01 08 20 FF FF FF FF FF FF FF"; // length=13
	String ctrlStr = "3C 00 89 47 04 0E04 02 01 0704 00 000000 0D000000";
	byte[] referenceData = StringUtils.toByteArray(ctrlStr + pinStr, true);
	assertEquals(referenceData, structData);
    }

    @Test
    public void verifyASCII() throws IFDException {
	PasswordAttributesType pwdAttr = create(false, ASCII_NUMERIC, 4, 4);
	PCSCPinVerify ctrlStruct = new PCSCPinVerify(pwdAttr, StringUtils.toByteArray("00200001"));
	ctrlStruct.setLang(Locale.GERMANY);
	byte[] structData = ctrlStruct.toBytes();
	String pinStr = "00 20 00 01"; // length=5
	String ctrlStr = "3C 00 82 04 00 0404 02 01 0704 00 000000 04000000";
	byte[] referenceData = StringUtils.toByteArray(ctrlStr + pinStr, true);
	assertEquals(referenceData, structData);
    }

    @Test(enabled=false)
    public void testModifyPin() throws IFDException, WSMarshallerException, SAXException {
	IFD ifd = new IFD();
	ClientEnv env = new ClientEnv();
	env.setGUI(new SwingUserConsent(new SwingDialogWrapper()));
	ifd.setEnvironment(env);
	EstablishContext eCtx = new EstablishContext();
	byte[] ctxHandle = ifd.establishContext(eCtx).getContextHandle();

	ListIFDs listIFDs = new ListIFDs();
	listIFDs.setContextHandle(ctxHandle);
	String ifdName = ifd.listIFDs(listIFDs).getIFDName().get(0);

	Connect connect = new Connect();
	connect.setContextHandle(ctxHandle);
	connect.setIFDName(ifdName);
	connect.setSlot(BigInteger.ZERO);
	byte[] slotHandle = ifd.connect(connect).getSlotHandle();

	// prepare pace call
	String xmlCall = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
		"<iso:EstablishChannel xmlns:iso=\"urn:iso:std:iso-iec:24727:tech:schema\">\n" +
		"  <iso:SlotHandle>" + ByteUtils.toHexString(slotHandle) + "</iso:SlotHandle>\n" +
		"  <iso:AuthenticationProtocolData Protocol=\"urn:oid:0.4.0.127.0.7.2.2.4\">\n" +
		"    <iso:PinID>03</iso:PinID>\n" +
		"  </iso:AuthenticationProtocolData>\n" +
		"</iso:EstablishChannel>";
	WSMarshaller m = WSMarshallerFactory.createInstance();
	EstablishChannel eCh = (EstablishChannel) m.unmarshal(m.str2doc(xmlCall));

	// send pace call
	EstablishChannelResponse eChR = ifd.establishChannel(eCh);
	assertEquals(eChR.getResult().getResultMajor(), ECardConstants.Major.OK);

	PasswordAttributesType pwdAttr = create(true, ASCII_NUMERIC, 6, 6, 6);
	pwdAttr.setPadChar(new byte[]{(byte) 0x3F});
	PCSCPinModify ctrlStruct = new PCSCPinModify(pwdAttr, StringUtils.toByteArray("002C0203"));
	byte[] structData = ctrlStruct.toBytes();
	String pinStr = "00 2C 02 03 06 3F3F3F3F3F3F";
	String ctrlStr = "15 05 82 06 00 00 00 0606 01 02 02 0407 00 01 02 000000 0B000000";
	// This is the command the 'AusweisApp' sends
	//String ausweisApp = "150582080000000606010202090400010200000005000000002C020300";

	byte[] referenceData = StringUtils.toByteArray(ctrlStr + pinStr, true);
	assertEquals(referenceData, structData);

	ControlIFD controlIFD = new ControlIFD();
	controlIFD.setCommand(ByteUtils.concatenate((byte) PCSCFeatures.MODIFY_PIN_DIRECT, structData));
	controlIFD.setSlotHandle(slotHandle);
	ControlIFDResponse response = ifd.controlIFD(controlIFD);
    }

    @Test(enabled=false)
    public void verifyeGK() {
	IFD ifd = new IFD();
	ClientEnv env = new ClientEnv();
	env.setGUI(new SwingUserConsent(new SwingDialogWrapper()));
	ifd.setEnvironment(env);
	EstablishContext eCtx = new EstablishContext();
	byte[] ctxHandle = ifd.establishContext(eCtx).getContextHandle();

	ListIFDs listIFDs = new ListIFDs();
	listIFDs.setContextHandle(ctxHandle);
	String ifdName = ifd.listIFDs(listIFDs).getIFDName().get(0);

	Connect connect = new Connect();
	connect.setContextHandle(ctxHandle);
	connect.setIFDName(ifdName);
	connect.setSlot(BigInteger.ZERO);
	byte[] slotHandle = ifd.connect(connect).getSlotHandle();

	VerifyUser verify = new VerifyUser();
	verify.setSlotHandle(slotHandle);
	InputUnitType inputUnit = new InputUnitType();
	verify.setInputUnit(inputUnit);
	PinInputType pinInput = new PinInputType();
	inputUnit.setPinInput(pinInput);
	pinInput.setIndex(BigInteger.ZERO);
	pinInput.setPasswordAttributes(create(true, ISO_9564_1, 6, 8, 8));
	verify.setTemplate(StringUtils.toByteArray("00 20 00 01", true));
	VerifyUserResponse verifyR = ifd.verifyUser(verify);
	byte[] responseCode = verifyR.getResponse();
    }

    @Test(enabled=false)
    public void executePACE_PIN() throws UnsupportedDataTypeException, JAXBException, SAXException, WSMarshallerException {
	IFD ifd = new IFD();
	ClientEnv env = new ClientEnv();
	env.setGUI(new SwingUserConsent(new SwingDialogWrapper()));
	ifd.setEnvironment(env);
	EstablishContext eCtx = new EstablishContext();
	byte[] ctxHandle = ifd.establishContext(eCtx).getContextHandle();

	ListIFDs listIFDs = new ListIFDs();
	listIFDs.setContextHandle(ctxHandle);
	String ifdName = ifd.listIFDs(listIFDs).getIFDName().get(0);

	Connect connect = new Connect();
	connect.setContextHandle(ctxHandle);
	connect.setIFDName(ifdName);
	connect.setSlot(BigInteger.ZERO);
	byte[] slotHandle = ifd.connect(connect).getSlotHandle();

	// prepare pace call
	String xmlCall = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
		"<iso:EstablishChannel xmlns:iso=\"urn:iso:std:iso-iec:24727:tech:schema\">\n" +
		"  <iso:SlotHandle>" + ByteUtils.toHexString(slotHandle) + "</iso:SlotHandle>\n" +
		"  <iso:AuthenticationProtocolData Protocol=\"urn:oid:0.4.0.127.0.7.2.2.4\">\n" +
		"    <iso:PinID>03</iso:PinID>\n" +
		"  </iso:AuthenticationProtocolData>\n" +
		"</iso:EstablishChannel>";
	WSMarshaller m = WSMarshallerFactory.createInstance();
	EstablishChannel eCh = (EstablishChannel) m.unmarshal(m.str2doc(xmlCall));

	// send pace call
	EstablishChannelResponse eChR = ifd.establishChannel(eCh);
    }

}


text:
package envoy_data_cluster_v3

import (
	"bytes"
	"errors"
	"fmt"
	"net"
	"net/mail"
	"net/url"
	"regexp"
	"strings"
	"time"
	"unicode/utf8"

	"github.com/golang/protobuf/ptypes"
)

// ensure the imports are used
var (
	_ = bytes.MinRead
	_ = errors.New("")
	_ = fmt.Print
	_ = utf8.UTFMax
	_ = (*regexp.Regexp)(nil)
	_ = (*strings.Reader)(nil)
	_ = net.IPv4len
	_ = time.Duration(0)
	_ = (*url.URL)(nil)
	_ = (*mail.Address)(nil)
	_ = ptypes.DynamicAny{}
)

// define the regex for a UUID once up-front
var _outlier_detection_event_uuidPattern = regexp.MustCompile("^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$")

// Validate checks the field values on OutlierDetectionEvent with the rules
// defined in the proto definition for this message. If any rules are
// violated, an error is returned.
func (m *OutlierDetectionEvent) Validate() error {
	if m == nil {
		return nil
	}

	if _, ok := OutlierEjectionType_name[int32(m.GetType())]; !ok {
		return OutlierDetectionEventValidationError{
			field:  "Type",
			reason: "value must be one of the defined enum values",
		}
	}

	if v, ok := interface{}(m.GetTimestamp()).(interface{ Validate() error }); ok {
		if err := v.Validate(); err != nil {
			return OutlierDetectionEventValidationError{
				field:  "Timestamp",
				reason: "embedded message failed validation",
				cause:  err,
			}
		}
	}

	if v, ok := interface{}(m.GetSecsSinceLastAction()).(interface{ Validate() error }); ok {
		if err := v.Validate(); err != nil {
			return OutlierDetectionEventValidationError{
				field:  "SecsSinceLastAction",
				reason: "embedded message failed validation",
				cause:  err,
			}
		}
	}

	if len(m.GetClusterName()) < 1 {
		return OutlierDetectionEventValidationError{
			field:  "ClusterName",
			reason: "value length must be at least 1 bytes",
		}
	}

	if len(m.GetUpstreamUrl()) < 1 {
		return OutlierDetectionEventValidationError{
			field:  "UpstreamUrl",
			reason: "value length must be at least 1 bytes",
		}
	}

	if _, ok := Action_name[int32(m.GetAction())]; !ok {
		return OutlierDetectionEventValidationError{
			field:  "Action",
			reason: "value must be one of the defined enum values",
		}
	}

	// no validation rules for NumEjections

	// no validation rules for Enforced

	switch m.Event.(type) {

	case *OutlierDetectionEvent_EjectSuccessRateEvent:

		if v, ok := interface{}(m.GetEjectSuccessRateEvent()).(interface{ Validate() error }); ok {
			if err := v.Validate(); err != nil {
				return OutlierDetectionEventValidationError{
					field:  "EjectSuccessRateEvent",
					reason: "embedded message failed validation",
					cause:  err,
				}
			}
		}

	case *OutlierDetectionEvent_EjectConsecutiveEvent:

		if v, ok := interface{}(m.GetEjectConsecutiveEvent()).(interface{ Validate() error }); ok {
			if err := v.Validate(); err != nil {
				return OutlierDetectionEventValidationError{
					field:  "EjectConsecutiveEvent",
					reason: "embedded message failed validation",
					cause:  err,
				}
			}
		}

	case *OutlierDetectionEvent_EjectFailurePercentageEvent:

		if v, ok := interface{}(m.GetEjectFailurePercentageEvent()).(interface{ Validate() error }); ok {
			if err := v.Validate(); err != nil {
				return OutlierDetectionEventValidationError{
					field:  "EjectFailurePercentageEvent",
					reason: "embedded message failed validation",
					cause:  err,
				}
			}
		}

	default:
		return OutlierDetectionEventValidationError{
			field:  "Event",
			reason: "value is required",
		}

	}

	return nil
}

// OutlierDetectionEventValidationError is the validation error returned by
// OutlierDetectionEvent.Validate if the designated constraints aren't met.
type OutlierDetectionEventValidationError struct {
	field  string
	reason string
	cause  error
	key    bool
}

// Field function returns field value.
func (e OutlierDetectionEventValidationError) Field() string { return e.field }

// Reason function returns reason value.
func (e OutlierDetectionEventValidationError) Reason() string { return e.reason }

// Cause function returns cause value.
func (e OutlierDetectionEventValidationError) Cause() error { return e.cause }

// Key function returns key value.
func (e OutlierDetectionEventValidationError) Key() bool { return e.key }

// ErrorName returns error name.
func (e OutlierDetectionEventValidationError) ErrorName() string {
	return "OutlierDetectionEventValidationError"
}

// Error satisfies the builtin error interface
func (e OutlierDetectionEventValidationError) Error() string {
	cause := ""
	if e.cause != nil {
		cause = fmt.Sprintf(" | caused by: %v", e.cause)
	}

	key := ""
	if e.key {
		key = "key for "
	}

	return fmt.Sprintf(
		"invalid %sOutlierDetectionEvent.%s: %s%s",
		key,
		e.field,
		e.reason,
		cause)
}

var _ error = OutlierDetectionEventValidationError{}

var _ interface {
	Field() string
	Reason() string
	Key() bool
	Cause() error
	ErrorName() string
} = OutlierDetectionEventValidationError{}

// Validate checks the field values on OutlierEjectSuccessRate with the rules
// defined in the proto definition for this message. If any rules are
// violated, an error is returned.
func (m *OutlierEjectSuccessRate) Validate() error {
	if m == nil {
		return nil
	}

	if m.GetHostSuccessRate() > 100 {
		return OutlierEjectSuccessRateValidationError{
			field:  "HostSuccessRate",
			reason: "value must be less than or equal to 100",
		}
	}

	if m.GetClusterAverageSuccessRate() > 100 {
		return OutlierEjectSuccessRateValidationError{
			field:  "ClusterAverageSuccessRate",
			reason: "value must be less than or equal to 100",
		}
	}

	if m.GetClusterSuccessRateEjectionThreshold() > 100 {
		return OutlierEjectSuccessRateValidationError{
			field:  "ClusterSuccessRateEjectionThreshold",
			reason: "value must be less than or equal to 100",
		}
	}

	return nil
}

// OutlierEjectSuccessRateValidationError is the validation error returned by
// OutlierEjectSuccessRate.Validate if the designated constraints aren't met.
type OutlierEjectSuccessRateValidationError struct {
	field  string
	reason string
	cause  error
	key    bool
}

// Field function returns field value.
func (e OutlierEjectSuccessRateValidationError) Field() string { return e.field }

// Reason function returns reason value.
func (e OutlierEjectSuccessRateValidationError) Reason() string { return e.reason }

// Cause function returns cause value.
func (e OutlierEjectSuccessRateValidationError) Cause() error { return e.cause }

// Key function returns key value.
func (e OutlierEjectSuccessRateValidationError) Key() bool { return e.key }

// ErrorName returns error name.
func (e OutlierEjectSuccessRateValidationError) ErrorName() string {
	return "OutlierEjectSuccessRateValidationError"
}

// Error satisfies the builtin error interface
func (e OutlierEjectSuccessRateValidationError) Error() string {
	cause := ""
	if e.cause != nil {
		cause = fmt.Sprintf(" | caused by: %v", e.cause)
	}

	key := ""
	if e.key {
		key = "key for "
	}

	return fmt.Sprintf(
		"invalid %sOutlierEjectSuccessRate.%s: %s%s",
		key,
		e.field,
		e.reason,
		cause)
}

var _ error = OutlierEjectSuccessRateValidationError{}

var _ interface {
	Field() string
	Reason() string
	Key() bool
	Cause() error
	ErrorName() string
} = OutlierEjectSuccessRateValidationError{}

// Validate checks the field values on OutlierEjectConsecutive with the rules
// defined in the proto definition for this message. If any rules are
// violated, an error is returned.
func (m *OutlierEjectConsecutive) Validate() error {
	if m == nil {
		return nil
	}

	return nil
}

// OutlierEjectConsecutiveValidationError is the validation error returned by
// OutlierEjectConsecutive.Validate if the designated constraints aren't met.
type OutlierEjectConsecutiveValidationError struct {
	field  string
	reason string
	cause  error
	key    bool
}

// Field function returns field value.
func (e OutlierEjectConsecutiveValidationError) Field() string { return e.field }

// Reason function returns reason value.
func (e OutlierEjectConsecutiveValidationError) Reason() string { return e.reason }

// Cause function returns cause value.
func (e OutlierEjectConsecutiveValidationError) Cause() error { return e.cause }

// Key function returns key value.
func (e OutlierEjectConsecutiveValidationError) Key() bool { return e.key }

// ErrorName returns error name.
func (e OutlierEjectConsecutiveValidationError) ErrorName() string {
	return "OutlierEjectConsecutiveValidationError"
}

// Error satisfies the builtin error interface
func (e OutlierEjectConsecutiveValidationError) Error() string {
	cause := ""
	if e.cause != nil {
		cause = fmt.Sprintf(" | caused by: %v", e.cause)
	}

	key := ""
	if e.key {
		key = "key for "
	}

	return fmt.Sprintf(
		"invalid %sOutlierEjectConsecutive.%s: %s%s",
		key,
		e.field,
		e.reason,
		cause)
}

var _ error = OutlierEjectConsecutiveValidationError{}

var _ interface {
	Field() string
	Reason() string
	Key() bool
	Cause() error
	ErrorName() string
} = OutlierEjectConsecutiveValidationError{}

// Validate checks the field values on OutlierEjectFailurePercentage with the
// rules defined in the proto definition for this message. If any rules are
// violated, an error is returned.
func (m *OutlierEjectFailurePercentage) Validate() error {
	if m == nil {
		return nil
	}

	if m.GetHostSuccessRate() > 100 {
		return OutlierEjectFailurePercentageValidationError{
			field:  "HostSuccessRate",
			reason: "value must be less than or equal to 100",
		}
	}

	return nil
}

// OutlierEjectFailurePercentageValidationError is the validation error
// returned by OutlierEjectFailurePercentage.Validate if the designated
// constraints aren't met.
type OutlierEjectFailurePercentageValidationError struct {
	field  string
	reason string
	cause  error
	key    bool
}

// Field function returns field value.
func (e OutlierEjectFailurePercentageValidationError) Field() string { return e.field }

// Reason function returns reason value.
func (e OutlierEjectFailurePercentageValidationError) Reason() string { return e.reason }

// Cause function returns cause value.
func (e OutlierEjectFailurePercentageValidationError) Cause() error { return e.cause }

// Key function returns key value.
func (e OutlierEjectFailurePercentageValidationError) Key() bool { return e.key }

// ErrorName returns error name.
func (e OutlierEjectFailurePercentageValidationError) ErrorName() string {
	return "OutlierEjectFailurePercentageValidationError"
}

// Error satisfies the builtin error interface
func (e OutlierEjectFailurePercentageValidationError) Error() string {
	cause := ""
	if e.cause != nil {
		cause = fmt.Sprintf(" | caused by: %v", e.cause)
	}

	key := ""
	if e.key {
		key = "key for "
	}

	return fmt.Sprintf(
		"invalid %sOutlierEjectFailurePercentage.%s: %s%s",
		key,
		e.field,
		e.reason,
		cause)
}

var _ error = OutlierEjectFailurePercentageValidationError{}

var _ interface {
	Field() string
	Reason() string
	Key() bool
	Cause() error
	ErrorName() string
} = OutlierEjectFailurePercentageValidationError{}


text:
static int counter = 0;

static once_flag onceTestFlag = ONCE_FLAG_INIT;

static void onceTest(void);

static void onceTestFunc(void);

static int onceTestThread(void *arg);

#define NUM_THREADS 100

int main(void) {

    onceTest();

    puts("Resetting flag and counter");

    onceTestFlag = ONCE_FLAG_INIT;
    counter = 0;

    onceTest();

    return 0;

}

static void onceTest() {
    thrd_t threads[NUM_THREADS];

    for (int i = 0; i < NUM_THREADS; ++i)
        thrd_create(threads + i, onceTestThread, NULL);

    for (int i = 0; i < NUM_THREADS; ++i)
        thrd_join(threads[i], NULL);

    printf("Counter: %d (expecting: 1)\n", counter);
}

static void onceTestFunc(void) {
    puts("This should only appear once");
    counter++;
}

static int onceTestThread(void *arg) {
    (void)arg;
    call_once(&onceTestFlag, onceTestFunc);

    return 0;
}


text:
package de.jungblut.antcolony;

import java.util.Random;

import com.google.common.util.concurrent.AtomicDouble;

/**
 * Contains the "Pheromones" and abstractions to access them in a multithreaded
 * setting.
 *
 * @author thomas.jungblut
 *
 */
public final class WeightMatrix {

  private final double pheromonePersistence;
  // TODO this is not super efficient for very large matrices, since we want to
  // enforce a sparse matrix for weights
  private final AtomicDouble[][] weights;

  public WeightMatrix(int length, double pheromonePersistence) {
    this.pheromonePersistence = pheromonePersistence;
    weights = new AtomicDouble[length][length];
    initializeWeights();
  }

  public double readWeight(int x, int y) {
    return weights[x][y].get();
  }

  public void adjustWeight(int x, int y, double weightUpdate) {
    while (true) {
      final double val = weights[x][y].get();
      final double result = weightDecay(val, weightUpdate);
      boolean success = false;
      if (result >= 0.0d) {
        success = weights[x][y].compareAndSet(val, result);
      } else {
        success = weights[x][y].compareAndSet(val, 0);
      }
      if (success) {
        break;
      }
    }
  }

  public int numRows() {
    return weights.length;
  }

  private double weightDecay(double current, double weightUpdate) {
    return weightUpdate + (1d - pheromonePersistence) * current;
  }

  private void initializeWeights() {
    final int rows = weights.length;
    Random rand = new Random();
    for (int row = 0; row < rows; row++) {
      for (int column = 0; column < rows; column++) {
        weights[row][column] = new AtomicDouble(rand.nextDouble());
      }
    }

  }

}


text:
P = ..

BOARD_TAG = oscarleo
MONITOR_PORT = /dev/leo.usb*
ARDUINO_LIBS = AdapterBoard Backlight RGBLed EEPROM Bounce2
USER_LIB_PATH = libs

ARDUINO_DIR = $P/Arduino/
ARDUINO_CORE_PATH = $P/Arduino/hardware/arduino/cores/oscar
ARDMK_DIR = $P/Arduino-Makefile
ARDMK_PATH = $P/Arduino-Makefile/bin
OPTIMIZATION_LEVEL = 3

include $P/Arduino-Makefile/Arduino.mk


text:
<?php defined('WERUA') or include('../bad.php');

class wfitem extends wfitembase{
     var $curnode;
     var $onpage=30;
   var $curadmin;
    var $currows=array();
    var $rowscount=0;
    var $pagescount=0;var $page=0;
    var $adminnodes=array();    var $noticecount=0;
    var $totalcount=0;
    function  wfitem($wf){
      $this->noticecount=  wra_adminnotices::getcount();
      if (wra_userscontext::isloged($wf)&&wra_userscontext::hasright('adminpage')) {
              $wf->cp->baseico = true;
              $wf->cp->norobots();
              $wf->cp->bodyclass = "admin_login";
      }else {
          WRA::gotopage(WRA::base_url().'admin/login');
          $wf->nicedie();
      }

      $this->adminnodes=  WRA_ENV::adminnodes();
      for($i=0;$i<count($this->adminnodes);$i++){
        $r = wra_userscontext::getaccess($this->adminnodes[$i]->link);
        if($wf->requestedpage==$this->adminnodes[$i]->link){
            if (!$r) {
              $wf->set404();
              break;
            }
            $this->curnode=$this->adminnodes[$i];
            $this->curadmin = new wfadmin($this->curnode->link);
            break;
        }
        if (!$r) unset($this->adminnodes[$i]);
      }

      $this->header=$this->curnode->name;
      // WRA::debug($_POST);
      if(isset($_POST['import_source'])){
        $this->importUrl = $_POST['import_source'];
      }
      $this->showAlbums = false;
      if (isset($_POST['import_source_search_btn'])&&!empty($this->importUrl)) {
        $this->get_albums_list();
        $this->showAlbums = true;
      }
      $this->importAlbums = false; $this->importIndex = 0;
      if (isset($_POST['import_source_execute_btn'])&&!empty($this->importUrl)) {
        $this->get_albums_list();
        $this->importAlbums = true;
        if (isset($_POST['importIndex'])){
          $this->importIndex = (int)$_POST['importIndex'];
          if (isset($_POST['import_album'])){
            if (!empty($this->list)) {
              if (isset($_POST['parttype'])&&!empty($_POST['parttype'])){
                $parttype = $_POST['parttype'];
                $classname=  'wra_'.$parttype;
                // $code_b = $classname . '::adminit($this);';
                if (class_exists($classname)) {
                    $h = $this->list[$this->importIndex]['header'];
                    $code_b = '$retid = '.$classname.'::create_from_import($h,$h);';
                    eval($code_b);

                    $img = new wra_image();
                    $img->header = '';
                    $img->description = '';
                    $ismessage = false;
                    $admimessage = '';
                    $img->keywords = '';
                    $img->galinfoid = $retid;
                    $img->parttype = $parttype;

                    foreach ($this->list[$this->importIndex]['images'] as $k => $v) {
                      $r0 = new resizeImage();
                      $curPath = $this->importUrl.'/'.$this->list[$this->importIndex]['header'].'/'.$v;
                      $r0->setImage($curPath);
                      // WRA::debug(WRA_Path.'upload/gallery');
                      $r0->createThumb(0,250,WRA_Path.'/upload/gallery');
                      $img->tmbpic = 'upload/gallery/'.$r0->thumbName;
                      $r0->createThumb(0,1000,WRA_Path.'/upload/gallery');
                      $img->pic = 'upload/gallery/'.$r0->thumbName;
                      // WRA::debug($img);
                      // die();

                      // $wimage= wra_admintable::getpic($img->pic, $img->tmbpic, $ismessage, $admimessage, 'gallery/', 340, 'qqfile', false, true);
                      // $img->galinfoid =0;
                      // $img->width=$wimage->imagewidth;
                      // $img->height=$wimage->imageheight;

                      $languages=wra_lang::getlist();
                      $img->id = '';
                      $img->add("_ru");
                      $ruid=$img->id;
                      foreach($languages as $l0){
                          if($l0->alias!='ru'){
                            $img->id = $ruid;
                            $img->add('_'.$l0->alias);
                          }
                      }
                      // WRA::debug($img);
                    }
                }
              }
            }
          }
          // if not last album, inc album index
          if ($this->importIndex < count($this->list)){
            $this->importIndex++;
            $this->last = false;
          } else {
            $this->last = true;
          }
        }
      }
      if(isset($_POST['btnclicked'])){
        switch($_POST['btnclicked']) {
          case 'btnfind':
            // $this->curadmin->search=addslashes($_REQUEST['txtfind']);
            break;
        }
      }
      if(!$this->curadmin->multilanguages){
        // $this->currows = $this->curadmin->getrows('',$this->page+1, $this->onpage);
        // $this->totalcount=$this->curadmin->getcount();
      } else{
        // $this->currows = $this->curadmin->getrows('_'.WRA_CONF::$language,$this->page+1, $this->onpage);
        // $this->totalcount=$this->curadmin->getcount('_'.WRA_CONF::$language);
      }
      // $this->pagescount=$this->getcount();
      // WRA::debug($this->pagescount);
      // WRA::debug($this->totalcount);
    }

    function get_albums_list() {
      $this->list = array();
      $this->dirlist = scandir($this->importUrl);
      foreach ($this->dirlist as $k => $v) {
        if ($v == '..' || $v == '.') continue;
        $curPath = $this->importUrl.'/'.$v;
        if (is_dir($curPath)) {
          $this->list[count($this->list)]['header'] = $v;
          $this->list[count($this->list)-1]['curPath'] = $curPath;
          $this->list[count($this->list)-1]['images'] = scandir($curPath);
          array_shift($this->list[count($this->list)-1]['images']);
          array_shift($this->list[count($this->list)-1]['images']);
        }
      }
    }

    function run(){
      $this->nofooter=true;
      $this->noheader=true;
      if(isset($_POST['btnclicked'])){
        switch($_POST['btnclicked']) {
          case 'btnfind':
            break;
          case 'btnAdd':
            // WRA::gotopage(WRA::base_url().$this->curnode->link.'/edit');
            break;
        }
      }
    }
    function getcount(){
      $result=1;
      $amount = $this->totalcount;
      if (($amount / $this->onpage) > intval($amount / $this->onpage)) {
         $result = intval($amount / $this->onpage) + 1;
      } else {
         $result = intval($amount / $this->onpage);
      }
      return $result;
      // return ($result == 0)?($result+1):($result);
    }
    function addscripts() {
      $this->wf->cp->add_script('scripts/jquery/jquery.js');
      $this->wf->cp->add_script('scripts/jquery-migrate-1.2.1.js');
      $this->wf->cp->add_script('scripts/jquery/jquery-ui.js');
      $this->wf->cp->add_script('scripts/jquery/json.js');
      $this->wf->cp->add_script('scripts/jquery/jquery.cookie.js');
      $this->wf->cp->add_script('scripts/jquery/jquery.treetable.js');
      $this->wf->cp->add_script('scripts/admin/jstorage.js');
      $this->wf->cp->add_script('scripts/admin/jquery.jqgrid.min.js');
      $this->wf->cp->add_script('scripts/jquery/flexigrid.js');
      $this->wf->cp->add_script('scripts/tiny_mce/jquery.tinymce.js');
      $this->wf->cp->add_script('scripts/admin/admin.js');
    }

    function addstyles() {
      $this->wf->cp->add_style('styles/admin/jquery-ui.css');
      $this->wf->cp->add_style('styles/admin/jquery.treeTable.css');
      $this->wf->cp->add_style('styles/admin/flexigrid.pack.css');
         $this->wf->cp->add_style('styles/admin/ui.jqgrid.css');
      $this->wf->cp->add_style('styles/admin/workflower.css');
    }
    function show(){
        include  WRA_Path.'/template/admin/header.php';
        include  WRA_Path.'/template/admin/image/import.php';
        include  WRA_Path.'/template/admin/footer.php';
    }
}

?>


text:
import React from 'react'
import { Link } from 'react-router'
import {Card, CardActions, CardHeader, CardMedia, CardTitle, CardText} from 'material-ui/Card'
import FlatButton from 'material-ui/FlatButton'
import { StyleSheet, css } from 'aphrodite'
import ReactCSSTransitionGroup from 'react-addons-css-transition-group' // ES6
import AnimateFadeIn from '../../../components/AnimateFadeIn'
import AnimateFadeUp from '../../../components/AnimateFadeUp'

const RebateListItem = ({ rebate }) => (

    <AnimateFadeUp key={rebate.uuid}>
      <Card>
        <CardHeader
          title={rebate.title}
          avatar={rebate.brand.logo}
          />
        <CardMedia>

        </CardMedia>
        <CardTitle subtitle={`\$${rebate.amount} rebate`} />
        <CardActions>
          <FlatButton label='claim' containerElement={<Link to={`/rebate/${rebate.slug}`} />} primary />
          <FlatButton label='shop' containerElement={<Link to={rebate.amazon} />} target='_blank' />
        </CardActions>
      </Card>
    </AnimateFadeUp>

)

const styles = StyleSheet.create({
  listItem: {
    // margin: '0 auto 1.5rem'
    // width: '100%',
    width: 300,
    maxWidth: 300
  },
  title: {
    fontSize: 28,
    textDecoration: 'none',
    lineHeight: '1.2',
    margin: '0 0 1.5rem',
    color: '#000',
    transition: '.3s opacity ease',
    ':hover': {
      opacity: 0.5
    }
  },
  image: {
    maxWidth: '100%'
  }
})

export default RebateListItem


text:
nagios-plugins-mq
=================

IBM Websphere MQ - Nagios check plugins

#Requirements
pymqi


text:
<?php
session_start();
    include('db.php');

    if(isset($_POST['sub'])){
      $name = $_POST['name'] ;
      $password = $_POST['pass'] ;
      $query = "INSERT INTO user VALUES (NULL,'$name','$password',NULL,NULL,NULL,NULL,NULL)";
      $result = mysqli_query($conn,$query);
      $_SESSION['username']=$_POST['name'];
    }

    if(isset($_POST['submit'])){
      $name = $_POST['username'] ;
      $pass = $_POST['psw'];
      $result = mysqli_query($conn,"SELECT username,password FROM user where username='$name' and password='$pass'");
    if(mysqli_num_rows($result) > 0){
    $_SESSION['signed_in']=true ;
    $_SESSION['username']=$_POST['username'];
    header('location: index.php');
    }
    else
    header('location: home.php?error');
    }

?>

    	<button class="navbar-toggle" type="button" data-toggle="collapse" data-target=".js-navbar-collapse">
			Toggle navigation

		</button>
		Feed Me

    			Discover

Governorates

Ariana

Manouba

Sousse

Sfax

Touzer

Kef

Kbeli

Nabeul

Restaurants

Le Duc

Restaurant Chez Slah

Dar El Jeld

Restaurant le Parnasse

Restaurant El-Walima

Coloured Headers

Primary Buttons & Default

Good Deals

chicken fingers

                                    <button class="btn btn-primary" type="button">4.9 DT</button> <button href="#" class="btn btn-default" type="button"> Add to Wishlist</button>

Double Beef Sandwish

                                    <button class="btn btn-primary" type="button">6.5 DT</button> <button href="#" class="btn btn-default" type="button"> Add to Wishlist</button>

Humberger

                                    <button class="btn btn-primary" type="button">5 DT</button> <button href="#" class="btn btn-default" type="button"> Add to Wishlist</button>

                                Previous

                                Next

See more suggestions

          <?php  if (!$_SESSION['signed_in']) { ?>

          Log in

  ×

  <form class="modal-content animate" action="/index.php">

      Username
      <input type="text" placeholder="Enter Username" name="uname" required="">

      Password
      <input type="password" placeholder="Enter Password" name="psw" required="">

      <button type="submit">Login</button>
      <input type="checkbox" checked="checked"> Remember me

      <button type="button" onclick="document.getElementById('id01').style.display='none'" class="cancelbtn">Cancel</button>
      Forgot password?

  </form>

          Sign up

            ×
            <form class="modal-content animate" action="index.php">

                Username
                <input type="text" placeholder="Enter Username" name="username" required="">

                Password
                <input type="password" placeholder="Enter Password" name="psw" required="">

                Repeat Password
                <input type="password" placeholder="Repeat Password" name="psw-repeat" required="">
                <input type="checkbox" checked="checked"> Remember me

By creating an account you agree to our Terms & Privacy.

                  <button type="button" onclick="document.getElementById('id01').style.display='none'" class="cancelbtn">Cancel</button>
                  <button type="submit" class="signupbtn">Sign Up</button>

            </form>

    <?php   }else{  ?>

          <?=$_SESSION['username'] ?>

          sign out

  <?php   } ?>

Become a partner


text:
package assert

import "reflect"

type nilValueMatcher struct {
	message string
}

// NilValue checks if the value is nil
func NilValue() *nilValueMatcher {
	matcher := new(nilValueMatcher)
	return matcher
}

func (m *nilValueMatcher) Message(message string) Matcher {
	m.message = message
	return m
}

func (m *nilValueMatcher) Matches(value interface{}) bool {
	if value == nil {
		return true
	}
	r := reflect.ValueOf(value)
	if r.Kind() != reflect.Ptr {
		return false
	}
	return r.IsNil()
}

func (m *nilValueMatcher) DescribeMismatch(value interface{}) error {
	return buildError("expected nil but: was <%v>", m.message, value)
}


text:
export default {
  methods: {
    lineCssClass(line) {
      return {
        head: line.isHead,
        origin: line.isOrigin,
        match: line.hasMatch,
        selected: line.isSelected,
        unselected: line.isUnselected,
      };
    },
  },
};


text:
<?php
/*
* private variable and functions are prefixed with underscore('_')
*/

require_once('TranslationContainer.php');

class TMXParser {
	private $_parser = null;
	private $_xmlFile = null;

	private $_currentTuid = null;
	private $_boolSeg = false;
	private $_currentLanguage = null;

	private $_currentPage = null;
	private $_boolPage = false;

	private $_currentData = '';
	private $_tc = null;

	private $_masterLanguage = 'en';

	public function __construct($xmlFile='', $masterLanguage = '') {
		if($masterLanguage != '') {
			$this->_masterLanguage = $masterLanguage;
		}

		$this->_xmlFile = $xmlFile;
	}

	public function doParse() {

		$this->_tc = new TranslationContainer($this->_masterLanguage);

		$this->_parser = xml_parser_create();
		xml_set_element_handler($this->_parser, "_startElement", "_endElement");
		xml_set_object($this->_parser, $this);
		xml_parser_set_option($this->_parser, XML_OPTION_CASE_FOLDING, 0);
		xml_parser_set_option($this->_parser, XML_OPTION_TARGET_ENCODING, 'utf-8');
		xml_set_character_data_handler($this->_parser, "_contentElement");

		if ($this->_xmlFile === null) {
			throw new Exception('Translation source xml is set. Use setXML() or constructor to set source xml.');
		}

		if (!is_readable($this->_xmlFile)) {
			throw new Exception('Translation source xml is not readable.');
		}

		if (!xml_parse($this->_parser, file_get_contents($this->_xmlFile))) {
			$ex = sprintf('XML error: %s at line %d',
					xml_error_string(xml_get_error_code($this->_parser)),
					xml_get_current_line_number($this->_parser));

			xml_parser_free($this->_parser);

			throw new Exception($ex);
		}

		return $this->_tc;
	}

	private function _startElement($parser, $name, $atrrs) {
		//echo '
name='.$name.'
';
		//print_r($atrrs);
		if ($this->_boolSeg != false) {
			//echo '
##############
';
			$this->_currentData .= "<".$name;
			foreach($atrrs as $key => $value) {
				$this->_currentData .= " $key=\"$value\"";
			}
			$this->_content .= ">";
		}
		else {
			switch (strtolower($name)) {
				case 'tu':
					if(isset($atrrs['tuid']) === true){
						$this->_currentTuid = $atrrs['tuid'];
					}
					break;
				case 'tuv':
					if(isset($atrrs['xml:lang']) === true){
						$this->_currentLanguage = $atrrs['xml:lang'];
					}
					break;
				case 'prop':
					if( isset($atrrs['type']) === true && $atrrs['type'] == 'page' ){
						$this->_boolPage = true;
						$this->_currentPage = '';
					}
					break;
				case 'seg':
					$this->_boolSeg = true;
					$this->_currentData = '';
					break;
			}
		}
	}

	private function _endElement($parser, $name)  {
		//echo '
endname='.$name.'
';
		if (($this->_boolSeg != false) and ($name !== 'seg')) {
			//echo '
##############
';
			$this->_currentData .= "</".$name.">";
		}
		else {
			switch (strtolower($name)) {
				case 'tu':
					$this->_currentTuid = null;
					break;

				case 'tuv':
					$this->_currentLanguage = null;
					break;

				case 'prop':
					if( $this->_boolPage ){
						$this->_boolPage = false;
						//$this->_currentPage = '';
					}
					break;

				case 'seg':
					$this->_boolSeg = false;
					if( ($this->_tc !== null) || !$this->_tc->hasId($this->_currentTuid) ) {
						//$this->_currentData = html_entity_decode($this->_currentData, ENT_QUOTES, 'utf-8');
						$this->_currentData = base64_decode($this->_currentData);

						$this->_tc->addWordTuid($this->_currentTuid, $this->_currentData, $this->_currentLanguage, $this->_currentPage);
						//echo '
 '.$this->_currentData;
					}

					break;
			}
		}
	}

	private function _contentElement($parser, $data) {
		//echo '
content='.$this->_currentData;
		if($this->_boolSeg && $this->_currentTuid !== null && $this->_currentLanguage !== null ) {
			$this->_currentData .= $data;

		}

		if( $this->_boolPage ) {
			$this->_currentPage = $data;
		}
	}

	public function getXML() {
		return $this->_xmlFile;
	}

	public function setXML($xmlFile) {
		$this->_xmlFile = $xmlFile;
	}

	public function getMasterLanguage() {
		return $this->_xmlFile;
	}

	public function setMasterLanguage($lang) {
		$this->_masterLanguage = $lang;
	}
}


text:
@implementation EqumentCollectionViewCell

- (instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
       CGFloat weight = [UIScreen mainScreen].bounds.size.width;
        self.picImg = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, weight/5, weight/5)];
        _picImg.layer.cornerRadius = 20;
        _picImg.layer.masksToBounds = YES;
        _picImg.backgroundColor = [UIColor blueColor];
        [self addSubview:_picImg];

        self.textLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, weight/5+2, weight/5, 50)];
        _textLabel.numberOfLines = 0;
        _textLabel.font = [UIFont systemFontOfSize:13];
        _textLabel.textAlignment = NSTextAlignmentCenter;
        [self addSubview:_textLabel];
    }

    return self;
}

@end


text:
<?php
/* fr/order_list.php */

/* mobile order list */
$lang['mobile_orderList_myAccount'] = 'Mon Compte';
$lang['mobile_orderList_myOrders'] = 'Mes Commandes';
$lang['mobile_orderList_orderId'] = 'Numéro de Commande';
$lang['mobile_orderList_total'] = 'Total de la commande';
$lang['mobile_orderList_date'] = 'Date';
$lang['mobile_orderList_status'] = 'Statut';
$lang['mobile_orderList_noOrders'] = 'Vous n\'avez jamais commandé.';


text:
"""
    instabot example

    Workflow:
    1) Unarchives your last medias

"""

import os
import sys

sys.path.append(os.path.join(sys.path[0], "../"))
from instabot import Bot  # noqa: E402

bot = Bot()
bot.login()
medias = bot.get_archived_medias()
bot.unarchive_medias(medias)


text:
using namespace std;

class ACO
{
private:
	Node* listofNode;
	Edge* listofEdges;
	Ant* listofAnts;
	double** amatrix;
	int amatrixsize;
	int amountofedges = 0;
	double alpha;
	double beta;
	bool allFinished(int ants)
	{
		for (int i = 0; i < ants; i++)
		{
			if (!listofAnts[i].isFinished())
			{
				return true;
			}
		}
		return false;
	}
public:
	ACO();
	ACO(double** amatrix, int amatrixsize, double alpha, double beta);
	~ACO();
	void printSelectedPath(int startNode, int endNode)
	{
		Ant ant;
		ant.setupAnt(startNode, endNode, 1, listofNode, listofEdges, amatrixsize, amountofedges, 2, 0);

		ant.printPath();
	}
	void findroute(int ants, int startNode, int endNode,int trips)
	{
		int antsfinsished = 0;
		//create array of ants
		listofAnts = new Ant[ants];
		for (int i = 0; i < ants; i++)
		{
			listofAnts[i].setupAnt(startNode, endNode, trips, listofNode, listofEdges, amatrixsize, amountofedges, alpha, beta);
		}

		while(allFinished(ants))
		{
			//let all ants travel
			for (int i = 0; i < ants; i++)
			{
				listofAnts[i].travel();
			}
			//lay Pheromones for traveled edges
			for (int i = 0; i < ants; i++)
			{
				listofAnts[i].layPheromones();
			}
			//decay Pheromones for all edges
			for (int i = 0; i < amountofedges; i++)
			{
				listofEdges[i].pheromoneDecay();
			}
		}
		delete[] listofAnts;
		printSelectedPath(startNode, endNode);
	}

};
ACO::ACO()
{

}
ACO::ACO(double** amatrix, int amatrixsize, double alpha, double beta)
{
	this->alpha = alpha;
	this->beta = beta;
	this->amatrixsize = amatrixsize;
	//creating nodes
	listofNode = new Node[amatrixsize];
	//finding out how many edges in graph
	for (int i = 0; i < amatrixsize; i++){
		for (int j = i; j < amatrixsize; j++){
			if (amatrix[i][j] != -1)
				amountofedges++;
			}
	}

	listofEdges = new Edge[amountofedges];
	int edgecount = 0;

	//creating edges
	for (int i = 0; i < amatrixsize; i++)
	{
		listofNode[i].setnodeIdentity(i + 1);

		for (int j = i; j < amatrixsize; j++)
		{

			if (amatrix[i][j] != -1)
			{
				listofEdges[edgecount].setEdgeID(edgecount + 1);
				listofEdges[edgecount].setStartNode(i+1);
				listofEdges[edgecount].setEndNode(j+1);
				listofEdges[edgecount].setdistance(amatrix[i][j]);
				edgecount++;
			}
		}
	}
	for (int i = 0; i < amatrixsize; i++)
	{
		delete[] amatrix[i];
	}
	delete[] amatrix;
}
ACO::~ACO()
{
	delete[] listofEdges;
	delete[] listofNode;

}


text:
package com.google.cloud.tools.appengine.configuration;

import com.google.common.base.Preconditions;
import java.util.Collection;
import javax.annotation.Nullable;

public class VersionsSelectionConfiguration {

  @Nullable private final String service;
  @Nullable private final String projectId;
  private final Collection<String> versions;

  private VersionsSelectionConfiguration(
      @Nullable String service, @Nullable String projectId, Collection<String> versions) {
    this.service = service;
    this.projectId = projectId;
    this.versions = versions;
  }

  public Collection<String> getVersions() {
    return versions;
  }

  @Nullable
  public String getService() {
    return service;
  }

  @Nullable
  public String getProjectId() {
    return projectId;
  }

  public static Builder builder(Collection<String> versions) {
    return new Builder(versions);
  }

  public static class Builder {
    @Nullable private String service;
    @Nullable private String projectId;
    private final Collection<String> versions;

    private Builder(Collection<String> versions) {
      Preconditions.checkNotNull(versions);
      Preconditions.checkArgument(versions.size() != 0);

      this.versions = versions;
    }

    public Builder service(@Nullable String service) {
      this.service = service;
      return this;
    }

    public Builder projectId(@Nullable String projectId) {
      this.projectId = projectId;
      return this;
    }

    public VersionsSelectionConfiguration build() {
      return new VersionsSelectionConfiguration(service, projectId, versions);
    }
  }
}


text:
let fs = require("fs");
let _ = require("lodash");
let util = require("../util");

let data = fs.readFileSync("./data").toString();

let distances = {};

data.split("\n").forEach(line => {
	let parts = line.split(" to ");

	let fromCity = parts[0];
	let toCity = parts[1].split(" = ")[0];
	let distance = parseInt(parts[1].split(" = ")[1]);

	if (!distances[fromCity]) distances[fromCity] = {};
	if (!distances[toCity]) distances[toCity] = {};

	distances[fromCity][toCity] = distance;
	distances[toCity][fromCity] = distance;
});

function getDistance(cityA, cityB) {
	return distances[cityA][cityB];
}

const cities = Object.keys(distances);

let travelDistances = util.permutations(cities).map(possibility => {
	let distanceTraveled = 0;

	let lastCity = possibility.shift();

	while (possibility.length > 0) {
		let currentCity = possibility.shift();
		distanceTraveled += getDistance(lastCity, currentCity);
		lastCity = currentCity;
	}

	return distanceTraveled;
});

let sortedDistances = travelDistances.sort((a, b) => a - b);

console.log("Part 1:", sortedDistances[0]);
console.log("Part 2:", sortedDistances[sortedDistances.length - 1]);


text:
/**
 * Created by allianzcortex on 17-4-19.
 */
import org.apache.thrift.server.TServer;
import org.apache.thrift.server.TServer.Args;
import org.apache.thrift.server.TSimpleServer;
import org.apache.thrift.transport.TServerSocket;
import org.apache.thrift.transport.TServerTransport;

public class MultiplicationServer {

  public static MultiplicationHandler handler;

  public static MultiplicationService.Processor processor;

  public static void main(String [] args) {
    try {
      handler = new MultiplicationHandler();
      processor = new MultiplicationService.Processor(handler);

      Runnable simple = new Runnable() {
        public void run() {
          simple(processor);
        }
      };

      new Thread(simple).start();
    } catch (Exception x) {
      x.printStackTrace();
    }
  }

  public static void simple(MultiplicationService.Processor processor) {
    try {
      TServerTransport serverTransport = new TServerSocket(9090);
      TServer server = new TSimpleServer(new Args(serverTransport).processor(processor));

      System.out.println("Starting the simple server...");
      server.serve();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

}


text:
namespace Ui {
class ControlWidget;
}

class ControlWidget : public QWidget
{
    Q_OBJECT

public:
    explicit ControlWidget(QWidget *parent = 0, QString id_game = "", QString id_player = "");
    void paintEvent(QPaintEvent*);
    void setCursorText(bool course);
    ~ControlWidget();

public slots:
    void chatClosed();
    void openChat();

private:
    QWidget *chat = nullptr;
    Ui::ControlWidget *ui;
    bool chatOpen = false;
    QString _id_game;
    QString _id_player;
};

#endif // CONTROLWIDGET_H


text:
function os::build::image() {
	local tag=$1
	local directory=$2
	local extra_tag

	if [[ ! "${tag}" == *":"* ]]; then
		# if no tag was specified in the image name,
		# tag with :latest and the release commit, if
		# available, falling back to the last commit
		# if no release commit is recorded
		local release_commit
		release_commit="${OS_RELEASE_COMMIT-}"
		if [[ -z "${release_commit}" && -f "${OS_OUTPUT_RELEASEPATH}/.commit" ]]; then
			release_commit="$( cat "${OS_OUTPUT_RELEASEPATH}/.commit" )"
		fi
		if [[ -z "${release_commit}" ]]; then
			release_commit="$( git log -1 --pretty=%h )"
		fi
		extra_tag="${tag}:${release_commit}"

		tag="${tag}:latest"
	fi

	local result=1
	local image_build_log
	image_build_log="$( mktemp "${BASETMPDIR}/imagelogs.XXXXX" )"
	for (( i = 0; i < "${OS_BUILD_IMAGE_NUM_RETRIES:-2}"; i++ )); do
		if [[ "${i}" -gt 0 ]]; then
			os::log::internal::prefix_lines "[${tag%:*}]" "$( cat "${image_build_log}" )"
			os::log::warning "Retrying image build for ${tag}, attempt ${i}..."
		fi

		if os::build::image::internal::generic "${tag}" "${directory}" "${extra_tag:-}" >"${image_build_log}" 2>&1; then
			result=0
			break
		fi
	done

	os::log::internal::prefix_lines "[${tag%:*}]" "$( cat "${image_build_log}" )"
	return "${result}"
}
readonly -f os::build::image

# os::build::image::internal::generic builds a container image using either imagebuilder
# or docker, defaulting to imagebuilder if present
#
# Globals:
#  - OS_BUILD_IMAGE_ARGS
# Arguments:
#  - 1: the directory in which to build
#  - 2: the tag to apply to the image
#  - 3: optionally, extra tags to add
# Returns:
#  None
function os::build::image::internal::generic() {
	local directory=$2

	local result=1
	if os::util::find::system_binary 'imagebuilder' >/dev/null; then
		if os::build::image::internal::imagebuilder "$@"; then
			result=0
		fi
	else
		os::log::warning "Unable to locate 'imagebuilder' on PATH, falling back to Docker build"
		if os::build::image::internal::docker "$@"; then
			result=0
		fi
	fi

	# ensure the temporary contents are cleaned up
	git clean -fdx "${directory}"
	return "${result}"
}
readonly -f os::build::image::internal::generic

# os::build::image::internal::imagebuilder builds a container image using imagebuilder
#
# Globals:
#  - OS_BUILD_IMAGE_ARGS
# Arguments:
#  - 1: the directory in which to build
#  - 2: the tag to apply to the image
#  - 3: optionally, extra tags to add
# Returns:
#  None
function os::build::image::internal::imagebuilder() {
	local tag=$1
	local directory=$2
	local extra_tag="${3-}"
	local options=()

	if [[ -n "${OS_BUILD_IMAGE_ARGS:-}" ]]; then
		options=( ${OS_BUILD_IMAGE_ARGS} )
	fi

	if [[ -n "${extra_tag}" ]]; then
		options+=( -t "${extra_tag}" )
	fi

	imagebuilder "${options[@]:-}" -t "${tag}" "${directory}"
}
readonly -f os::build::image::internal::imagebuilder

# os::build::image::internal::docker builds a container image using docker
#
# Globals:
#  - OS_BUILD_IMAGE_ARGS
# Arguments:
#  - 1: the directory in which to build
#  - 2: the tag to apply to the image
#  - 3: optionally, extra tags to add
# Returns:
#  None
function os::build::image::internal::docker() {
	local tag=$1
	local directory=$2
	local extra_tag="${3-}"
	local options=()

	if ! docker build ${OS_BUILD_IMAGE_ARGS:-} -t "${tag}" "${directory}"; then
		return 1
	fi

	if [[ -n "${extra_tag}" ]]; then
		docker tag "${tag}" "${extra_tag}"
	fi
}
readonly -f os::build::image::internal::docker


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
version (Jena Framework)
</TITLE>

<META NAME="date" CONTENT="2010-06-01">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

jena

Class version

java.lang.Object
  jena.version

All Implemented Interfaces:
Jena

public class version
extends java.lang.Object
implements Jena

jena.version
 Print out jena version information and exit.

Author:

Jeremy J. Carroll

Field Summary

Fields inherited from interface com.hp.hpl.jena.Jena

BUILD_DATE, MAJOR_VERSION, MINOR_VERSION, NAME, PATH, REVISION_VERSION, UNSET, VERSION, VERSION_STATUS, WEBSITE

Constructor Summary

version()

Method Summary

static void
main(java.lang.String[] args)

          Print out jena version information and exit.

Methods inherited from class java.lang.Object

equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

version

public version()

Method Detail

main

public static void main(java.lang.String[] args)
                 throws java.lang.IllegalArgumentException,
                        java.lang.IllegalAccessException

Print out jena version information and exit.

Parameters:
args -

Throws:

java.lang.IllegalAccessException

java.lang.IllegalArgumentException

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

Copyright © 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009 Hewlett-Packard Development Company, LP