text:
package org.onosproject.provider.lldp.impl;

import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Maps;
import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Deactivate;
import org.apache.felix.scr.annotations.Modified;
import org.apache.felix.scr.annotations.Property;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.ReferenceCardinality;
import org.onlab.packet.Ethernet;
import org.onosproject.cfg.ComponentConfigService;
import org.onosproject.core.ApplicationId;
import org.onosproject.core.CoreService;
import org.onosproject.mastership.MastershipEvent;
import org.onosproject.mastership.MastershipListener;
import org.onosproject.mastership.MastershipService;
import org.onosproject.net.ConnectPoint;
import org.onosproject.net.Device;
import org.onosproject.net.DeviceId;
import org.onosproject.net.LinkKey;
import org.onosproject.net.Port;
import org.onosproject.net.device.DeviceEvent;
import org.onosproject.net.device.DeviceListener;
import org.onosproject.net.device.DeviceService;
import org.onosproject.net.flow.DefaultTrafficSelector;
import org.onosproject.net.flow.TrafficSelector;
import org.onosproject.net.link.DefaultLinkDescription;
import org.onosproject.net.link.LinkProvider;
import org.onosproject.net.link.LinkProviderRegistry;
import org.onosproject.net.link.LinkProviderService;
import org.onosproject.net.link.LinkService;
import org.onosproject.net.packet.PacketContext;
import org.onosproject.net.packet.PacketPriority;
import org.onosproject.net.packet.PacketProcessor;
import org.onosproject.net.packet.PacketService;
import org.onosproject.net.provider.AbstractProvider;
import org.onosproject.net.provider.ProviderId;
import org.osgi.service.component.ComponentContext;
import org.slf4j.Logger;

import java.io.IOException;
import java.util.Dictionary;
import java.util.EnumSet;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledExecutorService;

import static com.google.common.base.Strings.isNullOrEmpty;
import static java.util.concurrent.Executors.newSingleThreadScheduledExecutor;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.onlab.util.Tools.get;
import static org.onlab.util.Tools.groupedThreads;
import static org.onosproject.net.Link.Type.DIRECT;
import static org.slf4j.LoggerFactory.getLogger;

/**
 * Provider which uses LLDP and BDDP packets to detect network infrastructure links.
 */
@Component(immediate = true)
public class LLDPLinkProvider extends AbstractProvider implements LinkProvider {

    private static final String PROVIDER_NAME = "org.onosproject.provider.lldp";

    private static final String FORMAT =
            "Settings: enabled={}, useBDDP={}, probeRate={}, " +
                    "staleLinkAge={}, lldpSuppression={}";

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

    @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
    protected CoreService coreService;

    @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
    protected LinkProviderRegistry providerRegistry;

    @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
    protected DeviceService deviceService;

    @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
    protected LinkService linkService;

    @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
    protected PacketService packetService;

    @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
    protected MastershipService masterService;

    @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
    protected ComponentConfigService cfgService;

    private LinkProviderService providerService;

    private ScheduledExecutorService executor;

    // TODO: Add sanity checking for the configurable params based on the delays
    private static final long DEVICE_SYNC_DELAY = 5;
    private static final long LINK_PRUNER_DELAY = 3;

    private static final String PROP_ENABLED = "enabled";
    @Property(name = PROP_ENABLED, boolValue = true,
            label = "If false, link discovery is disabled")
    private boolean enabled = false;

    private static final String PROP_USE_BDDP = "useBDDP";
    @Property(name = PROP_USE_BDDP, boolValue = true,
            label = "Use BDDP for link discovery")
    private boolean useBDDP = true;

    private static final String PROP_PROBE_RATE = "probeRate";
    private static final int DEFAULT_PROBE_RATE = 3_000;
    @Property(name = PROP_PROBE_RATE, intValue = DEFAULT_PROBE_RATE,
            label = "LLDP and BDDP probe rate specified in millis")
    private int probeRate = DEFAULT_PROBE_RATE;

    private static final String PROP_STALE_LINK_AGE = "staleLinkAge";
    private static final int DEFAULT_STALE_LINK_AGE = 10_000;
    @Property(name = PROP_STALE_LINK_AGE, intValue = DEFAULT_STALE_LINK_AGE,
            label = "Number of millis beyond which links will be considered stale")
    private int staleLinkAge = DEFAULT_STALE_LINK_AGE;

    // FIXME: convert to use network config subsystem instead
    private static final String PROP_LLDP_SUPPRESSION = "lldpSuppression";
    private static final String DEFAULT_LLDP_SUPPRESSION_CONFIG = "../config/lldp_suppression.json";
    @Property(name = PROP_LLDP_SUPPRESSION, value = DEFAULT_LLDP_SUPPRESSION_CONFIG,
            label = "Path to LLDP suppression configuration file")
    private String lldpSuppression = DEFAULT_LLDP_SUPPRESSION_CONFIG;

    private final DiscoveryContext context = new InternalDiscoveryContext();
    private final InternalRoleListener roleListener = new InternalRoleListener();
    private final InternalDeviceListener deviceListener = new InternalDeviceListener();
    private final InternalPacketProcessor packetProcessor = new InternalPacketProcessor();

    // Device link discovery helpers.
    protected final Map<DeviceId, LinkDiscovery> discoverers = new ConcurrentHashMap<>();

    // Most recent time a tracked link was seen; links are tracked if their
    // destination connection point is mastered by this controller instance.
    private final Map<LinkKey, Long> linkTimes = Maps.newConcurrentMap();

    private SuppressionRules rules;
    private ApplicationId appId;

    /**
     * Creates an OpenFlow link provider.
     */
    public LLDPLinkProvider() {
        super(new ProviderId("lldp", PROVIDER_NAME));
    }

    @Activate
    public void activate(ComponentContext context) {
        cfgService.registerProperties(getClass());
        appId = coreService.registerApplication(PROVIDER_NAME);
        modified(context);
        log.info("Started");
    }

    @Deactivate
    public void deactivate() {
        cfgService.unregisterProperties(getClass(), false);
        disable();
        log.info("Stopped");
    }

    @Modified
    public void modified(ComponentContext context) {
        Dictionary<?, ?> properties = context != null ? context.getProperties() : new Properties();

        boolean newEnabled, newUseBddp;
        int newProbeRate, newStaleLinkAge;
        String newLldpSuppression;
        try {
            String s = get(properties, PROP_ENABLED);
            newEnabled = isNullOrEmpty(s) || Boolean.parseBoolean(s.trim());

            s = get(properties, PROP_USE_BDDP);
            newUseBddp = isNullOrEmpty(s) || Boolean.parseBoolean(s.trim());

            s = get(properties, PROP_PROBE_RATE);
            newProbeRate = isNullOrEmpty(s) ? probeRate : Integer.parseInt(s.trim());

            s = get(properties, PROP_STALE_LINK_AGE);
            newStaleLinkAge = isNullOrEmpty(s) ? staleLinkAge : Integer.parseInt(s.trim());

            s = get(properties, PROP_LLDP_SUPPRESSION);
            newLldpSuppression = isNullOrEmpty(s) ? DEFAULT_LLDP_SUPPRESSION_CONFIG : s;

        } catch (NumberFormatException e) {
            log.warn(e.getMessage());
            newEnabled = enabled;
            newUseBddp = useBDDP;
            newProbeRate = probeRate;
            newStaleLinkAge = staleLinkAge;
            newLldpSuppression = lldpSuppression;
        }

        boolean wasEnabled = enabled;

        enabled = newEnabled;
        useBDDP = newUseBddp;
        probeRate = newProbeRate;
        staleLinkAge = newStaleLinkAge;
        lldpSuppression = newLldpSuppression;

        if (!wasEnabled && enabled) {
            enable();
        } else if (wasEnabled && !enabled) {
            disable();
        }

        log.info(FORMAT, enabled, useBDDP, probeRate, staleLinkAge, lldpSuppression);
    }

    /**
     * Enables link discovery processing.
     */
    private void enable() {
        providerService = providerRegistry.register(this);
        masterService.addListener(roleListener);
        deviceService.addListener(deviceListener);
        packetService.addProcessor(packetProcessor, PacketProcessor.advisor(0));

        loadSuppressionRules();
        loadDevices();

        executor = newSingleThreadScheduledExecutor(groupedThreads("onos/link", "discovery-%d"));
        executor.scheduleAtFixedRate(new SyncDeviceInfoTask(),
                                     DEVICE_SYNC_DELAY, DEVICE_SYNC_DELAY, SECONDS);
        executor.scheduleAtFixedRate(new LinkPrunerTask(),
                                     LINK_PRUNER_DELAY, LINK_PRUNER_DELAY, SECONDS);

        requestIntercepts();
    }

    /**
     * Disables link discovery processing.
     */
    private void disable() {
        withdrawIntercepts();

        providerRegistry.unregister(this);
        masterService.removeListener(roleListener);
        deviceService.removeListener(deviceListener);
        packetService.removeProcessor(packetProcessor);

        if (executor != null) {
            executor.shutdownNow();
        }
        discoverers.values().forEach(LinkDiscovery::stop);
        discoverers.clear();

        providerService = null;
    }

    /**
     * Loads available devices and registers their ports to be probed.
     */
    private void loadDevices() {
        for (Device device : deviceService.getAvailableDevices()) {
            if (rules.isSuppressed(device)) {
                log.debug("LinkDiscovery from {} disabled by configuration", device.id());
                continue;
            }
            LinkDiscovery ld = new LinkDiscovery(device, context);
            discoverers.put(device.id(), ld);
            addPorts(ld, device.id());
        }
    }

    /**
     * Adds ports of the specified device to the specified discovery helper.
     */
    private void addPorts(LinkDiscovery discoverer, DeviceId deviceId) {
        for (Port p : deviceService.getPorts(deviceId)) {
            if (rules.isSuppressed(p)) {
                continue;
            }
            if (!p.number().isLogical()) {
                discoverer.addPort(p);
            }
        }
    }

    /**
     * Loads LLDP suppression rules.
     */
    private void loadSuppressionRules() {
        // FIXME: convert to use network configuration
        SuppressionRulesStore store = new SuppressionRulesStore(lldpSuppression);
        try {
            log.info("Reading suppression rules from {}", lldpSuppression);
            rules = store.read();
        } catch (IOException e) {
            log.info("Failed to load {}, using built-in rules", lldpSuppression);
            // default rule to suppress ROADM to maintain compatibility
            rules = new SuppressionRules(ImmutableSet.of(),
                                         EnumSet.of(Device.Type.ROADM),
                                         ImmutableMap.of());
        }

        // should refresh discoverers when we need dynamic reconfiguration
    }

    /**
     * Requests packet intercepts.
     */
    private void requestIntercepts() {
        TrafficSelector.Builder selector = DefaultTrafficSelector.builder();
        selector.matchEthType(Ethernet.TYPE_LLDP);
        packetService.requestPackets(selector.build(), PacketPriority.CONTROL, appId);

        selector.matchEthType(Ethernet.TYPE_BSN);
        if (useBDDP) {
            packetService.requestPackets(selector.build(), PacketPriority.CONTROL, appId);
        } else {
            packetService.cancelPackets(selector.build(), PacketPriority.CONTROL, appId);
        }
    }

