text:
package page_writer

import (
	"sync/atomic"
)

func (up *UploadPipeline) LockForRead(startOffset, stopOffset int64) {
	startLogicChunkIndex := LogicChunkIndex(startOffset / up.ChunkSize)
	stopLogicChunkIndex := LogicChunkIndex(stopOffset / up.ChunkSize)
	if stopOffset%up.ChunkSize > 0 {
		stopLogicChunkIndex += 1
	}
	up.activeReadChunksLock.Lock()
	defer up.activeReadChunksLock.Unlock()
	for i := startLogicChunkIndex; i < stopLogicChunkIndex; i++ {
		if count, found := up.activeReadChunks[i]; found {
			up.activeReadChunks[i] = count + 1
		} else {
			up.activeReadChunks[i] = 1
		}
	}
}

func (up *UploadPipeline) UnlockForRead(startOffset, stopOffset int64) {
	startLogicChunkIndex := LogicChunkIndex(startOffset / up.ChunkSize)
	stopLogicChunkIndex := LogicChunkIndex(stopOffset / up.ChunkSize)
	if stopOffset%up.ChunkSize > 0 {
		stopLogicChunkIndex += 1
	}
	up.activeReadChunksLock.Lock()
	defer up.activeReadChunksLock.Unlock()
	for i := startLogicChunkIndex; i < stopLogicChunkIndex; i++ {
		if count, found := up.activeReadChunks[i]; found {
			if count == 1 {
				delete(up.activeReadChunks, i)
			} else {
				up.activeReadChunks[i] = count - 1
			}
		}
	}
}

func (up *UploadPipeline) IsLocked(logicChunkIndex LogicChunkIndex) bool {
	up.activeReadChunksLock.Lock()
	defer up.activeReadChunksLock.Unlock()
	if count, found := up.activeReadChunks[logicChunkIndex]; found {
		return count > 0
	}
	return false
}

func (up *UploadPipeline) waitForCurrentWritersToComplete() {
	up.uploaderCountCond.L.Lock()
	t := int32(100)
	for {
		t = atomic.LoadInt32(&up.uploaderCount)
		if t <= 0 {
			break
		}
		up.uploaderCountCond.Wait()
	}
	up.uploaderCountCond.L.Unlock()
}


text:
class CaerbannogGenerator < Rails::Generators::Base
  include Rails::Generators::Migration
  source_root File.expand_path('../templates', __FILE__)

  def self.next_migration_number(path)
    Time.now.utc.strftime('%Y%m%d%H%M%S')
  end

  def copy_migration
    migration_template 'add_caerbannog_messages.rb', 'db/migrate/add_caerbannog_messages.rb'
  end

  def create_message_model
    copy_file 'caerbannog_message.rb', 'app/models/caerbannog_message.rb'
  end

  def create_caerbannog_initializer
    copy_file 'caerbannog_initializer.rb', 'config/initializers/caerbannog_initializer.rb'
  end
end

redpajama_set_name: RedPajamaGithub


text:
/*global Widget */

/**
 * Constructor of AlertWidget
 *
 * @param {Object} widget Object representing DOM node of a widget.
 * @param {String} configName Name of a config file.
 * @constructor
 */
function AlertWidget(widget, configName) {

    this.widget = widget;
    this.configName = configName;

    this.dataToBind = {
        'value': '',
        'arrowClass': '',
        'percentageDiff': 0,
        'oldValue': '',
        'lastUpdate': ''
    };
}

AlertWidget.prototype = new Widget();
AlertWidget.prototype.constructor = AlertWidget;

$.extend(AlertWidget.prototype, {
    /**
     * Invoked after each response from long polling server
     *
     * @param response Response from long polling server
     */
    handleResponse: function (response) {
        this.prepareData(response);
    },

    /**
     * Updates widget's state
     *
     * @param {Object} response Response object from long polling controller
     */
    prepareData: function (response) {

        this.dataToBind.value = response.data;

        $.extend(this.dataToBind, this.setDifference(this.oldValue, this.dataToBind.value));

        this.oldValue = this.dataToBind.value;

        this.dataToBind.lastUpdate = response.updateTime;

        this.renderTemplate(this.dataToBind);
    }
});


text:
package org.apache.beam.sdk.transforms;

import java.io.Serializable;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Set;
import org.apache.beam.sdk.annotations.Experimental;
import org.apache.beam.sdk.annotations.Experimental.Kind;
import org.apache.beam.sdk.values.PCollectionView;
import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.Sets;

/** Describes the run-time requirements of a {@link Contextful}, such as access to side inputs. */
@Experimental(Kind.CONTEXTFUL)
@SuppressWarnings({
  "rawtypes" // TODO(https://issues.apache.org/jira/browse/BEAM-10556)
})
public final class Requirements implements Serializable {
  private final Collection<PCollectionView<?>> sideInputs;

  private Requirements(Collection<PCollectionView<?>> sideInputs) {
    this.sideInputs = sideInputs;
  }

  /** The side inputs that this {@link Contextful} needs access to. */
  public Collection<PCollectionView<?>> getSideInputs() {
    return sideInputs;
  }

  /** Describes the need for access to the given side inputs. */
  public static Requirements requiresSideInputs(Collection<PCollectionView<?>> sideInputs) {
    return new Requirements(sideInputs);
  }

  /** Like {@link #requiresSideInputs(Collection)}. */
  public static Requirements requiresSideInputs(PCollectionView<?>... sideInputs) {
    return requiresSideInputs(Arrays.asList(sideInputs));
  }

  /** Describes an empty set of requirements. */
  public static Requirements empty() {
    return new Requirements(Collections.emptyList());
  }

  /** Whether this is an empty set of requirements. */
  public boolean isEmpty() {
    return sideInputs.isEmpty();
  }

  public static Requirements union(Contextful... contextfuls) {
    Set<PCollectionView<?>> sideInputs = Sets.newHashSet();
    for (Contextful c : contextfuls) {
      sideInputs.addAll(c.getRequirements().getSideInputs());
    }
    return requiresSideInputs(sideInputs);
  }
}


text:
> Use property paths (`a.b.c`) get a nested value from an object.

**[Benchmarks](./benchmark)**

