text:
package com.gmail.kamiloleksik.jfxkonwerter.util;

import java.util.Comparator;

import com.gmail.kamiloleksik.jfxkonwerter.model.entity.Unit;

public class NumberBaseComparator implements Comparator<Unit>
{
	@Override
	public int compare(Unit o1, Unit o2)
	{
		return extractInt(o1) - extractInt(o2);
	}

	private int extractInt(Unit unit)
	{
		String s = unit.getUnitName();
		String num = s.replaceAll("\\D", "");
		return num.isEmpty() ? 0 : Integer.parseInt(num);
	}
}

redpajama_set_name: RedPajamaGithub


text:
krado
=====

Simple grid system, probably been done a million times before


text:
local KLDPenalty, parent = torch.class('nn.KLDPenalty', 'nn.Module')

function KLDPenalty:updateOutput(input)
    local mean, log_var = table.unpack(input)
    self.output = input

    -- Appendix B from VAE paper: 0.5 * sum(1 + log(sigma^2) - mu^2 - sigma^2)
    local mean_sq = torch.pow(mean, 2)
    local KLDelements = log_var:clone()
    KLDelements:exp():mul(-1)
    KLDelements:add(-1, torch.pow(mean, 2))
    KLDelements:add(1)
    KLDelements:add(log_var)
    self.loss = -0.5 * torch.sum(KLDelements)

    return self.output
end

function KLDPenalty:updateGradInput(input, gradOutput)
    assert(#gradOutput == 2)
    local mean, log_var = table.unpack(input)
    self.gradInput = {}
    self.gradInput[1] = mean:clone() + gradOutput[1]

    -- Fix this to be nicer
    self.gradInput[2] = torch.exp(log_var):mul(-1):add(1):mul(-0.5) + gradOutput[2]

    return self.gradInput
end


text:
package main

import (
	"net/http"
	_ "net/http/pprof"

	"github.com/prometheus/client_golang/prometheus"
	"github.com/prometheus/client_golang/prometheus/promhttp"
	"github.com/prometheus/common/log"
	"github.com/prometheus/common/version"
	"github.com/Jean-Daniel/node_exporter/collector"
	"gopkg.in/alecthomas/kingpin.v2"
)

func init() {
	prometheus.MustRegister(version.NewCollector("node_exporter"))
}

func main() {
	var (
		listenAddress = kingpin.Flag("web.listen-address", "Address on which to expose metrics and web interface.").Default(":9100").String()
		metricsPath   = kingpin.Flag("web.telemetry-path", "Path under which to expose metrics.").Default("/metrics").String()
	)

	log.AddFlags(kingpin.CommandLine)
	kingpin.Version(version.Print("node_exporter"))
	kingpin.HelpFlag.Short('h')
	kingpin.Parse()

	log.Infoln("Starting node_exporter", version.Info())
	log.Infoln("Build context", version.BuildContext())

	nc, err := collector.NewNodeCollector()
	if err != nil {
		log.Fatalf("Couldn't create collector: %s", err)
	}
	log.Infof("Enabled collectors:")
	for n := range nc.Collectors {
		log.Infof(" - %s", n)
	}

	if err := prometheus.Register(nc); err != nil {
		log.Fatalf("Couldn't register collector: %s", err)
	}
	handler := promhttp.HandlerFor(prometheus.DefaultGatherer,
		promhttp.HandlerOpts{
			ErrorLog:      log.NewErrorLogger(),
			ErrorHandling: promhttp.ContinueOnError,
		})

	// TODO(ts): Remove deprecated and problematic InstrumentHandler usage.
	http.Handle(*metricsPath, prometheus.InstrumentHandler("prometheus", handler))
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte(`
			<title>Node Exporter</title>

Node Exporter

<a href="` + *metricsPath + `">Metrics

			`))
	})

	log.Infoln("Listening on", *listenAddress)
	err = http.ListenAndServe(*listenAddress, nil)
	if err != nil {
		log.Fatal(err)
	}
}


text:
if type(hooks.before_rest_response) == 'function' then
	hooks.before_rest_response()
end


text:
<?php

namespace GarbledTutors\RadiusIntegrationBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class RadiusIntegrationBundle extends Bundle
{
}


text:
package v1

import (
	"context"
	"fmt"
	"github.com/lastbackend/lastbackend/pkg/distribution/types"
	"io"
	"net/http"
	"strconv"

	rv1 "github.com/lastbackend/lastbackend/pkg/api/types/v1/request"
	vv1 "github.com/lastbackend/lastbackend/pkg/api/types/v1/views"
	"github.com/lastbackend/lastbackend/pkg/distribution/errors"
	"github.com/lastbackend/lastbackend/pkg/util/http/request"
)

type PodClient struct {
	client *request.RESTClient

	parent struct {
		kind     string
		selflink string
	}

	namespace string
	name      string
}

func (pc *PodClient) List(ctx context.Context) (*vv1.PodList, error) {

	var s *vv1.PodList
	var e *errors.Http

	var url string

	switch pc.parent.kind {
	case types.KindDeployment:
		dsl := types.DeploymentSelfLink{}
		if err := dsl.Parse(pc.parent.selflink); err != nil {
			return nil, err
		}
		_, svc := dsl.Parent()
		url = fmt.Sprintf("/namespace/%s/service/%s/deployment/%s/pod", pc.namespace, svc.Name(), dsl.Name())
	case types.KindTask:
		tsl := types.TaskSelfLink{}
		if err := tsl.Parse(pc.parent.selflink); err != nil {
			return nil, err
		}
		_, job := tsl.Parent()
		url = fmt.Sprintf("/namespace/%s/job/%s/task/%s/pod", pc.namespace, job.Name(), tsl.Name())
	}

	err := pc.client.Get(url).
		AddHeader("Content-Type", "application/json").
		JSON(&s, &e)

	if err != nil {
		return nil, err
	}
	if e != nil {
		return nil, errors.New(e.Message)
	}

	if s == nil {
		list := make(vv1.PodList, 0)
		s = &list
	}

	return s, nil
}

func (pc *PodClient) Get(ctx context.Context) (*vv1.Pod, error) {

	var s *vv1.Pod
	var e *errors.Http

	var url string

	switch pc.parent.kind {
	case types.KindDeployment:
		dsl := types.DeploymentSelfLink{}
		if err := dsl.Parse(pc.parent.selflink); err != nil {
			return nil, err
		}
		_, svc := dsl.Parent()
		url = fmt.Sprintf("/namespace/%s/service/%s/deployment/%s/pod/%s", pc.namespace, svc.Name(), dsl.Name(), pc.name)
	case types.KindTask:
		tsl := types.TaskSelfLink{}
		if err := tsl.Parse(pc.parent.selflink); err != nil {
			return nil, err
		}
		_, job := tsl.Parent()
		url = fmt.Sprintf("/namespace/%s/job/%s/task/%s/pod/%s", pc.namespace, job.Name(), tsl.Name(), pc.name)
	}

	err := pc.client.Get(url).
		AddHeader("Content-Type", "application/json").
		JSON(&s, &e)

	if err != nil {
		return nil, err
	}
	if e != nil {
		return nil, errors.New(e.Message)
	}

	return s, nil
}

func (pc *PodClient) Logs(ctx context.Context, opts *rv1.PodLogsOptions) (io.ReadCloser, *http.Response, error) {

	var url, parent string

	switch pc.parent.kind {
	case types.KindDeployment:
		dsl := types.DeploymentSelfLink{}
		if err := dsl.Parse(pc.parent.selflink); err != nil {
			return nil, nil, err
		}
		parent = dsl.Name()
		_, svc := dsl.Parent()
		url = fmt.Sprintf("/namespace/%s/service/%s/logs", pc.namespace, svc.Name())
	case types.KindTask:
		tsl := types.TaskSelfLink{}
		if err := tsl.Parse(pc.parent.selflink); err != nil {
			return nil, nil, err
		}
		parent = tsl.Name()
		_, job := tsl.Parent()
		url = fmt.Sprintf("/namespace/%s/job/%s/logs", pc.namespace, job.Name())
	}

	res := pc.client.Get(url)

	if opts != nil {

		switch pc.parent.kind {
		case types.KindDeployment:
			res.Param("deployment", parent)
		case types.KindTask:
			res.Param("task", parent)
		}

		res.Param("pod", pc.name)
		res.Param("container", opts.Container)

		if opts.Follow {
			res.Param("follow", strconv.FormatBool(opts.Follow))
		}
	}

	return res.Stream()
}

func newPodClient(client *request.RESTClient, namespace, kind, parent, name string) *PodClient {
	pc := PodClient{client: client, namespace: namespace, name: name}
	pc.parent.kind = kind
	pc.parent.selflink = parent
	return &pc
}


text: A Fast & Reliable open source Job delegation & queueing server.


text:
'use strict';