    /**
     * Withdraws packet intercepts.
     */
    private void withdrawIntercepts() {
        TrafficSelector.Builder selector = DefaultTrafficSelector.builder();
        selector.matchEthType(Ethernet.TYPE_LLDP);
        packetService.cancelPackets(selector.build(), PacketPriority.CONTROL, appId);
        selector.matchEthType(Ethernet.TYPE_BSN);
        packetService.cancelPackets(selector.build(), PacketPriority.CONTROL, appId);
    }

    /**
     * Processes device mastership role changes.
     */
    private class InternalRoleListener implements MastershipListener {
        @Override
        public void event(MastershipEvent event) {
            if (MastershipEvent.Type.BACKUPS_CHANGED.equals(event.type())) {
                // only need new master events
                return;
            }

            DeviceId deviceId = event.subject();
            Device device = deviceService.getDevice(deviceId);
            if (device == null) {
                log.debug("Device {} doesn't exist, or isn't there yet", deviceId);
                return;
            }
            if (rules.isSuppressed(device)) {
                return;
            }
            discoverers.computeIfAbsent(deviceId, k -> new LinkDiscovery(device, context));
        }

    }

    /**
     * Processes device events.
     */
    private class InternalDeviceListener implements DeviceListener {
        @Override
        public void event(DeviceEvent event) {
            LinkDiscovery ld;
            Device device = event.subject();
            Port port = event.port();
            if (device == null) {
                log.error("Device is null.");
                return;
            }
            log.trace("{} {} {}", event.type(), event.subject(), event);
            final DeviceId deviceId = device.id();
            switch (event.type()) {
                case DEVICE_ADDED:
                case DEVICE_UPDATED:
                    synchronized (discoverers) {
                        ld = discoverers.get(deviceId);
                        if (ld == null) {
                            if (rules.isSuppressed(device)) {
                                log.debug("LinkDiscovery from {} disabled by configuration", device.id());
                                return;
                            }
                            log.debug("Device added ({}) {}", event.type(), deviceId);
                            discoverers.put(deviceId, new LinkDiscovery(device, context));
                        } else {
                            if (ld.isStopped()) {
                                log.debug("Device restarted ({}) {}", event.type(), deviceId);
                                ld.start();
                            }
                        }
                    }
                    break;
                case PORT_ADDED:
                case PORT_UPDATED:
                    if (port.isEnabled()) {
                        ld = discoverers.get(deviceId);
                        if (ld == null) {
                            return;
                        }
                        if (rules.isSuppressed(port)) {
                            log.debug("LinkDiscovery from {}@{} disabled by configuration",
                                      port.number(), device.id());
                            return;
                        }
                        if (!port.number().isLogical()) {
                            log.debug("Port added {}", port);
                            ld.addPort(port);
                        }
                    } else {
                        log.debug("Port down {}", port);
                        ConnectPoint point = new ConnectPoint(deviceId, port.number());
                        providerService.linksVanished(point);
                    }
                    break;
                case PORT_REMOVED:
                    log.debug("Port removed {}", port);
                    ConnectPoint point = new ConnectPoint(deviceId, port.number());
                    providerService.linksVanished(point);

                    break;
                case DEVICE_REMOVED:
                case DEVICE_SUSPENDED:
                    log.debug("Device removed {}", deviceId);
                    ld = discoverers.get(deviceId);
                    if (ld == null) {
                        return;
                    }
                    ld.stop();
                    providerService.linksVanished(deviceId);
                    break;
                case DEVICE_AVAILABILITY_CHANGED:
                    ld = discoverers.get(deviceId);
                    if (ld == null) {
                        return;
                    }
                    if (deviceService.isAvailable(deviceId)) {
                        log.debug("Device up {}", deviceId);
                        ld.start();
                    } else {
                        providerService.linksVanished(deviceId);
                        log.debug("Device down {}", deviceId);
                        ld.stop();
                    }
                    break;
                case PORT_STATS_UPDATED:
                    break;
                default:
                    log.debug("Unknown event {}", event);
            }
        }
    }

    /**
     * Processes incoming packets.
     */
    private class InternalPacketProcessor implements PacketProcessor {
        @Override
        public void process(PacketContext context) {
            if (context == null) {
                return;
            }
            LinkDiscovery ld = discoverers.get(context.inPacket().receivedFrom().deviceId());
            if (ld == null) {
                return;
            }

            if (ld.handleLLDP(context)) {
                context.block();
            }
        }
    }

    /**
     * Auxiliary task to keep device ports up to date.
     */
    private final class SyncDeviceInfoTask implements Runnable {
        @Override
        public void run() {
            if (Thread.currentThread().isInterrupted()) {
                log.info("Interrupted, quitting");
                return;
            }
            // check what deviceService sees, to see if we are missing anything
            try {
                for (Device dev : deviceService.getDevices()) {
                    if (rules.isSuppressed(dev)) {
                        continue;
                    }
                    DeviceId did = dev.id();
                    synchronized (discoverers) {
                        LinkDiscovery ld = discoverers
                                .computeIfAbsent(did, k -> new LinkDiscovery(dev, context));
                        addPorts(ld, did);
                    }
                }
            } catch (Exception e) {
                // Catch all exceptions to avoid task being suppressed
                log.error("Exception thrown during synchronization process", e);
            }
        }
    }

    /**
     * Auxiliary task for pruning stale links.
     */
    private class LinkPrunerTask implements Runnable {
        @Override
        public void run() {
            if (Thread.currentThread().isInterrupted()) {
                log.info("Interrupted, quitting");
                return;
            }

            try {
                // TODO: There is still a slight possibility of mastership
                // change occurring right with link going stale. This will
                // result in the stale link not being pruned.
                Maps.filterEntries(linkTimes, e -> {
                    if (!masterService.isLocalMaster(e.getKey().dst().deviceId())) {
                        return true;
                    }
                    if (isStale(e.getValue())) {
                        providerService.linkVanished(new DefaultLinkDescription(e.getKey().src(),
                                                                                e.getKey().dst(),
                                                                                DIRECT));
                        return true;
                    }
                    return false;
                }).clear();

            } catch (Exception e) {
                // Catch all exceptions to avoid task being suppressed
                log.error("Exception thrown during link pruning process", e);
            }
        }

        private boolean isStale(long lastSeen) {
            return lastSeen < System.currentTimeMillis() - staleLinkAge;
        }
    }

    /**
     * Provides processing context for the device link discovery helpers.
     */
    private class InternalDiscoveryContext implements DiscoveryContext {
        @Override
        public MastershipService mastershipService() {
            return masterService;
        }

        @Override
        public LinkProviderService providerService() {
            return providerService;
        }

        @Override
        public PacketService packetService() {
            return packetService;
        }

        @Override
        public long probeRate() {
            return probeRate;
        }

        @Override
        public boolean useBDDP() {
            return useBDDP;
        }

        @Override
        public void touchLink(LinkKey key) {
            linkTimes.put(key, System.currentTimeMillis());
        }
    }

}


text:
import django_filters
from django.contrib.auth import get_user_model
from django.db.models import Q
from rest_framework import generics
from rest_framework import status
from rest_framework.response import Response

import models
import permissions
import serializers

class UserFilter(django_filters.FilterSet):
    username = django_filters.CharFilter()
    first_name = django_filters.CharFilter()
    last_name = django_filters.CharFilter()
    status = django_filters.CharFilter()

    class Meta:
        model = models.User
        fields = ['status', 'username', 'first_name', 'last_name']

class AccountView(generics.RetrieveUpdateDestroyAPIView):
    lookup_field = 'username'
    permission_classes = (permissions.IsAdminOrTenantPrimaryContact, )
    serializer_class = serializers.AccountSerializer
    model = get_user_model()

class TenantView(generics.RetrieveUpdateAPIView):
    permission_classes = (permissions.IsAdminOrTenantPrimaryContact, )
    serializer_class = serializers.TenantSerializer
    model = models.Tenant

    def get_object(self, *args, **kw):
        return self.request.user.tenant

class UserListView(generics.ListCreateAPIView):
    permission_classes = (permissions.IsTenantPrimaryContact, )
    filter_class = UserFilter
    model = models.User
    paginate_by = 50

    def get_serializer_class(self, *args, **kw):
        return {
            'GET': serializers.UserSerializer
        }.get(self.request.method, serializers.NewUserSerializer)

    def filter_queryset(self, qs, *args, **kw):
        qs = super(UserListView, self).filter_queryset(qs)
        qs = qs.filter(tenant__primary_contact=self.request.user)
        term = self.request.GET.get('q')
        if term:
            qs = qs.filter(
                Q(first_name__istartswith=term) |
                Q(last_name__istartswith=term) |
                Q(username__startswith=term)
            )
        return qs

class UserView(generics.RetrieveUpdateDestroyAPIView):
    permission_classes = (permissions.IsAdminOrTenantPrimaryContact, )
    serializer_class = serializers.UserSerializer
    model = models.User

    def delete(self, request, *args, **kw):
        self.get_object().delete(editor=self.request.user)
        return Response(status=status.HTTP_204_NO_CONTENT)

class UserGroupListView(generics.ListCreateAPIView):
    permission_classes = (permissions.IsTenantPrimaryContact, )
    serializer_class = serializers.UserGroupSerializer
    model = models.UserGroup

class UserGroupView(generics.RetrieveUpdateDestroyAPIView):
    permission_classes = (permissions.IsAdminOrTenantPrimaryContact, )
    serializer_class = serializers.UserGroupSerializer
    model = models.UserGroup

redpajama_set_name: RedPajamaGithub


text:
<resources>

    <style name="AppTheme" parent="AppTheme.Base" />
    <!-- Base application theme. -->
    <style name="AppTheme.Base" parent="style/Theme.AppCompat.Light">

        <item name="android:textColorPrimaryNoDisable">@color/colourGrey900</item>

        <item name="android:textColorSecondary">@color/colourGrey700</item>

        <!-- colorPrimary is used for the default action bar background -->
        <item name="colorPrimary">@color/colourBlue500</item>

        <!-- colorPrimaryDark is used for the status bar -->
        <item name="colorPrimaryDark">@color/colourBlue900</item>

        <!-- colorAccent is used as the default value for colorControlActivated
             which is used to tint widgets -->
        <item name="colorAccent">@color/colourBlue800</item>

        <item name="android:windowBackground">@color/colourBlue50</item>
    </style>

</resources>


text:
/**
 * Contains the Border class, which represents a UI border component.
 * @module "ui/animation/keyframe-animation"
 */ /** */

import { ContentView } from "../content-view";

/**
 * Represents a UI border component.
 */
export class Border extends ContentView {
    /**
     * Gets or sets the corner radius of the border component.
     */
    cornerRadius: number;
}


text:
$ErrorActionPreference = "Stop";

$ROOT = split-path -parent $MyInvocation.MyCommand.Definition

# discover BROOKLYN_HOME if not set, by attempting to resolve absolute path of this command (brooklyn)
if ( $env:BROOKLYN_HOME -eq $null ) {
    $BROOKLYN_HOME = split-path -parent $ROOT
} else {
    $BROOKLYN_HOME = $env:BROOKLYN_HOME
}