This is 10x faster and more performant than [dot-prop](https://github.com/sindresorhus/dot-prop), and it passes all of the dot-prop tests.

Of the libs benchmarked, _dot-prop was the least performant_:

```bash
#1: deep
  get-value x 3,308,335 ops/sec ±1.32% (94 runs sampled)
  dot-prop x 197,631 ops/sec ±1.27% (94 runs sampled)
  getobject x 218,635 ops/sec ±1.51% (91 runs sampled)

#2: shallow
  get-value x 5,762,976 ops/sec ±1.21% (95 runs sampled)
  dot-prop x 695,892 ops/sec ±1.42% (95 runs sampled)
  getobject x 724,493 ops/sec ±1.46% (93 runs sampled)
```

Also, get-value supports escaping dots in paths, which is common when object keys are file paths with extensions, dot-prop does not.

## Install with [npm](npmjs.org)

```bash
npm i get-value --save
```

## Install with [bower](https://github.com/bower/bower)

```bash
bower install get-value --save
```

## Usage

```js
var get = require('get-value');

var obj = {a: {b : {c: {d: 'foo'}}}};
get(obj, 'a.b.c');
//=> {d: 'foo'}

get(obj, 'a.b.c.d');
//=> 'foo'
```

## Related projects

* [get-property](https://github.com/jonschlinkert/get-property): Get a nested property or its value from an object using simple `  a.b.c` paths.
* [get-object](https://github.com/jonschlinkert/get-object): Get a object from a property on a nested object.
* [has-value](https://github.com/jonschlinkert/has-value): Returns true if a value exists, false if empty. Works with deeply nested values using… [more](https://github.com/jonschlinkert/has-value)
* [set-value](https://github.com/jonschlinkert/set-value): Create nested values and any intermediaries using dot notation (`'a.b.c'`) paths.

## Contributing

Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](https://github.com/jonschlinkert/get-value/issues)

## Running tests

Install dev dependencies:

```bash
npm i -d && npm test
```

## Author

**Jon Schlinkert**

+ [github/jonschlinkert](https://github.com/jonschlinkert)
+ [twitter/jonschlinkert](http://twitter.com/jonschlinkert)

## License

Copyright (c) 2014-2015 Jon Schlinkert
Released under the MIT license.

***

_This file was generated by [verb-cli](https://github.com/assemble/verb-cli) on May 03, 2015._

[assemble]: http://assemble.io
[template]: https://github.com/jonschlinkert/template
[verb]: https://github.com/assemble/verb


text:
<?php

// sensors.php?mac=F8:F0:5:F5:CF:DD&light=984&water=1023&c=9
if (empty($_GET['mac']) || empty($_GET['light']) || empty($_GET['water'])) exit();

// sanity checks
if (!preg_match('/^([0-9a-f:])+$/i', $_GET['mac']) || !is_numeric($_GET['light']) || !is_numeric($_GET['water'])) exit();

// connect to database
mysql_connect('localhost', 'intelleau', 'intelleau');
mysql_select_db('intelleau');

// get sensor ID
$res = mysql_query('SELECT ID FROM sensors WHERE mac="' . $_GET['mac'] . '"');
$row = mysql_fetch_array($res);

// need to add to database?
if (empty($row))
{
	mysql_query('INSERT INTO sensors (mac) VALUES("' . $_GET['mac'] . '")');
	$res = mysql_query('SELECT ID FROM sensors WHERE mac="' . $_GET['mac'] . '"');
	$row = mysql_fetch_array($res);
	if (empty($row)) exit('database problem');
}

// now we have an ID
$sensorid = $row['ID'];

// add datas to database
mysql_query('INSERT INTO datas (ID_sensor, collecttime, light, water) VALUES (' . $sensorid . ', NOW(), ' . $_GET['light'] . ', ' . $_GET['water'] . ')');

// close database
mysql_close();

?>


text:
/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/generic/memory/lib/dimm/ddr5/ddr5_mr51.H $         */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2022                             */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* 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.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
// EKB-Mirror-To: hostboot

///
/// @file ddr5_mr51.H
/// @brief Run and manage the DDR5 MR51 loading
///
// *HWP HWP Owner: Stephen Glancy <sglancy@us.ibm.com>
// *HWP HWP Backup: Louis Stermole <stermole@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 3
// *HWP Consumed by: FSP:HB

#ifndef _GENERIC_DDR5_MR51_H_
#define _GENERIC_DDR5_MR51_H_

#include <fapi2.H>

#include <mss_generic_attribute_getters.H>
#include <generic/memory/lib/utils/shared/mss_generic_consts.H>
#include <generic/memory/lib/utils/c_str.H>
#include <generic/memory/lib/utils/mss_rank.H>
#include <generic/memory/lib/utils/mss_generic_check.H>
#include <generic/memory/lib/utils/num.H>

namespace mss
{

namespace ddr5
{

///
/// @brief Data structure for DDR5 MR51
/// @tparam MC the memory controller type
///
template<mss::mc_type MC>
class mr51_data
{
    public:
        // Needed as we need to know what MR for the CCS instruction created by the lab tooling
        static constexpr uint64_t iv_mr = 51;

        ///
        /// @brief mr51_data ctor
        /// @param[in] a fapi2::TARGET_TYPE_DIMM target
        /// @param[in,out] fapi2::ReturnCode FAPI2_RC_SUCCESS iff ok
        ///
        mr51_data( const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target, fapi2::ReturnCode& io_rc )
        {
            if (io_rc != fapi2::FAPI2_RC_SUCCESS)
            {
                return;
            }

            const auto& l_port = mss::find_target<fapi2::TARGET_TYPE_MEM_PORT>(i_target);

            FAPI_TRY(mss::attr::get_ddr5_wr_crc_autodisable_threshold(l_port, iv_wr_crc_autodisable_threshold),
                     "Error in ddr5::mr50_data()");

            io_rc = fapi2::FAPI2_RC_SUCCESS;
            return;
        fapi_try_exit:
            io_rc = fapi2::current_err;
            FAPI_ERR(TARGTIDFORMAT " unable to get attributes for ddr5::mr51", TARGTID);
            return;
        }

        ///
        /// @brief Default constructor
        /// @note Default constructor is defined to allow for the use of STL data structures
        ///
        mr51_data() = default;

        ///
        /// @brief Checks the WR CRC threshold value
        /// @param[in] a fapi2::TARGET_TYPE_DIMM target
        /// @param[in] i_value the WR CRC threshold value to check
        /// @return FAPI2_RC_SUCCESS if and only if ok
        ///
        fapi2::ReturnCode check_threshold(const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target, const uint8_t i_value) const
        {
            constexpr uint8_t MAX = 0b01111111;
            FAPI_ASSERT( (i_value <= MAX),
                         fapi2::MSS_DDR5_MR51_BAD_WR_CRC_THRESHOLD()
                         .set_DIMM_IN_ERROR(i_target)
                         .set_VALUE(i_value),
                         TARGTIDFORMAT " DDR5 MR51. Bad WR CRC threshold input: %u <= %u", TARGTID, i_value, MAX);

            return fapi2::FAPI2_RC_SUCCESS;
        fapi_try_exit:
            return fapi2::current_err;
        }

        ///
        /// @brief Assembles the MR based upon the passed in rank info and DRAM number
        /// @param[in] i_rank_info the rank information class
        /// @param[out] o_mr_data the mode register OP data in [7:0] format
        /// @param[in] i_dram_number the DRAM number - not used for MR51
        /// @return FAPI2_RC_SUCCESS if and only if ok
        /// @note DRAM number is not used for MR51 but is kept to keep the interface common across all MR
        ///
        fapi2::ReturnCode assemble_data(const mss::rank::info<MC>& i_rank_info,
                                        uint8_t& o_mr_data,
                                        const uint8_t i_dram_number = 0) const
        {
            fapi2::buffer<uint8_t> l_data;

            FAPI_TRY(check_threshold(i_rank_info.get_dimm_target(), iv_wr_crc_autodisable_threshold));

            l_data. template insertFromRight<THRESHOLD, THRESHOLD_LEN>(iv_wr_crc_autodisable_threshold);

            o_mr_data = l_data;

            return fapi2::FAPI2_RC_SUCCESS;
        fapi_try_exit:
            return fapi2::current_err;
        }

        ///
        /// @brief Displays the information that makes up the MR
        /// @param[in] i_rank_info the rank on which to operate
        /// @param[in] i_dram_number the DRAM on which to operate - not used for MR51 but included to keep the API common
        /// @return FAPI2_RC_SUCCESS if and only if ok
        ///
        fapi2::ReturnCode display(const mss::rank::info<MC>& i_rank_info, const uint8_t i_dram_number = 0) const
        {
            this->display(i_rank_info.get_dimm_target());
            return fapi2::FAPI2_RC_SUCCESS;
        }

        ///
        /// @brief Reads in the MR information into this data class
        /// @param[in] i_rank_info the rank on which to operate - unused for MR51 but keeping to match existing API
        /// @param[in] i_mr_data the mode register OP data in [7:0] format
        /// @param[in] i_dram_number the DRAM on which to operate - not used for MR51 but included to keep the API common
        /// @return FAPI2_RC_SUCCESS if and only if ok
        /// @note This can be used for decoding mode register reads
        ///
        fapi2::ReturnCode read_from_data(const mss::rank::info<MC>& i_rank_info,
                                         const uint8_t i_mr_data,
                                         const uint8_t i_dram_number = 0)
        {
            const fapi2::buffer<uint8_t> l_data(i_mr_data);

            iv_wr_crc_autodisable_threshold = 0;
            l_data. template extractToRight<THRESHOLD, THRESHOLD_LEN>(iv_wr_crc_autodisable_threshold);

            return fapi2::FAPI2_RC_SUCCESS;
        }

        enum
        {
            THRESHOLD = 1,
            THRESHOLD_LEN = 7,
        };

        uint8_t iv_wr_crc_autodisable_threshold = 0;

    private:

        ///
        /// @brief Displays the information that makes up the MR
        /// @param[in] a fapi2::TARGET_TYPE_DIMM target
        ///
        void display(const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target) const
        {
            FAPI_INF(TARGTIDFORMAT " DDR5 MR51. WR CRC auto-disable threshold: %u.",
                     TARGTID, iv_wr_crc_autodisable_threshold);
        }

};

} // ns ddr5

} // ns mss

#endif


text:
title: 'Apfelkorb #1 - Automator'
eyecatch: fa-youtube-play
slug: apfelkorb-1_Automator
description: 'Apfelkorb #1 - Automator'
date: 2012-12-10
tags: [youtube, apfelkorb]
---

In diesem Video zeige ich euch was man mit dem in OSX integierten
Automator alles machen kann.

{{< youtube GuhbFHFZkY0 >}}


text:
<dc:title>NATIONAL CREDIT UNION ADMIN.</dc:title>
<dc:language>en-US</dc:language>
<dc:creator opf:file-as="NYPL" opf:role="aut">NYPL</dc:creator>
<dc:publisher>NYPL</dc:publisher>
<dc:date opf:event="publication">2015-01-15</dc:date>
<dc:rights>Copyright ©2015 by Cornell Law and NYPL</dc:rights>


text:
#ifndef MPI_PHYSICAL_COMMUNICATION_LAYER_H
#define MPI_PHYSICAL_COMMUNICATION_LAYER_H

#include "warped.h"
#include "eclmplCommonInclude.h"
#include "PhysicalCommunicationLayer.h"
#include "MPIMessage.h"

/** The MPIPhysicalCommunicationLayer class.

*/
class MPIPhysicalCommunicationLayer : public PhysicalCommunicationLayer {
public:
    /**@name Public Class Methods of MPIPhysicalCommunicationLayer. */
    //@{

    /// Default Constructor.
    MPIPhysicalCommunicationLayer();

    /// Destructor.
    ~MPIPhysicalCommunicationLayer();

    /** Init physical layer.

        MPI_init(argc, argv) is called from this method, as need to be
        done before any other MPI call can be done. Thus, argc and argv
        needs to be passed in to this method.

        @param configuration The simulation configuration being used.
    */
    virtual void physicalInit();

    /** Get the Id of the simulation manager.

        @return Id of the simulation manager.
    */
    int physicalGetId() const;

    /** Send buffer.

        @param buffer Char buffer to send.
        @param size Size of the buffer to send.
    */
    virtual void physicalSend(const SerializedInstance* toSend, unsigned int dest);

    /** Check the MPI-probe to see if there are message to retrieve.

        @return The retrieved message (NULL if no message).
    */
    virtual SerializedInstance* physicalProbeRecv();

    /** Retrieve message into a buffer.

        @param buffer Buffer to which we save the message.
        @param size Size of the buffer.
        @param sizeStatus Was the size of retr. msg > size?
        @return True/False, Was any message retrieved?
    */
    virtual bool physicalProbeRecvBuffer(char* buffer, int size, bool& sizeStatus);

    /// Clean up and call MPI_Finalize.
    void physicalFinalize();

    /** Return how many processes are involved in the communicator.

        @return The number of processes involved in the communicator.
    */
    virtual int physicalGetSize() const;

    //@} // End of Public Class Methods of MPIPhysicalCommunicationLayer.

protected:
    /**@name Protected Class Attributes of MPIPhysicalCommunicationLayer. */
    //@{

    /// Id of the simulation manager.
    int mySimulationManagerID;

    //@} // End of Protected Class Attributes of MPIPhysicalCommunicationLayer.

private:
    /**
       Checks the status of pending sends.  Clears completed sends out of the
       pendingSend vector, and deallocates the resources associated with
       them.
    */
    void checkPendingSends();

    /**
       Does the dirty work of actually starting MPI.
    */
    void startMPI();

    vector<MPIMessage> pendingSends;
    vector<MPIMessage> pendingReceives;
};

#endif


text:
using NUnit.Framework;
using System;
using Symbooglix;
using Symbooglix.Solver;

namespace SymbooglixLibTests
{
    [TestFixture()]
    public class TerminationReporting : SymbooglixTest
    {
        public TerminationCounter Counter;

        public void InitAndRun(string program)
        {
            Counter = new TerminationCounter();
            p = LoadProgramFrom(program);
            e = GetExecutor(p, new DFSStateScheduler(), GetSolver());
            Counter.Connect(e);

            try
            {
                e.Run(GetMain(p));
            }
            catch (InitialStateTerminated)
            {
                // Ignore this
            }
        }

        [Test()]
        public void FailingAssert()
        {
            InitAndRun("programs/assert_false.bpl");
            Assert.AreEqual(1,Counter.FailingAsserts);
        }

        [Test()]
        public void TerminateWithoutError()
        {
            InitAndRun("programs/assert_true.bpl");
            Assert.AreEqual(0, Counter.FailingAsserts);
            Assert.AreEqual(Counter.Sucesses, 1);
        }

        [Test()]
        public void UnsatAssume()
        {
            InitAndRun("programs/assume_false.bpl");
            Assert.AreEqual(1,Counter.UnsatisfiableAssumes);
        }

        [Test()]
        public void UnsatEntryRequires()
        {
            InitAndRun("programs/UnsatisfiableEntryRequires.bpl");
            Assert.AreEqual(1, Counter.UnsatisfiableRequiresOnEntry);
            Assert.AreEqual(0, Counter.Sucesses);
            Assert.AreEqual(1, Counter.NumberOfFailures);
        }

        [Test()]
        public void FailingRequires()
        {
            InitAndRun("programs/FailingRequires.bpl");
            Assert.AreEqual(1, Counter.FailingRequires);
            Assert.AreEqual(0, Counter.Sucesses);
            Assert.AreEqual(1, Counter.NumberOfFailures);
        }

        [Test()]
        public void FailingEnsures()
        {
            InitAndRun("programs/FailingEnsures.bpl");
            Assert.AreEqual(1, Counter.FailingEnsures);
            Assert.AreEqual(0, Counter.Sucesses);
            Assert.AreEqual(1, Counter.NumberOfFailures);
        }

        [Test()]
        public void UnsatEnsures()
        {
            InitAndRun("programs/UnsatisfiableEnsures.bpl");
            Assert.AreEqual(1, Counter.UnsatisfiableEnsures);
            Assert.AreEqual(0, Counter.Sucesses);
            Assert.AreEqual(1, Counter.NumberOfFailures);
        }

        [Test()]
        public void UnsatAxiom()
        {
            InitAndRun("programs/InconsistentAxioms.bpl");
            Assert.AreEqual(1, Counter.UnsatisfiableAxioms);
            Assert.AreEqual(0, Counter.Sucesses);
            Assert.AreEqual(1, Counter.NumberOfFailures);
        }

        [Test()]
        public void DisallowedSpeculativeExecutionPath()
        {
            p = LoadProgramFrom("programs/TwoPaths.bpl");

            // By using a dummy solver which always returns "UNKNOWN" every path should
            // be consider to be speculative
            e = GetExecutor(p, new DFSStateScheduler(), new SimpleSolver( new DummySolver(Result.UNKNOWN)));

            this.Counter = new TerminationCounter(TerminationCounter.CountType.ONLY_NON_SPECULATIVE);
            var speculativeCounter = new TerminationCounter(TerminationCounter.CountType.ONLY_SPECULATIVE);
            Counter.Connect(e);
            speculativeCounter.Connect(e);

            e.Run(GetMain(p));

            Assert.AreEqual(0, Counter.DisallowedSpeculativePaths);
            Assert.AreEqual(0, Counter.Sucesses);
            Assert.AreEqual(0, Counter.NumberOfFailures);
            Assert.AreEqual(0, Counter.NumberOfTerminatedStates);

            Assert.AreEqual(2, speculativeCounter.DisallowedSpeculativePaths);
            Assert.AreEqual(0, speculativeCounter.Sucesses);
            Assert.AreEqual(0, speculativeCounter.NumberOfFailures);
            Assert.AreEqual(2, speculativeCounter.NumberOfTerminatedStates);
        }

        [Test()]
        public void UnexplorableGotos()
        {
            p = LoadProgramFrom("programs/GotoUnsatTargets.bpl");
            e = GetExecutor(p, new DFSStateScheduler(), GetSolver());
            e.UseGotoLookAhead = true;

            var counter = new TerminationCounter();
            counter.Connect(e);
            e.Run(GetMain(p));

            Assert.AreEqual(0, counter.Sucesses);
            Assert.AreEqual(1, counter.UnexplorableGotos);
        }

        [Test()]
        public void UnsatUniqueAttribute()
        {
            p = LoadProgramFrom(@"
                const unique a:int;
                const unique b:int;
                axiom a == b;

                procedure main()
                {
                    var x:int;
                    x := a;
                }

            ", "test.bpl");

            var counter = new TerminationCounter();
            e = GetExecutor(p, new DFSStateScheduler(), GetSolver());
            counter.Connect(e);

            bool initialStateTerminated = false;
            try
            {
                e.Run(GetMain(p));
            }
            catch (InitialStateTerminated)
            {
                initialStateTerminated = true;
            }

            Assert.AreEqual(0, counter.Sucesses);
            Assert.AreEqual(1, counter.UnsatsifiableUniqueConstants);
            Assert.AreEqual(1, counter.NumberOfFailures);
            Assert.AreEqual(1, counter.NumberOfTerminatedStates);
            Assert.IsTrue(initialStateTerminated);
        }
    }
}


text:
package org.xwalk.embedding.base;

import org.chromium.content.browser.test.util.CallbackHelper;

public class OnDocumentLoadedInFrameHelper extends CallbackHelper{

    private long mFrameId;

    public long getFrameId() {
        assert getCallCount() > 0;
        return mFrameId;
    }

    public void notifyCalled(long frameId) {
        mFrameId = frameId;
        notifyCalled();
    }
}


text:
using namespace gpos;
using namespace gpdxl;

//---------------------------------------------------------------------------
//	@function:
//		CDXLPhysicalExternalScan::CDXLPhysicalExternalScan
//
//	@doc:
//		Ctor
//
//---------------------------------------------------------------------------
CDXLPhysicalExternalScan::CDXLPhysicalExternalScan(CMemoryPool *mp)
	: CDXLPhysicalTableScan(mp)
{
}

//---------------------------------------------------------------------------
//	@function:
//		CDXLPhysicalExternalScan::CDXLPhysicalExternalScan
//
//	@doc:
//		Ctor
//
//---------------------------------------------------------------------------
CDXLPhysicalExternalScan::CDXLPhysicalExternalScan(CMemoryPool *mp,
												   CDXLTableDescr *table_descr)
	: CDXLPhysicalTableScan(mp, table_descr)
{
}

//---------------------------------------------------------------------------
//	@function:
//		CDXLPhysicalExternalScan::GetDXLOperator
//
//	@doc:
//		Operator type
//
//---------------------------------------------------------------------------
Edxlopid
CDXLPhysicalExternalScan::GetDXLOperator() const
{
	return EdxlopPhysicalExternalScan;
}

//---------------------------------------------------------------------------
//	@function:
//		CDXLPhysicalExternalScan::GetOpNameStr
//
//	@doc:
//		Operator name
//
//---------------------------------------------------------------------------
const CWStringConst *
CDXLPhysicalExternalScan::GetOpNameStr() const
{
	return CDXLTokens::GetDXLTokenStr(EdxltokenPhysicalExternalScan);
}

// EOF


text:
package org.assertj.core.api.iterable;

import java.util.function.Predicate;

import org.assertj.core.api.ConcreteIterableAssert;
import org.assertj.core.api.IterableAssertBaseTest;
import org.assertj.core.presentation.PredicateDescription;
import org.junit.Before;

import static org.mockito.Mockito.verify;

public class IterableAssert_allMatch_with_description_Test extends IterableAssertBaseTest {

  private Predicate<Object> predicate;

  @Before
  public void beforeOnce() {
    predicate = o -> o != null;
  }

  @Override
  protected ConcreteIterableAssert<Object> invoke_api_method() {
    return assertions.allMatch(predicate, "custom");
  }

  @Override
  protected void verify_internal_effects() {
    verify(iterables)
      .assertAllMatch(getInfo(assertions), getActual(assertions), predicate, new PredicateDescription("custom"));
  }
}


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Mono.Debugging.Client;

namespace Mono.Debugger.Client.Commands
{
    sealed class BreakpointCommand : MultiCommand
    {
        sealed class BreakpointAddCommand : MultiCommand
        {
            sealed class BreakpointAddLocationCommand : Command
            {
                public override string[] Names
                {
                    get { return new[] { "location", "at" }; }
                }

                public override string Summary
                {
                    get { return "Add a breakpoint at a source location."; }
                }

                public override string Syntax
                {
                    get { return "break|bp add location <file> <line>"; }
                }

                public override string Help
                {
                    get
                    {
                        return "Adds a breakpoint to the specified source location.\n" +
                               "\n" +
                               "This is a 'normal' breakpoint associated with a file name and line\n" +
                               "which can have an optional condition expression.";
                    }
                }

                public override void Process(string args)
                {
                    var splitArgs = args.Split(' ').Where(x => x != string.Empty);
                    var count = splitArgs.Count();

                    if (count == 0)
                    {
                        Log.Error("No file name given");
                        return;
                    }

                    if (count == 1)
                    {
                        Log.Error("No line number given");
                        return;
                    }

                    var lineStr = splitArgs.Last();

                    int line;

                    if (!int.TryParse(lineStr, out line))
                    {
                        Log.Error("Invalid line number");
                        return;
                    }

                    var file = new string(args.Take(args.Length - lineStr.Length).ToArray()).Trim();

                    try
                    {
                        file = Path.GetFullPath(file);
                    }
                    catch (Exception ex)
                    {
                        Log.Info("Could not compute absolute path of '{0}':");
                        Log.Info(ex.ToString());

                        return;
                    }

                    foreach (var be in Debugger.Breakpoints)
                    {
                        var bp = be.Value as Breakpoint;

                        if (bp == null)
                            continue;

                        if (bp.FileName == file && bp.Line == line)
                        {
                            Log.Error("A breakpoint at '{0}:{1}' already exists ('{2}')", file, line, be.Key);
                            return;
                        }
                    }

                    var id = Debugger.GetBreakpointId();

                    Debugger.Breakpoints.Add(id, Debugger.BreakEvents.Add(file, line));

                    Log.Info("Breakpoint '{0}' added at '{1}:{2}'", id, file, line);
                }
            }

            sealed class BreakpointAddMethodCommand : Command
            {
                public override string[] Names
                {
                    get { return new[] { "method", "function" }; }
                }

                public override string Summary
                {
                    get { return "Add a breakpoint at a method."; }
                }

                public override string Syntax
                {
                    get { return "break|bp add method|function <name>"; }
                }

                public override string Help
                {
                    get
                    {
                        return "Adds a breakpoint at the specified method.\n" +
                               "\n" +
                               "A breakpint of this type has no location or condition; it simply\n" +
                               "triggers whenever execution enters the specified method.";
                    }
                }

                public override void Process(string args)
                {
                    if (args.Length == 0)
                    {
                        Log.Error("No method name given");
                        return;
                    }

                    foreach (var be in Debugger.Breakpoints)
                    {
                        if (!(be.Value is FunctionBreakpoint))
                            continue;

                        if (((FunctionBreakpoint)be.Value).FunctionName == args)
                        {
                            Log.Error("A method breakpoint for '{0}' already exists ('{1}')", args, be.Key);
                            return;
                        }
                    }

                    // TODO: Parameter types too.

                    var id = Debugger.GetBreakpointId();
                    var fbp = new FunctionBreakpoint(args, "C#");

                    Debugger.Breakpoints.Add(id, fbp);
                    Debugger.BreakEvents.Add(fbp);

                    Log.Info("Breakpoint '{0}' added for method '{1}'", id, args);
                }
            }

            public BreakpointAddCommand()
            {
                AddCommand<BreakpointAddLocationCommand>();
                AddCommand<BreakpointAddMethodCommand>();
            }

            public override string[] Names
            {
                get { return new[] { "add" }; }
            }

            public override string Summary
            {
                get { return "Add a breakpoint at a location or method."; }
            }

            public override string Help
            {
                get
                {
                    return "Adds a breakpoint at a source location or method entry.\n" +
                           "\n" +
                           "Breakpoints are initially toggled on when added.";
                }
            }

            public override string Parent
            {
                get { return "break"; }
            }
        }

        sealed class BreakpointClearCommand : Command
        {
            public override string[] Names
            {
                get { return new[] { "clear" }; }
            }

            public override string Summary
            {
                get { return "Clear all breakpoints."; }
            }

            public override string Syntax
            {
                get { return "break|bp clear"; }
            }

            public override string Help
            {
                get
                {
                    return "Removes all breakpoints.";
                }
            }

            public override void Process(string args)
            {
                Debugger.Breakpoints.Clear();
                Debugger.BreakEvents.ClearBreakpoints();

                Log.Info("All breakpoints cleared");
            }
        }

        sealed class BreakpointConditionCommand : Command
        {
            public override string[] Names
            {
                get { return new[] { "condition", "expression" }; }
            }

            public override string Summary
            {
                get { return "Set a conditional expression for a breakpoint."; }
            }

            public override string Syntax
            {
                get { return "break|bp condition|expression <id> [expr]"; }
            }

            public override string Help
            {
                get
                {
                    return "Without any expression argument, unsets the condition for the given\n" +
                           "breakpoint. If an expression is given, the breakpoint's condition is\n" +
                           "set to that value, such that it will only trigger if the condition\n" +
                           "evaluates to true.";
                }
            }

            public override void Process(string args)
            {
                var id = args.Split(' ').Where(x => x != string.Empty).FirstOrDefault();

                if (id == null)
                {
                    Log.Error("No breakpoint ID given");
                    return;
                }

                long num;

                if (!long.TryParse(id, out num))
                {
                    Log.Error("Invalid breakpoint ID");
                    return;
                }

                BreakEvent b;

                if (!Debugger.Breakpoints.TryGetValue(num, out b))
                {
                    Log.Error("Breakpoint '{0}' not found", num);
                    return;
                }

                if (b is FunctionBreakpoint)
                {
                    Log.Error("Breakpoint '{0}' is a method breakpoint", num);
                    return;
                }

                var expr = new string(args.Skip(id.Length).ToArray()).Trim();

                var bp = (Breakpoint)b;
                var was = bp.ConditionExpression != null ?
                          string.Format(" (was '{0}')", bp.ConditionExpression) :
                          string.Empty;

                if (expr.Length == 0)
                {
                    bp.ConditionExpression = null;

                    Log.Info("Condition for breakpoint '{0}' unset{1}", num, was);
                }
                else
                {
                    bp.ConditionExpression = expr;

                    Log.Info("Condition for breakpoint '{0}' set to '{1}'{2}", num, expr, was);
                }
            }
        }

        sealed class BreakpointDeleteCommand : Command
        {
            public override string[] Names
            {
                get { return new[] { "delete", "remove" }; }
            }

            public override string Summary
            {
                get { return "Delete a breakpoint by ID."; }
            }

            public override string Syntax
            {
                get { return "break|bp delete|remove <id>"; }
            }

            public override string Help
            {
                get
                {
                    return "Deletes the breakpoint with the specified ID, if it exists.";
                }
            }

            public override void Process(string args)
            {
                long num;

                if (!long.TryParse(args, out num))
                {
                    Log.Error("Invalid breakpoint ID");
                    return;
                }

                BreakEvent b;

                if (!Debugger.Breakpoints.TryGetValue(num, out b))
                {
                    Log.Error("Breakpoint '{0}' not found", num);
                    return;
                }

                Debugger.Breakpoints.Remove(num);
                Debugger.BreakEvents.Remove(b);

                Log.Info("Breakpoint '{0}' deleted", num);
            }
        }

        sealed class BreakpointListCommand : Command
        {
            public override string[] Names
            {
                get { return new[] { "list" }; }
            }

            public override string Summary
            {
                get { return "List all set breakpoints and their IDs."; }
            }

            public override string Syntax
            {
                get { return "break|bp list"; }
            }

            public override string Help
            {
                get
                {
                    return "Lists all breakpoints, along with their IDs and settings.";
                }
            }

            public override void Process(string args)
            {
                if (Debugger.Breakpoints.Count == 0)
                {
                    Log.Info("No breakpoints");
                    return;
                }

                foreach (var pair in Debugger.Breakpoints)
                {
                    var bp = pair.Value as Breakpoint;
                    var fbp = pair.Value as FunctionBreakpoint;

                    var at = fbp != null ? fbp.FunctionName : string.Format("{0}:{1}", bp.FileName, bp.Line);
                    var expr = bp != null && bp.ConditionExpression != null ?
                               string.Format(" '{0}'", bp.ConditionExpression) :
                               string.Empty;

                    // TODO: Parameter types too.

                    Log.Info("#{0} '{1}'{2}", pair.Key, at, expr);
                }
            }
        }

        sealed class BreakpointToggleCommand : Command
        {
            public override string[] Names
            {
                get { return new[] { "toggle" }; }
            }

            public override string Summary
            {
                get { return "Toggle a breakpoint on/off."; }
            }

            public override string Syntax
            {
                get { return "break|bp toggle <id>"; }
            }

            public override string Help
            {
                get
                {
                    return "Toggles a breakpint on or off.\n" +
                           "\n" +
                           "Toggling a breakpoint off keeps it in the breakpoint list but makes it\n" +
                           "not actually trigger, regardless of its type or condition.";
                }
            }

            public override void Process(string args)
            {
                long num;

                if (!long.TryParse(args, out num))
                {
                    Log.Error("Invalid breakpoint ID");
                    return;
                }

                BreakEvent b;

                if (!Debugger.Breakpoints.TryGetValue(num, out b))
                {
                    Log.Error("Breakpoint '{0}' not found", num);
                    return;
                }

                if (Debugger.BreakEvents.Contains(b))
                {
                    Debugger.BreakEvents.Remove(b);

                    Log.Info("Breakpoint '{0}' disabled", num);
                }
                else
                {
                    Debugger.BreakEvents.Add(b);

                    Log.Info("Breakpoint '{0}' enabled", num);
                }
            }
        }

        public BreakpointCommand()
        {
            AddCommand<BreakpointAddCommand>();
            AddCommand<BreakpointClearCommand>();
            AddCommand<BreakpointConditionCommand>();
            AddCommand<BreakpointDeleteCommand>();
            AddCommand<BreakpointListCommand>();
            AddCommand<BreakpointToggleCommand>();

            Forward<BreakpointListCommand>();
        }

        public override string[] Names
        {
            get { return new[] { "breakpoint", "bp" }; }
        }

        public override string Summary
        {
            get { return "Add, delete, and show breakpoints."; }
        }

        public override string Help
        {
            get
            {
                return "Manipulates breakpoints.\n" +
                       "\n" +
                       "Breakpoints can be set at specific lines of source files or on the entry of\n" +
                       "managed methods. Non-method breakpoints can also have conditions set such\n" +
                       "that they only cause the debugger to break if the condition is true.";
            }
        }
    }
}


text:
<?php

// @codingStandardsIgnoreFile

namespace Magento\Sales\Test\Unit\Block\Order\Email\Items;

class DefaultItemsTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Sales\Block\Order\Email\Items\DefaultItem
     */
    protected $block;

    /**
     * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Backend\Block\Template
     */
    protected $priceRenderBlock;

    /**
     * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\View\Layout
     */
    protected $layoutMock;

    /**
     * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager
     */
    protected $objectManager;

    /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Quote\Model\Quote\Item  */
    protected $itemMock;

    /**
     * Initialize required data
     */
    protected function setUp()
    {
        $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this);

        $this->layoutMock = $this->getMockBuilder('\Magento\Framework\View\Layout')
            ->disableOriginalConstructor()
            ->setMethods(['getBlock'])
            ->getMock();

        $this->block = $this->objectManager->getObject(
            'Magento\Sales\Block\Order\Email\Items\DefaultItems',
            [
                'context' => $this->objectManager->getObject(
                        'Magento\Backend\Block\Template\Context',
                        ['layout' => $this->layoutMock]
                    )
            ]
        );

        $this->priceRenderBlock = $this->getMockBuilder('\Magento\Backend\Block\Template')
            ->disableOriginalConstructor()
            ->setMethods(['setItem', 'toHtml'])
            ->getMock();

        $this->itemMock = $this->getMockBuilder('\Magento\Sales\Model\Order\Item')
            ->disableOriginalConstructor()
            ->setMethods(['__wakeup'])
            ->getMock();
    }

    public function testGetItemPrice()
    {
        $html = '$34.28';

        $this->layoutMock->expects($this->once())
            ->method('getBlock')
            ->with('item_price')
            ->will($this->returnValue($this->priceRenderBlock));

        $this->priceRenderBlock->expects($this->once())
            ->method('setItem')
            ->with($this->itemMock);

        $this->priceRenderBlock->expects($this->once())
            ->method('toHtml')
            ->will($this->returnValue($html));

        $this->assertEquals($html, $this->block->getItemPrice($this->itemMock));
    }
}


text:
using namespace llvm;

// Pin the vtable to this file.
void MachineRegisterInfo::Delegate::anchor() {}

MachineRegisterInfo::MachineRegisterInfo(const TargetMachine &TM)
  : TM(TM), TheDelegate(0), IsSSA(true), TracksLiveness(true) {
  VRegInfo.reserve(256);
  RegAllocHints.reserve(256);
  UsedRegUnits.resize(getTargetRegisterInfo()->getNumRegUnits());
  UsedPhysRegMask.resize(getTargetRegisterInfo()->getNumRegs());

  // Create the physreg use/def lists.
  PhysRegUseDefLists =
    new MachineOperand*[getTargetRegisterInfo()->getNumRegs()];
  memset(PhysRegUseDefLists, 0,
         sizeof(MachineOperand*)*getTargetRegisterInfo()->getNumRegs());
}

MachineRegisterInfo::~MachineRegisterInfo() {
  delete [] PhysRegUseDefLists;
}

/// setRegClass - Set the register class of the specified virtual register.
///
void
MachineRegisterInfo::setRegClass(unsigned Reg, const TargetRegisterClass *RC) {
  assert(RC && RC->isAllocatable() && "Invalid RC for virtual register");
  VRegInfo[Reg].first = RC;
}

const TargetRegisterClass *
MachineRegisterInfo::constrainRegClass(unsigned Reg,
                                       const TargetRegisterClass *RC,
                                       unsigned MinNumRegs) {
  const TargetRegisterClass *OldRC = getRegClass(Reg);
  if (OldRC == RC)
    return RC;
  const TargetRegisterClass *NewRC =
    getTargetRegisterInfo()->getCommonSubClass(OldRC, RC);
  if (!NewRC || NewRC == OldRC)
    return NewRC;
  if (NewRC->getNumRegs() < MinNumRegs)
    return 0;
  setRegClass(Reg, NewRC);
  return NewRC;
}

bool
MachineRegisterInfo::recomputeRegClass(unsigned Reg, const TargetMachine &TM) {
  const TargetInstrInfo *TII = TM.getInstrInfo();
  const TargetRegisterClass *OldRC = getRegClass(Reg);
  const TargetRegisterClass *NewRC =
    getTargetRegisterInfo()->getLargestLegalSuperClass(OldRC);

  // Stop early if there is no room to grow.
  if (NewRC == OldRC)
    return false;

  // Accumulate constraints from all uses.
  for (reg_nodbg_iterator I = reg_nodbg_begin(Reg), E = reg_nodbg_end(); I != E;
       ++I) {
    const TargetRegisterClass *OpRC =
      I->getRegClassConstraint(I.getOperandNo(), TII,
                               getTargetRegisterInfo());
    if (unsigned SubIdx = I.getOperand().getSubReg()) {
      if (OpRC)
        NewRC = getTargetRegisterInfo()->getMatchingSuperRegClass(NewRC, OpRC,
                                                                  SubIdx);
      else
        NewRC = getTargetRegisterInfo()->getSubClassWithSubReg(NewRC, SubIdx);
    } else if (OpRC)
      NewRC = getTargetRegisterInfo()->getCommonSubClass(NewRC, OpRC);
    if (!NewRC || NewRC == OldRC)
      return false;
  }
  setRegClass(Reg, NewRC);
  return true;
}

/// createVirtualRegister - Create and return a new virtual register in the
/// function with the specified register class.
///
unsigned
MachineRegisterInfo::createVirtualRegister(const TargetRegisterClass *RegClass){
  assert(RegClass && "Cannot create register without RegClass!");
  assert(RegClass->isAllocatable() &&
         "Virtual register RegClass must be allocatable.");

  // New virtual register number.
  unsigned Reg = TargetRegisterInfo::index2VirtReg(getNumVirtRegs());
  VRegInfo.grow(Reg);
  VRegInfo[Reg].first = RegClass;
  RegAllocHints.grow(Reg);
  if (TheDelegate)
    TheDelegate->MRI_NoteNewVirtualRegister(Reg);
  return Reg;
}

/// clearVirtRegs - Remove all virtual registers (after physreg assignment).
void MachineRegisterInfo::clearVirtRegs() {
#ifndef NDEBUG
  for (unsigned i = 0, e = getNumVirtRegs(); i != e; ++i) {
    unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
    if (!VRegInfo[Reg].second)
      continue;
    verifyUseList(Reg);
    llvm_unreachable("Remaining virtual register operands");
  }
#endif
  VRegInfo.clear();
}

void MachineRegisterInfo::verifyUseList(unsigned Reg) const {
#ifndef NDEBUG
  bool Valid = true;
  for (reg_iterator I = reg_begin(Reg), E = reg_end(); I != E; ++I) {
    MachineOperand *MO = &I.getOperand();
    MachineInstr *MI = MO->getParent();
    if (!MI) {
      errs() << PrintReg(Reg, getTargetRegisterInfo())
             << " use list MachineOperand " << MO
             << " has no parent instruction.\n";
      Valid = false;
    }
    MachineOperand *MO0 = &MI->getOperand(0);
    unsigned NumOps = MI->getNumOperands();
    if (!(MO >= MO0 && MO < MO0+NumOps)) {
      errs() << PrintReg(Reg, getTargetRegisterInfo())
             << " use list MachineOperand " << MO
             << " doesn't belong to parent MI: " << *MI;
      Valid = false;
    }
    if (!MO->isReg()) {
      errs() << PrintReg(Reg, getTargetRegisterInfo())
             << " MachineOperand " << MO << ": " << *MO
             << " is not a register\n";
      Valid = false;
    }
    if (MO->getReg() != Reg) {
      errs() << PrintReg(Reg, getTargetRegisterInfo())
             << " use-list MachineOperand " << MO << ": "
             << *MO << " is the wrong register\n";
      Valid = false;
    }
  }
  assert(Valid && "Invalid use list");
#endif
}

void MachineRegisterInfo::verifyUseLists() const {
#ifndef NDEBUG
  for (unsigned i = 0, e = getNumVirtRegs(); i != e; ++i)
    verifyUseList(TargetRegisterInfo::index2VirtReg(i));
  for (unsigned i = 1, e = getTargetRegisterInfo()->getNumRegs(); i != e; ++i)
    verifyUseList(i);
#endif
}

/// Add MO to the linked list of operands for its register.
void MachineRegisterInfo::addRegOperandToUseList(MachineOperand *MO) {
  assert(!MO->isOnRegUseList() && "Already on list");
  MachineOperand *&HeadRef = getRegUseDefListHead(MO->getReg());
  MachineOperand *const Head = HeadRef;

  // Head points to the first list element.
  // Next is NULL on the last list element.
  // Prev pointers are circular, so Head->Prev == Last.

  // Head is NULL for an empty list.
  if (!Head) {
    MO->Contents.Reg.Prev = MO;
    MO->Contents.Reg.Next = 0;
    HeadRef = MO;
    return;
  }
  assert(MO->getReg() == Head->getReg() && "Different regs on the same list!");

  // Insert MO between Last and Head in the circular Prev chain.
  MachineOperand *Last = Head->Contents.Reg.Prev;
  assert(Last && "Inconsistent use list");
  assert(MO->getReg() == Last->getReg() && "Different regs on the same list!");
  Head->Contents.Reg.Prev = MO;
  MO->Contents.Reg.Prev = Last;

  // Def operands always precede uses. This allows def_iterator to stop early.
  // Insert def operands at the front, and use operands at the back.
  if (MO->isDef()) {
    // Insert def at the front.
    MO->Contents.Reg.Next = Head;
    HeadRef = MO;
  } else {
    // Insert use at the end.
    MO->Contents.Reg.Next = 0;
    Last->Contents.Reg.Next = MO;
  }
}

/// Remove MO from its use-def list.
void MachineRegisterInfo::removeRegOperandFromUseList(MachineOperand *MO) {
  assert(MO->isOnRegUseList() && "Operand not on use list");
  MachineOperand *&HeadRef = getRegUseDefListHead(MO->getReg());
  MachineOperand *const Head = HeadRef;
  assert(Head && "List already empty");

  // Unlink this from the doubly linked list of operands.
  MachineOperand *Next = MO->Contents.Reg.Next;
  MachineOperand *Prev = MO->Contents.Reg.Prev;

  // Prev links are circular, next link is NULL instead of looping back to Head.
  if (MO == Head)
    HeadRef = Next;
  else
    Prev->Contents.Reg.Next = Next;

  (Next ? Next : Head)->Contents.Reg.Prev = Prev;

  MO->Contents.Reg.Prev = 0;
  MO->Contents.Reg.Next = 0;
}

/// Move NumOps operands from Src to Dst, updating use-def lists as needed.
///
/// The Dst range is assumed to be uninitialized memory. (Or it may contain
/// operands that won't be destroyed, which is OK because the MO destructor is
/// trivial anyway).
///
/// The Src and Dst ranges may overlap.
void MachineRegisterInfo::moveOperands(MachineOperand *Dst,
                                       MachineOperand *Src,
                                       unsigned NumOps) {
  assert(Src != Dst && NumOps && "Noop moveOperands");

  // Copy backwards if Dst is within the Src range.
  int Stride = 1;
  if (Dst >= Src && Dst < Src + NumOps) {
    Stride = -1;
    Dst += NumOps - 1;
    Src += NumOps - 1;
  }

  // Copy one operand at a time.
  do {
    new (Dst) MachineOperand(*Src);

    // Dst takes Src's place in the use-def chain.
    if (Src->isReg()) {
      MachineOperand *&Head = getRegUseDefListHead(Src->getReg());
      MachineOperand *Prev = Src->Contents.Reg.Prev;
      MachineOperand *Next = Src->Contents.Reg.Next;
      assert(Head && "List empty, but operand is chained");
      assert(Prev && "Operand was not on use-def list");

      // Prev links are circular, next link is NULL instead of looping back to
      // Head.
      if (Src == Head)
        Head = Dst;
      else
        Prev->Contents.Reg.Next = Dst;

      // Update Prev pointer. This also works when Src was pointing to itself
      // in a 1-element list. In that case Head == Dst.
      (Next ? Next : Head)->Contents.Reg.Prev = Dst;
    }

    Dst += Stride;
    Src += Stride;
  } while (--NumOps);
}

/// replaceRegWith - Replace all instances of FromReg with ToReg in the
/// machine function.  This is like llvm-level X->replaceAllUsesWith(Y),
/// except that it also changes any definitions of the register as well.
void MachineRegisterInfo::replaceRegWith(unsigned FromReg, unsigned ToReg) {
  assert(FromReg != ToReg && "Cannot replace a reg with itself");

  // TODO: This could be more efficient by bulk changing the operands.
  for (reg_iterator I = reg_begin(FromReg), E = reg_end(); I != E; ) {
    MachineOperand &O = I.getOperand();
    ++I;
    O.setReg(ToReg);
  }
}

/// getVRegDef - Return the machine instr that defines the specified virtual
/// register or null if none is found.  This assumes that the code is in SSA
/// form, so there should only be one definition.
MachineInstr *MachineRegisterInfo::getVRegDef(unsigned Reg) const {
  // Since we are in SSA form, we can use the first definition.
  def_iterator I = def_begin(Reg);
  assert((I.atEnd() || llvm::next(I) == def_end()) &&
         "getVRegDef assumes a single definition or no definition");
  return !I.atEnd() ? &*I : 0;
}

/// getUniqueVRegDef - Return the unique machine instr that defines the
/// specified virtual register or null if none is found.  If there are
/// multiple definitions or no definition, return null.
MachineInstr *MachineRegisterInfo::getUniqueVRegDef(unsigned Reg) const {
  if (def_empty(Reg)) return 0;
  def_iterator I = def_begin(Reg);
  if (llvm::next(I) != def_end())
    return 0;
  return &*I;
}

bool MachineRegisterInfo::hasOneNonDBGUse(unsigned RegNo) const {
  use_nodbg_iterator UI = use_nodbg_begin(RegNo);
  if (UI == use_nodbg_end())
    return false;
  return ++UI == use_nodbg_end();
}

/// clearKillFlags - Iterate over all the uses of the given register and
/// clear the kill flag from the MachineOperand. This function is used by
/// optimization passes which extend register lifetimes and need only
/// preserve conservative kill flag information.
void MachineRegisterInfo::clearKillFlags(unsigned Reg) const {
  for (use_iterator UI = use_begin(Reg), UE = use_end(); UI != UE; ++UI)
    UI.getOperand().setIsKill(false);
}

bool MachineRegisterInfo::isLiveIn(unsigned Reg) const {
  for (livein_iterator I = livein_begin(), E = livein_end(); I != E; ++I)
    if (I->first == Reg || I->second == Reg)
      return true;
  return false;
}

/// getLiveInPhysReg - If VReg is a live-in virtual register, return the
/// corresponding live-in physical register.
unsigned MachineRegisterInfo::getLiveInPhysReg(unsigned VReg) const {
  for (livein_iterator I = livein_begin(), E = livein_end(); I != E; ++I)
    if (I->second == VReg)
      return I->first;
  return 0;
}

/// getLiveInVirtReg - If PReg is a live-in physical register, return the
/// corresponding live-in physical register.
unsigned MachineRegisterInfo::getLiveInVirtReg(unsigned PReg) const {
  for (livein_iterator I = livein_begin(), E = livein_end(); I != E; ++I)
    if (I->first == PReg)
      return I->second;
  return 0;
}

/// EmitLiveInCopies - Emit copies to initialize livein virtual registers
/// into the given entry block.
void
MachineRegisterInfo::EmitLiveInCopies(MachineBasicBlock *EntryMBB,
                                      const TargetRegisterInfo &TRI,
                                      const TargetInstrInfo &TII) {
  // Emit the copies into the top of the block.
  for (unsigned i = 0, e = LiveIns.size(); i != e; ++i)
    if (LiveIns[i].second) {
      if (use_empty(LiveIns[i].second)) {
        // The livein has no uses. Drop it.
        //
        // It would be preferable to have isel avoid creating live-in
        // records for unused arguments in the first place, but it's
        // complicated by the debug info code for arguments.
        LiveIns.erase(LiveIns.begin() + i);
        --i; --e;
      } else {
        // Emit a copy.
        BuildMI(*EntryMBB, EntryMBB->begin(), DebugLoc(),
                TII.get(TargetOpcode::COPY), LiveIns[i].second)
          .addReg(LiveIns[i].first);

        // Add the register to the entry block live-in set.
        EntryMBB->addLiveIn(LiveIns[i].first);
      }
    } else {
      // Add the register to the entry block live-in set.
      EntryMBB->addLiveIn(LiveIns[i].first);
    }
}

#ifndef NDEBUG
void MachineRegisterInfo::dumpUses(unsigned Reg) const {
  for (use_iterator I = use_begin(Reg), E = use_end(); I != E; ++I)
    I.getOperand().getParent()->dump();
}
#endif

void MachineRegisterInfo::freezeReservedRegs(const MachineFunction &MF) {
  ReservedRegs = getTargetRegisterInfo()->getReservedRegs(MF);
  assert(ReservedRegs.size() == getTargetRegisterInfo()->getNumRegs() &&
         "Invalid ReservedRegs vector from target");
}

bool MachineRegisterInfo::isConstantPhysReg(unsigned PhysReg,
                                            const MachineFunction &MF) const {
  assert(TargetRegisterInfo::isPhysicalRegister(PhysReg));

  // Check if any overlapping register is modified, or allocatable so it may be
  // used later.
  for (MCRegAliasIterator AI(PhysReg, getTargetRegisterInfo(), true);
       AI.isValid(); ++AI)
    if (!def_empty(*AI) || isAllocatable(*AI))
      return false;
  return true;
}


text:
import time
from rspy.stopwatch import Stopwatch

# A timer counting backwards in time(vs forwards in the `stopwatch` class )
# It supply basic timer API, start, has_expired..
class Timer:

    _delta = 0
    _sw = Stopwatch()

    def __init__(self, timeout_in_sec):
        self._delta = timeout_in_sec

    # Start timer
    def start(self):
        self._sw.reset()

    # Check if timer time expired
    def has_expired(self):
        return self._sw.get_elapsed() >= self._delta

    # Force time expiration
    def set_expired(self):
        self._sw.reset(time.perf_counter() - (self._delta + 0.00001))


text:
package comlib.adk.launcher.option;

import rescuecore2.config.Config;

public abstract class Option {

    public abstract String getKey();

    public abstract void setValue(Config config, String[] datas);
}


text:
module Moneybird
  module HttpError
    class PaymentRequired < Faraday::Error
    end
  end
end


text:
All notable changes to this project will be documented in this file. SPTDataLoader adheres to [Semantic Versioning](http://semver.org/).

--

## [2.2.0](https://github.com/spotify/SPTDataLoader/releases/tag/2.2.0)
_Released on 2022-06-02._

### Added
* Added SPTDataLoaderSwift convenience methods for accessing active requests
* Added SPTDataLoaderSwift response code validators
* Added SPTDataLoaderSwift wrappers for Concurrency and Combine
* Added Xcode 13 support

### Fixed
* Fixed invalid response body for retried requests

### Changed
* Changed SPTDataLoaderSwift to ignore status code related errors by default
* Changed SPTDataLoaderSwift to allow throwing errors within a request modifier
* Changed chunked responses to use the unenumerated data

## [2.1.1](https://github.com/spotify/SPTDataLoader/releases/tag/2.1.1)
_Released on 2021-02-17._

### Changed
* Standardized deployment targets across project

## [2.1.0](https://github.com/spotify/SPTDataLoader/releases/tag/2.1.0)
_Released on 2021-02-16._

### Added
* Added SPTDataLoaderBlockWrapper callback API
* Added SPTDataLoaderSwift overlay
* Added Xcode 12 support

### Changed
* Changed Accept-Language header to remove duplicates
* Changed modules to be disabled by default for static library and test targets

## [2.0.0](https://github.com/spotify/SPTDataLoader/releases/tag/2.0.0)
_Released on 2020-07-23._

### Changed
* SPTDataLoaderAuthorizer: requestFailedAuthorisation also accepts SPTDataLoaderResponse (breaking change)
* Fixed multiple issues

## [1.1.1](https://github.com/spotify/SPTDataLoader/releases/tag/1.1.1)
_Released on 2016-02-20._

### Added
* Added support for SSL pinning.
* Added iOS 10 support.

### Fixed
* Fixed nil URLs in the rate limiter causing a crash.
* Fixed requests executing after they have been cancelled due to a race condition.
* Fixed unique identifiers incrementing by 2 on every request made.

### Removed
* Removed iOS 7.0 support.

## [1.1.0](https://github.com/spotify/SPTDataLoader/releases/tag/1.1.0)
_Released on 2016-02-15._

### Added
* Added support for watchOS and tvOS.
* Added error handling when a chunked request is made without the delegate supporting chunks.

### Fixed
* Fixed HTTP errors not being correctly reported if they are not above the 400 HTTP status codes.
* Fixed a bug allowing infinite retries of requests.

### Removed
* Removed the non-optional status of cancellation callbacks in the delegate.

### Changed
* Changed Accept-Language values to be publically accessible.
* Changed blanket HTTPS certificate accepting a runtime variable rather than a preprocessor macro.
* Changed the name of SPTCancellationToken to SPTDataLoaderCancellationToken.

## [1.0.1](https://github.com/spotify/SPTDataLoader/releases/tag/1.0.1)
_Released on 2015-12-22._

### Added
* Added an option to skip NSURLCache.
* Added absolute timeouts regardless of retries.
* Added a build flag option that can allow SPTDataLoader to ignore valid HTTPS certificates.
* Added source identifiers to request objects (for view based tracking of HTTP usage).
* Added support for custom URL protocols.
* Added clang module support.
* Added Accept-Language headers to all requests.
* Added redirection limit.
* Added sending the response rather than the request in the SPTDataLoaderConsumer protocol.

### Fixed
* Fixed a crash that can occur occasionally when copying data from NSURLSession.
* Fixed Xcode 6.2 project warnings.
* Fixed retry timeouts from firing constantly when certain conditions are met.
* Fixed Xcode 6.3 project warnings.
* Fixed crashes that can occur when calling SPTDataLoader from multiple threads.
* Fixed swallowing 401s if retrying is not possible.
* Fixed Xcode 7 warnings.
* Fixed HTTP redirects not working.

## [1.0.0](https://github.com/spotify/SPTDataLoader/releases/tag/1.0.0)
_Released on 2015-02-01._

### Added
* Initial release of SPTDataLoader.


text:
import React from 'react';

import ShowcaseButton from '../showcase-components/showcase-button';
import {
  XYPlot,
  XAxis,
  YAxis,
  VerticalGridLines,
  HorizontalGridLines,
  MarkSeries
} from 'react-vis';

function generateData() {
  return [...new Array(10)].map(() => ({
    x: Math.random() * 5,
    y: Math.random() * 10
  }));
}

const MODE = ['noWobble', 'gentle', 'wobbly', 'stiff'];

export default class Example extends React.Component {
  state = {
    data: generateData(),
    modeIndex: 0
  };

  updateModeIndex = increment => () => {
    const newIndex = this.state.modeIndex + (increment ? 1 : -1);
    const modeIndex =
      newIndex < 0 ? MODE.length - 1 : newIndex >= MODE.length ? 0 : newIndex;
    this.setState({
      modeIndex
    });
  };

  render() {
    const {modeIndex, data} = this.state;
    return (

          <ShowcaseButton
            onClick={this.updateModeIndex(false)}
            buttonContent={'PREV'}
          />

 {`ANIMATION TECHNIQUE: ${MODE[modeIndex]}`}

          <ShowcaseButton
            onClick={this.updateModeIndex(true)}
            buttonContent={'NEXT'}
          />

        <XYPlot width={300} height={300}>
          <VerticalGridLines />
          <HorizontalGridLines />
          <XAxis />
          <YAxis />
          <MarkSeries animation={MODE[modeIndex]} data={data} />
        </XYPlot>
        <ShowcaseButton
          onClick={() => this.setState({data: generateData()})}
          buttonContent={'UPDATE DATA'}
        />

    );
  }
}


text:
/* $Id: ExpirationTester.java 1226141 2011-12-31 17:23:35Z kwright $ */

/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.manifoldcf.filesystem_tests;

import org.apache.manifoldcf.core.interfaces.*;
import org.apache.manifoldcf.agents.interfaces.*;
import org.apache.manifoldcf.crawler.interfaces.*;
import org.apache.manifoldcf.crawler.system.ManifoldCF;

import java.io.*;
import java.util.*;

/** This is a test which checks to see if document expiration works properly. */
public class ExpirationTester
{
  protected org.apache.manifoldcf.crawler.tests.ManifoldCFInstance instance;

  public ExpirationTester(org.apache.manifoldcf.crawler.tests.ManifoldCFInstance instance)
  {
    this.instance = instance;
  }

  public void setupTestArea()
    throws Exception
  {
    File f = new File("testdata");
    FileHelper.removeDirectory(f);
    FileHelper.createDirectory(f);
  }

  public void teardownTestArea()
    throws Exception
  {
    File f = new File("testdata");
    FileHelper.removeDirectory(f);
  }

  public void executeTest()
    throws Exception
  {
    // Hey, we were able to install the file system connector etc.
    // Now, create a local test job and run it.
    IThreadContext tc = ThreadContextFactory.make();

    // Create a basic file system connection, and save it.
    IRepositoryConnectionManager mgr = RepositoryConnectionManagerFactory.make(tc);
    IRepositoryConnection conn = mgr.create();
    conn.setName("File Connection");
    conn.setDescription("File Connection");
    conn.setClassName("org.apache.manifoldcf.crawler.connectors.filesystem.FileConnector");
    conn.setMaxConnections(100);
    // Now, save
    mgr.save(conn);

    // Create a basic null output connection, and save it.
    IOutputConnectionManager outputMgr = OutputConnectionManagerFactory.make(tc);
    IOutputConnection outputConn = outputMgr.create();
    outputConn.setName("Null Connection");
    outputConn.setDescription("Null Connection");
    outputConn.setClassName("org.apache.manifoldcf.agents.output.nullconnector.NullConnector");
    outputConn.setMaxConnections(100);
    // Now, save
    outputMgr.save(outputConn);

    // Create a job.
    IJobManager jobManager = JobManagerFactory.make(tc);
    IJobDescription job = jobManager.createJob();
    job.setDescription("Test Job");
    job.setConnectionName("File Connection");
    job.setOutputConnectionName("Null Connection");
    job.setType(job.TYPE_SPECIFIED);
    job.setStartMethod(job.START_DISABLE);
    job.setHopcountMode(job.HOPCOUNT_ACCURATE);
    // 60-second expiration for all documents..
    job.setExpiration(new Long(60000L));
    // Infinite rescan interval.
    job.setInterval(null);
    // Continuous job.
    job.setType(IJobDescription.TYPE_CONTINUOUS);

    // Now, set up the document specification.
    DocumentSpecification ds = job.getSpecification();
    // Crawl everything underneath the 'testdata' area
    File testDataFile = new File("testdata").getCanonicalFile();
    if (!testDataFile.exists())
      throw new ManifoldCFException("Test data area not found!  Looking in "+testDataFile.toString());
    if (!testDataFile.isDirectory())
      throw new ManifoldCFException("Test data area not a directory!  Looking in "+testDataFile.toString());
    SpecificationNode sn = new SpecificationNode("startpoint");
    sn.setAttribute("path",testDataFile.toString());
    SpecificationNode n = new SpecificationNode("include");
    n.setAttribute("type","file");
    n.setAttribute("match","*");
    sn.addChild(sn.getChildCount(),n);
    n = new SpecificationNode("include");
    n.setAttribute("type","directory");
    n.setAttribute("match","*");
    sn.addChild(sn.getChildCount(),n);
    ds.addChild(ds.getChildCount(),sn);

    // Set up the output specification.
    OutputSpecification os = job.getOutputSpecification();
    // Null output connections have no output specification, so this is a no-op.

    // Save the job.
    jobManager.save(job);

    // Create the test data files.
    FileHelper.createFile(new File("testdata/test1.txt"),"This is a test file");
    FileHelper.createFile(new File("testdata/test2.txt"),"This is another test file");
    FileHelper.createDirectory(new File("testdata/testdir"));
    FileHelper.createFile(new File("testdata/testdir/test3.txt"),"This is yet another test file");
    FileHelper.createDirectory(new File("testdata/testdir/seconddir"));
    FileHelper.createFile(new File("testdata/testdir/seconddir/test4.txt"),"Lowest test file");

    // Now, start the job, and wait until it is running.
    jobManager.manualStart(job.getID());
    instance.waitJobRunningNative(jobManager,job.getID(),30000L);

    JobStatus status;

    // Now we wait, and we should see 7 documents eventually.
    long startTime = System.currentTimeMillis();
    while (System.currentTimeMillis() < startTime + 120000L)
    {
      status = jobManager.getStatus(job.getID());
      if (status.getDocumentsProcessed() == 7)
        break;

      ManifoldCF.sleep(1000L);
    }

    // At this point there should be 7 documents.
    // OK, documents should expire starting a minute later.  The number of documents will go quickly to zero after this time.
    // So all we need to do is confirm that the job stops within 2 minutes.
    instance.waitJobInactiveNative(jobManager,job.getID(),180000L);

    status = jobManager.getStatus(job.getID());
    if (status.getDocumentsProcessed() != 0)
      throw new ManifoldCFException("Wrong number of documents processed - expected 0, saw "+new Long(status.getDocumentsProcessed()).toString());

    // Now, delete the job.
    jobManager.deleteJob(job.getID());
    instance.waitJobDeletedNative(jobManager,job.getID(),120000L);

    // Cleanup is automatic by the base class, so we can feel free to leave jobs and connections lying around.
  }

}


text:
ALTER TABLE `users` ADD INDEX `index_search_nationalcode` (`nationalcode`);
ALTER TABLE `users` ADD INDEX `index_search_pasportcode` (`pasportcode`);


text:
%w[bencode uri yaml erb].each {|lib| require lib}
%w[clogger core_extensions peer torrent request].each {|lib| require File.join($rootdir, "lib", lib)}

module STracker
  class TrackerException < Exception; end

  class Tracker
    attr_reader :tracker_id, :announce_interval, :timeout_interval, :min_announce_interval, :allow_unregistered_torrents, :allow_noncompact, :full_scrape

    def initialize
      config = YAML.load_file File.join($rootdir, "config", "tracker.yaml")
      config[$environment].each { |key, value| instance_variable_set("@#{key}", value) }

      @logger = CustomLogger.new(File.join($rootdir, "log", "tracker.log"), 2, 1024 * 1024 * 2)

      @mongo_uri = ERB.new(@mongo_uri).result
      init_mongo
    end

    def announce(req)
      begin
        request = Request.new(req)

        if @allow_non_compact and not request.compact
          raise TrackerException, "Non-compact response is not supported!"
        end

        torrent = Torrent.find(:one, :conditions => {:_id => request.info_hash}).first

        if torrent.nil?
          if @allow_unregistered_torrents
            @logger.info "Torrent #{request.info_hash} was not in list, added."
            torrent = Torrent.new(:_id => request.info_hash)
          else
            raise TrackerException, "Torrent not in list!"
          end
        end

        torrent.update_torrent(request)

        return "" if request.event == "stopped"

        zombies = torrent.clear_zombies(Time.now - @timeout_interval)
        @logger.info "Torrent had #{zombies} in it, removed them." if zombies > 0

        peers = torrent.get_peers(request.numwant, request.compact)
        @logger.info "Sent #{request.compact ? (peers.size / 6)  : peers.count} peers to #{request.ip} for torrent #{request.info_hash}."

        {"complete" => torrent.seeders,
         "incomplete" => torrent.leechers,
         "interval" => @announce_interval,
         "tracker id" => @tracker_id,
         "min interval" => @min_announce_interval,
         "peers" => peers,
         "downloaded" => torrent.completed}.bencode
      rescue TrackerException => ex
        @logger.info "Request from #{req["ip"]} failed. Reason: #{ex.message}"
        return send_error(ex.message)
      end
    end

    def scrape(params)
      if params.keys.include? "info_hash"
        torrents = [] << Torrent.where(:_id => params["info_hash"].to_hex).only(:seeders, :leechers, :completed).first
      elsif @full_scrape
        torrents = Torrent.only(:seeders, :leechers, :completed)
      else
        return send_error("Full scrape is not permitted!")
      end

      out = {}
      torrents.each do |torrent|
        out.merge!({
          torrent.id.to_bin => {
            "complete" => torrent.seeders,
            "incomplete" => torrent.leechers,
            "downloaded" => torrent.completed
          }
        })
      end

      if not out.empty?
        {"files" => out}.bencode
      else
        send_error("The tracker is empty!")
      end
    end

    def status
      {:torrents => Torrent.all}
    end

    private

    def send_error(msg)
      {"failure reason" => msg}.bencode
    end

    def init_mongo
      Mongoid.configure do |config|
        logger = Logger.new(File.join($rootdir, "log/mongoid.log"), 2, 1024 * 1024 * 2)
        config.master = Mongo::Connection.from_uri(@mongo_uri, :logger => logger).db(URI.parse(@mongo_uri).path.gsub(/^\//, ''))
      end
    end
  end
end


text:
PykCharts.oneD.electionPie = function (options) {
    var that = this;
    that.interval = "";
    var theme = new PykCharts.Configuration.Theme({});

    this.execute = function(pykquery_data) {

        that = new PykCharts.validation.processInputs(that, options, 'oneDimensionalCharts');
        if(options.chart_height || options.chart_height === undefined) {
            try {
                if (options.chart_height === undefined) {
                    options.chart_height = "";
                }
                else if (isNaN(options.chart_height)) {
                    options.chart_height = "";
                    throw "chart_height"
                }
            }
            catch (err) {
                that.k.warningHandling(err);
            }
        }
        if(PykCharts["boolean"](options.chart_height)) {
            that.chart_height = options.chart_height;
            that.calculation = undefined;
            that.height_translate = that.chart_height/2;
        } else {
            that.chart_height = that.chart_width/2;
            that.calculation = "pie";
            that.height_translate = that.chart_height;
        }

        that.pie_radius_percent = options.pie_radius_percent ? options.pie_radius_percent : theme.oneDimensionalCharts.pie_radius_percent;

        try {
            if(isNaN(that.pie_radius_percent)) {
                that.pie_radius_percent = theme.oneDimensionalCharts.pie_radius_percent;
                throw "pie_radius_percent"
            }
        }

        catch (err) {
            that.k.warningHandling(err,"1");
        }

        if(that.stop) {
            return;
        }

        that.k.storeInitialDivHeight();
        if(that.pie_radius_percent > 100) {
            that.pie_radius_percent = 100;
        }
        if(that.mode === "default") {
           that.k.loading();
        }
        that.innerRadiusPercent = 0;

        that.executeData = function (data) {
            var validate = that.k.validator().validatingJSON(data),
                id = that.selector.substring(1,that.selector.length);
            if(that.stop || validate === false) {
                that.k.remove_loading_bar(id);
                return;
            }

            that.data = that.k.__proto__._groupBy("oned",data);
            that.compare_data = that.k.__proto__._groupBy("oned",data);
            that.k.remove_loading_bar(id);
            var pieFunctions = new PykCharts.oneD.pieFunctions(options,that,"election pie");
            that.clubdata_enable = that.data.length > that.clubdata_maximum_nodes ? that.clubdata_enable : "no";
            pieFunctions.render();

        };
        if (PykCharts['boolean'](that.interactive_enable)) {
            that.k.dataFromPykQuery(pykquery_data);
            that.k.dataSourceFormatIdentification(that.data,that,"executeData");
        } else {
            that.k.dataSourceFormatIdentification(options.data,that,"executeData");
        }
    };
};


text:
SELECT JsonArrayUnnest('[1, 2, 3, 4, 5]') OVER ();
SELECT SUM(numbers) FROM (SELECT JsonArrayUnnest('[1, 2, 3, 4, 5]') OVER () AS numbers) AS result;

SELECT JsonArrayUnnest('[1, 2.5, true, false, null, [1, 2, 3], [], {}, { "foo": [3, 4, 5] }]') OVER ();

SELECT JsonArrayUnnest('["foo", "bar", "baz"]') OVER ();
SELECT JsonArrayUnnestStrings('["foo", "bar", "baz"]') OVER ();
SELECT JsonArrayUnnestUnquoted('["foo", "bar", "baz"]') OVER ();

SELECT JsonArrayUnnest('["foo", true, false, "bar"]') OVER ();
SELECT JsonArrayUnnestStrings('["foo", true, false, "bar"]') OVER ();
SELECT JsonArrayUnnestUnquoted('["foo", true, false, "bar"]') OVER ();

SELECT JsonArrayUnnest('["foo", true, 1, 0.1]'::long varchar) OVER ();
SELECT JsonArrayUnnestStrings('["foo", true, 1, 0.1]'::long varchar) OVER ();
SELECT JsonArrayUnnestUnquoted('["foo", true, 1, 0.1]'::long varchar) OVER ();

\set object_json '\'[{ "foo": 4, "bar": true }, { "foo": 8, "bar": false }, { "foo": 16, "bar": true }]\''
SELECT JsonQuery(object, 'foo')
FROM (SELECT JsonArrayUnnest(:object_json) OVER () AS object)
AS selected
WHERE JsonQuery(object, 'bar')::boolean;


text:
package blob

import (
	"fmt"
	"net/http"
	"net/http/httptest"
	"testing"

	"github.com/goharbor/harbor/src/controller/blob"
	"github.com/google/uuid"
	"github.com/stretchr/testify/suite"
)

type PatchBlobUploadMiddlewareTestSuite struct {
	suite.Suite
}

func (suite *PatchBlobUploadMiddlewareTestSuite) TestMiddleware() {
	next := func(rangeHeader string) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			w.WriteHeader(http.StatusAccepted)
			w.Header().Set("Range", rangeHeader)
		})
	}

	sessionID := uuid.New().String()
	path := fmt.Sprintf("/v2/library/photon/blobs/uploads/%s", sessionID)

	req := httptest.NewRequest(http.MethodPatch, path, nil)
	res := httptest.NewRecorder()
	PatchBlobUploadMiddleware()(next("bad value")).ServeHTTP(res, req)
	suite.Equal(http.StatusInternalServerError, res.Code)

	req = httptest.NewRequest(http.MethodPatch, path, nil)
	res = httptest.NewRecorder()
	PatchBlobUploadMiddleware()(next("0-511")).ServeHTTP(res, req)
	suite.Equal(http.StatusAccepted, res.Code)

	size, err := blob.Ctl.GetAcceptedBlobSize(sessionID)
	suite.Nil(err)
	suite.Equal(int64(512), size)
}

func TestPatchBlobUploadMiddlewareTestSuite(t *testing.T) {
	suite.Run(t, &PatchBlobUploadMiddlewareTestSuite{})
}