$(document).ready(function() {
    function make_panel(nav, heading) {
        var panel = $('
');
        nav.append(panel);
        var panel_header = $(
            '
' + heading + '
');
        panel.append(panel_header);
        var panel_body = $('
');
        panel.append(panel_body);
        return panel_body;
    }

    function make_value_selector_panel(nav, heading, values, setup_callback) {
        var panel_body = make_panel(nav, heading);
        var vertical = false;
        var buttons = $('
');

        panel_body.append(buttons);

        $.each(values, function (idx, value) {
            var button = $(
                '');
            setup_callback(idx, value, button);
            buttons.append(button);
        });

        return panel_body;
    }

    function reflow_value_selector_panels(no_timeout) {
        $('.panel').each(function (i, panel_obj) {
            var panel = $(panel_obj);
            panel.find('.btn-group').each(function (i, buttons_obj) {
                var buttons = $(buttons_obj);
                var width = 0;

                if (buttons.hasClass('reflow-done')) {
                    /* already processed */
                    return;
                }

                $.each(buttons.children(), function(idx, value) {
                    width += value.scrollWidth;
                });

                var max_width = panel_obj.clientWidth;

                if (width >= max_width) {
                    buttons.addClass("btn-group-vertical");
                    buttons.css("width", "100%");
                    buttons.css("max-height", "20ex");
                    buttons.css("overflow-y", "auto");
                }
                else {
                    buttons.addClass("btn-group-justified");
                }

                /* The widths can be zero if the UI is not fully layouted yet,
                   so mark the adjustment complete only if this is not the case */
                if (width > 0 && max_width > 0) {
                    buttons.addClass("reflow-done");
                }
            });
        });

        if (!no_timeout) {
            /* Call again asynchronously, in case the UI was not fully layouted yet */
            setTimeout(function() { $.asv.ui.reflow_value_selector_panels(true); }, 0);
        }
    }

    function network_error(ajax, status, error) {
        $("#error-message").text(
            "Error fetching content. " +
            "Perhaps web server has gone down.");
        $("#error").modal('show');
    }

    function hover_graph(element, graph_url, benchmark_basename, parameter_idx, revisions) {
        /* Show the summary graph as a popup */
        var plot_div = $('
');
        plot_div.css('width', '11.8em');
        plot_div.css('height', '7em');
        plot_div.css('border', '2px solid black');
        plot_div.css('background-color', 'white');

        function update_plot() {
            var markings = [];

            if (revisions) {
                $.each(revisions, function(i, revs) {
                    var rev_a = revs[0];
                    var rev_b = revs[1];

                    if (rev_a !== null) {
                        markings.push({ color: '#d00', lineWidth: 2, xaxis: { from: rev_a, to: rev_a }});
                        markings.push({ color: "rgba(255,0,0,0.1)", xaxis: { from: rev_a, to: rev_b }});
                    }
                    markings.push({ color: '#d00', lineWidth: 2, xaxis: { from: rev_b, to: rev_b }});
                });
            }

            $.asv.load_graph_data(
                graph_url
            ).done(function (data) {
                var params = $.asv.master_json.benchmarks[benchmark_basename].params;
                data = $.asv.filter_graph_data_idx(data, 0, parameter_idx, params);
                var options = {
                    colors: ['#000'],
                    series: {
                        lines: {
                            show: true,
                            lineWidth: 2
                        },
                        shadowSize: 0
                    },
                    grid: {
                        borderWidth: 1,
                        margin: 0,
                        labelMargin: 0,
                        axisMargin: 0,
                        minBorderMargin: 0,
                        markings: markings,
                    },
                    xaxis: {
                        ticks: [],
                    },
                    yaxis: {
                        ticks: [],
                        min: 0
                    },
                    legend: {
                        show: false
                    }
                };
                var plot = $.plot(plot_div, [{data: data}], options);
            }).fail(function () {
                // TODO: Handle failure
            });

            return plot_div;
        }

        element.popover({
            placement: 'left auto',
            trigger: 'hover',
            html: true,
            delay: 50,
            content: $('
').append(plot_div)
        });

        element.on('show.bs.popover', update_plot);
    }

    function hover_summary_graph(element, benchmark_basename) {
        /* Show the summary graph as a popup */
        var plot_div = $('
');
        plot_div.css('width', '11.8em');
        plot_div.css('height', '7em');
        plot_div.css('border', '2px solid black');
        plot_div.css('background-color', 'white');

        function update_plot() {
            var markings = [];

            $.asv.load_graph_data(
                'graphs/summary/' + benchmark_basename + '.json'
            ).done(function (data) {
                var options = {
                    colors: $.asv.colors,
                    series: {
                        lines: {
                            show: true,
                            lineWidth: 2
                        },
                        shadowSize: 0
                    },
                    grid: {
                        borderWidth: 1,
                        margin: 0,
                        labelMargin: 0,
                        axisMargin: 0,
                        minBorderMargin: 0,
                        markings: markings,
                    },
                    xaxis: {
                        ticks: [],
                    },
                    yaxis: {
                        ticks: [],
                        min: 0
                    },
                    legend: {
                        show: false
                    }
                };
                var plot = $.plot(plot_div, [{data: data}], options);
            }).fail(function () {
                // TODO: Handle failure
            });

            return plot_div;
        }

        element.popover({
            placement: 'left auto',
            trigger: 'hover',
            html: true,
            delay: 50,
            content: $('
').append(plot_div)
        });

        element.on('show.bs.popover', update_plot);
    }

    /*
      Set up $.asv.ui
     */

    this.network_error = network_error;
    this.make_panel = make_panel;
    this.make_value_selector_panel = make_value_selector_panel;
    this.reflow_value_selector_panels = reflow_value_selector_panels;
    this.hover_graph = hover_graph;
    this.hover_summary_graph = hover_summary_graph;

    $.asv.ui = this;
});


text:
<?php

namespace Flarum\User;

use Flarum\Http\UrlGenerator;
use Flarum\Settings\SettingsRepositoryInterface;
use Flarum\User\Event\EmailChangeRequested;
use Flarum\User\Event\Registered;
use Illuminate\Contracts\Events\Dispatcher;
use Illuminate\Contracts\Mail\Mailer;
use Illuminate\Contracts\Translation\Translator;
use Illuminate\Mail\Message;

class EmailConfirmationMailer
{
    /**
     * @var SettingsRepositoryInterface
     */
    protected $settings;

    /**
     * @var Mailer
     */
    protected $mailer;

    /**
     * @var UrlGenerator
     */
    protected $url;

    /**
     * @var Translator
     */
    protected $translator;

    /**
     * @param \Flarum\Settings\SettingsRepositoryInterface $settings
     * @param Mailer $mailer
     * @param UrlGenerator $url
     * @param Translator $translator
     */
    public function __construct(SettingsRepositoryInterface $settings, Mailer $mailer, UrlGenerator $url, Translator $translator)
    {
        $this->settings = $settings;
        $this->mailer = $mailer;
        $this->url = $url;
        $this->translator = $translator;
    }

    /**
     * @param Dispatcher $events
     */
    public function subscribe(Dispatcher $events)
    {
        $events->listen(Registered::class, [$this, 'whenUserWasRegistered']);
        $events->listen(EmailChangeRequested::class, [$this, 'whenUserEmailChangeWasRequested']);
    }

    /**
     * @param \Flarum\User\Event\Registered $event
     */
    public function whenUserWasRegistered(Registered $event)
    {
        $user = $event->user;

        if ($user->is_activated) {
            return;
        }

        $data = $this->getEmailData($user, $user->email);

        $body = $this->translator->trans('core.email.activate_account.body', $data);

        $this->mailer->raw($body, function (Message $message) use ($user, $data) {
            $message->to($user->email);
            $message->subject('['.$data['{forum}'].'] '.$this->translator->trans('core.email.activate_account.subject'));
        });
    }

    /**
     * @param \Flarum\User\Event\EmailChangeRequested $event
     */
    public function whenUserEmailChangeWasRequested(EmailChangeRequested $event)
    {
        $email = $event->email;
        $data = $this->getEmailData($event->user, $email);

        $body = $this->translator->trans('core.email.confirm_email.body', $data);

        $this->mailer->raw($body, function (Message $message) use ($email, $data) {
            $message->to($email);
            $message->subject('['.$data['{forum}'].'] '.$this->translator->trans('core.email.confirm_email.subject'));
        });
    }

    /**
     * @param User $user
     * @param string $email
     * @return EmailToken
     */
    protected function generateToken(User $user, $email)
    {
        $token = EmailToken::generate($email, $user->id);
        $token->save();

        return $token;
    }

    /**
     * Get the data that should be made available to email templates.
     *
     * @param User $user
     * @param string $email
     * @return array
     */
    protected function getEmailData(User $user, $email)
    {
        $token = $this->generateToken($user, $email);

        return [
            '{username}' => $user->display_name,
            '{url}' => $this->url->to('forum')->route('confirmEmail', ['token' => $token->id]),
            '{forum}' => $this->settings->get('forum_title')
        ];
    }
}


text:
<?php

namespace Pinq\Providers\DSL\Compilation\Processors\Visitors;

use Pinq\Providers\DSL\Compilation\Processors;
use Pinq\Queries\Operations;
use Pinq\Queries;

/**
 * Implementation of the operation query processor using the visitor pattern.
 *
 * @author Elliot Levin <elliotlevin@hotmail.com>
 */
class OperationQueryProcessor extends Processors\OperationQueryProcessor implements Operations\IOperationVisitor
{
    /**
     * @var Queries\IOperation
     */
    protected $operation;

    protected function processOperation(Queries\IScope $scope, Queries\IOperation $operation)
    {
        $this->operation = $operation->traverse($this);

        return $this->operation;
    }

    public function visitUnsetIndex(Operations\UnsetIndex $operation)
    {
        return $operation;
    }

    public function visitApply(Operations\Apply $operation)
    {
        return $operation;
    }

    public function visitClear(Operations\Clear $operation)
    {
        return $operation;
    }

    public function visitSetIndex(Operations\SetIndex $operation)
    {
        return $operation;
    }

    public function visitAddValues(Operations\AddValues $operation)
    {
        return $operation->update(
                $this->scopeProcessor->processSource($operation->getSource())
        );
    }

    public function visitRemoveWhere(Operations\RemoveWhere $operation)
    {
        return $operation;
    }

    public function visitJoinApply(Operations\JoinApply $operation)
    {
        return $operation->update(
                $operation->getOptions()->updateSource(
                        $this->scopeProcessor->processSource($operation->getOptions()->getSource())
                ),
                $operation->getMutatorFunction()
        );
    }

    public function visitRemoveValues(Operations\RemoveValues $operation)
    {
        return $operation->update(
                $this->scopeProcessor->processSource($operation->getSource())
        );
    }
}


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

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>jp.co.yahoo.dataplatform.mds</groupId>
    <artifactId>multiple-dimension-spread-base</artifactId>
    <version>0.8.11_hive-1.2.1000.2.6.4.0-91</version>
    <relativePath>../pom.xml</relativePath>
  </parent>

  <artifactId>multiple-dimension-spread-arrow</artifactId>
  <packaging>jar</packaging>
  <name>multiple dimension spread arrow</name>
  <description>Supporting Apache Arrow by Multiple-Dimension-Spread</description>

  <dependencies>
    <dependency>
      <groupId>org.apache.arrow</groupId>
      <artifactId>arrow-vector</artifactId>
      <version>0.11.0</version>
      <optional>true</optional>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.9.8</version>
      <optional>true</optional>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-annotations</artifactId>
      <version>2.9.8</version>
      <optional>true</optional>
    </dependency>
    <dependency>
      <groupId>jp.co.yahoo.dataplatform.mds</groupId>
      <artifactId>multiple-dimension-spread-common</artifactId>
      <version>${project.version}</version>
    </dependency>
    <dependency>
      <groupId>jp.co.yahoo.dataplatform.schema</groupId>
      <artifactId>schema-common</artifactId>
      <version>${schemalibVersion}</version>
    </dependency>
    <dependency>
      <groupId>jp.co.yahoo.dataplatform.config</groupId>
      <artifactId>dataplatform-common-config</artifactId>
      <version>${configlibVersion}</version>
    </dependency>
  </dependencies>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-jar-plugin</artifactId>
        <executions>
          <execution>
            <phase>package</phase>
            <goals>
              <goal>test-jar</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
      <plugin>
        <groupId>org.apache.rat</groupId>
        <artifactId>apache-rat-plugin</artifactId>
        <configuration>
          <excludes>
            <exclude>**/*.json</exclude>
          </excludes>
        </configuration>
      </plugin>
    </plugins>
  </build>

</project>


text:
--TEST--
Test xml_set_start_namespace_decl_handler() function : error conditions
--SKIPIF--
<?php
if (!extension_loaded("xml")) {
	print "skip - XML extension not loaded";
}
?>
--FILE--
<?php
/* Prototype  : proto int xml_set_start_namespace_decl_handler(resource parser, string hdl)
 * Description: Set up character data handler
 * Source code: ext/xml/xml.c
 * Alias to functions:
 */

echo "*** Testing xml_set_start_namespace_decl_handler() : error conditions ***\n";

//Test xml_set_start_namespace_decl_handler with one more than the expected number of arguments
echo "\n-- Testing xml_set_start_namespace_decl_handler() function with more than expected no. of arguments --\n";

$hdl = 'string_val';
$extra_arg = 10;
var_dump( xml_set_start_namespace_decl_handler(null, $hdl, $extra_arg) );

// Testing xml_set_start_namespace_decl_handler with one less than the expected number of arguments
echo "\n-- Testing xml_set_start_namespace_decl_handler() function with less than expected no. of arguments --\n";

var_dump( xml_set_start_namespace_decl_handler(null) );

echo "Done";
?>
--EXPECTF--
*** Testing xml_set_start_namespace_decl_handler() : error conditions ***

-- Testing xml_set_start_namespace_decl_handler() function with more than expected no. of arguments --

Warning: xml_set_start_namespace_decl_handler() expects exactly 2 parameters, 3 given in %s on line %d
NULL

-- Testing xml_set_start_namespace_decl_handler() function with less than expected no. of arguments --

Warning: xml_set_start_namespace_decl_handler() expects exactly 2 parameters, 1 given in %s on line %d
NULL
Done


text:
/*
 * iperf, Copyright (c) 2014, 2015, 2016, The Regents of the University of
 * California, through Lawrence Berkeley National Laboratory (subject
 * to receipt of any required approvals from the U.S. Dept. of
 * Energy).  All rights reserved.
 *
 * If you have questions about your rights to use or distribute this
 * software, please contact Berkeley Lab's Technology Transfer
 * Department at TTD@lbl.gov.
 *
 * NOTICE.  This software is owned by the U.S. Department of Energy.
 * As such, the U.S. Government has been granted for itself and others
 * acting on its behalf a paid-up, nonexclusive, irrevocable,
 * worldwide license in the Software to reproduce, prepare derivative
 * works, and perform publicly and display publicly.  Beginning five
 * (5) years after the date permission to assert copyright is obtained
 * from the U.S. Department of Energy, and subject to any subsequent
 * five (5) year renewals, the U.S. Government is granted for itself
 * and others acting on its behalf a paid-up, nonexclusive,
 * irrevocable, worldwide license in the Software to reproduce,
 * prepare derivative works, distribute copies to the public, perform
 * publicly and display publicly, and to permit others to do so.
 *
 * This code is distributed under a BSD style license, see the LICENSE
 * file for complete information.
 */
#include <stdio.h>
#include <errno.h>
#include <netdb.h>
#include <string.h>
#include <stdlib.h>
#include <stdarg.h>
#include "iperf.h"
#include "iperf_api.h"

/* Do a printf to stderr. */
void iperf_err(struct iperf_test *test, const char *format, ...)
{
	va_list argp;
	char str[1000];

	va_start(argp, format);
	vsnprintf(str, sizeof(str), format, argp);
	if (test != NULL && test->json_output && test->json_top != NULL) {
		cJSON_AddStringToObject(test->json_top, "error", str);
	} else if (test && test->outfile) {
		fprintf(test->outfile, "iperf3: %s\n", str);
	} else {
		fprintf(stderr, "iperf3: %s\n", str);
	}
	va_end(argp);
}

/* Do a printf to stderr or log file as appropriate, then exit. */
void iperf_errexit(struct iperf_test *test, const char *format, ...)
{
	va_list argp;
	char str[1000];

	va_start(argp, format);
	vsnprintf(str, sizeof(str), format, argp);
	if (test != NULL && test->json_output && test->json_top != NULL) {
		cJSON_AddStringToObject(test->json_top, "error", str);
		iperf_json_finish(test);
	} else if (test && test->outfile) {
		fprintf(test->outfile, "iperf3: %s\n", str);
	} else {
		fprintf(stderr, "iperf3: %s\n", str);
	}
	va_end(argp);
	if (test) {
		iperf_delete_pidfile(test);
	}
	exit(1);
}

int i_errno;

char *iperf_strerror(int err)
{
	static char errstr[256];
	int len;
	int perr;
	int herr;
	perr = herr = 0;

	len = sizeof(errstr);
	memset(errstr, 0, len);

	switch (err) {
	case IENONE:
		snprintf(errstr, len, "no error");
		break;
	case IESERVCLIENT:
		snprintf(errstr, len, "cannot be both server and client");
		break;
	case IENOROLE:
		snprintf(errstr, len, "must either be a client (-c) or server (-s)");
		break;
	case IESERVERONLY:
		snprintf(errstr, len, "some option you are trying to set is server only");
		break;
	case IECLIENTONLY:
		snprintf(errstr, len, "some option you are trying to set is client only");
		break;
	case IEDURATION:
		snprintf(errstr, len, "test duration too long (maximum = %d seconds)", MAX_TIME);
		break;
	case IENUMSTREAMS:
		snprintf(errstr, len, "number of parallel streams too large (maximum = %d)", MAX_STREAMS);
		break;
	case IEBLOCKSIZE:
		snprintf(errstr, len, "block size too large (maximum = %d bytes)", MAX_BLOCKSIZE);
		break;
	case IEBUFSIZE:
		snprintf(errstr, len, "socket buffer size too large (maximum = %d bytes)", MAX_TCP_BUFFER);
		break;
	case IEINTERVAL:
		snprintf(errstr, len, "invalid report interval (min = %g, max = %g seconds)", MIN_INTERVAL, MAX_INTERVAL);
		break;
	case IEBIND:
		snprintf(errstr, len, "--bind must be specified to use --cport");
		break;
	case IEUDPBLOCKSIZE:
		snprintf(errstr, len, "block size too large (maximum = %d bytes)", MAX_UDP_BLOCKSIZE);
		break;
	case IEBADTOS:
		snprintf(errstr, len, "bad TOS value (must be between 0 and 255 inclusive)");
		break;
	case IEMSS:
		snprintf(errstr, len, "TCP MSS too large (maximum = %d bytes)", MAX_MSS);
		break;
	case IENOSENDFILE:
		snprintf(errstr, len, "this OS does not support sendfile");
		break;
	case IEOMIT:
		snprintf(errstr, len, "bogus value for --omit");
		break;
	case IEUNIMP:
		snprintf(errstr, len, "an option you are trying to set is not implemented yet");
		break;
	case IEFILE:
		snprintf(errstr, len, "unable to open -F file");
		perr = 1;
		break;
	case IEBURST:
		snprintf(errstr, len, "invalid burst count (maximum = %d)", MAX_BURST);
		break;
	case IEENDCONDITIONS:
		snprintf(errstr, len, "only one test end condition (-t, -n, -k) may be specified");
		break;
	case IELOGFILE:
		snprintf(errstr, len, "unable to open log file");
		perr = 1;
		break;
	case IENOSCTP:
		snprintf(errstr, len, "no SCTP support available");
		break;
	case IENEWTEST:
		snprintf(errstr, len, "unable to create a new test");
		perr = 1;
		break;
	case IEINITTEST:
		snprintf(errstr, len, "test initialization failed");
		perr = 1;
		break;
	case IELISTEN:
		snprintf(errstr, len, "unable to start listener for connections");
		perr = 1;
		break;
	case IECONNECT:
		snprintf(errstr, len, "unable to connect to server");
		perr = 1;
		break;
	case IEACCEPT:
		snprintf(errstr, len, "unable to accept connection from client");
		herr = 1;
		perr = 1;
		break;
	case IESENDCOOKIE:
		snprintf(errstr, len, "unable to send cookie to server");
		perr = 1;
		break;
	case IERECVCOOKIE:
		snprintf(errstr, len, "unable to receive cookie at server");
		perr = 1;
		break;
	case IECTRLWRITE:
		snprintf(errstr, len, "unable to write to the control socket");
		perr = 1;
		break;
	case IECTRLREAD:
		snprintf(errstr, len, "unable to read from the control socket");
		perr = 1;
		break;
	case IECTRLCLOSE:
		snprintf(errstr, len, "control socket has closed unexpectedly");
		break;
	case IEMESSAGE:
		snprintf(errstr, len, "received an unknown control message");
		break;
	case IESENDMESSAGE:
		snprintf(errstr, len, "unable to send control message");
		perr = 1;
		break;
	case IERECVMESSAGE:
		snprintf(errstr, len, "unable to receive control message");
		perr = 1;
		break;
	case IESENDPARAMS:
		snprintf(errstr, len, "unable to send parameters to server");
		perr = 1;
		break;
	case IERECVPARAMS:
		snprintf(errstr, len, "unable to receive parameters from client");
		perr = 1;
		break;
	case IEPACKAGERESULTS:
		snprintf(errstr, len, "unable to package results");
		perr = 1;
		break;
	case IESENDRESULTS:
		snprintf(errstr, len, "unable to send results");
		perr = 1;
		break;
	case IERECVRESULTS:
		snprintf(errstr, len, "unable to receive results");
		perr = 1;
		break;
	case IESELECT:
		snprintf(errstr, len, "select failed");
		perr = 1;
		break;
	case IECLIENTTERM:
		snprintf(errstr, len, "the client has terminated");
		break;
	case IESERVERTERM:
		snprintf(errstr, len, "the server has terminated");
		break;
	case IEACCESSDENIED:
		snprintf(errstr, len, "the server is busy running a test. try again later");
		break;
	case IESETNODELAY:
		snprintf(errstr, len, "unable to set TCP/SCTP NODELAY");
		perr = 1;
		break;
	case IESETMSS:
		snprintf(errstr, len, "unable to set TCP/SCTP MSS");
		perr = 1;
		break;
	case IESETBUF:
		snprintf(errstr, len, "unable to set socket buffer size");
		perr = 1;
		break;
	case IESETTOS:
		snprintf(errstr, len, "unable to set IP TOS");
		perr = 1;
		break;
	case IESETCOS:
		snprintf(errstr, len, "unable to set IPv6 traffic class");
		perr = 1;
		break;
	case IESETFLOW:
		snprintf(errstr, len, "unable to set IPv6 flow label");
		break;
	case IEREUSEADDR:
		snprintf(errstr, len, "unable to reuse address on socket");
		perr = 1;
		break;
	case IENONBLOCKING:
		snprintf(errstr, len, "unable to set socket to non-blocking");
		perr = 1;
		break;
	case IESETWINDOWSIZE:
		snprintf(errstr, len, "unable to set socket window size");
		perr = 1;
		break;
	case IEPROTOCOL:
		snprintf(errstr, len, "protocol does not exist");
		break;
	case IEAFFINITY:
		snprintf(errstr, len, "unable to set CPU affinity");
		perr = 1;
		break;
	case IEDAEMON:
		snprintf(errstr, len, "unable to become a daemon");
		perr = 1;
		break;
	case IECREATESTREAM:
		snprintf(errstr, len, "unable to create a new stream");
		herr = 1;
		perr = 1;
		break;
	case IEINITSTREAM:
		snprintf(errstr, len, "unable to initialize stream");
		herr = 1;
		perr = 1;
		break;
	case IESTREAMLISTEN:
		snprintf(errstr, len, "unable to start stream listener");
		perr = 1;
		break;
	case IESTREAMCONNECT:
		snprintf(errstr, len, "unable to connect stream");
		herr = 1;
		perr = 1;
		break;
	case IESTREAMACCEPT:
		snprintf(errstr, len, "unable to accept stream connection");
		perr = 1;
		break;
	case IESTREAMWRITE:
		snprintf(errstr, len, "unable to write to stream socket");
		perr = 1;
		break;
	case IESTREAMREAD:
		snprintf(errstr, len, "unable to read from stream socket");
		perr = 1;
		break;
	case IESTREAMCLOSE:
		snprintf(errstr, len, "stream socket has closed unexpectedly");
		break;
	case IESTREAMID:
		snprintf(errstr, len, "stream has an invalid id");
		break;
	case IENEWTIMER:
		snprintf(errstr, len, "unable to create new timer");
		perr = 1;
		break;
	case IEUPDATETIMER:
		snprintf(errstr, len, "unable to update timer");
		perr = 1;
		break;
	case IESETCONGESTION:
		snprintf(errstr, len, "unable to set TCP_CONGESTION: " "Supplied congestion control algorithm not supported on this host");
		break;
	case IEPIDFILE:
		snprintf(errstr, len, "unable to write PID file");
		perr = 1;
		break;
	case IEV6ONLY:
		snprintf(errstr, len, "Unable to set/reset IPV6_V6ONLY");
		perr = 1;
		break;
	case IESETSCTPDISABLEFRAG:
		snprintf(errstr, len, "unable to set SCTP_DISABLE_FRAGMENTS");
		perr = 1;
		break;
	case IESETSCTPNSTREAM:
		snprintf(errstr, len, "unable to set SCTP_INIT num of SCTP streams\n");
		perr = 1;
		break;
	case IESETPACING:
		snprintf(errstr, len, "unable to set socket pacing");
		perr = 1;
		break;
	}

	if (herr || perr) {
		strncat(errstr, ": ", len - strlen(errstr) - 1);
	}
	if (errno && perr) {
		strncat(errstr, strerror(errno), len - strlen(errstr) - 1);
	}

	return errstr;
}


text:
class ParticipantMergeView

  attr_reader :participant, :proposed_match, :possible_matches
  attr_accessor :effort_counts
  delegate :full_name, :first_name, :last_name, :id, to: :participant

  def initialize(participant, proposed_match_id)
    @participant = participant
    @proposed_match = proposed_match_id.present? ?
        Participant.find(proposed_match_id) :
        @participant.most_likely_duplicate
    @possible_matches = @participant.possible_matching_participants - [@proposed_match]
    set_effort_counts
  end

  def proposed_match_name
    "#{proposed_match.last_name}, #{proposed_match.first_name}"
  end

  private

  def set_effort_counts
    participants = possible_matches + [proposed_match] + [participant]
    @effort_counts = Effort.group(:participant_id).where(participant: participants).size
  end
end


text:
package com.aspectran.web.activity.request;

import com.aspectran.core.lang.NonNull;
import com.aspectran.core.lang.Nullable;
import jakarta.servlet.http.HttpServletRequest;

import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

/**
 * Wrapper class for getting attributes from HttpServletRequest.
 *
 *
Created: 2018. 9. 15.

 *
 * @since 5.2.0
 */
public class RequestAttributeMap implements Map<String, Object> {

    private final HttpServletRequest request;

    public RequestAttributeMap(HttpServletRequest request) {
        this.request = request;
    }

    @Override
    public int size() {
        return Collections.list(request.getAttributeNames()).size();
    }

    @Override
    public boolean isEmpty() {
        return !request.getAttributeNames().hasMoreElements();
    }

    @Override
    public boolean containsKey(Object key) {
        return (request.getAttribute((String)key) != null);
    }

    @Override
    public boolean containsValue(Object value) {
        Enumeration<String> names = request.getAttributeNames();
        while (names.hasMoreElements()) {
            String name = names.nextElement();
            Object object = request.getAttribute(name);
            if (Objects.equals(value, object)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public Object get(Object key) {
        return request.getAttribute((String)key);
    }

    @Override
    public Object put(String name, Object value) {
        Object old = request.getAttribute(name);
        request.setAttribute(name, value);
        return old;
    }

    @Override
    public Object remove(Object key) {
        Object old = request.getAttribute((String)key);
        request.removeAttribute((String)key);
        return old;
    }

    @Override
    public void putAll(@Nullable Map<? extends String, ?> map) {
        if (map != null) {
            for (Entry<? extends String, ?> entry : map.entrySet()) {
                request.setAttribute(entry.getKey(), entry.getValue());
            }
        }
    }

    @Override
    public void clear() {
        for (String name : Collections.list(request.getAttributeNames())) {
            request.removeAttribute(name);
        }
    }

    @Override
    @NonNull
    public Set<String> keySet() {
        return new HashSet<>(Collections.list(request.getAttributeNames()));
    }

    @Override
    @NonNull
    public Collection<Object> values() {
        List<Object> list = new ArrayList<>();
        Enumeration<String> names = request.getAttributeNames();
        while (names.hasMoreElements()) {
            String name = names.nextElement();
            Object value = request.getAttribute(name);
            list.add(value);
        }
        return list;
    }

    @Override
    @NonNull
    public Set<Entry<String, Object>> entrySet() {
        Set<Entry<String, Object>> set = new HashSet<>();
        Enumeration<String> names = request.getAttributeNames();
        while (names.hasMoreElements()) {
            String name = names.nextElement();
            Object value = request.getAttribute(name);
            set.add(new AbstractMap.SimpleImmutableEntry<>(name, value));
        }
        return set;
    }

}


text:
using System.Data;
using Moq;
using NUnit.Framework;

namespace SJP.Schematic.MySql.Tests
{
    [TestFixture]
    internal static class MySqlDialectTests
    {
        [Test]
        public static void CreateConnectionAsync_GivenNull_ThrowsArgumentNullException()
        {
            Assert.That(() => MySqlDialect.CreateConnectionAsync(null), Throws.ArgumentNullException);
        }

        [Test]
        public static void CreateConnectionAsync_GivenEmptyString_ThrowsArgumentNullException()
        {
            Assert.That(() => MySqlDialect.CreateConnectionAsync(string.Empty), Throws.ArgumentNullException);
        }

        [Test]
        public static void CreateConnectionAsync_GivenWhiteSpaceString_ThrowsArgumentNullException()
        {
            Assert.That(() => MySqlDialect.CreateConnectionAsync("   "), Throws.ArgumentNullException);
        }

        [Test]
        public static void QuoteIdentifier_GivenNull_ThrowsArgumentNullException()
        {
            var connection = Mock.Of<IDbConnection>();
            var dialect = new MySqlDialect(connection);

            Assert.That(() => dialect.QuoteIdentifier(null), Throws.ArgumentNullException);
        }

        [Test]
        public static void QuoteIdentifier_GivenEmptyString_ThrowsArgumentNullException()
        {
            var connection = Mock.Of<IDbConnection>();
            var dialect = new MySqlDialect(connection);

            Assert.That(() => dialect.QuoteIdentifier(string.Empty), Throws.ArgumentNullException);
        }

        [Test]
        public static void QuoteIdentifier_GivenWhiteSpace_ThrowsArgumentNullException()
        {
            var connection = Mock.Of<IDbConnection>();
            var dialect = new MySqlDialect(connection);

            Assert.That(() => dialect.QuoteIdentifier("    "), Throws.ArgumentNullException);
        }

        [Test]
        public static void QuoteName_GivenNull_ThrowsArgumentNullException()
        {
            var connection = Mock.Of<IDbConnection>();
            var dialect = new MySqlDialect(connection);

            Assert.That(() => dialect.QuoteName(null), Throws.ArgumentNullException);
        }

        [Test]
        public static void QuoteName_GivenEmptyString_ThrowsArgumentNullException()
        {
            var connection = Mock.Of<IDbConnection>();
            var dialect = new MySqlDialect(connection);

            Assert.That(() => dialect.QuoteName(string.Empty), Throws.ArgumentNullException);
        }

        [Test]
        public static void QuoteName_GivenWhiteSpace_ThrowsArgumentNullException()
        {
            var connection = Mock.Of<IDbConnection>();
            var dialect = new MySqlDialect(connection);

            Assert.That(() => dialect.QuoteName("    "), Throws.ArgumentNullException);
        }

        [Test]
        public static void QuoteIdentifier_GivenRegularLocalName_ReturnsQuotedIdentifier()
        {
            const string input = "test_table";
            const string expected = "`test_table`";

            var connection = Mock.Of<IDbConnection>();
            var dialect = new MySqlDialect(connection);

            var result = dialect.QuoteIdentifier(input);

            Assert.That(result, Is.EqualTo(expected));
        }

        [Test]
        public static void QuoteIdentifier_GivenNameWithWhitespace_ReturnsQuotedIdentifier()
        {
            const string input = "test table name";
            const string expected = "`test table name`";

            var connection = Mock.Of<IDbConnection>();
            var dialect = new MySqlDialect(connection);

            var result = dialect.QuoteIdentifier(input);

            Assert.That(result, Is.EqualTo(expected));
        }

        [Test]
        public static void QuoteIdentifier_GivenNameWithDotSeparators_ReturnsQuotedIdentifier()
        {
            const string input = "test.table.name";
            const string expected = "`test.table.name`";

            var connection = Mock.Of<IDbConnection>();
            var dialect = new MySqlDialect(connection);

            var result = dialect.QuoteIdentifier(input);

            Assert.That(result, Is.EqualTo(expected));
        }

        [Test]
        public static void QuoteIdentifier_GivenNameWithBacktick_ReturnsQuotedIdentifier()
        {
            const string input = "test`table";
            const string expected = "`test``table`";

            var connection = Mock.Of<IDbConnection>();
            var dialect = new MySqlDialect(connection);

            var result = dialect.QuoteIdentifier(input);

            Assert.That(result, Is.EqualTo(expected));
        }
    }
}


text:
// @formatter:off

package com.microsoft.alm.visualstudio.services.security;

import java.util.HashMap;
import com.microsoft.alm.visualstudio.services.identity.IdentityDescriptor;

/**
 * The AccessControlList class is meant to associate a set of AccessControlEntries with a security token and its inheritance settings.
 *
 */
public class AccessControlList {

    /**
    * Storage of permissions keyed on the identity the permission is for.
    */
    private HashMap<IdentityDescriptor, AccessControlEntry> acesDictionary;
    /**
    * True if this ACL holds ACEs that have extended information.
    */
    private boolean includeExtendedInfo;
    /**
    * True if the given token inherits permissions from parents.
    */
    private boolean inheritPermissions;
    /**
    * The token that this AccessControlList is for.
    */
    private String token;

    /**
    * Storage of permissions keyed on the identity the permission is for.
    */
    public HashMap<IdentityDescriptor, AccessControlEntry> getAcesDictionary() {
        return acesDictionary;
    }

    /**
    * Storage of permissions keyed on the identity the permission is for.
    */
    public void setAcesDictionary(final HashMap<IdentityDescriptor, AccessControlEntry> acesDictionary) {
        this.acesDictionary = acesDictionary;
    }

    /**
    * True if this ACL holds ACEs that have extended information.
    */
    public boolean getIncludeExtendedInfo() {
        return includeExtendedInfo;
    }

    /**
    * True if this ACL holds ACEs that have extended information.
    */
    public void setIncludeExtendedInfo(final boolean includeExtendedInfo) {
        this.includeExtendedInfo = includeExtendedInfo;
    }

    /**
    * True if the given token inherits permissions from parents.
    */
    public boolean getInheritPermissions() {
        return inheritPermissions;
    }

    /**
    * True if the given token inherits permissions from parents.
    */
    public void setInheritPermissions(final boolean inheritPermissions) {
        this.inheritPermissions = inheritPermissions;
    }

    /**
    * The token that this AccessControlList is for.
    */
    public String getToken() {
        return token;
    }

    /**
    * The token that this AccessControlList is for.
    */
    public void setToken(final String token) {
        this.token = token;
    }
}


text:
package com.azure.spring.cloud.core.util;

import com.azure.core.amqp.AmqpTransportType;
import com.azure.core.http.policy.HttpLogDetailLevel;
import com.azure.core.management.AzureEnvironment;
import com.azure.spring.cloud.core.implementation.properties.AzureAmqpSdkProperties;
import com.azure.spring.cloud.core.implementation.properties.AzureHttpSdkProperties;
import com.azure.spring.cloud.core.implementation.util.AzurePropertiesUtils;
import com.azure.spring.cloud.core.properties.AzureProperties;
import com.azure.spring.cloud.core.properties.authentication.TokenCredentialProperties;
import com.azure.spring.cloud.core.properties.client.ClientProperties;
import com.azure.spring.cloud.core.properties.client.HeaderProperties;
import com.azure.spring.cloud.core.properties.profile.AzureProfileProperties;
import com.azure.spring.cloud.core.properties.proxy.ProxyProperties;
import com.azure.spring.cloud.core.properties.retry.RetryProperties;
import com.azure.spring.cloud.core.provider.RetryOptionsProvider;
import org.junit.jupiter.api.Test;

import java.time.Duration;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

import static com.azure.spring.cloud.core.provider.AzureProfileOptionsProvider.CloudType.AZURE;
import static com.azure.spring.cloud.core.provider.AzureProfileOptionsProvider.CloudType.AZURE_CHINA;
import static com.azure.spring.cloud.core.provider.AzureProfileOptionsProvider.CloudType.OTHER;
import static com.azure.spring.cloud.core.provider.RetryOptionsProvider.RetryMode.EXPONENTIAL;
import static com.azure.spring.cloud.core.provider.RetryOptionsProvider.RetryMode.FIXED;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;

class AzurePropertiesUtilsTests {

    @Test
    void testCopyPropertiesToNewObjectShouldEqual() {
        AzurePropertiesA source = new AzurePropertiesA();
        source.client.setApplicationId("client-application-id-A");
        source.profile.setCloudType(AZURE_CHINA);
        source.profile.setTenantId("profile-tenant-id-A");
        source.profile.setSubscriptionId("profile-sub-id-A");
        source.profile.getEnvironment().setActiveDirectoryEndpoint("aad-endpoint-A");
        source.proxy.setType("proxy-type-A");
        source.proxy.setHostname("proxy-hostname-A");
        source.proxy.setPort(1234);
        source.proxy.setUsername("proxy-username-A");
        source.proxy.setPassword("proxy-password-A");
        source.retry.setMode(FIXED);
        source.retry.getExponential().setMaxRetries(3);
        source.retry.getExponential().setBaseDelay(Duration.ofSeconds(4));
        source.retry.getExponential().setMaxDelay(Duration.ofSeconds(5));
        source.retry.getFixed().setDelay(Duration.ofSeconds(6));
        source.retry.getFixed().setMaxRetries(7);
        source.credential.setClientId("credential-client-id-A");
        source.credential.setClientSecret("credential-client-secret-A");
        source.credential.setClientCertificatePath("credential-client-cert-path-A");
        source.credential.setClientCertificatePassword("credential-client-cert-password-A");
        source.credential.setUsername("credential-username-A");
        source.credential.setPassword("credential-password-A");
        source.credential.setManagedIdentityEnabled(true);

        final AzurePropertiesB target = new AzurePropertiesB();
        AzurePropertiesUtils.copyAzureCommonProperties(source, target);

        assertEquals("client-application-id-A", target.client.getApplicationId());
        assertEquals(AZURE_CHINA, target.profile.getCloudType());
        assertEquals("profile-tenant-id-A", target.profile.getTenantId());
        assertEquals("profile-sub-id-A", target.profile.getSubscriptionId());
        assertEquals("aad-endpoint-A", target.profile.getEnvironment().getActiveDirectoryEndpoint());
        assertEquals(AzureEnvironment.AZURE_CHINA.getActiveDirectoryGraphApiVersion(), target.profile.getEnvironment().getActiveDirectoryGraphApiVersion());
        assertEquals("proxy-type-A", target.proxy.getType());
        assertEquals("proxy-hostname-A", target.proxy.getHostname());
        assertEquals(1234, target.proxy.getPort());
        assertEquals("proxy-username-A", target.proxy.getUsername());
        assertEquals("proxy-password-A", target.proxy.getPassword());
        assertEquals(FIXED, target.retry.getMode());
        assertEquals(3, target.retry.getExponential().getMaxRetries());
        assertEquals(Duration.ofSeconds(4), target.retry.getExponential().getBaseDelay());
        assertEquals(Duration.ofSeconds(5), target.retry.getExponential().getMaxDelay());
        assertEquals(Duration.ofSeconds(6), target.retry.getFixed().getDelay());
        assertEquals(7, target.retry.getFixed().getMaxRetries());
        assertEquals("credential-client-id-A", target.credential.getClientId());
        assertEquals("credential-client-secret-A", target.credential.getClientSecret());
        assertEquals("credential-client-cert-path-A", target.credential.getClientCertificatePath());
        assertEquals("credential-client-cert-password-A", target.credential.getClientCertificatePassword());
        assertEquals("credential-username-A", target.credential.getUsername());
        assertEquals("credential-password-A", target.credential.getPassword());

    }

    @Test
    void testCopyPropertiesToObjectWithSameFieldsSetShouldOverrideWithNull() {
        AzurePropertiesB target = new AzurePropertiesB();
        target.client.setApplicationId("client-application-id-B");
        target.profile.setCloudType(AZURE);
        target.profile.setTenantId("profile-tenant-id-B");
        target.profile.setSubscriptionId("profile-sub-id-B");
        target.profile.getEnvironment().setActiveDirectoryEndpoint("aad-endpoint-B");
        target.proxy.setType("proxy-type-B");
        target.proxy.setHostname("proxy-hostname-B");
        target.proxy.setPort(1234);
        target.proxy.setUsername("proxy-username-B");
        target.proxy.setPassword("proxy-password-B");
        target.retry.setMode(FIXED);
        target.retry.getExponential().setMaxRetries(3);
        target.retry.getExponential().setBaseDelay(Duration.ofSeconds(4));
        target.retry.getExponential().setMaxDelay(Duration.ofSeconds(5));
        target.retry.getFixed().setDelay(Duration.ofSeconds(6));
        target.retry.getFixed().setMaxRetries(7);
        target.credential.setClientId("credential-client-id-B");
        target.credential.setClientSecret("credential-client-secret-B");
        target.credential.setClientCertificatePath("credential-client-cert-path-B");
        target.credential.setClientCertificatePassword("credential-client-cert-password-B");
        target.credential.setUsername("credential-username-B");
        target.credential.setPassword("credential-password-B");
        target.credential.setManagedIdentityEnabled(true);

        // assert properties have been set correctly to target
        assertEquals("client-application-id-B", target.client.getApplicationId());
        assertEquals(AZURE, target.profile.getCloudType());
        assertEquals("profile-tenant-id-B", target.profile.getTenantId());
        assertEquals("profile-sub-id-B", target.profile.getSubscriptionId());
        assertEquals("aad-endpoint-B", target.profile.getEnvironment().getActiveDirectoryEndpoint());
        assertEquals(AzureEnvironment.AZURE.getActiveDirectoryGraphApiVersion(), target.profile.getEnvironment().getActiveDirectoryGraphApiVersion());
        assertEquals("proxy-type-B", target.proxy.getType());
        assertEquals("proxy-hostname-B", target.proxy.getHostname());
        assertEquals(1234, target.proxy.getPort());
        assertEquals("proxy-username-B", target.proxy.getUsername());
        assertEquals("proxy-password-B", target.proxy.getPassword());
        assertEquals(FIXED, target.retry.getMode());
        assertEquals(3, target.retry.getExponential().getMaxRetries());
        assertEquals(Duration.ofSeconds(4), target.retry.getExponential().getBaseDelay());
        assertEquals(Duration.ofSeconds(5), target.retry.getExponential().getMaxDelay());
        assertEquals(Duration.ofSeconds(6), target.retry.getFixed().getDelay());
        assertEquals(7, target.retry.getFixed().getMaxRetries());
        assertEquals("credential-client-id-B", target.credential.getClientId());
        assertEquals("credential-client-secret-B", target.credential.getClientSecret());
        assertEquals("credential-client-cert-path-B", target.credential.getClientCertificatePath());
        assertEquals("credential-client-cert-password-B", target.credential.getClientCertificatePassword());
        assertEquals("credential-username-B", target.credential.getUsername());
        assertEquals("credential-password-B", target.credential.getPassword());

        AzurePropertiesA source = new AzurePropertiesA();
        source.client.setApplicationId("client-application-id-A");
        source.profile.setCloudType(AZURE_CHINA);
        source.profile.setTenantId("profile-tenant-id-A");
        source.proxy.setHostname("proxy-hostname-A");
        source.retry.getExponential().setMaxRetries(13);
        source.retry.getExponential().setMaxDelay(Duration.ofSeconds(14));
        source.credential.setClientId("credential-client-id-A");

        AzurePropertiesUtils.copyAzureCommonProperties(source, target);

        // assert properties have been set correctly to target after copy
        assertEquals("client-application-id-A", target.client.getApplicationId());
        assertEquals(AZURE_CHINA, target.profile.getCloudType());
        assertEquals("profile-tenant-id-A", target.profile.getTenantId());
        assertNull(target.profile.getSubscriptionId());
        assertEquals(AzureEnvironment.AZURE_CHINA.getActiveDirectoryEndpoint(), target.profile.getEnvironment().getActiveDirectoryEndpoint());
        assertEquals(AzureEnvironment.AZURE_CHINA.getActiveDirectoryGraphApiVersion(), target.profile.getEnvironment().getActiveDirectoryGraphApiVersion());
        assertNull(target.proxy.getType());
        assertEquals("proxy-hostname-A", target.proxy.getHostname());
        assertNull(target.proxy.getPort());
        assertNull(target.proxy.getUsername());
        assertNull(target.proxy.getPassword());
        assertEquals(EXPONENTIAL, target.retry.getMode());
        assertEquals(13, target.retry.getExponential().getMaxRetries());
        assertNull(target.retry.getExponential().getBaseDelay());
        assertEquals(Duration.ofSeconds(14), target.retry.getExponential().getMaxDelay());
        assertNull(target.retry.getFixed().getDelay());
        assertNull(target.retry.getFixed().getMaxRetries());
        assertEquals("credential-client-id-A", target.credential.getClientId());
        assertNull(target.credential.getClientSecret());
        assertNull(target.credential.getClientCertificatePath());
        assertNull(target.credential.getClientCertificatePassword());
        assertNull(target.credential.getUsername());
        assertNull(target.credential.getPassword());
    }

    @Test
    void testCopyPropertiesIgnoresNullToObjectWithSameFieldsSetShouldOverrideWithoutNull() {
        AzurePropertiesB target = new AzurePropertiesB();
        target.client.setApplicationId("client-application-id-B");
        target.profile.setCloudType(AZURE);
        target.profile.setTenantId("profile-tenant-id-B");
        target.profile.setSubscriptionId("profile-sub-id-B");
        target.profile.getEnvironment().setActiveDirectoryEndpoint("aad-endpoint-B");
        target.proxy.setType("proxy-type-B");
        target.proxy.setHostname("proxy-hostname-B");
        target.proxy.setPort(1234);
        target.proxy.setUsername("proxy-username-B");
        target.proxy.setPassword("proxy-password-B");
        target.retry.setMode(FIXED);
        target.retry.getExponential().setMaxRetries(3);
        target.retry.getExponential().setBaseDelay(Duration.ofSeconds(4));
        target.retry.getExponential().setMaxDelay(Duration.ofSeconds(5));
        target.retry.getFixed().setDelay(Duration.ofSeconds(6));
        target.retry.getFixed().setMaxRetries(7);
        target.credential.setClientId("credential-client-id-B");
        target.credential.setClientSecret("credential-client-secret-B");
        target.credential.setClientCertificatePath("credential-client-cert-path-B");
        target.credential.setClientCertificatePassword("credential-client-cert-password-B");
        target.credential.setUsername("credential-username-B");
        target.credential.setPassword("credential-password-B");
        target.credential.setManagedIdentityEnabled(true);

        // assert properties have been set correctly to target
        assertEquals("client-application-id-B", target.client.getApplicationId());
        assertEquals(AZURE, target.profile.getCloudType());
        assertEquals("profile-tenant-id-B", target.profile.getTenantId());
        assertEquals("profile-sub-id-B", target.profile.getSubscriptionId());
        assertEquals("aad-endpoint-B", target.profile.getEnvironment().getActiveDirectoryEndpoint());
        assertEquals(AzureEnvironment.AZURE.getActiveDirectoryGraphApiVersion(), target.profile.getEnvironment().getActiveDirectoryGraphApiVersion());
        assertEquals("proxy-type-B", target.proxy.getType());
        assertEquals("proxy-hostname-B", target.proxy.getHostname());
        assertEquals(1234, target.proxy.getPort());
        assertEquals("proxy-username-B", target.proxy.getUsername());
        assertEquals("proxy-password-B", target.proxy.getPassword());
        assertEquals(FIXED, target.retry.getMode());
        assertEquals(3, target.retry.getExponential().getMaxRetries());
        assertEquals(Duration.ofSeconds(4), target.retry.getExponential().getBaseDelay());
        assertEquals(Duration.ofSeconds(5), target.retry.getExponential().getMaxDelay());
        assertEquals(Duration.ofSeconds(6), target.retry.getFixed().getDelay());
        assertEquals(7, target.retry.getFixed().getMaxRetries());
        assertEquals("credential-client-id-B", target.credential.getClientId());
        assertEquals("credential-client-secret-B", target.credential.getClientSecret());
        assertEquals("credential-client-cert-path-B", target.credential.getClientCertificatePath());
        assertEquals("credential-client-cert-password-B", target.credential.getClientCertificatePassword());
        assertEquals("credential-username-B", target.credential.getUsername());
        assertEquals("credential-password-B", target.credential.getPassword());

        AzurePropertiesA source = new AzurePropertiesA();
        source.client.setApplicationId("client-application-id-A");
        source.profile.setCloudType(AZURE_CHINA);
        source.profile.setTenantId("profile-tenant-id-A");
        source.profile.getEnvironment().setActiveDirectoryEndpoint("aad-endpoint-A");
        source.proxy.setHostname("proxy-hostname-A");
        source.retry.getExponential().setMaxRetries(13);
        source.retry.getFixed().setMaxRetries(17);
        source.credential.setClientId("credential-client-id-A");

        AzurePropertiesUtils.copyAzureCommonPropertiesIgnoreNull(source, target);

        // assert properties have been set correctly to target after copy
        assertEquals("client-application-id-A", target.client.getApplicationId());
        assertEquals(AZURE_CHINA, target.profile.getCloudType());
        assertEquals("profile-tenant-id-A", target.profile.getTenantId());
        assertEquals("profile-sub-id-B", target.profile.getSubscriptionId());
        assertEquals("aad-endpoint-A", target.profile.getEnvironment().getActiveDirectoryEndpoint());
        assertEquals(AzureEnvironment.AZURE_CHINA.getActiveDirectoryGraphApiVersion(), target.profile.getEnvironment().getActiveDirectoryGraphApiVersion());
        assertEquals("proxy-type-B", target.proxy.getType());
        assertEquals("proxy-hostname-A", target.proxy.getHostname());
        assertEquals(1234, target.proxy.getPort());
        assertEquals("proxy-username-B", target.proxy.getUsername());
        assertEquals("proxy-password-B", target.proxy.getPassword());
        assertEquals(EXPONENTIAL, target.retry.getMode());
        assertEquals(13, target.retry.getExponential().getMaxRetries());
        assertEquals(Duration.ofSeconds(4), target.retry.getExponential().getBaseDelay());
        assertEquals(Duration.ofSeconds(5), target.retry.getExponential().getMaxDelay());
        assertEquals(Duration.ofSeconds(6), target.retry.getFixed().getDelay());
        assertEquals(17, target.retry.getFixed().getMaxRetries());
        assertEquals("credential-client-id-A", target.credential.getClientId());
        assertEquals("credential-client-secret-B", target.credential.getClientSecret());
        assertEquals("credential-client-cert-path-B", target.credential.getClientCertificatePath());
        assertEquals("credential-client-cert-password-B", target.credential.getClientCertificatePassword());
        assertEquals("credential-username-B", target.credential.getUsername());
        assertEquals("credential-password-B", target.credential.getPassword());
    }

    @Test
    void testMergePropertiesObjectWithSameFieldsSetShouldTakeLater() {
        AzurePropertiesB defaultProperties = new AzurePropertiesB();
        defaultProperties.client.setApplicationId("client-application-id-B");
        defaultProperties.profile.setCloudType(AZURE);
        defaultProperties.profile.setTenantId("profile-tenant-id-B");
        defaultProperties.profile.setSubscriptionId("profile-sub-id-B");
        defaultProperties.profile.getEnvironment().setActiveDirectoryEndpoint("aad-endpoint-B");
        defaultProperties.proxy.setType("proxy-type-B");
        defaultProperties.proxy.setHostname("proxy-hostname-B");
        defaultProperties.proxy.setPort(1234);
        defaultProperties.proxy.setUsername("proxy-username-B");
        defaultProperties.proxy.setPassword("proxy-password-B");
        defaultProperties.retry.setMode(FIXED);
        defaultProperties.retry.getExponential().setMaxRetries(3);
        defaultProperties.retry.getExponential().setBaseDelay(Duration.ofSeconds(4));
        defaultProperties.retry.getExponential().setMaxDelay(Duration.ofSeconds(5));
        defaultProperties.retry.getFixed().setDelay(Duration.ofSeconds(6));
        defaultProperties.retry.getFixed().setMaxRetries(7);
        defaultProperties.credential.setClientId("credential-client-id-B");
        defaultProperties.credential.setClientSecret("credential-client-secret-B");
        defaultProperties.credential.setClientCertificatePath("credential-client-cert-path-B");
        defaultProperties.credential.setClientCertificatePassword("credential-client-cert-password-B");
        defaultProperties.credential.setUsername("credential-username-B");
        defaultProperties.credential.setPassword("credential-password-B");
        defaultProperties.credential.setManagedIdentityEnabled(true);

        // assert properties have been set correctly to defaultProperties
        assertEquals("client-application-id-B", defaultProperties.client.getApplicationId());
        assertEquals(AZURE, defaultProperties.profile.getCloudType());
        assertEquals("profile-tenant-id-B", defaultProperties.profile.getTenantId());
        assertEquals("profile-sub-id-B", defaultProperties.profile.getSubscriptionId());
        assertEquals("aad-endpoint-B", defaultProperties.profile.getEnvironment().getActiveDirectoryEndpoint());
        assertEquals(AzureEnvironment.AZURE.getActiveDirectoryGraphApiVersion(), defaultProperties.profile.getEnvironment().getActiveDirectoryGraphApiVersion());
        assertEquals("proxy-type-B", defaultProperties.proxy.getType());
        assertEquals("proxy-hostname-B", defaultProperties.proxy.getHostname());
        assertEquals(1234, defaultProperties.proxy.getPort());
        assertEquals("proxy-username-B", defaultProperties.proxy.getUsername());
        assertEquals("proxy-password-B", defaultProperties.proxy.getPassword());
        assertEquals(FIXED, defaultProperties.retry.getMode());
        assertEquals(3, defaultProperties.retry.getExponential().getMaxRetries());
        assertEquals(Duration.ofSeconds(4), defaultProperties.retry.getExponential().getBaseDelay());
        assertEquals(Duration.ofSeconds(5), defaultProperties.retry.getExponential().getMaxDelay());
        assertEquals(Duration.ofSeconds(6), defaultProperties.retry.getFixed().getDelay());
        assertEquals(7, defaultProperties.retry.getFixed().getMaxRetries());
        assertEquals("credential-client-id-B", defaultProperties.credential.getClientId());
        assertEquals("credential-client-secret-B", defaultProperties.credential.getClientSecret());
        assertEquals("credential-client-cert-path-B", defaultProperties.credential.getClientCertificatePath());
        assertEquals("credential-client-cert-password-B", defaultProperties.credential.getClientCertificatePassword());
        assertEquals("credential-username-B", defaultProperties.credential.getUsername());
        assertEquals("credential-password-B", defaultProperties.credential.getPassword());

        AzurePropertiesA propertiesToOverride = new AzurePropertiesA();
        propertiesToOverride.client.setApplicationId("client-application-id-A");
        propertiesToOverride.profile.setCloudType(AZURE_CHINA);
        propertiesToOverride.profile.setTenantId("profile-tenant-id-A");
        propertiesToOverride.profile.getEnvironment().setActiveDirectoryEndpoint("aad-endpoint-A");
        propertiesToOverride.proxy.setHostname("proxy-hostname-A");
        propertiesToOverride.retry.getExponential().setMaxRetries(13);
        propertiesToOverride.retry.getFixed().setMaxRetries(17);
        propertiesToOverride.credential.setClientId("credential-client-id-A");

        AzurePropertiesB result = new AzurePropertiesB();
        AzurePropertiesUtils.mergeAzureCommonProperties(defaultProperties, propertiesToOverride, result);

        // assert properties have been set correctly to result after copy
        assertEquals("client-application-id-A", result.client.getApplicationId());
        assertEquals(AZURE_CHINA, result.profile.getCloudType());
        assertEquals("profile-tenant-id-A", result.profile.getTenantId());
        assertEquals("profile-sub-id-B", result.profile.getSubscriptionId());
        assertEquals("aad-endpoint-A", result.profile.getEnvironment().getActiveDirectoryEndpoint());
        assertEquals(AzureEnvironment.AZURE_CHINA.getActiveDirectoryGraphApiVersion(), result.profile.getEnvironment().getActiveDirectoryGraphApiVersion());
        assertEquals("proxy-type-B", result.proxy.getType());
        assertEquals("proxy-hostname-A", result.proxy.getHostname());
        assertEquals(1234, result.proxy.getPort());
        assertEquals("proxy-username-B", result.proxy.getUsername());
        assertEquals("proxy-password-B", result.proxy.getPassword());
        assertEquals(EXPONENTIAL, result.retry.getMode());
        assertEquals(13, result.retry.getExponential().getMaxRetries());
        assertEquals(Duration.ofSeconds(4), result.retry.getExponential().getBaseDelay());
        assertEquals(Duration.ofSeconds(5), result.retry.getExponential().getMaxDelay());
        assertEquals(Duration.ofSeconds(6), result.retry.getFixed().getDelay());
        assertEquals(17, result.retry.getFixed().getMaxRetries());
        assertEquals("credential-client-id-A", result.credential.getClientId());
        assertEquals("credential-client-secret-B", result.credential.getClientSecret());
        assertEquals("credential-client-cert-path-B", result.credential.getClientCertificatePath());
        assertEquals("credential-client-cert-password-B", result.credential.getClientCertificatePassword());
        assertEquals("credential-username-B", result.credential.getUsername());
        assertEquals("credential-password-B", result.credential.getPassword());
    }

    @Test
    void testCopyPropertiesIgnoreNullToObjectWithDifferentFieldsSetShouldMerge() {
        AzurePropertiesA source = new AzurePropertiesA();
        source.credential.setClientId("client-id-A");
        source.getProfile().setCloudType(AZURE);

        AzurePropertiesB target = new AzurePropertiesB();
        target.credential.setClientSecret("client-secret-B");
        target.retry.getExponential().setMaxDelay(Duration.ofSeconds(2));
        target.profile.setCloudType(OTHER);
        target.profile.getEnvironment().setActiveDirectoryEndpoint("abc");

        assertEquals(AZURE, source.getProfile().getCloudType());
        assertEquals(AzureEnvironment.AZURE.getActiveDirectoryEndpoint(),
            source.profile.getEnvironment().getActiveDirectoryEndpoint());
        assertEquals("client-secret-B", target.credential.getClientSecret());
        assertEquals(Duration.ofSeconds(2), target.retry.getExponential().getMaxDelay());

        AzurePropertiesUtils.copyAzureCommonPropertiesIgnoreNull(source, target);

        // target properties should be merged properties from source + target
        assertEquals("client-id-A", target.credential.getClientId());
        assertEquals("client-secret-B", target.credential.getClientSecret());
        assertEquals(Duration.ofSeconds(2), target.retry.getExponential().getMaxDelay());
        assertEquals(AZURE, source.getProfile().getCloudType());
        assertEquals(AzureEnvironment.AZURE.getActiveDirectoryEndpoint(),
            target.profile.getEnvironment().getActiveDirectoryEndpoint());

        // source properties should not be updated
        assertNull(source.credential.getClientSecret());
        assertEquals(AzureEnvironment.AZURE.getActiveDirectoryEndpoint(),
            source.profile.getEnvironment().getActiveDirectoryEndpoint());
    }

    @Test
    void testCopyPropertiesSourceNotChanged() {
        AzurePropertiesA source = new AzurePropertiesA();
        source.credential.setClientId("client-id-A");
        source.getProfile().setCloudType(AZURE);

        AzurePropertiesB target = new AzurePropertiesB();

        AzurePropertiesUtils.copyAzureCommonProperties(source, target);

        assertEquals("client-id-A", target.credential.getClientId());

        // Update target will not affect source
        target.retry.getExponential().setBaseDelay(Duration.ofSeconds(2));
        target.profile.setCloudType(OTHER);
        target.profile.getEnvironment().setActiveDirectoryEndpoint("abc");

        assertNull(source.retry.getExponential().getBaseDelay());
        assertEquals(AzureEnvironment.AZURE.getActiveDirectoryEndpoint(),
            source.profile.getEnvironment().getActiveDirectoryEndpoint());
    }

    @Test
    void testCopyPropertiesHttpClientPropertiesShouldBeCopied() {
        HeaderProperties headerProperties = new HeaderProperties();
        headerProperties.setName("header-1");
        headerProperties.setValues(Arrays.asList("value-1", "value-2"));
        AzureHttpClientProperties source = new AzureHttpClientProperties();
        source.getClient().setWriteTimeout(Duration.ofSeconds(3));
        source.getClient().setResponseTimeout(Duration.ofSeconds(4));
        source.getClient().setReadTimeout(Duration.ofSeconds(4));
        source.getClient().setConnectTimeout(Duration.ofSeconds(2));
        source.getClient().setMaximumConnectionPoolSize(5);
        source.getClient().setConnectionIdleTimeout(Duration.ofSeconds(5));
        source.getClient().setApplicationId("global-application-id");
        source.getClient().getLogging().setLevel(HttpLogDetailLevel.BODY_AND_HEADERS);
        source.getClient().getLogging().getAllowedHeaderNames().add("header-name1");
        source.getClient().getHeaders().add(headerProperties);
        AzureHttpClientProperties target = new AzureHttpClientProperties();
        target.getClient().setConnectTimeout(Duration.ofSeconds(3));
        target.getClient().setMaximumConnectionPoolSize(5);
        target.getClient().setConnectionIdleTimeout(Duration.ofSeconds(5));
        target.getClient().setApplicationId("target-global-application-id");
        target.getClient().getLogging().setLevel(HttpLogDetailLevel.HEADERS);
        target.getClient().getLogging().getAllowedHeaderNames().add("header-name2");
        HeaderProperties targetHeaderProperties = new HeaderProperties();
        targetHeaderProperties.setName("header-2");
        targetHeaderProperties.setValues(Arrays.asList("value-1", "value-2"));
        target.getClient().getHeaders().add(targetHeaderProperties);
        AzurePropertiesUtils.copyAzureCommonProperties(source, target);
        assertEquals(Duration.ofSeconds(3), target.getClient().getWriteTimeout());
        assertEquals(Duration.ofSeconds(4), target.getClient().getResponseTimeout());
        assertEquals(Duration.ofSeconds(4), target.getClient().getReadTimeout());
        assertEquals(Duration.ofSeconds(2), target.getClient().getConnectTimeout());
        assertEquals(Duration.ofSeconds(5), target.getClient().getConnectionIdleTimeout());
        assertEquals(5, target.getClient().getMaximumConnectionPoolSize());
        assertEquals("global-application-id", target.getClient().getApplicationId());
        assertEquals(HttpLogDetailLevel.BODY_AND_HEADERS, target.getClient().getLogging().getLevel());
        Set<String> allowedHeaderNames = new HashSet<>();
        allowedHeaderNames.add("header-name1");
        allowedHeaderNames.add("header-name2");
        assertEquals(allowedHeaderNames, target.getClient().getLogging().getAllowedHeaderNames());
        assertEquals(2, target.getClient().getHeaders().size());
    }

    @Test
    void testCopyPropertiesIgnoreNullHttpClientPropertiesShouldBeCopied() {
        AzureHttpClientProperties source = new AzureHttpClientProperties();
        source.getClient().setReadTimeout(Duration.ofSeconds(4));
        source.getClient().setConnectTimeout(Duration.ofSeconds(2));
        source.getClient().setMaximumConnectionPoolSize(5);
        source.getClient().getLogging().getAllowedHeaderNames().add("header-name1");
        AzureHttpClientProperties target = new AzureHttpClientProperties();
        target.getClient().setWriteTimeout(Duration.ofSeconds(4));
        target.getClient().setResponseTimeout(Duration.ofSeconds(5));
        target.getClient().setReadTimeout(Duration.ofSeconds(5));
        target.getClient().setConnectTimeout(Duration.ofSeconds(3));
        target.getClient().setMaximumConnectionPoolSize(5);
        target.getClient().setConnectionIdleTimeout(Duration.ofSeconds(5));
        target.getClient().setApplicationId("target-global-application-id");
        target.getClient().getLogging().setLevel(HttpLogDetailLevel.HEADERS);
        target.getClient().getLogging().getAllowedHeaderNames().add("header-name2");
        HeaderProperties headerProperties = new HeaderProperties();
        headerProperties.setName("header-2");
        headerProperties.setValues(Arrays.asList("value-1", "value-2"));
        target.getClient().getHeaders().add(headerProperties);
        AzurePropertiesUtils.copyAzureCommonPropertiesIgnoreNull(source, target);
        assertEquals(Duration.ofSeconds(4), target.getClient().getWriteTimeout());
        assertEquals(Duration.ofSeconds(5), target.getClient().getResponseTimeout());
        assertEquals(Duration.ofSeconds(4), target.getClient().getReadTimeout());
        assertEquals(Duration.ofSeconds(2), target.getClient().getConnectTimeout());
        assertEquals(Duration.ofSeconds(5), target.getClient().getConnectionIdleTimeout());
        assertEquals(5, target.getClient().getMaximumConnectionPoolSize());
        assertEquals("target-global-application-id", target.getClient().getApplicationId());
        assertEquals(HttpLogDetailLevel.HEADERS, target.getClient().getLogging().getLevel());
        Set<String> allowedHeaderNames = new HashSet<>();
        allowedHeaderNames.add("header-name1");
        allowedHeaderNames.add("header-name2");
        assertEquals(allowedHeaderNames, target.getClient().getLogging().getAllowedHeaderNames());
        assertEquals(1, target.getClient().getHeaders().size());
    }

    @Test
    void testCopyPropertiesAmqpClientPropertiesShouldBeCopied() {
        AzureAmqpClientProperties source = new AzureAmqpClientProperties();
        source.getClient().setApplicationId("global-application-id");
        source.getClient().setTransportType(AmqpTransportType.AMQP);
        AzureAmqpClientProperties target = new AzureAmqpClientProperties();
        target.getClient().setApplicationId("target-global-application-id");
        target.getClient().setTransportType(AmqpTransportType.AMQP_WEB_SOCKETS);
        AzurePropertiesUtils.copyAzureCommonProperties(source, target);
        assertEquals("global-application-id", target.getClient().getApplicationId());
        assertEquals(AmqpTransportType.AMQP, target.getClient().getTransportType());
    }

    @Test
    void testCopyPropertiesIgnoreNullAmqpClientPropertiesShouldBeCopied() {
        AzureAmqpClientProperties source = new AzureAmqpClientProperties();
        source.getClient().setTransportType(AmqpTransportType.AMQP);
        AzureAmqpClientProperties target = new AzureAmqpClientProperties();
        target.getClient().setApplicationId("target-global-application-id");
        target.getClient().setTransportType(AmqpTransportType.AMQP_WEB_SOCKETS);
        AzurePropertiesUtils.copyAzureCommonPropertiesIgnoreNull(source, target);
        assertEquals("target-global-application-id", target.getClient().getApplicationId());
        assertEquals(AmqpTransportType.AMQP, target.getClient().getTransportType());
    }

    static class AzureHttpClientProperties extends AzureHttpSdkProperties {

    }

    static class AzureAmqpClientProperties extends AzureAmqpSdkProperties {

    }

    static class AzurePropertiesA implements AzureProperties, RetryOptionsProvider {

        private final ClientProperties client = new ClientProperties();
        private final ProxyProperties proxy = new ProxyProperties();
        private final RetryProperties retry = new RetryProperties();
        private final TokenCredentialProperties credential = new TokenCredentialProperties();
        private final AzureProfileProperties profile = new AzureProfileProperties();

        @Override
        public ClientProperties getClient() {
            return client;
        }

        @Override
        public ProxyProperties getProxy() {
            return proxy;
        }

        @Override
        public RetryProperties getRetry() {
            return retry;
        }

        @Override
        public TokenCredentialProperties getCredential() {
            return credential;
        }

        @Override
        public AzureProfileProperties getProfile() {
            return profile;
        }
    }

    static class AzurePropertiesB implements AzureProperties, RetryOptionsProvider {

        private final ClientProperties client = new ClientProperties();
        private final ProxyProperties proxy = new ProxyProperties();
        private final RetryProperties retry = new RetryProperties();
        private final TokenCredentialProperties credential = new TokenCredentialProperties();
        private final AzureProfileProperties profile = new AzureProfileProperties();

        @Override
        public ClientProperties getClient() {
            return client;
        }

        @Override
        public ProxyProperties getProxy() {
            return proxy;
        }

        @Override
        public RetryProperties getRetry() {
            return retry;
        }

        @Override
        public TokenCredentialProperties getCredential() {
            return credential;
        }

        @Override
        public AzureProfileProperties getProfile() {
            return profile;
        }

    }

}


text:
//----------------------------------------------------------------------
//This code is developed as part of the Java CoG Kit project
//The terms of the license can be found at http://www.cogkit.org/license
//This message may not be removed or altered.
//----------------------------------------------------------------------

/*
 * Created on May 7, 2008
 */
package org.globus.cog.karajan.scheduler.submitQueue;

import org.globus.cog.abstraction.interfaces.Status;
import org.globus.cog.abstraction.interfaces.Task;
import org.globus.cog.abstraction.interfaces.TaskHandler;

public class NonBlockingCancel extends NonBlockingSubmit {
	private String message;

	public NonBlockingCancel(TaskHandler th, Task task, String message) {
		super(th, task, null);
		this.message = message;
	}

	public void run() {
		try {
			getTaskHandler().cancel(getTask(), message);
			notifyPreviousQueue(null);
		}
		catch (Exception e) {
			//force it
			getTask().setStatus(Status.CANCELED);
			notifyPreviousQueue(e);
		}
		catch (ThreadDeath td) {
			throw td;
		}
		catch (Throwable t) {
			notifyPreviousQueue(new Exception(t));
			t.printStackTrace();
		}
	}
}


text:
<?php

namespace Flarum\Approval\Tests\integration\api;

use Flarum\Approval\Tests\integration\InteractsWithUnapprovedContent;
use Flarum\Testing\integration\RetrievesAuthorizedUsers;
use Flarum\Testing\integration\TestCase;
use Illuminate\Support\Arr;

class ListPostsTest extends TestCase
{
    use RetrievesAuthorizedUsers;
    use InteractsWithUnapprovedContent;

    protected function setUp(): void
    {
        parent::setUp();

        $this->extension('flarum-approval');

        $this->prepareUnapprovedDatabaseContent();
    }

    /**
     * @dataProvider unallowedUsers
     * @test
     */
    public function can_only_see_approved_if_not_allowed_to_approve(?int $authenticatedAs)
    {
        $response = $this->send(
            $this
                ->request('GET', '/api/posts', compact('authenticatedAs'))
                ->withQueryParams([
                    'filter' => [
                        'discussion' => 7
                    ]
                ])
        );

        $body = json_decode($response->getBody()->getContents(), true);

        $this->assertEquals(200, $response->getStatusCode());
        $this->assertEqualsCanonicalizing([7, 8, 10], Arr::pluck($body['data'], 'id'));
    }

    /**
     * @dataProvider allowedUsers
     * @test
     */
    public function can_see_unapproved_if_allowed_to_approve(int $authenticatedAs)
    {
        $response = $this->send(
            $this
                ->request('GET', '/api/posts', compact('authenticatedAs'))
                ->withQueryParams([
                    'filter' => [
                        'discussion' => 7
                    ]
                ])
        );

        $body = json_decode($response->getBody()->getContents(), true);

        $this->assertEquals(200, $response->getStatusCode());
        $this->assertEqualsCanonicalizing([7, 8, 9, 10, 11], Arr::pluck($body['data'], 'id'));
    }
}


text:
@interface NXOAuth2Connection (Extension)

@end


text:
from setuptools import setup

setup(name='synology',
      version='0.1',
      description='Synology DSM 5 API',
      url='http://github.com/satreix/synology',
      author='Steve Barrau',
      author_email='satreix@gmail.com',
      license='MIT',
      packages=['synology'],
      install_requires=[
          'urllib3'
      ],
      test_suite='nose.collector',
      tests_require=['nose'],
      zip_safe=False)


text:
using System.Collections.Generic;
using System.Xml;
using System.Xml.Linq;
using Azure.Core;

namespace Azure.Data.Tables.Models
{
    public partial class TableServiceProperties : IXmlSerializable
    {
        void IXmlSerializable.Write(XmlWriter writer, string nameHint)
        {
            writer.WriteStartElement(nameHint ?? "StorageServiceProperties");
            if (Optional.IsDefined(Logging))
            {
                writer.WriteObjectValue(Logging, "Logging");
            }
            if (Optional.IsDefined(HourMetrics))
            {
                writer.WriteObjectValue(HourMetrics, "HourMetrics");
            }
            if (Optional.IsDefined(MinuteMetrics))
            {
                writer.WriteObjectValue(MinuteMetrics, "MinuteMetrics");
            }
            if (Optional.IsCollectionDefined(Cors))
            {
                writer.WriteStartElement("Cors");
                foreach (var item in Cors)
                {
                    writer.WriteObjectValue(item, "CorsRule");
                }
                writer.WriteEndElement();
            }
            writer.WriteEndElement();
        }

        internal static TableServiceProperties DeserializeTableServiceProperties(XElement element)
        {
            TableAnalyticsLoggingSettings logging = default;
            TableMetrics hourMetrics = default;
            TableMetrics minuteMetrics = default;
            IList<TableCorsRule> cors = default;
            if (element.Element("Logging") is XElement loggingElement)
            {
                logging = TableAnalyticsLoggingSettings.DeserializeTableAnalyticsLoggingSettings(loggingElement);
            }
            if (element.Element("HourMetrics") is XElement hourMetricsElement)
            {
                hourMetrics = TableMetrics.DeserializeTableMetrics(hourMetricsElement);
            }
            if (element.Element("MinuteMetrics") is XElement minuteMetricsElement)
            {
                minuteMetrics = TableMetrics.DeserializeTableMetrics(minuteMetricsElement);
            }
            if (element.Element("Cors") is XElement corsElement)
            {
                var array = new List<TableCorsRule>();
                foreach (var e in corsElement.Elements("CorsRule"))
                {
                    array.Add(TableCorsRule.DeserializeTableCorsRule(e));
                }
                cors = array;
            }
            return new TableServiceProperties(logging, hourMetrics, minuteMetrics, cors);
        }
    }
}


text:
#pragma once

#include <Eigen/Eigen>

namespace geometry {
template <class T>
inline T SquaredNorm(T* point) {
  return point[0] * point[0] + point[1] * point[1];
}

template <int IN, int P, int OUT>
struct Functor {
  constexpr static int InSize = IN;
  constexpr static int ParamSize = P;
  constexpr static int OutSize = OUT;
  template <bool C>
  static constexpr int Stride() {
    return C * ParamSize + InSize;
  }
};

/* Given two function f(x, a) and g(y, b), composed as f o g = f( g(x, b), a)
 * for which have jacobian stored as df/(dx | da) and dg/(dy | db), apply the
 * derivative chain-rule in order to get the derivative of
 *
 *     (f o g) = d(f o g)/d(x | b | a).
 */
template <class T, bool DERIV_PARAMS, int OutSize1, int Stride1, int ParamSize1,
          int OutSize2, int Stride2, int ParamSize2>
void ComposeDerivatives(
    const Eigen::Matrix<T, OutSize1, Stride1, Eigen::RowMajor>& jacobian1,
    const Eigen::Matrix<T, OutSize2, Stride2, Eigen::RowMajor>& jacobian2,
    T* jacobian) {
  Eigen::Map<Eigen::Matrix<T, OutSize2, Stride1 + DERIV_PARAMS * ParamSize2,
                           Eigen::RowMajor>>
      jacobian_mapped(jacobian);
  jacobian_mapped.template block<OutSize2, Stride1>(0, 0) =
      jacobian2.template block<OutSize2, OutSize1>(0, 0) * jacobian1;
  if (DERIV_PARAMS) {
    jacobian_mapped.template block<OutSize2, ParamSize2>(0, Stride1) =
        jacobian2.template block<OutSize2, ParamSize2>(0, OutSize1);
  }
}

/* Below are some utilities to generalize computation of functions (or their
 * jacobian) of composition of functions f(g(h(i ... ))). Most of the
 * implementation consists in recursing variadic template arguments. Usage is
 * then summarized as : ComposeForwardDerivatives<Func1, Func2, ... FuncN>() */
template <bool DERIV_PARAMS, class FUNC>
static constexpr int ComposeStrides() {
  return FUNC::template Stride<DERIV_PARAMS>();
}

template <bool DERIV_PARAMS, class FUNC1, class FUNC2, class... FUNCS>
static constexpr int ComposeStrides() {
  return DERIV_PARAMS * FUNC1::ParamSize +
         ComposeStrides<DERIV_PARAMS, FUNC2, FUNCS...>();
}

template <class FUNC>
static constexpr int ComposeIndex() {
  return FUNC::ParamSize;
}

template <class FUNC1, class FUNC2, class... FUNCS>
static constexpr int ComposeIndex() {
  return FUNC1::ParamSize + ComposeIndex<FUNC2, FUNCS...>();
}

template <class T, bool DERIV_PARAMS, class FUNC>
static void ComposeForwardDerivatives(const T* in, const T* parameters, T* out,
                                      T* jacobian) {
  FUNC::template ForwardDerivatives<T, DERIV_PARAMS>(in, parameters, out,
                                                     jacobian);
}

template <class T, bool DERIV_PARAMS, class FUNC1, class FUNC2, class... FUNCS>
static void ComposeForwardDerivatives(const T* in, const T* parameters, T* out,
                                      T* jacobian) {
  constexpr int StrideSub = ComposeStrides<DERIV_PARAMS, FUNC2, FUNCS...>();
  Eigen::Matrix<T, FUNC2::OutSize, StrideSub, Eigen::RowMajor> sub_jacobian;
  T tmp[FUNC2::OutSize];
  ComposeForwardDerivatives<T, DERIV_PARAMS, FUNC2, FUNCS...>(
      in, parameters, &tmp[0], sub_jacobian.data());

  constexpr int Index = ComposeIndex<FUNC2, FUNCS...>();
  constexpr int StrideFunc1 = FUNC1::template Stride<DERIV_PARAMS>();
  Eigen::Matrix<T, FUNC1::OutSize, StrideFunc1, Eigen::RowMajor>
      current_jacobian;
  FUNC1::template ForwardDerivatives<T, DERIV_PARAMS>(
      &tmp[0], parameters + Index, out, current_jacobian.data());

  ComposeDerivatives<T, DERIV_PARAMS, FUNC2::OutSize, StrideSub,
                     FUNC2::ParamSize, FUNC1::OutSize, StrideFunc1,
                     FUNC1::ParamSize>(sub_jacobian, current_jacobian,
                                       jacobian);
}

template <class T, class FUNC>
static void ComposeFunctions(const T* in, const T* parameters, T* out) {
  FUNC::template Apply<T>(in, parameters, out);
}

template <class T, class FUNC1, class FUNC2, class... FUNCS>
static void ComposeFunctions(const T* in, const T* parameters, T* out) {
  T tmp[FUNC2::OutSize];
  ComposeFunctions<T, FUNC2, FUNCS...>(in, parameters, tmp);

  constexpr int Index = ComposeIndex<FUNC2, FUNCS...>();
  FUNC1::template Apply<T>(&tmp[0], parameters + Index, out);
}
};  // namespace geometry


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#29000000">

    <include layout="@layout/my_video_background" />

    <!--Like Spotify image-->

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Inspector"
        android:layout_marginTop="35dp"
        android:id="@+id/appNameTextView"
        android:textColor="@color/colorPrimaryDark"
        android:textSize="60sp"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:textStyle="bold" />

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="46dp"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:orientation="horizontal">

        <Button
            android:id="@+id/signUp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="0.5"
            android:background="#FF2D2D2D"
            android:text="SIGN UP"
            android:textColor="@android:color/white" />

        <Button
            android:id="@+id/login"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="0.5"
            android:background="#FF669900"
            android:text="LOGIN"
            android:textColor="@android:color/white" />

    </LinearLayout>
</RelativeLayout>


text:
var auth = require("./auth.js").authenticate,
    conf = module.parent.parent.require('./meta').config,
    db = module.parent.parent.require('../src/database'),
    coreCategories = module.parent.parent.require('../src/categories');

Categories = {};

Categories.init = function(app){

    this.baseURL = conf["api:baseURL"] + "/categories";

    /*
        Create a new category.

        {
            "name":"Nueva categoría",
            "description": "Descripción de la nueva categoría",
            "bgColor": "#ccc",
            "color": "#888"
        }
    */
    app.post(this.baseURL,auth,function(req, res, next){

        if (!req.body.name || !req.body.description || !req.body.bgColor
            || !req.body.color ){

            res.status(400).json({
                message: "Bad parameters",
            });
            return;
        }

        data = {
            name : req.body.name,
            description : req.body.description,
            bgColor: req.body.bgColor,
            color: req.body.color,
            order: 0
        };

        coreCategories.getAllCategories(1,function(e,cats){
            for (var i=0;i<cats.length;i++){
                if (data.order < cats[i].order){
                    data.order = cats[i].order;
                }
            }
            data.order++;

            coreCategories.create(data, function(err,data){
                if (err){
                    res.status(500).json(err);
                }
                else{
                    res.status(200).json({
                        "slug" : data.slug,
                        "cid": data.cid,
                    });
                }
            });

        });

    });

    app.delete(this.baseURL +"/:cid",auth,function(req, res, next){

        data = {};
        data[req.params.cid] = { disabled : 1};

        coreCategories.update(data, function(e,data){
            if (e){
                res.status(400).json({
                    message : "Internal error",
                    error: e,
                });
            }
            else{
                res.json({
                    "message" : "Operation complete successfuly"
                });
            }
        });

    });

    app.delete(this.baseURL +"/:cid/purge",auth,function(req, res, next){

        coreCategories.purge(req.params.cid, function(e,data){
            if (e){
                res.status(400).json({
                    message : "Internal error",
                    error: e,
                });
            }
            else{
                res.json({
                    "message" : "Operation complete successfuly"
                });
            }

        });

    });

};

module.exports = Categories