# Discover the location of Java.
# Use JAVA_HOME environment variable, if available;
# else, search registry for Java installations;
# else, check the path;
# else fail.
$bin = [System.IO.Path]::Combine("bin", "java.exe")
if ( $env:JAVA_HOME -ne $null ) {
    $javahome = $env:JAVA_HOME
    $javabin = [System.IO.Path]::Combine($javahome, $bin)
}
if ( $javabin -eq $null ) {
    $reglocations = ( 'HKLM:\SOFTWARE\JavaSoft\Java Runtime Environment',
                      'HKLM:\SOFTWARE\Wow6432Node\JavaSoft\Java Runtime Environment' )
    $jres = @{}
    foreach ($loc in $reglocations) {
        $item = Get-Item $loc -ErrorAction SilentlyContinue
        if ($item -eq $null) { continue }
        foreach ($key in Get-ChildItem $loc) {
            $version = $key.PSChildName
            $jrehome = $key.GetValue("JavaHome")
            $jres.Add($version, $jrehome)
        }
    }
    # TODO - this does a simple sort on the registry key name (the JRE version). This is not ideal - better would be
    # to understand semantic versioning, filter out incompatible JREs (1.5 and earlier), prefer known good JREs (1.6
    # or 1.7) and pick the highest patchlevel.
    $last = ( $jres.Keys | Sort-Object | Select-Object -Last 1 )
    if ( $last -ne $null ) {
        $javahome = $jres.Get_Item($last)
        $javabin = [System.IO.Path]::Combine($javahome, $bin)
    }
}
if ( $javabin -eq $null ) {
    $where = Get-Command "java.exe" -ErrorAction SilentlyContinue
    if ( $where -ne $null ) {
        $javabin = $where.Definition
        $bindir = [System.IO.Path]::GetDirectoryName($javabin)
        $javahome = [System.IO.Path]::GetDirectoryName($bindir)
    }
}

if ( $javabin -eq $null ) {
    throw "Unable to locate a Java installation. Please set JAVA_HOME or PATH environment variables."
} elseif ( $( Get-Item $javabin -ErrorAction SilentlyContinue ) -eq $null ) {
    throw "java.exe does not exist where specified. Please check JAVA_HOME or PATH environment variables."
}

# set up the classpath
$cp = Get-ChildItem ${BROOKLYN_HOME}\conf | Select-Object -ExpandProperty FullName

if ( Test-Path ${BROOKLYN_HOME}\patch ) {
    $cp += Get-ChildItem ${BROOKLYN_HOME}\patch | Select-Object -ExpandProperty FullName
}

$cp += Get-ChildItem ${BROOKLYN_HOME}\lib\brooklyn | Select-Object -ExpandProperty FullName

if ( Test-Path ${BROOKLYN_HOME}\dropins ) {
    $cp += Get-ChildItem ${BROOKLYN_HOME}\dropins | Select-Object -ExpandProperty FullName
}

$INITIAL_CLASSPATH = $cp -join ';'

# specify additional CP args in BROOKLYN_CLASSPATH
if ( ! ( $env:BROOKLYN_CLASSPATH -eq $null )) {
    $INITIAL_CLASSPATH = "$($INITIAL_CLASSPATH);$($env:BROOKLYN_CLASSPATH)"
}

# start to build up the arguments to the java invocation
$javaargs = @()

# add the user's java opts, or use default memory settings, if not specified
if ( $env:JAVA_OPTS -eq $null ) {
    $javaargs +="-Xms256m -Xmx1g -XX:MaxPermSize=256m"
} else {
    $javaargs +=$env:JAVA_OPTS
}

# force resolution of localhost to be loopback, otherwise we hit problems
# TODO should be changed in code
$javaargs += "-Dbrooklyn.localhost.address=127.0.0.1 $($JAVA_OPTS)"

# workaround for http://bugs.sun.com/view_bug.do?bug_id=4787931
$javaargs += "-Duser.home=`"$env:USERPROFILE`""

# add the classpath
$javaargs += "-cp"
$javaargs += "`"$($INITIAL_CLASSPATH)`""

# main class
$javaargs += "brooklyn.cli.Main"

# copy in the arguments that were given to this script
$javaargs += $args

# start Brooklyn
$process = Start-Process -FilePath $javabin -ArgumentList $javaargs -NoNewWindow -PassThru

# save PID
Set-Content -Path ${BROOKLYN_HOME}\pid_java -Value $($process.Id)

# wait for it to finish
$process.WaitForExit()


text:
import { StandardProps } from '..';

export interface ListItemAvatarProps extends StandardProps<{}, ListItemAvatarClassKey> {
  children: React.ReactElement;
}

export type ListItemAvatarClassKey = 'root' | 'icon';

declare const ListItemAvatar: React.ComponentType<ListItemAvatarProps>;

export default ListItemAvatar;


text:
<?php

defined('_JEXEC') or die('RESTRICTED');

class WFAggregatorExtension_Vimeo extends WFAggregatorExtension
{
	/**
	* Constructor activating the default information of the class
	*
	* @access	protected
	*/
	function __construct()
	{
		parent::__construct(array(
			'format' => 'video'
		));
	}

	function display()
	{
		$document = WFDocument::getInstance();
		$document->addScript('vimeo', 'extensions/aggregator/vimeo/js');
	}

	function isEnabled()
	{
		$plugin = WFEditorPlugin::getInstance();
		return $plugin->checkAccess('aggregator.vimeo.enable', 1);
	}

	function getParams()
	{
		$plugin = WFEditorPlugin::getInstance();

		return array(
			'width'		=>	$plugin->getParam('aggregator.vimeo.width', 400),
			'height'	=>	$plugin->getParam('aggregator.vimeo.height', 225)
		);
	}
}


text:
namespace ash {
// A delegate which exposes browser functionality from //chrome to the face ml
// app ui page handler.
class FaceMLUserProvider {
 public:
  virtual ~FaceMLUserProvider() = default;

  virtual mojom::face_ml_app::UserInformation GetCurrentUserInformation() = 0;
};

}  // namespace ash

#endif  // ASH_WEBUI_FACE_ML_APP_UI_FACE_ML_USER_PROVIDER_H_


text:
package rafthttp

import (
	"fmt"
	"io"
	"io/ioutil"
	"net"
	"net/http"
	"path"
	"strconv"
	"strings"
	"sync"
	"time"

	"github.com/coreos/etcd/Godeps/_workspace/src/github.com/coreos/go-semver/semver"
	"github.com/coreos/etcd/etcdserver/stats"
	"github.com/coreos/etcd/pkg/httputil"
	"github.com/coreos/etcd/pkg/types"
	"github.com/coreos/etcd/raft/raftpb"
	"github.com/coreos/etcd/version"
)

const (
	streamTypeMessage  streamType = "message"
	streamTypeMsgAppV2 streamType = "msgappv2"
	streamTypeMsgApp   streamType = "msgapp"

	streamBufSize = 4096
)

var (
	errUnsupportedStreamType = fmt.Errorf("unsupported stream type")

	// the key is in string format "major.minor.patch"
	supportedStream = map[string][]streamType{
		"2.0.0": {streamTypeMsgApp},
		"2.1.0": {streamTypeMsgApp, streamTypeMsgAppV2, streamTypeMessage},
		"2.2.0": {streamTypeMsgApp, streamTypeMsgAppV2, streamTypeMessage},
	}
)

type streamType string

func (t streamType) endpoint() string {
	switch t {
	case streamTypeMsgApp: // for backward compatibility of v2.0
		return RaftStreamPrefix
	case streamTypeMsgAppV2:
		return path.Join(RaftStreamPrefix, "msgapp")
	case streamTypeMessage:
		return path.Join(RaftStreamPrefix, "message")
	default:
		plog.Panicf("unhandled stream type %v", t)
		return ""
	}
}

func (t streamType) String() string {
	switch t {
	case streamTypeMsgApp:
		return "stream MsgApp"
	case streamTypeMsgAppV2:
		return "stream MsgApp v2"
	case streamTypeMessage:
		return "stream Message"
	default:
		return "unknown stream"
	}
}

var (
	// linkHeartbeatMessage is a special message used as heartbeat message in
	// link layer. It never conflicts with messages from raft because raft
	// doesn't send out messages without From and To fields.
	linkHeartbeatMessage = raftpb.Message{Type: raftpb.MsgHeartbeat}
)

func isLinkHeartbeatMessage(m raftpb.Message) bool {
	return m.Type == raftpb.MsgHeartbeat && m.From == 0 && m.To == 0
}

type outgoingConn struct {
	t       streamType
	termStr string
	io.Writer
	http.Flusher
	io.Closer
}

// streamWriter is a long-running go-routine that writes messages into the
// attached outgoingConn.
type streamWriter struct {
	id     types.ID
	status *peerStatus
	fs     *stats.FollowerStats
	r      Raft

	mu      sync.Mutex // guard field working and closer
	closer  io.Closer
	working bool

	msgc  chan raftpb.Message
	connc chan *outgoingConn
	stopc chan struct{}
	done  chan struct{}
}

func startStreamWriter(id types.ID, status *peerStatus, fs *stats.FollowerStats, r Raft) *streamWriter {
	w := &streamWriter{
		id:     id,
		status: status,
		fs:     fs,
		r:      r,
		msgc:   make(chan raftpb.Message, streamBufSize),
		connc:  make(chan *outgoingConn),
		stopc:  make(chan struct{}),
		done:   make(chan struct{}),
	}
	go w.run()
	return w
}

func (cw *streamWriter) run() {
	var msgc chan raftpb.Message
	var heartbeatc <-chan time.Time
	var t streamType
	var msgAppTerm uint64
	var enc encoder
	var flusher http.Flusher
	tickc := time.Tick(ConnReadTimeout / 3)

	for {
		select {
		case <-heartbeatc:
			start := time.Now()
			if err := enc.encode(linkHeartbeatMessage); err != nil {
				reportSentFailure(string(t), linkHeartbeatMessage)

				cw.status.deactivate(failureType{source: t.String(), action: "heartbeat"}, err.Error())
				cw.close()
				heartbeatc, msgc = nil, nil
				continue
			}
			flusher.Flush()
			reportSentDuration(string(t), linkHeartbeatMessage, time.Since(start))
		case m := <-msgc:
			if t == streamTypeMsgApp && m.Term != msgAppTerm {
				// TODO: reasonable retry logic
				if m.Term > msgAppTerm {
					cw.close()
					heartbeatc, msgc = nil, nil
					// TODO: report to raft at peer level
					cw.r.ReportUnreachable(m.To)
				}
				continue
			}
			start := time.Now()
			if err := enc.encode(m); err != nil {
				reportSentFailure(string(t), m)

				cw.status.deactivate(failureType{source: t.String(), action: "write"}, err.Error())
				cw.close()
				heartbeatc, msgc = nil, nil
				cw.r.ReportUnreachable(m.To)
				continue
			}
			flusher.Flush()
			reportSentDuration(string(t), m, time.Since(start))
		case conn := <-cw.connc:
			cw.close()
			t = conn.t
			switch conn.t {
			case streamTypeMsgApp:
				var err error
				msgAppTerm, err = strconv.ParseUint(conn.termStr, 10, 64)
				if err != nil {
					plog.Panicf("could not parse term %s to uint (%v)", conn.termStr, err)
				}
				enc = &msgAppEncoder{w: conn.Writer, fs: cw.fs}
			case streamTypeMsgAppV2:
				enc = newMsgAppV2Encoder(conn.Writer, cw.fs)
			case streamTypeMessage:
				enc = &messageEncoder{w: conn.Writer}
			default:
				plog.Panicf("unhandled stream type %s", conn.t)
			}
			flusher = conn.Flusher
			cw.mu.Lock()
			cw.status.activate()
			cw.closer = conn.Closer
			cw.working = true
			cw.mu.Unlock()
			heartbeatc, msgc = tickc, cw.msgc
		case <-cw.stopc:
			cw.close()
			close(cw.done)
			return
		}
	}
}

func (cw *streamWriter) writec() (chan<- raftpb.Message, bool) {
	cw.mu.Lock()
	defer cw.mu.Unlock()
	return cw.msgc, cw.working
}

func (cw *streamWriter) close() {
	cw.mu.Lock()
	defer cw.mu.Unlock()
	if !cw.working {
		return
	}
	cw.closer.Close()
	if len(cw.msgc) > 0 {
		cw.r.ReportUnreachable(uint64(cw.id))
	}
	cw.msgc = make(chan raftpb.Message, streamBufSize)
	cw.working = false
}

func (cw *streamWriter) attach(conn *outgoingConn) bool {
	select {
	case cw.connc <- conn:
		return true
	case <-cw.done:
		return false
	}
}

func (cw *streamWriter) stop() {
	close(cw.stopc)
	<-cw.done
}

// streamReader is a long-running go-routine that dials to the remote stream
// endponit and reads messages from the response body returned.
type streamReader struct {
	tr            http.RoundTripper
	picker        *urlPicker
	t             streamType
	local, remote types.ID
	cid           types.ID
	status        *peerStatus
	recvc         chan<- raftpb.Message
	propc         chan<- raftpb.Message
	errorc        chan<- error

	mu         sync.Mutex
	msgAppTerm uint64
	cancel     func()
	closer     io.Closer
	stopc      chan struct{}
	done       chan struct{}
}

func startStreamReader(tr http.RoundTripper, picker *urlPicker, t streamType, local, remote, cid types.ID, status *peerStatus, recvc chan<- raftpb.Message, propc chan<- raftpb.Message, errorc chan<- error, term uint64) *streamReader {
	r := &streamReader{
		tr:         tr,
		picker:     picker,
		t:          t,
		local:      local,
		remote:     remote,
		cid:        cid,
		status:     status,
		recvc:      recvc,
		propc:      propc,
		errorc:     errorc,
		msgAppTerm: term,
		stopc:      make(chan struct{}),
		done:       make(chan struct{}),
	}
	go r.run()
	return r
}

func (cr *streamReader) run() {
	for {
		t := cr.t
		rc, err := cr.dial(t)
		// downgrade to streamTypeMsgApp if the remote doesn't support
		// streamTypeMsgAppV2
		if t == streamTypeMsgAppV2 && err == errUnsupportedStreamType {
			t = streamTypeMsgApp
			rc, err = cr.dial(t)
		}
		if err != nil {
			if err != errUnsupportedStreamType {
				cr.status.deactivate(failureType{source: t.String(), action: "dial"}, err.Error())
			}
		} else {
			cr.status.activate()
			err := cr.decodeLoop(rc, t)
			switch {
			// all data is read out
			case err == io.EOF:
			// connection is closed by the remote
			case isClosedConnectionError(err):
			// stream msgapp is only used for etcd 2.0, and etcd 2.0 doesn't
			// heartbeat on the idle stream, so it is expected to time out.
			case t == streamTypeMsgApp && isNetworkTimeoutError(err):
			default:
				cr.status.deactivate(failureType{source: t.String(), action: "read"}, err.Error())
			}
		}
		select {
		// Wait 100ms to create a new stream, so it doesn't bring too much
		// overhead when retry.
		case <-time.After(100 * time.Millisecond):
		case <-cr.stopc:
			close(cr.done)
			return
		}
	}
}

func (cr *streamReader) decodeLoop(rc io.ReadCloser, t streamType) error {
	var dec decoder
	cr.mu.Lock()
	switch t {
	case streamTypeMsgApp:
		dec = &msgAppDecoder{r: rc, local: cr.local, remote: cr.remote, term: cr.msgAppTerm}
	case streamTypeMsgAppV2:
		dec = newMsgAppV2Decoder(rc, cr.local, cr.remote)
	case streamTypeMessage:
		dec = &messageDecoder{r: rc}
	default:
		plog.Panicf("unhandled stream type %s", t)
	}
	cr.closer = rc
	cr.mu.Unlock()

	for {
		m, err := dec.decode()
		switch {
		case err != nil:
			cr.mu.Lock()
			cr.close()
			cr.mu.Unlock()
			return err
		case isLinkHeartbeatMessage(m):
			// do nothing for linkHeartbeatMessage
		default:
			recvc := cr.recvc
			if m.Type == raftpb.MsgProp {
				recvc = cr.propc
			}
			select {
			case recvc <- m:
			default:
				if cr.status.isActive() {
					plog.Warningf("dropped %s from %s since receiving buffer is full", m.Type, types.ID(m.From))
				} else {
					plog.Debugf("dropped %s from %s since receiving buffer is full", m.Type, types.ID(m.From))
				}
			}
		}
	}
}

// updateMsgAppTerm updates the term for MsgApp stream, and closes
// the existing MsgApp stream if term is updated.
func (cr *streamReader) updateMsgAppTerm(term uint64) {
	cr.mu.Lock()
	defer cr.mu.Unlock()
	if cr.msgAppTerm >= term {
		return
	}
	cr.msgAppTerm = term
	if cr.t == streamTypeMsgApp {
		cr.close()
	}
}

func (cr *streamReader) stop() {
	close(cr.stopc)
	cr.mu.Lock()
	if cr.cancel != nil {
		cr.cancel()
	}
	cr.close()
	cr.mu.Unlock()
	<-cr.done
}

func (cr *streamReader) isWorking() bool {
	cr.mu.Lock()
	defer cr.mu.Unlock()
	return cr.closer != nil
}

func (cr *streamReader) dial(t streamType) (io.ReadCloser, error) {
	u := cr.picker.pick()
	cr.mu.Lock()
	term := cr.msgAppTerm
	cr.mu.Unlock()

	uu := u
	uu.Path = path.Join(t.endpoint(), cr.local.String())

	req, err := http.NewRequest("GET", uu.String(), nil)
	if err != nil {
		cr.picker.unreachable(u)
		return nil, fmt.Errorf("failed to make http request to %s (%v)", u, err)
	}
	req.Header.Set("X-Server-From", cr.local.String())
	req.Header.Set("X-Server-Version", version.Version)
	req.Header.Set("X-Min-Cluster-Version", version.MinClusterVersion)
	req.Header.Set("X-Etcd-Cluster-ID", cr.cid.String())
	req.Header.Set("X-Raft-To", cr.remote.String())
	if t == streamTypeMsgApp {
		req.Header.Set("X-Raft-Term", strconv.FormatUint(term, 10))
	}

	cr.mu.Lock()
	select {
	case <-cr.stopc:
		cr.mu.Unlock()
		return nil, fmt.Errorf("stream reader is stopped")
	default:
	}
	cr.cancel = httputil.RequestCanceler(cr.tr, req)
	cr.mu.Unlock()

	resp, err := cr.tr.RoundTrip(req)
	if err != nil {
		cr.picker.unreachable(u)
		return nil, err
	}

	rv := serverVersion(resp.Header)
	lv := semver.Must(semver.NewVersion(version.Version))
	if compareMajorMinorVersion(rv, lv) == -1 && !checkStreamSupport(rv, t) {
		resp.Body.Close()
		return nil, errUnsupportedStreamType
	}

	switch resp.StatusCode {
	case http.StatusGone:
		resp.Body.Close()
		err := fmt.Errorf("the member has been permanently removed from the cluster")
		select {
		case cr.errorc <- err:
		default:
		}
		return nil, err
	case http.StatusOK:
		return resp.Body, nil
	case http.StatusNotFound:
		resp.Body.Close()
		return nil, fmt.Errorf("remote member %s could not recognize local member", cr.remote)
	case http.StatusPreconditionFailed:
		b, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			cr.picker.unreachable(u)
			return nil, err
		}
		resp.Body.Close()

		switch strings.TrimSuffix(string(b), "\n") {
		case errIncompatibleVersion.Error():
			plog.Errorf("request sent was ignored by peer %s (server version incompatible)", cr.remote)
			return nil, errIncompatibleVersion
		case errClusterIDMismatch.Error():
			plog.Errorf("request sent was ignored (cluster ID mismatch: remote[%s]=%s, local=%s)",
				cr.remote, resp.Header.Get("X-Etcd-Cluster-ID"), cr.cid)
			return nil, errClusterIDMismatch
		default:
			return nil, fmt.Errorf("unhandled error %q when precondition failed", string(b))
		}
	default:
		resp.Body.Close()
		return nil, fmt.Errorf("unhandled http status %d", resp.StatusCode)
	}
}

func (cr *streamReader) close() {
	if cr.closer != nil {
		cr.closer.Close()
	}
	cr.closer = nil
}

func canUseMsgAppStream(m raftpb.Message) bool {
	return m.Type == raftpb.MsgApp && m.Term == m.LogTerm
}

func isClosedConnectionError(err error) bool {
	operr, ok := err.(*net.OpError)
	return ok && operr.Err.Error() == "use of closed network connection"
}

// checkStreamSupport checks whether the stream type is supported in the
// given version.
func checkStreamSupport(v *semver.Version, t streamType) bool {
	nv := &semver.Version{Major: v.Major, Minor: v.Minor}
	for _, s := range supportedStream[nv.String()] {
		if s == t {
			return true
		}
	}
	return false
}

func isNetworkTimeoutError(err error) bool {
	nerr, ok := err.(net.Error)
	return ok && nerr.Timeout()
}


text:
package imj3.draft;

import static imj3.tools.IMJTools.read;
import static multij.tools.Tools.baseName;
import static multij.tools.Tools.debugPrint;

import imj3.core.Image2D;
import imj3.core.Image2D.Pixel2DProcessor;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

import multij.tools.CommandLineArgumentsParser;
import multij.tools.IllegalInstantiationException;

/**
 * @author codistmonk (creation 2016-06-03)
 */
public final class Segment {

	private Segment() {
		throw new IllegalInstantiationException();
	}

	/**
	 * @param commandLineArguments
	 * <br>unused
	 */
	public static final void main(final String... commandLineArguments) {
		final CommandLineArgumentsParser arguments = new CommandLineArgumentsParser(commandLineArguments);
		final String imagePath = arguments.get("image", "");
		final Image2D image = read(imagePath);
		final String outputPath = arguments.get("out", baseName(imagePath) + "_segments.png");
		final int idMask = arguments.get("idMask", 0x80000000)[0];
		final BufferedImage segments = process(image, idMask);

		try {
			debugPrint("Writing", outputPath + "...");
			ImageIO.write(segments, "png", new File(outputPath));
		} catch (final IOException exception) {
			exception.printStackTrace();
		}
	}

	public static final BufferedImage process(final Image2D image, final int idMask) {
		final BufferedImage result = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB);

		ExtractComponents.forEachPixelInEachComponent4(image, new Pixel2DProcessor() {

			private int id;

			@Override
			public final boolean pixel(final int x, final int y) {
				result.setRGB(x, y, idMask | this.id);

				return true;
			}

			@Override
			public final void endOfPatch() {
				++this.id;
			}

			private static final long serialVersionUID = -7088195004570881462L;

		});

		return result;
	}

}


text:
var mkdirp = require('../');
var path = require('path');
var fs = require('fs');
var exists = fs.exists || path.exists;
var test = require('tap').test;

test('implicit mode from umask', function (t) {
    t.plan(5);
    var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16);
    var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16);
    var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16);

    var file = '/tmp/' + [x,y,z].join('/');

    mkdirp(file, function (err) {
        t.ifError(err);
        exists(file, function (ex) {
            t.ok(ex, 'file created');
            fs.stat(file, function (err, stat) {
                t.ifError(err);
                t.equal(stat.mode & 0777, 0777 & (~process.umask()));
                t.ok(stat.isDirectory(), 'target not a directory');
            });
        })
    });
});


text:
package com.github.jbman.wichteln.mailer;

import com.github.jbman.wichteln.model.MailData;

public interface Mailer {

	void sendMail(MailData mailData);

}


text:
<?php

declare(strict_types=1);

namespace Geocoder;

use Geocoder\Exception\ProviderNotRegistered;
use Geocoder\Model\Coordinates;
use Geocoder\Query\GeocodeQuery;
use Geocoder\Query\ReverseQuery;
use Geocoder\Provider\Provider;

/**
 * @author William Durand <william.durand1@gmail.com>
 */
class ProviderAggregator implements Geocoder
{
    /**
     * @var Provider[]
     */
    private $providers = [];

    /**
     * @var Provider
     */
    private $provider;

    /**
     * @var int
     */
    private $limit;

    /**
     * A callable that decided what provider to use.
     *
     * @var callable
     */
    private $decider;

    /**
     * @param callable|null $decider
     * @param int           $limit
     */
    public function __construct(callable $decider = null, int $limit = Geocoder::DEFAULT_RESULT_LIMIT)
    {
        $this->limit = $limit;
        $this->decider = $decider ?? __CLASS__.'::getProvider';
    }

    /**
     * {@inheritdoc}
     */
    public function geocodeQuery(GeocodeQuery $query): Collection
    {
        if (null === $query->getLimit()) {
            $query = $query->withLimit($this->limit);
        }

        return call_user_func($this->decider, $query, $this->providers, $this->provider)->geocodeQuery($query);
    }

    /**
     * {@inheritdoc}
     */
    public function reverseQuery(ReverseQuery $query): Collection
    {
        if (null === $query->getLimit()) {
            $query = $query->withLimit($this->limit);
        }

        return call_user_func($this->decider, $query, $this->providers, $this->provider)->reverseQuery($query);
    }

    /**
     * {@inheritdoc}
     */
    public function getName(): string
    {
        return 'provider_aggregator';
    }

    /**
     * {@inheritdoc}
     */
    public function geocode(string $value): Collection
    {
        return $this->geocodeQuery(GeocodeQuery::create($value)
            ->withLimit($this->limit));
    }

    /**
     * {@inheritdoc}
     */
    public function reverse(float $latitude, float $longitude): Collection
    {
        return $this->reverseQuery(ReverseQuery::create(new Coordinates($latitude, $longitude))
            ->withLimit($this->limit));
    }

    /**
     * Registers a new provider to the aggregator.
     *
     * @param Provider $provider
     *
     * @return ProviderAggregator
     */
    public function registerProvider(Provider $provider): self
    {
        $this->providers[$provider->getName()] = $provider;

        return $this;
    }

    /**
     * Registers a set of providers.
     *
     * @param Provider[] $providers
     *
     * @return ProviderAggregator
     */
    public function registerProviders(array $providers = []): self
    {
        foreach ($providers as $provider) {
            $this->registerProvider($provider);
        }

        return $this;
    }

    /**
     * Sets the default provider to use.
     *
     * @param string $name
     *
     * @return ProviderAggregator
     */
    public function using(string $name): self
    {
        if (!isset($this->providers[$name])) {
            throw ProviderNotRegistered::create($name ?? '', $this->providers);
        }

        $this->provider = $this->providers[$name];

        return $this;
    }

    /**
     * Returns all registered providers indexed by their name.
     *
     * @return Provider[]
     */
    public function getProviders(): array
    {
        return $this->providers;
    }

    /**
     * Get a provider to use for this query.
     *
     * @param GeocodeQuery|ReverseQuery $query
     * @param Provider[]                $providers
     * @param Provider                  $currentProvider
     *
     * @return Provider
     *
     * @throws ProviderNotRegistered
     */
    private static function getProvider($query, array $providers, Provider $currentProvider = null): Provider
    {
        if (null !== $currentProvider) {
            return $currentProvider;
        }

        if (0 === count($providers)) {
            throw ProviderNotRegistered::noProviderRegistered();
        }

        // Take first
        $key = key($providers);

        return $providers[$key];
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Collema reflectens Nyl.

### Remarks
null


text:
// Copyright 2022 Google LLC
//
// 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.google.firebase.appcheck.playintegrity.internal;

import static com.google.common.truth.Truth.assertThat;

import org.json.JSONObject;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;

/** Tests for {@link ExchangePlayIntegrityTokenRequest}. */
@RunWith(RobolectricTestRunner.class)
@Config(manifest = Config.NONE)
public class ExchangePlayIntegrityTokenRequestTest {
  private static final String PLAY_INTEGRITY_TOKEN = "playIntegrityToken";

  @Test
  public void toJsonString_expectSerialized() throws Exception {
    ExchangePlayIntegrityTokenRequest exchangePlayIntegrityTokenRequest =
        new ExchangePlayIntegrityTokenRequest(PLAY_INTEGRITY_TOKEN);

    String jsonString = exchangePlayIntegrityTokenRequest.toJsonString();
    JSONObject jsonObject = new JSONObject(jsonString);

    assertThat(jsonObject.getString(ExchangePlayIntegrityTokenRequest.PLAY_INTEGRITY_TOKEN_KEY))
        .isEqualTo(PLAY_INTEGRITY_TOKEN);
  }
}


text:
package com.intellij.debugger.ui.impl.watch;

import com.intellij.debugger.DebuggerContext;
import com.intellij.debugger.engine.evaluation.EvaluateException;
import com.intellij.debugger.engine.evaluation.EvaluationContextImpl;
import com.intellij.debugger.impl.DebuggerUtilsEx;
import com.intellij.debugger.settings.NodeRendererSettings;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiExpression;
import com.sun.jdi.ClassNotLoadedException;
import com.sun.jdi.Method;
import com.sun.jdi.Type;
import com.sun.jdi.Value;
import org.jetbrains.annotations.NotNull;

public class MethodReturnValueDescriptorImpl extends ValueDescriptorImpl {
  private final Method myMethod;

  public MethodReturnValueDescriptorImpl(Project project, @NotNull Method method, Value value) {
    super(project, value);
    myMethod = method;
  }

  @Override
  public Value calcValue(EvaluationContextImpl evaluationContext) throws EvaluateException {
    return getValue();
  }

  @NotNull
  public Method getMethod() {
    return myMethod;
  }

  @Override
  public String getName() {
    return NodeRendererSettings.getInstance().getClassRenderer().renderTypeName(myMethod.declaringType().name()) + "." +
           DebuggerUtilsEx.methodNameWithArguments(myMethod);
  }

  @Override
  public Type getType() {
    Type type = super.getType();
    if (type == null) {
      try {
        type = myMethod.returnType();
      }
      catch (ClassNotLoadedException ignored) {
      }
    }
    return type;
  }

  @Override
  public PsiExpression getDescriptorEvaluation(DebuggerContext context) throws EvaluateException {
    return null;
  }

  @Override
  public boolean canSetValue() {
    return false;
  }
}


text:
// Copyright (c) Arch team. All rights reserved.

using System;
using System.Collections.Generic;

namespace Arch.EntityFrameworkCore.UnitOfWork.Collections
{
    /// <summary>
    /// Provides some extension methods for <see cref="IEnumerable{T}"/> to provide paging capability.
    /// </summary>
    public static class IEnumerablePagedListExtensions
    {
        /// <summary>
        /// Converts the specified source to <see cref="IPagedList{T}"/> by the specified <paramref name="pageIndex"/> and <paramref name="pageSize"/>.
        /// </summary>
        /// <typeparam name="T">The type of the source.</typeparam>
        /// <param name="source">The source to paging.</param>
        /// <param name="pageIndex">The index of the page.</param>
        /// <param name="pageSize">The size of the page.</param>
        /// <param name="indexFrom">The start index value.</param>
        /// <returns>An instance of the inherited from <see cref="IPagedList{T}"/> interface.</returns>
        public static IPagedList<T> ToPagedList<T>(this IEnumerable<T> source, int pageIndex, int pageSize, int indexFrom = 0) => new PagedList<T>(source, pageIndex, pageSize, indexFrom);

        /// <summary>
        /// Converts the specified source to <see cref="IPagedList{T}"/> by the specified <paramref name="converter"/>, <paramref name="pageIndex"/> and <paramref name="pageSize"/>
        /// </summary>
        /// <typeparam name="TSource">The type of the source.</typeparam>
        /// <typeparam name="TResult">The type of the result</typeparam>
        /// <param name="source">The source to convert.</param>
        /// <param name="converter">The converter to change the <typeparamref name="TSource"/> to <typeparamref name="TResult"/>.</param>
        /// <param name="pageIndex">The page index.</param>
        /// <param name="pageSize">The page size.</param>
        /// <param name="indexFrom">The start index value.</param>
        /// <returns>An instance of the inherited from <see cref="IPagedList{T}"/> interface.</returns>
        public static IPagedList<TResult> ToPagedList<TSource, TResult>(this IEnumerable<TSource> source, Func<IEnumerable<TSource>, IEnumerable<TResult>> converter, int pageIndex, int pageSize, int indexFrom = 0) => new PagedList<TSource, TResult>(source, converter, pageIndex, pageSize, indexFrom);
    }
}


text:
package cz.metacentrum.perun.dispatcher.scheduling;

import cz.metacentrum.perun.core.api.exceptions.InternalErrorException;
import cz.metacentrum.perun.dispatcher.jms.EngineMessageProducer;
import cz.metacentrum.perun.taskslib.exceptions.TaskStoreException;
import cz.metacentrum.perun.taskslib.model.Task;
import cz.metacentrum.perun.taskslib.model.TaskResult;
import cz.metacentrum.perun.taskslib.service.TaskStore;

import java.util.List;

/**
 * In-memory pool of all Tasks. On application start, all Tasks are reloaded from DB.
 *
 * New Tasks are added by EventProcessor, existing Tasks are updated.
 *
 * Tasks can be then pushed to waitingTasksQueue by EventProcessor (new Task), TaskScheduler or PropagationMaintainer.
 *
 * Allows association of Tasks with Engines (EngineMessageProducer queues).
 *
 * @see cz.metacentrum.perun.dispatcher.processing.EventProcessor
 * @see cz.metacentrum.perun.dispatcher.scheduling.TaskScheduler
 * @see cz.metacentrum.perun.dispatcher.scheduling.PropagationMaintainer
 * @see cz.metacentrum.perun.taskslib.model.Task
 *
 * @author Michal Voců
 * @author Michal Babacek
 * @author David Šarman
 * @author Pavel Zlámal <zlamal@cesnet.cz>
 */
public interface SchedulingPool extends TaskStore {

	/**
	 * Add Task to DB and internal scheduling pool.
	 *
	 * @param task Task to be added
	 * @return Current size of pool after adding
	 * @throws InternalErrorException When implementation fails.
	 * @throws TaskStoreException When Task can't be added.
	 */
	int addToPool(Task task) throws TaskStoreException;

	/**
	 * Adds supplied Task into DelayQueue and reset its source updated flag to false if Task is eligible for running.
	 *
	 * Forced Tasks will have delay set to 0, other will use system property: "dispatcher.task.delay.time"
	 * Also forced Tasks will have delayCount set to 0.
	 *
	 * Always retrieve Service/Facility from DB to cross-check actual data.
	 * Check if Service/Facility exists and has connection and is not blocked.
	 *
	 * If check fails, Task is not scheduled.
	 * If passes, status is changed to WAITING and timestamps are re-set.
	 * If Task was already in WAITING, timestamps are kept (so we could tell, when it was scheduled first time).
	 *
	 * @param task Task to schedule propagation for
	 * @param delayCount How long to wait before sending to engine
	 */
	void scheduleTask(Task task, int delayCount);

	/**
	 * Loads Tasks persisted in the database into internal scheduling pool maps.
	 * Immediately restart propagation of previously processing Tasks.
	 * Error and Done Tasks might be reschedule later by PropagationMaintainer.
	 */
	void reloadTasks();

	/**
	 * Clear all in-memory state of Tasks. Called during reloading of Tasks from DB.
	 */
	void clear();

	/**
	 * Return string representation of pool content like "TaskStatus = tasks count" for each TaskStatus.
	 *
	 * @return String representation of pool content
	 */
	String getReport();

	/**
	 * Switch all processing Tasks to ERROR if engine was restarted.
	 *
	 */
	void closeTasksForEngine();

	/**
	 * Store change in Task status sent from Engine.
	 *
	 * @param taskId ID of Task to update
	 * @param status TaskStatus to set
	 * @param date Timestamp of change (string)
	 */
	void onTaskStatusChange(int taskId, String status, String date);

	/**
	 * Store TaskResult sent from Engine.
	 *
	 * @param string Serialized TaskResult object
	 */
	void onTaskDestinationComplete(String string);

	/**
	 * Store TaskResult sent from Engine.
	 *
	 * @param taskResult TaskResult object
	 */
	void onTaskDestinationComplete(TaskResult taskResult);

}


text:
<?php
class Kwf_Util_ClearCache_Types_ProcessControl extends Kwf_Util_ClearCache_Types_Abstract
{
    public function getTypeName()
    {
        return 'processControl';
    }

    public function doesRefresh()
    {
        return true;
    }
    public function doesClear()
    {
        return false;
    }

    protected function _refreshCache($options)
    {
        $cmd = Kwf_Config::getValue('server.phpCli').' bootstrap.php process-control restart --silent 2>&1';
        exec($cmd, $out, $ret);
        if ($ret) {
            throw new Kwf_Exception("restart failed:\n".implode("\n", $out));
        } else {
            $this->_output(implode("\n", $out));
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:app="http://schemas.android.com/apk/res-auto">
  <item android:id="@+id/scan_qrcode_menu"
        android:icon="@drawable/ic_camera_alt_white_24dp"
        android:title="@string/scan_qrcode_menu"
        app:showAsAction="ifRoom"
        >
  </item>
  <item
      android:id="@+id/export_podcast_menu"
      android:icon="@drawable/ic_import_export_white_24dp"
      android:title="@string/export_podcast_menu"
      >
  </item>
  <!-- TODO: fix bug that cannot return to configure screen -->
  <!--
  <item
      android:id="@+id/podcast_page_menu"
      android:icon="@android:drawable/ic_menu_slideshow"
      android:title="@string/podcast_webpage_menu">
  </item>
  -->
</menu>


text:
require 'digest/sha1'
require 'travis/model'

class Url < Travis::Model
  validates :url,  :presence => true, :uniqueness => true
  validates :code, :presence => true, :uniqueness => true

  before_validation :set_code, :on => :create

  def self.shorten(url)
    find_or_create_by(url: url)
  end

  def short_url
    ["http://#{Travis.config.shorten_host}", code].join('/')
  end

  private

  def set_code
    self.code = Digest::SHA1.hexdigest(url)[0..9]
  end
end


text:
package com.marktony.zhihudaily.bean;

import com.google.gson.annotations.SerializedName;

import java.util.ArrayList;

/**
 * Created by Lizhaotailang on 2016/9/16.
 */

public class DoubanMomentNews {

    private int count;
    private ArrayList<posts> posts;
    private int offset;
    private String date;
    private int total;

    public int getCount() {
        return count;
    }

    public void setCount(int count) {
        this.count = count;
    }

    public ArrayList<DoubanMomentNews.posts> getPosts() {
        return posts;
    }

    public void setPosts(ArrayList<DoubanMomentNews.posts> posts) {
        this.posts = posts;
    }

    public int getOffset() {
        return offset;
    }

    public void setOffset(int offset) {
        this.offset = offset;
    }

    public String getDate() {
        return date;
    }

    public void setDate(String date) {
        this.date = date;
    }

    public int getTotal() {
        return total;
    }

    public void setTotal(int total) {
        this.total = total;
    }

    public class posts {

        private int display_style;
        private boolean is_editor_choice;
        private String published_time;
        private String url;
        private String short_url;
        private boolean is_liked;
        private author author;
        private String column;
        private int app_css;
        @SerializedName("abstract")
        private String abs;
        private String date;
        private int like_count;
        private int comments_count;
        private ArrayList<thumbs> thumbs;
        private String created_time;
        private String title;
        private String share_pic_url;
        private String type;
        private int id;

        public class thumbs {
            medium medium;
            String description;
            large large;
            String tag_name;
            small small;
            int id;

            public DoubanMomentNews.posts.medium getMedium() {
                return medium;
            }

            public void setMedium(DoubanMomentNews.posts.medium medium) {
                this.medium = medium;
            }

            public String getDescription() {
                return description;
            }

            public void setDescription(String description) {
                this.description = description;
            }

            public DoubanMomentNews.posts.large getLarge() {
                return large;
            }

            public void setLarge(DoubanMomentNews.posts.large large) {
                this.large = large;
            }

            public String getTag_name() {
                return tag_name;
            }

            public void setTag_name(String tag_name) {
                this.tag_name = tag_name;
            }

            public DoubanMomentNews.posts.small getSmall() {
                return small;
            }

            public void setSmall(DoubanMomentNews.posts.small small) {
                this.small = small;
            }

            public int getId() {
                return id;
            }

            public void setId(int id) {
                this.id = id;
            }
        }

        public class small {
            String url;
            int width;
            int height;

            public String getUrl() {
                return url;
            }
        }

        public class medium {
            String url;
            int width;
            int height;

            public String getUrl() {
                return url;
            }
        }

        public class large {
            String url;
            int width;
            int height;

            public String getUrl() {
                return url;
            }
        }

        public int getDisplay_style() {
            return display_style;
        }

        public void setDisplay_style(int display_style) {
            this.display_style = display_style;
        }

        public boolean is_editor_choice() {
            return is_editor_choice;
        }

        public void setIs_editor_choice(boolean is_editor_choice) {
            this.is_editor_choice = is_editor_choice;
        }

        public String getPublished_time() {
            return published_time;
        }

        public void setPublished_time(String published_time) {
            this.published_time = published_time;
        }

        public String getUrl() {
            return url;
        }

        public void setUrl(String url) {
            this.url = url;
        }

        public String getShort_url() {
            return short_url;
        }

        public void setShort_url(String short_url) {
            this.short_url = short_url;
        }

        public boolean is_liked() {
            return is_liked;
        }

        public void setIs_liked(boolean is_liked) {
            this.is_liked = is_liked;
        }

        public DoubanMomentNews.author getAuthor() {
            return author;
        }

        public void setAuthor(DoubanMomentNews.author author) {
            this.author = author;
        }

        public String getColumn() {
            return column;
        }

        public void setColumn(String column) {
            this.column = column;
        }

        public int getApp_css() {
            return app_css;
        }

        public void setApp_css(int app_css) {
            this.app_css = app_css;
        }

        public String getAbs() {
            return abs;
        }

        public void setAbs(String abs) {
            this.abs = abs;
        }

        public String getDate() {
            return date;
        }

        public void setDate(String date) {
            this.date = date;
        }

        public int getLike_count() {
            return like_count;
        }

        public void setLike_count(int like_count) {
            this.like_count = like_count;
        }

        public int getComments_count() {
            return comments_count;
        }

        public void setComments_count(int comments_count) {
            this.comments_count = comments_count;
        }

        public ArrayList<thumbs> getThumbs() {
            return thumbs;
        }

        public void setThumbs(ArrayList<thumbs> thumbs) {
            this.thumbs = thumbs;
        }

        public String getCreated_time() {
            return created_time;
        }

        public void setCreated_time(String created_time) {
            this.created_time = created_time;
        }

        public String getTitle() {
            return title;
        }

        public void setTitle(String title) {
            this.title = title;
        }

        public String getShare_pic_url() {
            return share_pic_url;
        }

        public void setShare_pic_url(String share_pic_url) {
            this.share_pic_url = share_pic_url;
        }

        public String getType() {
            return type;
        }

        public void setType(String type) {
            this.type = type;
        }

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }
    }

    private class author {
        boolean is_followed;
        String uid;
        String url;
        String avatar;
        String name;
        boolean is_special_user;
        int n_posts;
        String alt;
        String large_avatar;
        String id;
        boolean is_auth_author;
    }

}


text:
Here is my personal settings and configuration files. Take anything you want,
but use at your own risk. Let me know if you have any suggestion to improve.

## Install

Clone my repository to a directory:

    $ git clone https://github.com/vargad/dotfiles

Create symlinks to the configuration files you want to use, or just run my
install.sh script, which creates symlinks (or updates exsiting symlinks):

    $ ./install.sh

Please note that the script does not delete any files. It skips all existing
files (and prints a warning), unless it's a symlink, in that case it updates
the link.


text:
//  Copyright (c) 2014-2015 First Flamingo Enterprise B.V.
//
//  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.
//
//  FFERemoteObject.h
//  FlamingoModel
//
//  Created by Berend Schotanus on 21-04-14.
//

#import <Foundation/Foundation.h>

typedef enum {
    DataTypeUnknown,
    DataTypeXML,
    DataTypeJSON
} FFEDataType;

typedef enum {
    cancelSync = 0,
    syncWithPrevailingServer,
    syncWithPrevailingClient
} FFESyncInstruction;

@protocol FFESyncing <NSObject>

#pragma mark Identity of the object:

/**
 Base path (normally api/class_name) for composing a url.
 */
+ (NSString*)remotePath;

/**
 Path extension indicating the instance, when composing a url.
 */
@property (nonatomic, readonly) NSString *pathExtension;

/**
 Identifier by whitch the instance is known in the model logic.
 */
@property (nonatomic, strong) NSString *modelID;

/**
 Predicate that can be used to find an object with its model id.
 */
+ (NSPredicate*)predicateWithModelID:(NSString*)identifier;

#pragma mark Keeping track of changes:

/**
 Timestamp of the last time when the object was saved into the managedObjectContext.
 If the object was saved due to a server update, lastClientModification will be equal to lastServerModification.
 */
@property (nonatomic) NSDate *lastClientModification;

/**
 Timestamp of the last modification as indicated by the server.
 */
@property (nonatomic) NSDate *lastServerModification;

#pragma mark Reading and writing content:

/**
 Array of data types the object can handle
 */
+ (NSArray*)acceptedDataTypes;

/**
 An NSData object with the contents of the object in the requested format
 */
- (NSData*)contentWithDataType:(FFEDataType)type;

/**
 Fills the object with contents from an NSData object in the indicated format
 */
- (void)fillWithData:(NSData*)data ofType:(FFEDataType)type;

@end


text:
import Controller from '../../../controller'
import React from 'react'

export default class extends Controller {
    View = View;
    constructor(location, context) {
        super(location, context)
        if (context.isClient) {
            window.controller = this
        } else if (context.isServer) {
            global.controller = this
        }
    }
}

function View({ state }) {
    return
{JSON.stringify(state, null, 2)}

}


text:
// Copyright 2020 The NATS Authors
// 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 io.nats.examples.jetstream;

import io.nats.client.*;
import io.nats.examples.ExampleArgs;
import io.nats.examples.ExampleUtils;

import java.time.Duration;
import java.util.List;

import static io.nats.examples.jetstream.NatsJsUtils.*;

/**
 * This example will demonstrate miscellaneous uses cases of a pull subscription of:
 * batch size and expires pull: pullExpiresIn(int batchSize, Duration expiresIn),
 * requiring manual handling of null and 408 status.
 */
public class NatsJsPullSubExpireUseCases {
    static final String usageString =
            "\nUsage: java -cp <classpath> NatsJsPullSubExpireUseCases [-s server] [-strm stream] [-sub subject] [-dur durable]"
                    + "\n\nDefault Values:"
                    + "\n   [-strm stream]     expire-uc-ack-stream"
                    + "\n   [-sub subject]     expire-uc-ack-subject"
                    + "\n   [-dur durable]     expire-uc-ack-durable"
                    + "\n\nUse tls:// or opentls:// to require tls, via the Default SSLContext\n"
                    + "\nSet the environment variable NATS_NKEY to use challenge response authentication by setting a file containing your private key.\n"
                    + "\nSet the environment variable NATS_CREDS to use JWT/NKey authentication by setting a file containing your user creds.\n"
                    + "\nUse the URL for user/pass/token authentication.\n";

    public static void main(String[] args) {
        ExampleArgs exArgs = ExampleArgs.builder()
                .defaultStream("expire-uc-ack-stream")
                .defaultSubject("expire-uc-ack-subject")
                .defaultDurable("expire-uc-ack-durable")
                //.uniqueify() // uncomment to be able to re-run without re-starting server
                .build(args, usageString);

        try (Connection nc = Nats.connect(ExampleUtils.createExampleOptions(exArgs.server))) {
            NatsJsUtils.createOrUpdateStream(nc, exArgs.stream, exArgs.subject);

            // Create our JetStream context to receive JetStream messages.
            JetStream js = nc.jetStream();

            // Build our subscription options. Durable is REQUIRED for pull based subscriptions
            PullSubscribeOptions pullOptions = PullSubscribeOptions.builder()
                    .durable(exArgs.durable)      // required
                    .build();

            // 0.1 Initialize. subscription
            // 0.2 Flush outgoing communication with/to the server, useful when app is both publishing and subscribing.
            // 0.3 Start the pull, you don't have to call this again because AckMode.NEXT
            // -  When we ack a batch message the server starts preparing or adding to the next batch.
            System.out.println("\n----------\n0. Initialize the subscription and pull.");
            JetStreamSubscription sub = js.subscribe(exArgs.subject, pullOptions);
            nc.flush(Duration.ofSeconds(1));

            sub.pullExpiresIn(10, Duration.ofSeconds(2));

            // 1. Publish some that is less than the batch size.
            System.out.println("\n----------\n1. Publish some amount of messages, but not entire batch size.");
            publish(js, exArgs.subject, "A", 6);
            List<Message> messages = readMessagesAck(sub, Duration.ofSeconds(2));
            System.out.println("We should have received 6 total messages, we received: " + messages.size());
            System.out.println("We should have received 6 regular messages, we received: " + countJs(messages));
            System.out.println("We should have received 0 408 markers of last batch, we received: " + count408s(messages));

            // 2. Publish some more covering our pull size...
            System.out.println("----------\n2. Publish more than the batch size.");
            sub.pullExpiresIn(10, Duration.ofSeconds(2));
            publish(js, exArgs.subject, "B", 14);
            messages = readMessagesAck(sub, Duration.ofSeconds(2));
            System.out.println("We should have received 14 total messages, we received: " + messages.size());
            System.out.println("We should have received 10 regular messages, we received: " + countJs(messages));
            System.out.println("We should have received 4 408 markers of last batch, we received: " + count408s(messages));

            // 3. There are still 4 messages from B, but the batch was finished
            // -  won't get any messages until a pull is issued.
            System.out.println("----------\n3. Read without re-issue.");
            messages = readMessagesAck(sub, Duration.ofSeconds(2));
            System.out.println("We should have received 0 total messages, we received: " + messages.size());

            // 4. re-issue the pull to get the last 4
            System.out.println("----------\n4. Re-issue to get the last 4.");
            sub.pullExpiresIn(10, Duration.ofSeconds(2));
            messages = readMessagesAck(sub, Duration.ofSeconds(2));
            System.out.println("We should have received 4 total messages, we received: " + messages.size());
            System.out.println("We should have received 4 regular messages, we received: " + countJs(messages));
            System.out.println("We should have received 0 408 markers of last batch, we received: " + count408s(messages));

            // 5. publish a lot of messages
            System.out.println("----------\n5. Publish a lot of messages. The last pull was under the batch size.");
            publish(js, exArgs.subject, "C", 25);
            sub.pullExpiresIn(10, Duration.ofSeconds(2));
            messages = readMessagesAck(sub, Duration.ofSeconds(2));
            System.out.println("We should have received 16 total messages, we received: " + messages.size());
            System.out.println("We should have received 10 regular messages, we received: " + countJs(messages));
            System.out.println("We should have received 6 408 markers of last batch, we received: " + count408s(messages));

            // 6. there are still more messages
            System.out.println("----------\n6. Still more messages.");
            sub.pullExpiresIn(10, Duration.ofSeconds(2));
            messages = readMessagesAck(sub, Duration.ofSeconds(2));
            System.out.println("We should have received 1 total messages, we received: " + messages.size());
            System.out.println("We should have received 10 regular messages, we received: " + countJs(messages));
            System.out.println("We should have received 0 408 markers of last batch, we received: " + count408s(messages));

            // 7. there are still more messages
            System.out.println("----------\n7. Still more messages.");
            sub.pullExpiresIn(10, Duration.ofSeconds(2));
            messages = readMessagesAck(sub, Duration.ofSeconds(2));
            System.out.println("We should have received 5 total messages, we received: " + messages.size());
            System.out.println("We should have received 5 regular messages, we received: " + countJs(messages));
            System.out.println("We should have received 0 408 markers of last batch, we received: " + count408s(messages));

            // 8. we got them all
            System.out.println("----------\n7. No messages left.");
            sub.pullExpiresIn(10, Duration.ofSeconds(2));
            messages = readMessagesAck(sub, Duration.ofSeconds(2));
            System.out.println("We should have received 5 total messages, we received: " + messages.size());
            System.out.println("We should have received 0 regular messages, we received: " + countJs(messages));
            System.out.println("We should have received 5 408 markers of last batch, we received: " + count408s(messages));

            System.out.println("----------\n");
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
}


text:
if [ $EUID == 0 ]; then
     echo
     echo
     echo "[!] This option cannot be ran as root."
     echo
     exit
fi

clear
f_banner

echo -e "${BLUE}Run multiple instances of Nikto in parallel.${NC}"
echo
echo "1.  List of IPs"
echo "2.  List of IP:port"
echo "3.  Previous menu"
echo
echo -n "Choice: "
read choice

case $choice in
     1)
     f_location

     echo
     echo -n "Port (default 80): "
     read port
     echo

     # Check if port is a number
     echo "$port" | grep -E "^[0-9]+$" 2>/dev/null
     isnum=$?

     if [ $isnum -ne 0 ] && [ ${#port} -gt 0 ]; then
          f_error
     fi

     if [ ${#port} -eq 0 ]; then
          port=80
     fi

     if [ $port -lt 1 ] || [ $port -gt 65535 ]; then
          f_error
     fi

     mkdir $home/data/nikto-$port

     while read -r line; do
          xdotool key ctrl+shift+t
          xdotool type "nikto -h $line -port $port -no404 -maxtime 20m -Format htm --output $home/data/nikto-$port/$line.htm ; exit"
          sleep 1
          xdotool key Return
     done < "$location"
     ;;

     2)
     f_location

     mkdir $home/data/nikto

     while IFS=: read -r host port; do
          xdotool key ctrl+shift+t
          sleep 1
          xdotool type "nikto -h $host -port $port -no404 -maxtime 20m -Format htm --output $home/data/nikto/$host-$port.htm ; exit"
          sleep 1
          xdotool key Return
     done < "$location"
     ;;

     3) f_main;;
     *) f_error;;
esac

echo
echo $medium
echo
echo "***Scan complete.***"
echo
echo
echo -e "The new report is located at ${YELLOW}$home/data/nikto-$port/${NC}\n"


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Lilloa 22: 368 (1951)

#### Original name
Omphalia orickiana A.H. Sm., 1938

### Remarks
null


text:
<?php
function testIdentifierHasExpectedStartLine(SplObjectStorage $storage)
{
    return $storage->contains($storage);
}


text:
'use strict';

var core = require(__dirname + '/core.js');
var helpers = require(__dirname + '/helpers.js');

function buildNationalPartyMandatesSection() {
    var wrapper = $('
');
    helpers.appendSectionTitle(wrapper, 'Първа стъпка – разпределение на мандатите за всяка партия и коалиция на национално ниво:');

    helpers.appendInfoMessage(wrapper, 'Сума от всички действителни гласове: ' + core.getRealVotesSum());
    helpers.appendInfoMessage(wrapper, 'Четири на сто от действителните гласове в страната и извън страната: ' + core.getMinimumVotesToGetElected());
    helpers.appendInfoMessage(wrapper, 'Сума от действителни гласове за партии и коалиции от партии, които участват в разпределението на мандатите: ' + core.getElectedPartiesVotesSum());
    helpers.appendInfoMessage(wrapper, 'Квота на Хеър: ' + core.getHareQuote(core.getElectedPartiesVotesSum(), core.getTotalMandates()));

    var electedPartyDistributions = core.getElectedPartiesDistribution();
    var table = $('
');
    table.append(function () {
        var headerRow = helpers.headerRow('Партия');
        var realVotesRow = helpers.row('Действ. гласове');
        var quotientRow = helpers.row('Частно');
        var baseMandatesRow = helpers.row('Осн. манд.');
        var remindersRow = helpers.row('Остатък');
        var extraMandatesRow = helpers.row('Доп. манд.');
        var totalMandatesRow = helpers.row('Общо манд.');
        _.each(core.getParties(), function (partyName, partyId) {
            headerRow.append(helpers.cell(partyName));
            realVotesRow.append(helpers.cell(core.getPartyVotesSum(partyId)));

            if (!electedPartyDistributions.hasOwnProperty(partyId)) {
                _.each([quotientRow, baseMandatesRow, remindersRow, extraMandatesRow, totalMandatesRow], function (row) {
                   row.append(helpers.emptyCell());
                });
            } else {
                var partyDistribution = electedPartyDistributions[partyId];
                quotientRow.append(helpers.cell(partyDistribution.quotient.toFixed(10)));
                baseMandatesRow.append(helpers.cell(partyDistribution.baseMandates));
                remindersRow.append(helpers.cell(partyDistribution.reminder.toFixed(10)));
                extraMandatesRow.append(helpers.cell(partyDistribution.extraMandates));
                totalMandatesRow.append(helpers.cell(partyDistribution.totalMandates));
            }
        });

        return [headerRow, realVotesRow, quotientRow, baseMandatesRow, remindersRow, extraMandatesRow, totalMandatesRow];
    });

    wrapper.append(table);
    return wrapper;
}

module.exports = {
    buildNationalPartyMandatesSection: buildNationalPartyMandatesSection
};


text:
$(function(){
    function getUrlParameter(sParam)
    {
        var sPageURL = window.location.search.substring(1);
        var sURLVariables = sPageURL.split('&');
        for (var i = 0; i < sURLVariables.length; i++)
        {
            var sParameterName = sURLVariables[i].split('=');
            if (sParameterName[0] == sParam)
            {
                return sParameterName[1];
            }
        }
    }

    var e = fidelis($('body'));
    swal("Ready", "Please touch your phone to the TFC device")
    $(document).on('tfcend', function(ev){

        // jQuery leaves the token hiden deep within the event object
        // here's how you get it:
        var tfcToken = ev.originalEvent.detail.tfcToken

        // vibrate the device
        if ("vibrate" in navigator) {
            // vibration API supported
            navigator.vibrate(100);
        }
        console.log("got event")
        // update the readout

        swal("Thanks", "Please take your parcel", "success");

        var fidelis_event_url = "http://fidelis-api-1.appspot.com/v2/event";
        var headers = {'X-Auth-Token' : '841672af-577d-4486-979b-95a72025f6c7'};
        var post_data = {'token':String(tfcToken), 'user_device_id':getUrlParameter('user')};
        $.ajax({
            type: "POST",
            url: fidelis_event_url,
            data: JSON.stringify(post_data),
            dataType: "json",
            headers: headers,
            contentType : 'application/json'
        }).done(function(data) {
            console.log(data);
        }).fail(function(data, textStatus, errorThrown) {
            console.log("Failed");
            console.log(data);
            console.log(data.statusCode());
            console.log(errorThrown);
        });

    });
});


text:
package com.yaylas.sytech.facerecognizer;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.opencv.android.BaseLoaderCallback;
import org.opencv.android.LoaderCallbackInterface;
import org.opencv.android.OpenCVLoader;

import com.yaylas.sytech.facerecognizer.facedatabase.FacesDataSource;
import com.yaylas.sytech.facerecognizer.utils.FaceDetectionUtils;

import android.animation.Animator.AnimatorListener;
import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewTreeObserver.OnDrawListener;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;

public class SplashActivity extends Activity{

	private ImageView splashPage;
	private ImageView dot1;
	private ImageView dot2;
	private ImageView dot3;
	private Handler handler = new Handler();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_splash);
		splashPage = (ImageView)findViewById(R.id.splashImage);
		dot1 = (ImageView)findViewById(R.id.splashdot1);
		dot2 = (ImageView)findViewById(R.id.splashdot2);
		dot3 = (ImageView)findViewById(R.id.splashdot3);

//		new Thread(new Runnable() {
//
//			@Override
//			public void run() {
				 FaceDetectionUtils.initialize(SplashActivity.this);
//			}
//		}).start();
		openHomePage();

	}

	private void openHomePage(){
		AlphaAnimation fadeIn = new AlphaAnimation(1, 1);
		fadeIn.setInterpolator(new AccelerateInterpolator()); //add this
		fadeIn.setDuration(1);
		splashPage.setAnimation(fadeIn);
		fadeIn.setAnimationListener(new AnimationListener() {

			@Override
			public void onAnimationStart(Animation animation) {

			}

			@Override
			public void onAnimationRepeat(Animation animation) {
						// TODO Auto-generated method stub
			}

			@Override
			public void onAnimationEnd(Animation animation) {
				final int shift = dot1.getMeasuredWidth()+10;
				handler.postDelayed(new Runnable() {

					@Override
					public void run() {
						dotEnterAnimation(dot1, shift);
					}
				}, 100);
				handler.postDelayed(new Runnable() {

					@Override
					public void run() {
						dotEnterAnimation(dot2, 0);
					}
				}, 400);
				handler.postDelayed(new Runnable() {

					@Override
					public void run() {
						dotEnterAnimation(dot3, -shift);
					}
				}, 700);
			}
		});
		splashPage.invalidate();
		fadeIn.startNow();
		splashPage.startAnimation(fadeIn);

	}

	private void dotEnterAnimation(final ImageView dot, int shift){
		DisplayMetrics dm = new DisplayMetrics();
		SplashActivity.this.getWindowManager().getDefaultDisplay().getMetrics( dm );
		int originalPos[] = new int[2];
		dot.getLocationOnScreen(originalPos);

		int xDest = dm.widthPixels/2;
		xDest -= (dot.getMeasuredWidth()/2) + shift;

		final int lastPos = xDest - originalPos[0];
		TranslateAnimation dotSlide = new TranslateAnimation( 0, xDest - originalPos[0] , 0, 0);
		dotSlide.setInterpolator(new DecelerateInterpolator());
		dotSlide.setDuration(1000);
		dotSlide.setFillAfter(true);
		dotSlide.setAnimationListener(new AnimationListener() {

			@Override
			public void onAnimationStart(Animation animation) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onAnimationRepeat(Animation animation) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onAnimationEnd(Animation animation) {
				if(dot == dot1){
					dotExitAnimation(dot, 900, lastPos);
				} else if(dot == dot2){
					dotExitAnimation(dot, 700, lastPos);
				} else if(dot == dot3){
					dotExitAnimation(dot, 500, lastPos);
				}
			}
		});
		dot.clearAnimation();
		dot.setAnimation(dotSlide);
		dot.invalidate();
		dotSlide.startNow();
		dot.startAnimation(dotSlide);
	}

	private void dotExitAnimation(final ImageView dot,int time, final int lastPos){
		handler.postDelayed(new Runnable() {

			@Override
			public void run() {
				DisplayMetrics dm = new DisplayMetrics();
				SplashActivity.this.getWindowManager().getDefaultDisplay().getMetrics( dm );
				int originalPos[] = new int[2];
				dot.getLocationOnScreen(originalPos);

				int xDest = dm.widthPixels;

				TranslateAnimation dotSlide = new TranslateAnimation( lastPos, lastPos-xDest , 0, 0);
				dotSlide.setInterpolator(new DecelerateInterpolator());
				dotSlide.setDuration(800);
				dotSlide.setFillAfter(true);
				dotSlide.setAnimationListener(new AnimationListener() {

					@Override
					public void onAnimationStart(Animation animation) {
						// TODO Auto-generated method stub

					}

					@Override
					public void onAnimationRepeat(Animation animation) {
						// TODO Auto-generated method stub

					}

					@Override
					public void onAnimationEnd(Animation animation) {
						if(dot == dot3){
							splashFadeOut();
						}
					}
				});
				dot.clearAnimation();
				dot.setAnimation(dotSlide);
				dot.invalidate();
				dotSlide.startNow();
				dot.startAnimation(dotSlide);
			}
		}, time);

	}

	private void splashFadeOut(){
		if(FaceDetectionUtils.cascadeFilesLoaded){
			Intent intent = new Intent(SplashActivity.this, MainPageActivity.class);
			SplashActivity.this.startActivity(intent);
			SplashActivity.this.overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
			SplashActivity.this.finish();
		} else {
			openHomePage();
		}

	}

	@Override
	public boolean onKeyUp(int keyCode, KeyEvent event) {
		if(keyCode == KeyEvent.KEYCODE_BACK){
			return false;
		}
		return super.onKeyUp(keyCode, event);
	}
}


text:
import abc

from rally.common import logging
from rally import exceptions

import six

LOG = logging.getLogger(__name__)

@six.add_metaclass(abc.ABCMeta)
class CinderWrapper(object):
    def __init__(self, client, owner):
        self.owner = owner
        self.client = client

    @abc.abstractmethod
    def create_volume(self, volume):
        """Creates new volume."""

    @abc.abstractmethod
    def update_volume(self, volume):
        """Updates name and description for this volume."""

    @abc.abstractmethod
    def create_snapshot(self, volume_id):
        """Creates a volume snapshot."""

class CinderV1Wrapper(CinderWrapper):
    def create_volume(self, size, **kwargs):
        kwargs["display_name"] = self.owner.generate_random_name()
        volume = self.client.volumes.create(size, **kwargs)
        return volume

    def update_volume(self, volume, **update_args):
        update_args["display_name"] = self.owner.generate_random_name()
        update_args["display_description"] = (
            update_args.get("display_description"))
        self.client.volumes.update(volume, **update_args)

    def create_snapshot(self, volume_id, **kwargs):
        kwargs["display_name"] = self.owner.generate_random_name()
        snapshot = self.client.volume_snapshots.create(volume_id, **kwargs)
        return snapshot

class CinderV2Wrapper(CinderWrapper):
    def create_volume(self, size, **kwargs):
        kwargs["name"] = self.owner.generate_random_name()

        volume = self.client.volumes.create(size, **kwargs)
        return volume

    def update_volume(self, volume, **update_args):
        update_args["name"] = self.owner.generate_random_name()
        update_args["description"] = update_args.get("description")
        self.client.volumes.update(volume, **update_args)

    def create_snapshot(self, volume_id, **kwargs):
        kwargs["name"] = self.owner.generate_random_name()
        snapshot = self.client.volume_snapshots.create(volume_id, **kwargs)
        return snapshot

def wrap(client, owner):
    """Returns cinderclient wrapper based on cinder client version."""
    LOG.warning("Method wrap from %s and whole Cinder wrappers are "
                "deprecated since Rally 0.10.0 and will be removed soon. Use "
                "rally.plugins.openstack.services.storage.block.BlockStorage "
                "instead." % __file__)
    version = client.choose_version()
    if version == "1":
        return CinderV1Wrapper(client(), owner)
    elif version == "2":
        return CinderV2Wrapper(client(), owner)
    else:
        msg = "This version of API %s could not be identified." % version
        LOG.warning(msg)
        raise exceptions.InvalidArgumentsException(msg)