text:
/**
 *
The MarkLogic Data Movement SDK supports long-running write, read,
 * delete, or transform jobs.  Long-running write jobs are enabled by {@link
 * com.marklogic.client.datamovement.WriteBatcher}.
 * Long-running read, delete, or transform jobs are enabled by {@link
 * com.marklogic.client.datamovement.QueryBatcher} which can perform actions
 * {@link com.marklogic.client.datamovement.DataMovementManager#newQueryBatcher(
 * com.marklogic.client.query.StructuredQueryDefinition) on all uris matching a query} or
 * {@link com.marklogic.client.datamovement.DataMovementManager#newQueryBatcher(
 * java.util.Iterator) on all uris provided by an Iterator<String>}.

 *
 * Features:
 *
 *

 *
WriteBatcher
 *

 *
batches documents for
 *       bulk write
 *       but improves on performance because it
 *

 *
writes with many parallel threads
 *
writes round-robin to all hosts in the cluster with forests for
 *           the specified database
 *

 *
one instance safely receives calls to {@link
 *       com.marklogic.client.datamovement.WriteBatcher#add add} from many
 *       threads
 *
supports transforms, metadata, and temporal collections
 *

 *
QueryBatcher
 *

 *
offers high-performance import from sources not supported by
 *       mlcp
 *
runs provided code on a set of uris (common use cases include but
 *         are not limited to export, delete, and transform)
 *
provided code can leverage the full feature set of the Java Client API
 *
uris usually are matches to a query
 *
for corner cases uris can be provided by an Iterator<String>
 *
paginates through query matches for best scalability
 *
paginates with many threads for increased throughput
 *
directly queries each host in the cluster with forests for
 *         the specified database
 *

 *

 *
 *
 *
Using Provided Listeners

 *
 *
When using QueryBatcher, your custom listeners provided to {@link
 * com.marklogic.client.datamovement.QueryBatcher#onUrisReady onUrisReady} can do
 * anything with each batch of uris and will usually use the
 * MarkLogic Java Client API
 * to do things. However, to simplify common use cases, the
 * following listeners are also provided:

 *
 *

 *   {@link com.marklogic.client.datamovement.ApplyTransformListener}  - Modifies documents in-place in the database by applying a {@link com.marklogic.client.document.ServerTransform server-side transform}
 *   {@link com.marklogic.client.datamovement.ExportListener}          - Downloads each document for further processing in Java
 *   {@link com.marklogic.client.datamovement.ExportToWriterListener}  - Downloads each document and writes it to a Writer (could be a file, HTTP response, in-memory Writer, etc.
 *   {@link com.marklogic.client.datamovement.DeleteListener}          - Deletes each batch of documents from the server
 *   {@link com.marklogic.client.datamovement.UrisToWriterListener}    - Writes each uri to a Writer (could be a file, HTTP response, etc.).
 *

 *
 *
 *
Using QueryBatcher

 *
 *
When you need to perform actions on server documents beyond what can be
 * done with the provided listeners, register your
 * custom code with onUrisReady and your code will be run for each batch of
 * uris.

 *
 * For Example:
 *
{@code
 *     QueryBatcher qhb = dataMovementManager.newQueryBatcher(query)
 *         .withBatchSize(1000)
 *         .withThreadCount(20)
           .withConsistentSnapshot()
 *         .onUrisReady(batch -> {
 *             for ( String uri : batch.getItems() ) {
 *                 if ( uri.endsWith(".txt") ) {
 *                     client.newDocumentManager().delete(uri);
 *                 }
 *             }
 *         })
 *         .onQueryFailure(queryBatchException -> queryBatchException.printStackTrace());
 *     JobTicket ticket = dataMovementManager.startJob(qhb);
 *     qhb.awaitCompletion();
 *     dataMovementManager.stopJob(ticket);
 *}

 *
 *
 *
Using WriteBatcher

 *
 *
When you need to write a very large volume of documents and
 * mlcp
 * cannot meet your requirements, use WriteBatcher.

 *
 * For Example:
 *
{@code
 *     WriteBatcher whb = dataMovementManager.newWriteBatcher()
 *         .withBatchSize(100)
 *         .withThreadCount(20)
 *         .onBatchSuccess(batch -> {
 *             logger.debug("batch # {}, so far: {}", batch.getJobBatchNumber(), batch.getJobResultsSoFar());
 *         })
 *         .onBatchFailure((batch,throwable) -> throwable.printStackTrace() );
 *     JobTicket ticket = dataMovementManager.startJob(whb);
 *     // the add or addAs methods could be called in separate threads on the
 *     // single whb instance
 *     whb.add  ("doc1.txt", new StringHandle("doc1 contents"));
 *     whb.addAs("doc2.txt", "doc2 contents");
 *
 *     whb.flushAndWait(); // send the two docs even though they're not a full batch
 *     dataMovementManager.stopJob(ticket);
 *}

 *
 *
 *
 *
Writing Custom Listeners

 *
 *
As demonstrated above, listeners should be added to each instance of
 * QueryBatcher or WriteBatcher.  Ad-hoc listeners can be written as Java 8
 * lambda expressions.  More sophisticated custom listeners can implement the
 * appropriate listener interface or extend one of the
 * provided listeners listed above.

 *
 *
QueryBatchListener (onUrisReady) instances are necessary to do something
 * with the uris fetched by QueryBatcher.  What a custom QueryBatchListener
 * does is completely up to it, but any operation which operates on uris
 * offered by any part of the Java Client API could be used, as could any read
 * or write to an external system.  QueryFailureListener (onQueryFailure)
 * instances handle any exceptions encoutnered fetching the uris.
 * WriteBatchListener (onBatchSuccess) instances handle any custom tracking
 * requirements during a WriteBatcher job.  WriteFailureListener
 * (onBatchFailure) instances handle any exceptions encountered writing the
 * batches formed from docs send to the WriteBatcher instance.  See the
 * javadocs for each provided listener for an explantion of the
 * various listeners that can be registered for it to call.  See javadocs, the
 * Java Application Developer's Guide,
 * source code for provided listeners,
 * cookbook examples, and
 * unit tests
 * for more examples of listener implementation ideas.

 *
 *
 *
Listners Must Be Thread-Safe

 *
 *
Since listeners are called asynchronously by all threads in the pool inside
 * the QueryBatcher or WriteBatcher instance, they must only perform
 * thread-safe operations.  For example, accumulating to a collection should
 * only be done with collections wrapped as
 * {@link java.util.Collections#synchronizedCollection synchronized Collections}
 * rather than directly using un-synchronized collections such as HashMap or
 * ArrayList which are not thread-safe.  Similarly, accumulating to a string
 * should use StringBuffer insted of StringBuilder since StringBuffer is
 * synchronized (and thus thread-safe).  We also recommend {@link
 * java.util.concurrent.atomic java.util.concurrent.atomic classes}.

 *
 *
Listeners should handle their own exceptions as described below in
 * Handling Exceptions in Listeners.

 *
 *
 *
 *
Handling Exceptions in Listeners

 *
 * Since listeners are called asynchrounously, external exception handling
 * cannot wrap the call in a try-catch block.  Instead, a listener can and
 * should handle its own exceptions by wrapping the calls in its body in a
 * try-catch block.  When any listener does not handle its own exceptions and
 * throws any exception (Throwable), the exception is logged at error level
 * with a call like:
 *
 *
{@code
 *     logger.error("Exception thrown by an onBatchSuccess listener", throwable);
 *}

 *
 *
This achieves logging of exceptions without allowing them to prevent the job
 * from continuing.

 *
 *
A QueryFailureListener or WriteFailureListener will not be notified of
 * exceptions thrown by other listeners.  Instead, these failure listeners are
 * notified exclusively of exceptions in the operation of QueryBatcher or
 * WriteBatcher.

 *
 *
If you wish a custom QueryBatchListener or WriteBatchListener to trap its
 * own exceptions and pass them along to callbacks registered with it for
 * exception handling, it can of course do that in a custom way.  Examples of
 * this pattern can be seen in the interface of
 * {@link com.marklogic.client.datamovement.ApplyTransformListener}.

 *
 *
Pre-installed Listeners

 *
 *
Every time you create a new QueryBatcher or WriteBatcher it comes with some
 * pre-installed listeners such as
 * {@link com.marklogic.client.datamovement.HostAvailabilityListener} and a
 * listener to track counts for JobReport.  If you wish to remove these
 * listeners and their associated functionality call one of the following:
 * {@link com.marklogic.client.datamovement.QueryBatcher#setUrisReadyListeners
 * setUrisReadyListeners}, {@link
 * com.marklogic.client.datamovement.QueryBatcher#setQueryFailureListeners
 * setQueryFailureListeners}, {@link
 * com.marklogic.client.datamovement.WriteBatcher#setBatchSuccessListeners
 * setBatchSuccessListeners}, or {@link
 * com.marklogic.client.datamovement.WriteBatcher#setBatchFailureListeners
 * setBatchFailureListeners}.  Obviously, removing the functionality of
 * HostAvailabilityListener means it won't do its job of handling black-listing
 * hosts or retrying batches that occur when a host is unavailable.  And
 * removing the functionality of the listeners that track counts for JobReport
 * means JobReport should no longer be used.  If you would just like to change
 * the settings on HostAvailabilityListener or NoResponseListener, you can do
 * something like the following:

 *
 *
{@code
 *    HostAvailabilityListener.getInstance(batcher)
 *      .withSuspendTimeForHostUnavailable(Duration.ofMinutes(60))
 *      .withMinHosts(2);
 *}

 *
 *
 *
Enable Logging

 *
 *
We have made efforts to provide helpful logging as you use QueryBatcher and
 * WriteBatcher.  Please make sure to enable your slf4j-compliant
 * logging framework.

 *
 *

 *

 *

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


text:
namespace warped {

class LogicalProcess;

class ProfileGuidedPartitioner : public Partitioner {
public:
    ProfileGuidedPartitioner(std::string stats_file, std::vector<float> part_weights = {});

    std::vector<std::vector<LogicalProcess*>> partition(
             const std::vector<LogicalProcess*>& lps,
             const unsigned int num_partitions) const;

protected:
    void savePartition(unsigned int part_id,
                       const std::vector<LogicalProcess*>& lps,
                       const std::vector<idx_t>& xadj,
                       const std::vector<idx_t>& adjncy,
                       const std::vector<idx_t>& adjwgt,
                       const std::vector<unsigned int>& numbering = {}) const;

private:
    std::string stats_file_;

    mutable std::vector<float> part_weights_;
};

} // namespace warped

#endif

redpajama_set_name: RedPajamaGithub


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
Hist. pl. Dauphiné 3(2):731. 1789

#### Original name
null

### Remarks
null


text:
<?php

/**
 * Retrieve a list of friends for the authenticating user and then lookup
 * their details using users/lookup.
 *
 * Although this example uses your user token/secret, you can use
 * the user token/secret of any user who has authorised your application.
 *
 * Instructions:
 * 1) If you don't have one already, create a Twitter application on
 *      https://dev.twitter.com/apps
 * 2) From the application details page copy the consumer key and consumer
 *      secret into the place in this code marked with (YOUR_CONSUMER_KEY
 *      and YOUR_CONSUMER_SECRET)
 * 3) From the application details page copy the access token and access token
 *      secret into the place in this code marked with (A_USER_TOKEN
 *      and A_USER_SECRET)
 * 4) Visit this page using your web browser.
 *
 * @author themattharris
 */

define('PAGESIZE', 100);

require '../tmhOAuth.php';
require '../tmhUtilities.php';
$tmhOAuth = new tmhOAuth(array(
  'consumer_key'    => 'YOUR_CONSUMER_KEY',
  'consumer_secret' => 'YOUR_CONSUMER_SECRET',
  'user_token'      => 'A_USER_TOKEN',
  'user_secret'     => 'A_USER_SECRET',
));

function check_rate_limit($response) {
  $headers = $response['headers'];
  if ($headers['x_ratelimit_remaining'] == 0) :
    $reset = $headers['x_ratelimit_reset'];
    $sleep = time() - $reset;
    echo 'rate limited. reset time is ' . $reset . PHP_EOL;
    echo 'sleeping for ' . $sleep . ' seconds';
    sleep($sleep);
  endif;
}

$cursor = '-1';
$ids = array();

while (true) :
  if ($cursor == '0')
    break;

  $tmhOAuth->request('GET', $tmhOAuth->url('1/friends/ids'), array(
    'cursor' => $cursor
  ));

  // check the rate limit
  check_rate_limit($tmhOAuth->response);

  if ($tmhOAuth->response['code'] == 200) {
    $data = json_decode($tmhOAuth->response['response'], true);
    $ids += $data['ids'];
    $cursor = $data['next_cursor_str'];
  } else {
    echo $tmhOAuth->response['response'];
    break;
  }
endwhile;

// lookup users
$paging = ceil(count($ids) / PAGESIZE);
$users = array();
for ($i=0; $i < $paging ; $i++) {
  $set = array_slice($ids, $i*PAGESIZE, PAGESIZE);

  $tmhOAuth->request('GET', $tmhOAuth->url('1/users/lookup'), array(
    'user_id' => implode(',', $set)
  ));

  // check the rate limit
  check_rate_limit($tmhOAuth->response);

  if ($tmhOAuth->response['code'] == 200) {
    $data = json_decode($tmhOAuth->response['response'], true);
    $users += $data;
  } else {
    echo $tmhOAuth->response['response'];
    break;
  }

}
var_dump($users);

?>


text:
package com.google.common.collect.testing.testers;

import static com.google.common.collect.testing.features.CollectionSize.ZERO;

import com.google.common.collect.testing.AbstractCollectionTester;
import com.google.common.collect.testing.features.CollectionSize;

/**
 * A generic JUnit test which tests {@code isEmpty()} operations on a
 * collection. Can't be invoked directly; please see
 * {@link com.google.common.collect.testing.CollectionTestSuiteBuilder}.
 *
 * <p>This class is GWT compatible.
 *
 * @author Kevin Bourrillion
 */
public class CollectionIsEmptyTester<E> extends AbstractCollectionTester<E> {
  @CollectionSize.Require(ZERO)
  public void testIsEmpty_yes() {
    assertTrue("isEmpty() should return true", collection.isEmpty());
  }

  @CollectionSize.Require(absent = ZERO)
  public void testIsEmpty_no() {
    assertFalse("isEmpty() should return false", collection.isEmpty());
  }
}


text:
#pragma once
#include <aws/ec2/EC2_EXPORTS.h>
#include <aws/ec2/EC2Request.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
namespace EC2
{
namespace Model
{

  /**
   */
  class AWS_EC2_API DeleteIpamRequest : public EC2Request
  {
  public:
    DeleteIpamRequest();

    // Service request name is the Operation name which will send this request out,
    // each operation should has unique request name, so that we can get operation's name from this request.
    // Note: this is not true for response, multiple operations may have the same response name,
    // so we can not get operation's name from response.
    inline virtual const char* GetServiceRequestName() const override { return "DeleteIpam"; }

    Aws::String SerializePayload() const override;

  protected:
    void DumpBodyToUrl(Aws::Http::URI& uri ) const override;

  public:

    /**
     *
A check for whether you have the required permissions for the action without
     * actually making the request and provides an error response. If you have the
     * required permissions, the error response is DryRunOperation.
     * Otherwise, it is UnauthorizedOperation.

     */
    inline bool GetDryRun() const{ return m_dryRun; }

    /**
     *
A check for whether you have the required permissions for the action without
     * actually making the request and provides an error response. If you have the
     * required permissions, the error response is DryRunOperation.
     * Otherwise, it is UnauthorizedOperation.

     */
    inline bool DryRunHasBeenSet() const { return m_dryRunHasBeenSet; }

    /**
     *
A check for whether you have the required permissions for the action without
     * actually making the request and provides an error response. If you have the
     * required permissions, the error response is DryRunOperation.
     * Otherwise, it is UnauthorizedOperation.

     */
    inline void SetDryRun(bool value) { m_dryRunHasBeenSet = true; m_dryRun = value; }

    /**
     *
A check for whether you have the required permissions for the action without
     * actually making the request and provides an error response. If you have the
     * required permissions, the error response is DryRunOperation.
     * Otherwise, it is UnauthorizedOperation.

     */
    inline DeleteIpamRequest& WithDryRun(bool value) { SetDryRun(value); return *this;}

    /**
     *
The ID of the IPAM to delete.

     */
    inline const Aws::String& GetIpamId() const{ return m_ipamId; }

    /**
     *
The ID of the IPAM to delete.

     */
    inline bool IpamIdHasBeenSet() const { return m_ipamIdHasBeenSet; }

    /**
     *
The ID of the IPAM to delete.

     */
    inline void SetIpamId(const Aws::String& value) { m_ipamIdHasBeenSet = true; m_ipamId = value; }

    /**
     *
The ID of the IPAM to delete.

     */
    inline void SetIpamId(Aws::String&& value) { m_ipamIdHasBeenSet = true; m_ipamId = std::move(value); }

    /**
     *
The ID of the IPAM to delete.

     */
    inline void SetIpamId(const char* value) { m_ipamIdHasBeenSet = true; m_ipamId.assign(value); }

    /**
     *
The ID of the IPAM to delete.

     */
    inline DeleteIpamRequest& WithIpamId(const Aws::String& value) { SetIpamId(value); return *this;}

    /**
     *
The ID of the IPAM to delete.

     */
    inline DeleteIpamRequest& WithIpamId(Aws::String&& value) { SetIpamId(std::move(value)); return *this;}

    /**
     *
The ID of the IPAM to delete.

     */
    inline DeleteIpamRequest& WithIpamId(const char* value) { SetIpamId(value); return *this;}

    /**
     *
Enables you to quickly delete an IPAM, private scopes, pools in private
     * scopes, and any allocations in the pools in private scopes. You cannot delete
     * the IPAM with this option if there is a pool in your public scope. If you use
     * this option, IPAM does the following:

Deallocates any CIDRs
     * allocated to VPC resources (such as VPCs) in pools in private scopes.

     *
No VPC resources are deleted as a result of enabling this option. The CIDR
     * associated with the resource will no longer be allocated from an IPAM pool, but
     * the CIDR itself will remain unchanged.

Deprovisions
     * all IPv4 CIDRs provisioned to IPAM pools in private scopes.

     *
Deletes all IPAM pools in private scopes.

Deletes all
     * non-default private scopes in the IPAM.

Deletes the default
     * public and private scopes and the IPAM.

     */
    inline bool GetCascade() const{ return m_cascade; }

    /**
     *
Enables you to quickly delete an IPAM, private scopes, pools in private
     * scopes, and any allocations in the pools in private scopes. You cannot delete
     * the IPAM with this option if there is a pool in your public scope. If you use
     * this option, IPAM does the following:

Deallocates any CIDRs
     * allocated to VPC resources (such as VPCs) in pools in private scopes.

     *
No VPC resources are deleted as a result of enabling this option. The CIDR
     * associated with the resource will no longer be allocated from an IPAM pool, but
     * the CIDR itself will remain unchanged.

Deprovisions
     * all IPv4 CIDRs provisioned to IPAM pools in private scopes.

     *
Deletes all IPAM pools in private scopes.

Deletes all
     * non-default private scopes in the IPAM.

Deletes the default
     * public and private scopes and the IPAM.

     */
    inline bool CascadeHasBeenSet() const { return m_cascadeHasBeenSet; }

    /**
     *
Enables you to quickly delete an IPAM, private scopes, pools in private
     * scopes, and any allocations in the pools in private scopes. You cannot delete
     * the IPAM with this option if there is a pool in your public scope. If you use
     * this option, IPAM does the following:

Deallocates any CIDRs
     * allocated to VPC resources (such as VPCs) in pools in private scopes.

     *
No VPC resources are deleted as a result of enabling this option. The CIDR
     * associated with the resource will no longer be allocated from an IPAM pool, but
     * the CIDR itself will remain unchanged.

Deprovisions
     * all IPv4 CIDRs provisioned to IPAM pools in private scopes.

     *
Deletes all IPAM pools in private scopes.

Deletes all
     * non-default private scopes in the IPAM.

Deletes the default
     * public and private scopes and the IPAM.

     */
    inline void SetCascade(bool value) { m_cascadeHasBeenSet = true; m_cascade = value; }

    /**
     *
Enables you to quickly delete an IPAM, private scopes, pools in private
     * scopes, and any allocations in the pools in private scopes. You cannot delete
     * the IPAM with this option if there is a pool in your public scope. If you use
     * this option, IPAM does the following:

Deallocates any CIDRs
     * allocated to VPC resources (such as VPCs) in pools in private scopes.

     *
No VPC resources are deleted as a result of enabling this option. The CIDR
     * associated with the resource will no longer be allocated from an IPAM pool, but
     * the CIDR itself will remain unchanged.

Deprovisions
     * all IPv4 CIDRs provisioned to IPAM pools in private scopes.

     *
Deletes all IPAM pools in private scopes.

Deletes all
     * non-default private scopes in the IPAM.

Deletes the default
     * public and private scopes and the IPAM.

     */
    inline DeleteIpamRequest& WithCascade(bool value) { SetCascade(value); return *this;}

  private:

    bool m_dryRun;
    bool m_dryRunHasBeenSet = false;

    Aws::String m_ipamId;
    bool m_ipamIdHasBeenSet = false;

    bool m_cascade;
    bool m_cascadeHasBeenSet = false;
  };

} // namespace Model
} // namespace EC2
} // namespace Aws


text:
import requests

# Create your models here.

class card:
	def __init__(self, name, id, points, startDate, endDate):
		self.name = name
		self.id = id
		self.points = points
		self.startDate = startDate
		self.endDate = endDate

class cardDao:

	def find(self):
		r = requests.get('http://10.99.3.56:7070/api/v1/teams/boards/1/queues/1/cards/1')
		js = r.json()
		return example(js[u'name'], js[u'id'], js[u'points'], js[u'startDate'], js[u'endDate'])


text:
struct PP_Rect;

namespace webkit {
namespace ppapi {

class PPB_LayerCompositor_Impl
    : public ::ppapi::Resource,
      public ::ppapi::thunk::PPB_LayerCompositor_API {
 public:
  explicit PPB_LayerCompositor_Impl(PP_Instance instance);
  virtual ~PPB_LayerCompositor_Impl();

  static const PPB_LayerCompositor_Dev* GetInterface();

  // Resource override.
  virtual PPB_LayerCompositor_API* AsPPB_LayerCompositor_API();

  // PPB_LayerCompositor_API implementation.
  virtual PP_Bool AddLayer(PP_Resource layer) OVERRIDE;
  virtual void RemoveLayer(PP_Resource layer) OVERRIDE;
  virtual void SetZIndex(PP_Resource layer, int32_t index) OVERRIDE;
  virtual void SetRect(PP_Resource layer, const PP_Rect* rect) OVERRIDE;
  virtual void SetDisplay(PP_Resource layer, PP_Bool is_displayed) OVERRIDE;
  virtual void MarkAsDirty(PP_Resource layer) OVERRIDE;
  virtual int32_t SwapBuffers(
      scoped_refptr< ::ppapi::TrackedCallback> callback) OVERRIDE;

 private:
  DISALLOW_COPY_AND_ASSIGN(PPB_LayerCompositor_Impl);
};

}  // namespace ppapi
}  // namespace webkit

#endif  // WEBKIT_PLUGINS_PPAPI_PPB_LAYER_COMPOSITOR_IMPL_H_


text:
title: Internet Explorer 8 Support Will Be Removed in Ember 2.0
author: Tom Dale
tags: Compatibility, Recent Posts, 2015
responsive: true
---

After reviewing [this thread][rfc-ie8], it seems clear that the vast majority of
Ember users who have responded, including people working at large
corporations, are comfortable with dropping IE8 support in Ember 2.0.
On the other hand, while there is enormous support for dropping IE9
support as well, a number of people still rely on support for IE9, and
the benefits of dropping IE9 in Ember 2.0 are not as strong.

After reviewing discussion on the RFC proposal, many in-person conversations with Ember
users in large companies, and reviewing the private data sent to us via
email, we have decided that Ember 2.0 will support IE9+.

So how are we going to manage this transition, and what should you do
if your business still requires IE8 support for the time being?

## 1.13 with Extended Browser Support

The core team will continue to periodically release point releases in
the 1.13 series to patch security bugs and browser compatibility
issues, including issues in IE8.

No new features will be added, and we should be clear that we do not
intend people to stay on this release unless they must support IE8. Our
Semantic Version guarantees mean that the vast majority of the
community should migrate to the 2.x series as soon as possible.

It is important to note that Ember 1.13 will come with deprecation
warnings for everything that we will break in Ember 2.0. As a result,
if you are running Ember 1.13 without any deprecation warnings, you
should be able to easily upgrade to Ember 2.0. And because of the
Semantic Versioning guarantees in the Ember 2.x series, it should be
relatively simple to upgrade from Ember 1.13 to the most recent version
of Ember 2.x when you are able to drop IE8 support.

For example, imagine you build the Ember app for Big Widget Enterprise
Co. that requires IE8 support. You upgrade to 1.13 (the last release in
the 1.x series) and, over time, refactor code to eliminate all
deprecation warnings. Periodically, you apply 1.13 patch releases to
maintain browser compatibility and to fix potential security issues.

Then, in April of 2016, management decides that enough customers have
moved off IE8 that you no longer need to support it. At that time,
Ember 2.6 will be the most recent stable release. Because 1.13 without
deprecation warnings is forwards-compatible with Ember 2.6, you can
upgrade from 1.13 to 2.6 with little hassle.

With the integration of Ember CLI and Ember Data into the Semantic
Versioning guarantees, many of your dependencies will follow a similar
upgrade path.

## Ecosystem

Of course, the above guarantees only apply to Ember, Ember Data, Ember
CLI, and the rest of the core-supported packages. Addon authors are
free to define their own support matrices. We encourage those who
depend on older browsers to contribute back by submitting PRs to the
addons they use with compatibility patches. Likewise, we encourage
authors of existing addons to work with users to offer a browser
compatibility matrix as close to the core projects as possible.

If you require support for IE8 (and as a result, Ember 1.13), make sure
to make your voice heard across the addon ecosystem.

That said, you should expect that new addons that come out after Ember
2.0 will not target Ember 1.13, and you should factor that into your
decision to remain on the 1.13 Extended Browser Support release of
Ember.

## FastBoot

FastBoot, our effort to bring server-side rendering to all Ember apps,
is designed to offer even users with slow, low-feature browsers a fast
experience. While most people think of this as a benefit to mobile
users, IE8 certainly qualifies as a slow, low-feature browser.

Because Ember applications are written "route first", any idiomatic
Ember content app that uses links as the primary mode of navigation
will be able to provide a passable experience for users with an
unsupported version of JavaScript, or no JavaScript at all.

It is worth noting that FastBoot, in the medium term, will have good
support for read-only content sites. However, while it is possible to
support forms pretty easily, forms without JavaScript (using cookie
authentication) introduce the prospect of CSRF attacks. A good solution
for FastBoot forms that is also secure is probably a longer-term
project. We would encourage the community to experiment with a secure
approach to forms that works with FastBoot.

## jQuery Compatibility

In our RFC, we mentioned that dropping IE8 will give us the opportunity
to remove jQuery as a strict dependency. We should have been clearer
that we have no intent to remove the Ember APIs that delegate to jQuery
(such a Ember.$ and this.$() inside components).

Because these APIs will remain in 2.0, both for ease of upgrade and
because we have not yet made the jQuery dependency optional, Semantic
Versioning prohibits us from removing them until at least Ember 3.0.

On a personal note, we rely on jQuery heavily in our own apps. We think
it's a great library that remains hugely valuable to smooth over clunky
DOM APIs and browser quirks (even in modern browsers). For those users
who need the absolute smallest payload size, we don't want to saddle
you with a dependency that you don't need. But we expect the majority
of users to continue using jQuery, and we have no plans to remove the
Ember/jQuery integration at this time.

Thank you again for everyone who took the time to help us make this
decision, and thank you so much for being a part of the Ember
community.

[rfc-ie8]: https://github.com/emberjs/rfcs/pull/45


text:
class StoreMetadata(object):
    CATEGORIES_ENDPOINT = '/meta/apps/{market}/categories'
    DEVICES_ENDPOINT = '/meta/apps/{market}/devices'
    FEEDS_ENDPOINT = '/meta/apps/{market}/feeds'

    def __init__(self, meta, http_client, market=None):
        self.meta = meta
        self.http_client = http_client
        self.market = market

    def all(self):
        return self.meta.verticals().get('apps')

    def _format_uri(self, uri):
        if not self.market:
            raise ValueError("Store/market not specified")
        return uri.format(market=self.market)

    def categories(self):
        uri = self._format_uri(self.CATEGORIES_ENDPOINT)
        return self.http_client.request(uri).get('category_labels')

    def devices(self):
        uri = self._format_uri(self.DEVICES_ENDPOINT)
        return self.http_client.request(uri).get('devices')

    def feeds(self):
        uri = self._format_uri(self.FEEDS_ENDPOINT)
        return self.http_client.request(uri).get('feeds')


text:
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.chrome.browser.password_check.helper;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.provider.Browser;

import androidx.browser.customtabs.CustomTabsIntent;

import org.chromium.base.IntentUtils;
import org.chromium.chrome.browser.password_check.CompromisedCredential;
import org.chromium.chrome.browser.password_check.PasswordChangeType;
import org.chromium.chrome.browser.password_check.PasswordCheckComponentUi;
import org.chromium.chrome.browser.password_check.PasswordCheckUkmRecorder;
import org.chromium.components.browser_ui.settings.SettingsLauncher;

import java.util.Objects;

/**
 * Helper to launch apps, settings screens, or Chrome Custom tabs that enable the user to change a
 * compromised password.
 */
public class PasswordCheckChangePasswordHelper {
    private final Context mContext;
    private final SettingsLauncher mSettingsLauncher;
    private final PasswordCheckComponentUi.CustomTabIntentHelper mCustomTabIntentHelper;
    private final PasswordCheckComponentUi.TrustedIntentHelper mTrustedIntentHelper;

    public PasswordCheckChangePasswordHelper(Context context, SettingsLauncher settingsLauncher,
            PasswordCheckComponentUi.CustomTabIntentHelper customTabIntentHelper,
            PasswordCheckComponentUi.TrustedIntentHelper trustedIntentHelper) {
        mContext = context;
        mSettingsLauncher = settingsLauncher;
        mCustomTabIntentHelper = customTabIntentHelper;
        mTrustedIntentHelper = trustedIntentHelper;
    }

    /**
     * Launches an app (if available) or a CCT with the site the given credential was used on.
     * @param credential A {@link CompromisedCredential}.
     */
    public void launchAppOrCctWithChangePasswordUrl(CompromisedCredential credential) {
        if (!canManuallyChangeCredential(credential)) return;
        // TODO(crbug.com/1092444): Always launch the URL if possible and let Android handle the
        // match to open it.
        IntentUtils.safeStartActivity(mContext,
                credential.getAssociatedApp().isEmpty()
                        ? buildIntent(
                                credential.getPasswordChangeUrl(), PasswordChangeType.MANUAL_CHANGE)
                        : getPackageLaunchIntent(credential.getAssociatedApp()));
    }

    /**
     * @param credential A {@link CompromisedCredential}.
     * @return True iff there is a valid URL to navigate to or an app that can be opened.
     */
    public boolean canManuallyChangeCredential(CompromisedCredential credential) {
        return !credential.getPasswordChangeUrl().isEmpty()
                || getPackageLaunchIntent(credential.getAssociatedApp()) != null;
    }

    private Intent getPackageLaunchIntent(String packageName) {
        return Objects.requireNonNull(mContext).getPackageManager().getLaunchIntentForPackage(
                packageName);
    }

    /**
     * Builds an intent to launch a CCT.
     *
     * @param initialUrl Initial URL to launch a CCT.
     * @param passwordChangeType Password change type.
     * @return {@link Intent} for CCT.
     */
    private Intent buildIntent(String initialUrl, @PasswordChangeType int passwordChangeType) {
        CustomTabsIntent customTabIntent =
                new CustomTabsIntent.Builder().setShowTitle(true).build();
        customTabIntent.intent.setData(Uri.parse(initialUrl));
        Intent intent = mCustomTabIntentHelper.createCustomTabActivityIntent(
                mContext, customTabIntent.intent);
        intent.setPackage(mContext.getPackageName());
        intent.putExtra(Browser.EXTRA_APPLICATION_ID, mContext.getPackageName());
        intent.putExtra(PasswordCheckUkmRecorder.PASSWORD_CHECK_PACKAGE
                        + PasswordCheckUkmRecorder.PASSWORD_CHANGE_TYPE,
                passwordChangeType);
        mTrustedIntentHelper.addTrustedIntentExtras(intent);
        return intent;
    }
}


text:
package osrs.util;

import java.util.EnumMap;
import java.util.Set;

import javax.xml.bind.annotation.adapters.XmlAdapter;

import osrs.model.data.Levels;

public class LevelsEnumMapAdapter extends XmlAdapter<Integer[], EnumMap<Levels, Integer>> {

	@Override
	public EnumMap<Levels, Integer> unmarshal(Integer[] v) throws Exception {
		EnumMap<Levels, Integer> map = new EnumMap<Levels, Integer>(Levels.class);
		for(int i = 0; i < v.length; i++) {
			map.put(Levels.fromIndex(i), v[i]);
		}
		return map;
	}

	@Override
	public Integer[] marshal(EnumMap<Levels, Integer> v) throws Exception {
		Set<Levels> values = v.keySet();
		Integer[] result = new Integer[values.size()];

		for(Levels key : values) {
			result[key.index()] = v.get(key);
		}

		return result;
	}
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Xml;
using System.IO;

namespace GraphWebService.App_Code
{
    /// <summary>
    /// This class contains the methods used in older version
    /// of the graph web service
    /// </summary>
    public class SimpleSoapClient
    {
        public string VariableName { get; set; }

        public string XAxisvalue { get; set; }

        public string YAxisvalue { get; set; }

        public DataTable GetDataValuesSOAP(string start, string end, string siteCode, string variableCode, string url)
        {
            DataTable dt = new DataTable();

            dt.Columns.Add(new DataColumn("time", typeof(DateTime)));
            dt.Columns.Add(new DataColumn("value", typeof(double)));

            System.Collections.Generic.IList<DataValues.DataValues> ListDataValue = new System.Collections.Generic.List<DataValues.DataValues>();

            XMLSerialization objXMLSerialization = new XMLSerialization();

            string xml = CallWebService(url, siteCode, variableCode, start, end);

            ListDataValue = objXMLSerialization.ParseGetValues(xml);

            var ListVariableInfo = objXMLSerialization.GetMetaData(xml);

            if (ListVariableInfo.Count > 0)
                VariableName = ListVariableInfo[0].ToString();
            else
                VariableName = "unknown variable";

            if (ListVariableInfo.Count > 1)
                YAxisvalue = ListVariableInfo[1].ToString();
            else
                XAxisvalue = "unknown units";

            if (ListVariableInfo.Count > 2)
                XAxisvalue = ListVariableInfo[2].ToString();
            else
                XAxisvalue = "unknown units";

            for (int i = 0; i < ListDataValue.Count; i++)
            {
                DataRow row = dt.NewRow();
                row["time"] = ListDataValue[i].LocalDateTime;
                row["value"] = ListDataValue[i].Value;
                dt.Rows.Add(row);
            }
            return dt;
        }

        /// <summary>
        /// Calls any SOAP web service
        /// </summary>
        /// <param name="url">for example "http://hydrodata.info/chmi-d/cuahsi_1_1.asmx"</param>
        /// <param name="siteCode"></param>
        /// <param name="variableCode"></param>
        /// <param name="startTime"></param>
        /// <param name="endTime"></param>
        /// <returns></returns>
        public string CallWebService(string url, string siteCode, string variableCode, string startTime, string endTime)
        {
            System.Net.HttpWebRequest req = SOAPParsing.CreateGetValuesRequest(url, siteCode, variableCode, startTime, endTime);

            string XML;

            using (var resp = (System.Net.HttpWebResponse)req.GetResponse())
            {
                // we will read data via the response stream
                using (Stream ReceiveStream = resp.GetResponseStream())
                {
                    StreamReader sReader = new StreamReader(ReceiveStream);

                    XML = sReader.ReadToEnd();

                }
            }
            return XML;
        }
    }
}


text:
<?php

namespace Google\Service\Spanner;

class CreateInstanceConfigRequest extends \Google\Model
{
  protected $instanceConfigType = InstanceConfig::class;
  protected $instanceConfigDataType = '';
  /**
   * @var string
   */
  public $instanceConfigId;
  /**
   * @var bool
   */
  public $validateOnly;

  /**
   * @param InstanceConfig
   */
  public function setInstanceConfig(InstanceConfig $instanceConfig)
  {
    $this->instanceConfig = $instanceConfig;
  }
  /**
   * @return InstanceConfig
   */
  public function getInstanceConfig()
  {
    return $this->instanceConfig;
  }
  /**
   * @param string
   */
  public function setInstanceConfigId($instanceConfigId)
  {
    $this->instanceConfigId = $instanceConfigId;
  }
  /**
   * @return string
   */
  public function getInstanceConfigId()
  {
    return $this->instanceConfigId;
  }
  /**
   * @param bool
   */
  public function setValidateOnly($validateOnly)
  {
    $this->validateOnly = $validateOnly;
  }
  /**
   * @return bool
   */
  public function getValidateOnly()
  {
    return $this->validateOnly;
  }
}

// Adding a class alias for backwards compatibility with the previous class name.
class_alias(CreateInstanceConfigRequest::class, 'Google_Service_Spanner_CreateInstanceConfigRequest');


text:
'use strict';
var templates = require('../templates');

module.exports = {
  get: templates.get('invoice'),
  post: templates.post('invoice'),
  put: templates.put('invoice')
};


text:
#include <openssl/ec.h>

#include <assert.h>

#include "internal.h"
#include "../bn/internal.h"
#include "../../internal.h"

static void ec_GFp_simple_mul_single(const EC_GROUP *group, EC_RAW_POINT *r,
                                     const EC_RAW_POINT *p,
                                     const EC_SCALAR *scalar) {
  // This is a generic implementation for uncommon curves that not do not
  // warrant a tuned one. It uses unsigned digits so that the doubling case in
  // |ec_GFp_simple_add| is always unreachable, erring on safety and simplicity.

  // Compute a table of the first 32 multiples of |p| (including infinity).
  EC_RAW_POINT precomp[32];
  ec_GFp_simple_point_set_to_infinity(group, &precomp[0]);
  ec_GFp_simple_point_copy(&precomp[1], p);
  for (size_t j = 2; j < OPENSSL_ARRAY_SIZE(precomp); j++) {
    if (j & 1) {
      ec_GFp_simple_add(group, &precomp[j], &precomp[1], &precomp[j - 1]);
    } else {
      ec_GFp_simple_dbl(group, &precomp[j], &precomp[j / 2]);
    }
  }

  // Divide bits in |scalar| into windows.
  unsigned bits = BN_num_bits(&group->order);
  int r_is_at_infinity = 1;
  for (unsigned i = bits - 1; i < bits; i--) {
    if (!r_is_at_infinity) {
      ec_GFp_simple_dbl(group, r, r);
    }
    if (i % 5 == 0) {
      // Compute the next window value.
      const size_t width = group->order.width;
      uint8_t window = bn_is_bit_set_words(scalar->words, width, i + 4) << 4;
      window |= bn_is_bit_set_words(scalar->words, width, i + 3) << 3;
      window |= bn_is_bit_set_words(scalar->words, width, i + 2) << 2;
      window |= bn_is_bit_set_words(scalar->words, width, i + 1) << 1;
      window |= bn_is_bit_set_words(scalar->words, width, i);

      // Select the entry in constant-time.
      EC_RAW_POINT tmp;
      OPENSSL_memset(&tmp, 0, sizeof(EC_RAW_POINT));
      for (size_t j = 0; j < OPENSSL_ARRAY_SIZE(precomp); j++) {
        BN_ULONG mask = constant_time_eq_w(j, window);
        ec_felem_select(group, &tmp.X, mask, &precomp[j].X, &tmp.X);
        ec_felem_select(group, &tmp.Y, mask, &precomp[j].Y, &tmp.Y);
        ec_felem_select(group, &tmp.Z, mask, &precomp[j].Z, &tmp.Z);
      }

      if (r_is_at_infinity) {
        ec_GFp_simple_point_copy(r, &tmp);
        r_is_at_infinity = 0;
      } else {
        ec_GFp_simple_add(group, r, r, &tmp);
      }
    }
  }
  if (r_is_at_infinity) {
    ec_GFp_simple_point_set_to_infinity(group, r);
  }
}

void ec_GFp_simple_mul(const EC_GROUP *group, EC_RAW_POINT *r,
                       const EC_SCALAR *g_scalar, const EC_RAW_POINT *p,
                       const EC_SCALAR *p_scalar) {
  assert(g_scalar != NULL || p_scalar != NULL);
  if (p_scalar == NULL) {
    ec_GFp_simple_mul_single(group, r, &group->generator->raw, g_scalar);
  } else if (g_scalar == NULL) {
    ec_GFp_simple_mul_single(group, r, p, p_scalar);
  } else {
    // Support constant-time two-point multiplication for compatibility.  This
    // does not actually come up in keygen, ECDH, or ECDSA, so we implement it
    // the naive way.
    ec_GFp_simple_mul_single(group, r, &group->generator->raw, g_scalar);
    EC_RAW_POINT tmp;
    ec_GFp_simple_mul_single(group, &tmp, p, p_scalar);
    ec_GFp_simple_add(group, r, r, &tmp);
  }
}


text:
<?php

namespace Phpug\Controller;

class EventCacheControllerFactory
{
    public function __invoke($container)
    {
        return new EventCacheController(
            $container->getServiceLocator()->get('doctrine.entitymanager.orm_default'),
            $container->getServiceLocator()->get('config')
        );
    }
}


text:
set(BIN_INSTALL_DIR "bin" CACHE PATH "The binary install dir (default: bin)")
set(LIB_INSTALL_DIR "lib${LIB_SUFFIX}" CACHE PATH "The library install dir (default: lib${LIB_SUFFIX})")
set(INCLUDE_INSTALL_DIR "include" CACHE PATH "The library install dir (default: include)")
set(CMAKE_INSTALL_DIR "cmake" CACHE PATH "The subdirectory to install cmake config files (default: cmake)")
set(DOC_INSTALL_DIR "share/doc" CACHE PATH "The subdirectory to install documentation files (default: share/doc)")


text:
namespace Google.Cloud.Dataproc.V1.Snippets
{
    // [START dataproc_v1_generated_JobController_SubmitJob_async]
    using Google.Cloud.Dataproc.V1;
    using System.Threading.Tasks;

    public sealed partial class GeneratedJobControllerClientSnippets
    {
        /// <summary>Snippet for SubmitJobAsync</summary>
        /// <remarks>
        /// This snippet has been automatically generated for illustrative purposes only.
        /// It may require modifications to work in your environment.
        /// </remarks>
        public async Task SubmitJobRequestObjectAsync()
        {
            // Create client
            JobControllerClient jobControllerClient = await JobControllerClient.CreateAsync();
            // Initialize request argument(s)
            SubmitJobRequest request = new SubmitJobRequest
            {
                ProjectId = "",
                Job = new Job(),
                Region = "",
                RequestId = "",
            };
            // Make the request
            Job response = await jobControllerClient.SubmitJobAsync(request);
        }
    }
    // [END dataproc_v1_generated_JobController_SubmitJob_async]
}


text:
package org.kie.workbench.common.stunner.bpmn.backend.converters.tostunner;

import org.kie.workbench.common.stunner.bpmn.backend.converters.TypedFactoryManager;
import org.kie.workbench.common.stunner.bpmn.backend.converters.tostunner.activities.CallActivityConverter;
import org.kie.workbench.common.stunner.bpmn.backend.converters.tostunner.processes.RootProcessConverter;
import org.kie.workbench.common.stunner.bpmn.backend.converters.tostunner.processes.SubProcessConverter;
import org.kie.workbench.common.stunner.bpmn.backend.converters.tostunner.properties.PropertyReaderFactory;
import org.kie.workbench.common.stunner.bpmn.backend.converters.tostunner.tasks.TaskConverter;

public class ConverterFactory
        extends BaseConverterFactory {

    public ConverterFactory(DefinitionResolver definitionResolver,
                            TypedFactoryManager factoryManager) {
        super(definitionResolver, factoryManager, new PropertyReaderFactory(definitionResolver));
    }

    @Override
    public CallActivityConverter callActivityConverter() {
        return new CallActivityConverter(factoryManager, propertyReaderFactory);
    }

    @Override
    public RootProcessConverter rootProcessConverter() {
        return new RootProcessConverter(factoryManager, propertyReaderFactory, definitionResolver, this);
    }

    @Override
    public SubProcessConverter subProcessConverter() {
        return new SubProcessConverter(factoryManager,
                                       propertyReaderFactory,
                                       definitionResolver,
                                       this);
    }

    @Override
    public TaskConverter taskConverter() {
        return new TaskConverter(factoryManager, propertyReaderFactory);
    }
}


text:
Imports System.IO
Imports System.Runtime.InteropServices

Public Class Form1

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim objSEApplication As SolidEdgeFramework.Application = Nothing
        Dim objProfileSets As SolidEdgePart.ProfileSet = Nothing
        Dim objDoc As SolidEdgePart.PartDocument = Nothing
        Dim objFlatPatternModels As SolidEdgePart.FlatPatternModels = Nothing
        Dim objFlatPatternModel As SolidEdgePart.FlatPatternModel = Nothing
        Dim objFlatPattern As SolidEdgePart.FlatPattern = Nothing
        Dim objModels As SolidEdgePart.Models = Nothing
        Dim objModel As SolidEdgePart.Model = Nothing
        Dim objBlankSurfaces As SolidEdgePart.BlankSurfaces = Nothing
        Dim objBlankSurface As SolidEdgePart.BlankSurface = Nothing
        Dim FacesToFlatten(0 To 5) As Object
        Dim FacesToSet(0 To 5) As Object
        Dim FacesFromFlat(0 To 5) As Object

        Dim objBox As SolidEdgePart.BoxFeature = Nothing
        Dim objBoxes As SolidEdgePart.BoxFeatures = Nothing
        Dim objBaseModel As SolidEdgePart.Model = Nothing
        Dim objMatTable As SolidEdgeFramework.MatTable = Nothing
        Dim strLibrary As String = "Materials"
        Dim strMaterial As String = "Copper"

        Try
            ' Get a handle of Solid Edge...
            objSEApplication = Marshal.GetActiveObject("SolidEdge.Application")

            'Add part document
            objDoc = objSEApplication.Documents.Add("SolidEdge.PartDocument")

            ' Get material table object handle
            objMatTable = objSEApplication.GetMaterialTable()

            ' Set active document handle
            objMatTable.SetActiveDocument(objDoc)
            objMatTable.ApplyMaterialToDoc(objDoc, strMaterial, strLibrary)
            'Change Modeling mode to Synchronous
            objDoc.ModelingMode = SolidEdgePart.ModelingModeConstants.seModelingModeSynchronous
            objModels = objDoc.Models
            'Create a box
            objBaseModel = objModels.AddBoxByCenter(0.0, 0.0, 0.0, 0.01, 0.01, 0.0, 0.01, objDoc.RefPlanes.Item(3), SolidEdgePart.FeaturePropertyConstants.igLeft, False, Nothing, 0)
            objBlankSurfaces = objBaseModel.BlankSurfaces

            objBoxes = objBaseModel.BoxFeatures()
            objBox = objBaseModel.Features.Item(1)

            ' Define faces to flatten - from the box feature in this case

            FacesToFlatten(0) = objBox.Faces(SolidEdgeGeometry.FeatureTopologyQueryTypeConstants.igQueryPlane).Item(1)
            FacesToFlatten(1) = objBox.Faces(SolidEdgeGeometry.FeatureTopologyQueryTypeConstants.igQueryPlane).Item(2)
            FacesToFlatten(2) = objBox.Faces(SolidEdgeGeometry.FeatureTopologyQueryTypeConstants.igQueryPlane).Item(3)

            objBlankSurface = objBlankSurfaces.Add(nNumFaces:=3, _
                                            FaceArray:=FacesToFlatten, _
                                            DrawDirectionX:=0.0#, _
                                            DrawDirectionY:=1.0#, _
                                            DrawDirectionZ:=0.0#, _
                                            HardeningCoefficient:=0.2, _
                                            StrengthCoefficient:=550000000, _
                                            AccuracyFactor:=3, _
                                            RemoveLoops:=False)

        Catch ex As Exception
            MsgBox(ex.ToString)
        End Try
    End Sub
End Class


text:
'use strict';

// add the jquery
window.jQuery = window.$ = require('jquery');

// add system-tray
require('./js/system-tray.js');

// add the window menus
// just for testing purposes
require('./js/menus.js');

// add bootstrap scripts
require('./node_modules/bootstrap/dist/js/bootstrap.min.js');

// jexcel
require('./node_modules/jexcel/dist/js/excel-formula.min.js');
require('./node_modules/jexcel/dist/js/jquery.csv.min.js');
require('./node_modules/jexcel/dist/js/jquery.jcalendar.js');
require('./node_modules/jexcel/dist/js/jquery.jexcel.js');
require('./node_modules/jquery-ui-dist/jquery-ui.min.js');

// sweetalert
require('./node_modules/sweetalert/dist/sweetalert.min.js');

// main script
require('./js/main.js');

require('./js/settings.js');


text:
package translatableerror

// ServiceInstanceNotShareableError is returned when either the
// service_instance_sharing feature flag is disabled or the service broker has
// disabled sharing
type ServiceInstanceNotShareableError struct {
	FeatureFlagEnabled          bool
	ServiceBrokerSharingEnabled bool
}

func (e ServiceInstanceNotShareableError) Error() string {
	switch {
	case !e.FeatureFlagEnabled && !e.ServiceBrokerSharingEnabled:
		return `The "service_instance_sharing" feature flag is disabled for this Cloud Foundry platform. Also, service instance sharing is disabled for this service.`
	case !e.FeatureFlagEnabled && e.ServiceBrokerSharingEnabled:
		return `The "service_instance_sharing" feature flag is disabled for this Cloud Foundry platform.`
	case e.FeatureFlagEnabled && !e.ServiceBrokerSharingEnabled:
		return "Service instance sharing is disabled for this service."
	}
	return "Unexpected ServiceInstanceNotShareableError: service instance is shareable."
}

func (e ServiceInstanceNotShareableError) Translate(translate func(string, ...interface{}) string) string {
	return translate(e.Error())
}


text:
require 'net/http'
require 'json'
require 'yaml'

module EsFacts

  def self.add_fact(prefix, key, value)
    key = "#{prefix}_#{key}".to_sym
    ::Facter.add(key) do
      setcode { value }
    end
  end

  def self.run

    dir_prefix = '/etc/elasticsearch'
    ports = []

    # only when the directory exists we need to process the stuff
    if File.directory?(dir_prefix)

      Dir.foreach(dir_prefix) do |dir|
        next if dir == '.'

        if File.exists?("#{dir_prefix}/#{dir}/elasticsearch.yml")
          config_data = YAML.load_file("#{dir_prefix}/#{dir}/elasticsearch.yml")

          if not config_data['http.enabled'].nil? and \
              config_data['http.enabled'] == 'false'
            next
          elsif not config_data['http.port'].nil?
            port = config_data['http.port']
          else
            port = '9200'
          end

          ports << port
        end
      end

      begin
        if ports.count > 0

          add_fact('elasticsearch', 'ports', ports.join(",") )
          ports.each do |port|

            key_prefix = "elasticsearch_#{port}"

            uri = URI("http://localhost:#{port}")
            http = Net::HTTP.new(uri.host, uri.port)
            http.read_timeout = 10
            response = http.get("/")
            json_data = JSON.parse(response.body)
            next if json_data['status'] && json_data['status'] != 200

            add_fact(key_prefix, 'name', json_data['name'])
            add_fact(key_prefix, 'version', json_data['version']['number'])

            uri2 = URI("http://localhost:#{port}/_nodes/#{json_data['name']}")
            http2 = Net::HTTP.new(uri2.host, uri2.port)
            http2.read_timeout = 10
            response2 = http2.get(uri2.path)
            json_data_node = JSON.parse(response2.body)

            add_fact(key_prefix, 'cluster_name', json_data_node['cluster_name'])
            node_data = json_data_node['nodes'].first

            add_fact(key_prefix, 'node_id', node_data[0])

            nodes_data = json_data_node['nodes'][node_data[0]]

            process = nodes_data['process']
            add_fact(key_prefix, 'mlockall', process['mlockall'])

            plugins = nodes_data['plugins']

            plugin_names = []
            plugins.each do |plugin|
              plugin_names << plugin['name']

             plugin.each do |key, value|
                prefix = "#{key_prefix}_plugin_#{plugin['name']}"
                add_fact(prefix, key, value) unless key == 'name'
              end
            end
            add_fact(key_prefix, 'plugins', plugin_names.join(","))

          end

        end
      rescue
      end

    end

  end

end

EsFacts.run


text:
#ifndef QTOKEN_P_H
#define QTOKEN_P_H

//
//  W A R N I N G
//  -------------
//
// This file is not part of the Qt API. It exists for the convenience
// of the help generator tools. This header file may change from version
// to version without notice, or even be removed.
//
// We mean it.
//

#include "qclucene_global_p.h"

#include <QtCore/QString>
#include <QtCore/QSharedDataPointer>
#include <QtCore/QSharedData>

CL_NS_DEF(analysis)
    class Token;
CL_NS_END
CL_NS_USE(analysis)

QT_BEGIN_NAMESPACE

class QCLuceneTokenizer;
class QCLuceneTokenStream;
class QCLuceneStandardTokenizer;

class Q_CLUCENE_EXPORT QCLuceneTokenPrivate : public QSharedData
{
public:
    QCLuceneTokenPrivate();
    QCLuceneTokenPrivate(const QCLuceneTokenPrivate &other);

    ~QCLuceneTokenPrivate();

    Token *token;
    bool deleteCLuceneToken;

private:
    QCLuceneTokenPrivate &operator=(const QCLuceneTokenPrivate &other);
};

class Q_CLUCENE_EXPORT QCLuceneToken
{
public:
    QCLuceneToken();
    QCLuceneToken(const QString &text, qint32 startOffset,
                  qint32 endOffset, const QString &defaultTyp = QLatin1String("word"));

    virtual ~QCLuceneToken();

    void set(const QString &text, qint32 startOffset,
             qint32 endOffset, const QString &defaultTyp = QLatin1String("word"));

    quint32 bufferLength() const;
    void growBuffer(quint32 size);

    qint32 positionIncrement() const;
    void setPositionIncrement(qint32 positionIncrement);

    QString termText() const;
    void setTermText(const QString &text);

    quint32 termTextLength() const;
    void resetTermTextLength() const;

    qint32 startOffset() const;
    void setStartOffset(qint32 value);

    qint32 endOffset() const;
    void setEndOffset(qint32 value);

    QString type() const;
    void setType(const QString &type);

    QString toString() const;

protected:
    friend class QCLuceneTokenizer;
    friend class QCLuceneTokenStream;
    friend class QCLuceneStandardTokenizer;
    QSharedDataPointer<QCLuceneTokenPrivate> d;

private:
    TCHAR *tokenText;
    TCHAR *tokenType;
};

QT_END_NAMESPACE

#endif  // QTOKEN_P_H


text:
module AnthraciteCore
  VERSION = '0.0.1'
end


text:
require 'helper'

describe 'sending a single message' do
  subject          { Esendex.new(username, password) }
  let(:username)   { String.generate }
  let(:password)   { String.generate }
  let(:accounts)   { Accounts.generate(1) }
  let(:account)    { accounts.first }
  let(:recipient)  { PhoneNumber.generate }
  let(:body)       { String.generate }
  let(:batch_id)   { Guid.generate }
  let(:header_uri) { Uri.generate }
  let(:header_id)  { Guid.generate }

  let(:request_body) {
    <<EOS
<?xml version="1.0" encoding="utf-8"?>
<messages>
  <accountreference>#{account.reference}</accountreference>
  <message>
    <to>#{recipient}</to>
    <body>#{body}</body>
  </message>
</messages>
EOS
  }

  let(:response_body) {
    <<EOS
<?xml version="1.0" encoding="utf-8"?>
<messageheaders batchid="#{batch_id}"
    xmlns="http://api.esendex.com/ns/">
  <messageheader uri="#{header_uri}" id="#{header_id}" />
</messageheaders>
EOS
  }

  before {
    stub_request(:get, "https://#{username}:#{password}@api.esendex.com/v1.0/accounts?")
      .with(headers: {"User-Agent" => Esendex::Client::USER_AGENT})
      .to_return(status: 200, body: accounts.to_xml)

    stub_request(:post, "https://#{username}:#{password}@api.esendex.com/v1.0/messagedispatcher")
      .with(headers: {"User-Agent" => Esendex::Client::USER_AGENT},
            body: request_body)
      .to_return(status: 200, body: response_body)
  }

  it 'returns the created message batch' do
    returned = subject.account(account.reference).dispatcher.send(body, recipient)
  end
end


text:
package net.simonvt.menudrawer.samples;

import net.simonvt.menudrawer.MenuDrawer;
import net.simonvt.menudrawer.Position;

import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextView;

import java.util.ArrayList;

public class ViewPagerSample extends BaseListSample {

    private PagerAdapter mPagerAdapter;
    private ViewPager mViewPager;
    private int mPagerOffsetPixels;
    private int mPagerPosition;

    @Override
    protected void onCreate(Bundle inState) {
        super.onCreate(inState);

        mMenuDrawer.setContentView(R.layout.activity_viewpagersample);
        mMenuDrawer.setSlideDrawable(R.drawable.ic_drawer);
        mMenuDrawer.setDrawerIndicatorEnabled(true);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
            getActionBar().setDisplayHomeAsUpEnabled(true);
        }

        mMenuDrawer.setTouchMode(MenuDrawer.TOUCH_MODE_FULLSCREEN);
        mMenuDrawer.setOnInterceptMoveEventListener(new MenuDrawer.OnInterceptMoveEventListener() {
            @Override
            public boolean isViewDraggable(View v, int dx, int x, int y) {
                if (v == mViewPager) {
                    return !(mPagerPosition == 0 && mPagerOffsetPixels == 0) || dx < 0;
                }

                return false;
            }
        });

        mViewPager = (ViewPager) findViewById(R.id.view_pager);
        mViewPager
                .setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
                    @Override
                    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                        mPagerPosition = position;
                        mPagerOffsetPixels = positionOffsetPixels;
                    }
                });

        mPagerAdapter = new PagerAdapter(this);
        mPagerAdapter.addTab(TextViewFragment.class, null);
        mPagerAdapter.addTab(TextViewFragment.class, null);
        mPagerAdapter.addTab(TextViewFragment.class, null);

        mViewPager.setAdapter(mPagerAdapter);
    }

    @Override
    protected void onMenuItemClicked(int position, Item item) {
        mMenuDrawer.closeMenu();
    }

    @Override
    protected int getDragMode() {
        return MenuDrawer.MENU_DRAG_CONTENT;
    }

    @Override
    protected Position getDrawerPosition() {
        return Position.LEFT;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                mMenuDrawer.toggleMenu();
                return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBackPressed() {
        final int drawerState = mMenuDrawer.getDrawerState();
        if (drawerState == MenuDrawer.STATE_OPEN
                || drawerState == MenuDrawer.STATE_OPENING) {
            mMenuDrawer.closeMenu();
            return;
        }

        super.onBackPressed();
    }

    /**
     * This is a helper class that implements the management of tabs and all
     * details of connecting a ViewPager with associated TabHost. It relies on a
     * trick. Normally a tab host has a simple API for supplying a View or
     * Intent that each tab will show. This is not sufficient for switching
     * between pages. So instead we make the content part of the tab host 0dp
     * high (it is not shown) and the TabsAdapter supplies its own dummy view to
     * show as the tab content. It listens to changes in tabs, and takes care of
     * switch to the correct paged in the ViewPager whenever the selected tab
     * changes.
     */
    public static class PagerAdapter extends FragmentPagerAdapter {

        private final Context mContext;
        private final ArrayList<TabInfo> mTabs = new ArrayList<TabInfo>();

        static final class TabInfo {

            private final Class<?> mClss;
            private final Bundle mArgs;

            TabInfo(Class<?> aClass, Bundle args) {
                mClss = aClass;
                mArgs = args;
            }
        }

        public PagerAdapter(FragmentActivity activity) {
            super(activity.getSupportFragmentManager());
            mContext = activity;
        }

        @Override
        public int getCount() {
            return mTabs.size();
        }

        @Override
        public Fragment getItem(int position) {
            TabInfo info = mTabs.get(position);
            return Fragment.instantiate(mContext, info.mClss.getName(),
                    info.mArgs);
        }

        public void addTab(Class<?> clss, Bundle args) {
            TabInfo info = new TabInfo(clss, args);
            mTabs.add(info);
            notifyDataSetChanged();
        }

    }

    public static class TextViewFragment extends Fragment {

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            FrameLayout frameLayout = new FrameLayout(getActivity());
            frameLayout.setLayoutParams(new FrameLayout.LayoutParams(
                    FrameLayout.LayoutParams.MATCH_PARENT,
                    FrameLayout.LayoutParams.MATCH_PARENT, Gravity.CENTER));

            TextView tv = new TextView(getActivity());
            tv.setText("This is an example of a Fragment in a View Pager");
            frameLayout.addView(tv);
            return frameLayout;
        }
    }
}


text:
package storage

import (
	"context"
	"fmt"
	"strings"
	"testing"

	"cloud.google.com/go/storage"
	"github.com/GoogleCloudPlatform/compute-image-import/cli_tools/common/domain"
	"github.com/GoogleCloudPlatform/compute-image-import/cli_tools/mocks"
	"github.com/golang/mock/gomock"
	"github.com/stretchr/testify/assert"
	"google.golang.org/api/iterator"
)

func TestCreateScratchBucketErrorWhenProjectNotProvided(t *testing.T) {
	mockCtrl := gomock.NewController(t)
	defer mockCtrl.Finish()

	ctx := context.Background()
	mockStorageClient := mocks.NewMockStorageClientInterface(mockCtrl)

	c := ScratchBucketCreator{mockStorageClient, ctx, nil}
	bucket, region, err := c.CreateScratchBucket("", "", "")
	assertErrorFromCreateScratchBucket(t, bucket, region, err)
}

func TestCreateScratchBucketNoSourceFileDefaultBucketCreatedBasedOnDefaultRegion(t *testing.T) {
	mockCtrl := gomock.NewController(t)
	defer mockCtrl.Finish()

	project := "proJect1"
	expectedBucket := "project1-daisy-bkt-us"
	expectedRegion := "US"
	ctx := context.Background()

	mockStorageClient := mocks.NewMockStorageClientInterface(mockCtrl)
	mockStorageClient.EXPECT().CreateBucket(expectedBucket, project, &storage.BucketAttrs{
		Name:         expectedBucket,
		Location:     defaultRegion,
		StorageClass: defaultStorageClass,
	}).Return(nil)

	c := ScratchBucketCreator{mockStorageClient, ctx, createMockBucketIteratorWithRandomBuckets(mockCtrl, &ctx, mockStorageClient, project)}
	bucket, region, err := c.CreateScratchBucket("", project, "")
	assert.Equal(t, expectedBucket, bucket)
	assert.Equal(t, expectedRegion, region)
	assert.Nil(t, err)
}

func TestCreateScratchBucketNoSourceFileTranslateGoogleDomainDefaultBucketCreatedBasedOnDefaultRegion(t *testing.T) {
	mockCtrl := gomock.NewController(t)
	defer mockCtrl.Finish()

	project := "google.com:proJect1"
	expectedBucket := "elgoog_com-project1-daisy-bkt-us"
	expectedRegion := "US"
	ctx := context.Background()

	mockStorageClient := mocks.NewMockStorageClientInterface(mockCtrl)
	mockStorageClient.EXPECT().CreateBucket(expectedBucket, project, &storage.BucketAttrs{
		Name:         expectedBucket,
		Location:     defaultRegion,
		StorageClass: defaultStorageClass,
	}).Return(nil)

	c := ScratchBucketCreator{mockStorageClient, ctx, createMockBucketIteratorWithRandomBuckets(mockCtrl, &ctx, mockStorageClient, project)}
	bucket, region, err := c.CreateScratchBucket("", project, "")
	assert.Equal(t, expectedBucket, bucket)
	assert.Equal(t, expectedRegion, region)
	assert.Nil(t, err)
}

func TestCreateScratchBucketNoSourceFileBucketCreatedBasedOnInputZone(t *testing.T) {
	mockCtrl := gomock.NewController(t)
	defer mockCtrl.Finish()

	project := "proJect1"
	expectedBucket := "project1-daisy-bkt-asia-east1"
	expectedRegion := "asia-east1"
	ctx := context.Background()

	mockStorageClient := mocks.NewMockStorageClientInterface(mockCtrl)
	mockStorageClient.EXPECT().CreateBucket(expectedBucket, project, &storage.BucketAttrs{
		Name:         expectedBucket,
		Location:     "asia-east1",
		StorageClass: regionalStorageClass,
	}).Return(nil)

	c := ScratchBucketCreator{mockStorageClient, ctx, createMockBucketIteratorWithRandomBuckets(mockCtrl, &ctx, mockStorageClient, project)}
	bucket, region, err := c.CreateScratchBucket("", project, "asia-east1-b")
	assert.Equal(t, expectedBucket, bucket)
	assert.Equal(t, expectedRegion, region)
	assert.Nil(t, err)
}

func TestCreateScratchBucketNoSourceErrorCreatingDefaultBucket(t *testing.T) {
	mockCtrl := gomock.NewController(t)
	defer mockCtrl.Finish()

	project := "proJect1"
	wouldBeBucketName := "project1-daisy-bkt-us"
	ctx := context.Background()

	mockStorageClient := mocks.NewMockStorageClientInterface(mockCtrl)
	mockStorageClient.EXPECT().CreateBucket(wouldBeBucketName, project, &storage.BucketAttrs{
		Name:         wouldBeBucketName,
		Location:     defaultRegion,
		StorageClass: defaultStorageClass,
	}).Return(fmt.Errorf("some error"))

	c := ScratchBucketCreator{mockStorageClient, ctx, createMockBucketIteratorWithRandomBuckets(mockCtrl, &ctx, mockStorageClient, project)}
	bucket, region, err := c.CreateScratchBucket("", project, "")
	assert.Equal(t, "", bucket)
	assert.Equal(t, "", region)
	assert.NotNil(t, err)
	assert.Equal(t, "some error", err.Error())
}

func TestCreateScratchBucketNewBucketCreatedProject(t *testing.T) {
	mockCtrl := gomock.NewController(t)
	defer mockCtrl.Finish()
	project := "PROJECT1"

	ctx := context.Background()

	sourceBucketAttrs := &storage.BucketAttrs{
		Name:         "sourcebucket",
		Location:     "us-west2",
		StorageClass: "regional",
	}
	anotherBucketAttrs := &storage.BucketAttrs{
		Name:         "anotherbucket",
		Location:     "europe-north1",
		StorageClass: "regional",
	}

	scratchBucketAttrs := &storage.BucketAttrs{
		Name:         "project1-daisy-bkt-us-west2",
		Location:     "us-west2",
		StorageClass: "regional",
	}

	mockStorageClient := mocks.NewMockStorageClientInterface(mockCtrl)
	mockStorageClient.EXPECT().GetBucketAttrs(sourceBucketAttrs.Name).Return(sourceBucketAttrs, nil).Times(1)
	mockStorageClient.EXPECT().CreateBucket("project1-daisy-bkt-us-west2", project, scratchBucketAttrs).Return(nil).Times(1)

	mockBucketIterator := mocks.NewMockBucketIteratorInterface(mockCtrl)
	first := mockBucketIterator.EXPECT().Next().Return(anotherBucketAttrs, nil)
	second := mockBucketIterator.EXPECT().Next().Return(sourceBucketAttrs, nil)
	third := mockBucketIterator.EXPECT().Next().Return(nil, iterator.Done)

	gomock.InOrder(
		first,
		second,
		third,
	)

	mockBucketIteratorCreator := mocks.NewMockBucketIteratorCreatorInterface(mockCtrl)
	mockBucketIteratorCreator.EXPECT().
		CreateBucketIterator(ctx, mockStorageClient, project).
		Return(mockBucketIterator).
		Times(1)

	c := ScratchBucketCreator{mockStorageClient, ctx, mockBucketIteratorCreator}
	bucket, region, err := c.CreateScratchBucket("gs://sourcebucket/sourcefile", project, "")
	assert.Equal(t, "project1-daisy-bkt-us-west2", bucket)
	assert.Equal(t, "us-west2", region)
	assert.Nil(t, err)
}

func TestCreateScratchBucketInvalidSourceFileErrorThrown(t *testing.T) {
	mockCtrl := gomock.NewController(t)
	defer mockCtrl.Finish()

	project := "proJect1"

	c := ScratchBucketCreator{}
	gcsPath := "NOT_A_GS_PATH"
	_, _, err := c.CreateScratchBucket(gcsPath, project, "")
	assert.NotNil(t, err)
	assert.True(t, strings.HasPrefix(err.Error(), fmt.Sprintf("file GCS path `%v` is invalid:", gcsPath)))
}

func TestCreateScratchBucketErrorRetrievingSourceFileBucketMetadataDefaultBucketCreated(t *testing.T) {
	mockCtrl := gomock.NewController(t)
	defer mockCtrl.Finish()

	project := "proJect1"
	expectedBucket := "project1-daisy-bkt-us"
	expectedRegion := "US"
	ctx := context.Background()

	mockStorageClient := mocks.NewMockStorageClientInterface(mockCtrl)
	mockStorageClient.EXPECT().GetBucketAttrs("sourcebucket").Return(&storage.BucketAttrs{}, fmt.Errorf("error retrieving bucket attrs")).Times(1)
	mockStorageClient.EXPECT().CreateBucket(expectedBucket, project, &storage.BucketAttrs{
		Name:         expectedBucket,
		Location:     defaultRegion,
		StorageClass: defaultStorageClass,
	}).Return(nil)

	c := ScratchBucketCreator{mockStorageClient, ctx, createMockBucketIteratorWithRandomBuckets(mockCtrl, &ctx, mockStorageClient, project)}
	bucket, region, err := c.CreateScratchBucket("gs://sourcebucket/sourcefile", project, "")
	assert.Equal(t, expectedBucket, bucket)
	assert.Equal(t, expectedRegion, region)
	assert.Nil(t, err)
}

func TestCreateScratchBucketErrorRetrievingSourceFileBucketMetadataBucketCreatedBasedOnInputZone(t *testing.T) {
	mockCtrl := gomock.NewController(t)
	defer mockCtrl.Finish()

	project := "proJect1"
	expectedBucket := "project1-daisy-bkt-asia-east1"
	expectedRegion := "asia-east1"
	ctx := context.Background()

	mockStorageClient := mocks.NewMockStorageClientInterface(mockCtrl)
	mockStorageClient.EXPECT().GetBucketAttrs("sourcebucket").Return(&storage.BucketAttrs{}, fmt.Errorf("error retrieving bucket attrs")).Times(1)
	mockStorageClient.EXPECT().CreateBucket(expectedBucket, project, &storage.BucketAttrs{
		Name:         expectedBucket,
		Location:     "asia-east1",
		StorageClass: regionalStorageClass,
	}).Return(nil)

	c := ScratchBucketCreator{mockStorageClient, ctx, createMockBucketIteratorWithRandomBuckets(mockCtrl, &ctx, mockStorageClient, project)}
	bucket, region, err := c.CreateScratchBucket("gs://sourcebucket/sourcefile", project, "asia-east1-b")
	assert.Equal(t, expectedBucket, bucket)
	assert.Equal(t, expectedRegion, region)
	assert.Nil(t, err)
}

func TestCreateScratchBucketNilSourceFileBucketMetadataDefaultBucketCreated(t *testing.T) {
	mockCtrl := gomock.NewController(t)
	defer mockCtrl.Finish()

	project := "proJect1"
	expectedBucket := "project1-daisy-bkt-us"
	expectedRegion := "US"
	ctx := context.Background()

	mockStorageClient := mocks.NewMockStorageClientInterface(mockCtrl)
	mockStorageClient.EXPECT().GetBucketAttrs("sourcebucket").Return(nil, nil).Times(1)
	mockStorageClient.EXPECT().CreateBucket(expectedBucket, project, &storage.BucketAttrs{
		Name:         expectedBucket,
		Location:     defaultRegion,
		StorageClass: defaultStorageClass,
	}).Return(nil)

	c := ScratchBucketCreator{mockStorageClient, ctx, createMockBucketIteratorWithRandomBuckets(mockCtrl, &ctx, mockStorageClient, project)}
	bucket, region, err := c.CreateScratchBucket("gs://sourcebucket/sourcefile", project, "")
	assert.Equal(t, expectedBucket, bucket)
	assert.Equal(t, expectedRegion, region)
	assert.Nil(t, err)
}

func TestCreateScratchBucketErrorWhenIteratingOverProjectBucketsWhileCreatingBucketBasedOnSourceFile(t *testing.T) {
	mockCtrl := gomock.NewController(t)
	defer mockCtrl.Finish()
	ctx := context.Background()

	projectID := "PROJECT1"

	sourceBucketAttrs := &storage.BucketAttrs{
		Name:         "sourcebucket",
		Location:     "us-west2",
		StorageClass: "regional",
	}
	mockStorageClient := mocks.NewMockStorageClientInterface(mockCtrl)
	mockStorageClient.EXPECT().GetBucketAttrs("sourcebucket").Return(sourceBucketAttrs, nil).Times(1)

	mockBucketIterator := mocks.NewMockBucketIteratorInterface(mockCtrl)
	mockBucketIterator.EXPECT().Next().Return(nil, fmt.Errorf("iterator error"))

	mockBucketIteratorCreator := mocks.NewMockBucketIteratorCreatorInterface(mockCtrl)
	mockBucketIteratorCreator.EXPECT().CreateBucketIterator(ctx, mockStorageClient, projectID).
		Return(mockBucketIterator)

	c := ScratchBucketCreator{mockStorageClient, ctx, mockBucketIteratorCreator}
	_, _, err := c.CreateScratchBucket("gs://sourcebucket/sourcefile", projectID, "")
	assert.NotNil(t, err)
	assert.Equal(t, "iterator error", err.Error())
}

func TestCreateScratchBucketReturnsExistingScratchBucketNoCreate(t *testing.T) {
	mockCtrl := gomock.NewController(t)
	defer mockCtrl.Finish()
	ctx := context.Background()

	projectID := "PROJECT1"

	sourceBucketAttrs := &storage.BucketAttrs{
		Name:         "sourcebucket",
		Location:     "us-west2",
		StorageClass: "regional",
	}
	anotherBucketAttrs := &storage.BucketAttrs{
		Name:         "anotherbucket",
		Location:     "europe-north1",
		StorageClass: "regional",
	}

	scratchBucketAttrs := &storage.BucketAttrs{
		Name:         "project1-daisy-bkt-us-west2",
		Location:     "us-west2",
		StorageClass: "regional",
	}
	mockStorageClient := mocks.NewMockStorageClientInterface(mockCtrl)
	mockStorageClient.EXPECT().GetBucketAttrs("sourcebucket").Return(sourceBucketAttrs, nil).Times(1)

	mockBucketIterator := mocks.NewMockBucketIteratorInterface(mockCtrl)
	first := mockBucketIterator.EXPECT().Next().Return(anotherBucketAttrs, nil)
	second := mockBucketIterator.EXPECT().Next().Return(sourceBucketAttrs, nil)
	third := mockBucketIterator.EXPECT().Next().Return(scratchBucketAttrs, nil)

	gomock.InOrder(first, second, third)

	mockBucketIteratorCreator := mocks.NewMockBucketIteratorCreatorInterface(mockCtrl)
	mockBucketIteratorCreator.EXPECT().
		CreateBucketIterator(ctx, mockStorageClient, projectID).
		Return(mockBucketIterator).
		Times(1)

	c := ScratchBucketCreator{mockStorageClient, ctx, mockBucketIteratorCreator}
	bucket, region, err := c.CreateScratchBucket("gs://sourcebucket/sourcefile", projectID, "")
	assert.Equal(t, "project1-daisy-bkt-us-west2", bucket)
	assert.Equal(t, "us-west2", region)
	assert.Nil(t, err)
}

func TestCreateScratchBucketErrorWhenCreatingBucket(t *testing.T) {
	mockCtrl := gomock.NewController(t)
	defer mockCtrl.Finish()
	ctx := context.Background()

	project := "PROJECT1"

	sourceBucketAttrs := &storage.BucketAttrs{
		Name:         "sourcebucket",
		Location:     "us-west2",
		StorageClass: "regional",
	}
	anotherBucketAttrs := &storage.BucketAttrs{
		Name:         "anotherbucket",
		Location:     "europe-north1",
		StorageClass: "regional",
	}

	scratchBucketAttrs := &storage.BucketAttrs{
		Name:         "project1-daisy-bkt-us-west2",
		Location:     "us-west2",
		StorageClass: "regional",
	}
	mockStorageClient := mocks.NewMockStorageClientInterface(mockCtrl)
	mockStorageClient.EXPECT().
		GetBucketAttrs("sourcebucket").
		Return(sourceBucketAttrs, nil).
		Times(1)
	mockStorageClient.EXPECT().
		CreateBucket("project1-daisy-bkt-us-west2", project, scratchBucketAttrs).
		Return(fmt.Errorf("error creating a bucket")).
		Times(1)

	mockBucketIterator := mocks.NewMockBucketIteratorInterface(mockCtrl)
	first := mockBucketIterator.EXPECT().Next().Return(anotherBucketAttrs, nil)
	second := mockBucketIterator.EXPECT().Next().Return(sourceBucketAttrs, nil)
	third := mockBucketIterator.EXPECT().Next().Return(nil, iterator.Done)

	gomock.InOrder(first, second, third)

	mockBucketIteratorCreator := mocks.NewMockBucketIteratorCreatorInterface(mockCtrl)
	mockBucketIteratorCreator.EXPECT().
		CreateBucketIterator(ctx, mockStorageClient, project).
		Return(mockBucketIterator)

	c := ScratchBucketCreator{mockStorageClient, ctx, mockBucketIteratorCreator}
	_, _, err := c.CreateScratchBucket("gs://sourcebucket/sourcefile", project, "")
	assert.NotNil(t, err)
	assert.Equal(t, "error creating a bucket", err.Error())
}

func TestIsBucketInProjectTrue(t *testing.T) {
	mockCtrl := gomock.NewController(t)
	defer mockCtrl.Finish()
	ctx := context.Background()

	projectID := "PROJECT1"

	anotherBucketAttrs := &storage.BucketAttrs{
		Name:         "anotherbucket",
		Location:     "europe-north1",
		StorageClass: "regional",
	}
	scratchBucketAttrs := &storage.BucketAttrs{
		Name:         "project1-daisy-bkt-us-west2",
		Location:     "us-west2",
		StorageClass: "regional",
	}
	mockStorageClient := mocks.NewMockStorageClientInterface(mockCtrl)
	mockBucketIterator := mocks.NewMockBucketIteratorInterface(mockCtrl)
	first := mockBucketIterator.EXPECT().Next().Return(anotherBucketAttrs, nil)
	second := mockBucketIterator.EXPECT().Next().Return(scratchBucketAttrs, nil)

	gomock.InOrder(first, second)

	mockBucketIteratorCreator := mocks.NewMockBucketIteratorCreatorInterface(mockCtrl)
	mockBucketIteratorCreator.EXPECT().
		CreateBucketIterator(ctx, mockStorageClient, projectID).
		Return(mockBucketIterator).
		Times(1)

	c := ScratchBucketCreator{mockStorageClient, ctx, mockBucketIteratorCreator}
	result := c.IsBucketInProject(projectID, "project1-daisy-bkt-us-west2")
	assert.True(t, result)
}

func TestIsBucketInProjectFalseOnNoBucket(t *testing.T) {
	mockCtrl := gomock.NewController(t)
	defer mockCtrl.Finish()
	ctx := context.Background()

	projectID := "PROJECT1"

	anotherBucketAttrs := &storage.BucketAttrs{
		Name:         "anotherbucket",
		Location:     "europe-north1",
		StorageClass: "regional",
	}
	scratchBucketAttrs := &storage.BucketAttrs{
		Name:         "some-other-bucket",
		Location:     "us-west2",
		StorageClass: "regional",
	}
	mockStorageClient := mocks.NewMockStorageClientInterface(mockCtrl)
	mockBucketIterator := mocks.NewMockBucketIteratorInterface(mockCtrl)
	first := mockBucketIterator.EXPECT().Next().Return(anotherBucketAttrs, nil)
	second := mockBucketIterator.EXPECT().Next().Return(scratchBucketAttrs, nil)
	third := mockBucketIterator.EXPECT().Next().Return(nil, iterator.Done)
	gomock.InOrder(first, second, third)

	mockBucketIteratorCreator := mocks.NewMockBucketIteratorCreatorInterface(mockCtrl)
	mockBucketIteratorCreator.EXPECT().
		CreateBucketIterator(ctx, mockStorageClient, projectID).
		Return(mockBucketIterator).
		Times(1)

	c := ScratchBucketCreator{mockStorageClient, ctx, mockBucketIteratorCreator}
	result := c.IsBucketInProject(projectID, "project1-daisy-bkt-us-west2")
	assert.False(t, result)
}

func TestIsBucketInProjectFalseOnIteratorError(t *testing.T) {
	mockCtrl := gomock.NewController(t)
	defer mockCtrl.Finish()
	ctx := context.Background()

	projectID := "PROJECT1"

	mockStorageClient := mocks.NewMockStorageClientInterface(mockCtrl)
	mockBucketIterator := mocks.NewMockBucketIteratorInterface(mockCtrl)
	first := mockBucketIterator.EXPECT().Next().Return(nil, fmt.Errorf(""))
	gomock.InOrder(first)

	mockBucketIteratorCreator := mocks.NewMockBucketIteratorCreatorInterface(mockCtrl)
	mockBucketIteratorCreator.EXPECT().
		CreateBucketIterator(ctx, mockStorageClient, projectID).
		Return(mockBucketIterator).
		Times(1)

	c := ScratchBucketCreator{mockStorageClient, ctx, mockBucketIteratorCreator}
	result := c.IsBucketInProject(projectID, "project1-daisy-bkt-us-west2")
	assert.False(t, result)
}

func createMockBucketIteratorWithRandomBuckets(mockCtrl *gomock.Controller, ctx *context.Context,
	storageClient domain.StorageClientInterface,
	project string) domain.BucketIteratorCreatorInterface {
	firstBucketAttrs := &storage.BucketAttrs{
		Name:         "firstbucket",
		Location:     "us-west2",
		StorageClass: "regional",
	}
	secondBucketAttrs := &storage.BucketAttrs{
		Name:         "secondbucket",
		Location:     "EU",
		StorageClass: "multi_regional",
	}
	thirdBucketAttrs := &storage.BucketAttrs{
		Name:         "thirdbucket",
		Location:     "europe-north1",
		StorageClass: "regional",
	}

	mockBucketIterator := mocks.NewMockBucketIteratorInterface(mockCtrl)
	first := mockBucketIterator.EXPECT().Next().Return(firstBucketAttrs, nil)
	second := mockBucketIterator.EXPECT().Next().Return(secondBucketAttrs, nil)
	third := mockBucketIterator.EXPECT().Next().Return(thirdBucketAttrs, nil)
	fourth := mockBucketIterator.EXPECT().Next().Return(nil, iterator.Done)
	gomock.InOrder(first, second, third, fourth)

	mockBucketIteratorCreator := mocks.NewMockBucketIteratorCreatorInterface(mockCtrl)
	mockBucketIteratorCreator.EXPECT().
		CreateBucketIterator(*ctx, storageClient, project).
		Return(mockBucketIterator).
		Times(1)
	return mockBucketIteratorCreator
}

func assertErrorFromCreateScratchBucket(t *testing.T, bucket string, region string, err error) {
	assert.Equal(t, "", bucket)
	assert.Equal(t, "", region)
	assert.NotNil(t, err)
}


text:
"""
    Swaggy Jenkins

    Jenkins API clients generated from Swagger / Open API specification  # noqa: E501

    The version of the OpenAPI document: 1.5.1-pre.0
    Contact: blah@cliffano.com
    Generated by: https://openapi-generator.tech
"""

import re  # noqa: F401
import sys  # noqa: F401
import typing  # noqa: F401
import functools  # noqa: F401

from frozendict import frozendict  # noqa: F401

import decimal  # noqa: F401
from datetime import date, datetime  # noqa: F401
from frozendict import frozendict  # noqa: F401

from openapi_client.schemas import (  # noqa: F401
    AnyTypeSchema,
    ComposedSchema,
    DictSchema,
    ListSchema,
    StrSchema,
    IntSchema,
    Int32Schema,
    Int64Schema,
    Float32Schema,
    Float64Schema,
    NumberSchema,
    UUIDSchema,
    DateSchema,
    DateTimeSchema,
    DecimalSchema,
    BoolSchema,
    BinarySchema,
    NoneSchema,
    none_type,
    Configuration,
    Unset,
    unset,
    ComposedBase,
    ListBase,
    DictBase,
    NoneBase,
    StrBase,
    IntBase,
    Int32Base,
    Int64Base,
    Float32Base,
    Float64Base,
    NumberBase,
    UUIDBase,
    DateBase,
    DateTimeBase,
    BoolBase,
    BinaryBase,
    Schema,
    _SchemaValidator,
    _SchemaTypeChecker,
    _SchemaEnumMaker
)

class PipelineBranches(
    ListSchema
):
    """NOTE: This class is auto generated by OpenAPI Generator.
    Ref: https://openapi-generator.tech

    Do not edit the class manually.
    """

    @classmethod
    @property
    def _items(cls) -> typing.Type['PipelineBranchesitem']:
        return PipelineBranchesitem

from openapi_client.model.pipeline_branchesitem import PipelineBranchesitem


text:
//Copyright (c) 2017 Jan Pluskal
//
//Permission is hereby granted, free of charge, to any person
//obtaining a copy of this software and associated documentation
//files (the "Software"), to deal in the Software without
//restriction, including without limitation the rights to use,
//copy, modify, merge, publish, distribute, sublicense, and/or sell
//copies of the Software, and to permit persons to whom the
//Software is furnished to do so, subject to the following
//conditions:
//
//The above copyright notice and this permission notice shall be
//included in all copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
//EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
//OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
//NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
//HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
//WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
//FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
//OTHER DEALINGS IN THE SOFTWARE.

using System;
using System.Collections.Generic;
using System.Linq;
using AppIdent.Metrics;
using AppIdent.Misc;
using AppIdent.Models;
using Framework.Models;
using Netfox.Core.Enums;

namespace AppIdent.Features.Bases
{
    public class MeanInterArrivalTimeBase : FeatureBase
    {
        public MeanInterArrivalTimeBase() { }
        public MeanInterArrivalTimeBase(L7Conversation l7Conversation, DaRFlowDirection flowDirection) : base(l7Conversation, flowDirection) { }
        public MeanInterArrivalTimeBase(double featureValue) : base(featureValue) { }
        public override FeatureKind FeatureKind { get; } = FeatureKind.Continous;
        public override double WeightBias { get; } = 0.3;

        public override double ComputeDistanceToProtocolModel(FeatureBase sampleFeature)
        {
            return Math.Abs(this.Normalize(this.FeatureValue) - this.Normalize(sampleFeature.FeatureValue));
        }

        public override double ComputeFeature(L7Conversation l7Conversation, DaRFlowDirection flowDirection)
        {
            IEnumerable<L7PDU> pdus;
            switch(flowDirection)
            {
                case DaRFlowDirection.up:
                    pdus = l7Conversation.UpFlowPDUs;
                    break;
                case DaRFlowDirection.down:
                    pdus = l7Conversation.DownFlowPDUs;
                    break;
                case DaRFlowDirection.non:
                    pdus = l7Conversation.L7PDUs;
                    break;
                default: throw new ArgumentOutOfRangeException(nameof(flowDirection), flowDirection, null);
            }

            var l7Pdus = pdus as L7PDU[] ?? pdus.ToArray();
            if(!l7Pdus.Any()) { return -1; }

            var length = l7Pdus.Count();

            if(length <= 1) { return 0; }

            var tmpTime = 0.0;

            for(var i = 0; i < length - 1; i++) { tmpTime += (l7Pdus[i + 1].FirstSeen - l7Pdus[i].FirstSeen).TotalSeconds; }
            var meanTime = tmpTime / length;

            return meanTime;
        }

        public override void ComputeFeatureForProtocolModel(IFeatureCollectionWrapper<FeatureBase> featureValues)
        {
            this.FeatureValue = FeatureMetrics.FeatureMetricAverage(featureValues);
            this.Weight = WeightMetrics.WeightUsingNormEntropy(featureValues);
        }
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Summa veg. Scand. (Stockholm), Section Post. 481 (1849)

#### Original name
Myriophysa atra Fr.

### Remarks
null


text:
import {assert} from '@ciscospark/test-helper-chai';
import {SparkHttpError} from '@ciscospark/spark-core';
import sinon from '@ciscospark/test-helper-sinon';
import testUsers from '@ciscospark/test-helper-test-users';
import CiscoSpark from 'ciscospark';
import {find} from 'lodash';

describe(`ciscospark`, function() {
  this.timeout(60000);

  let spark, user;
  before(() => testUsers.create({count: 1})
    .then(([u]) => {
      user = u;
      spark = new CiscoSpark({credentials: user.token});
    }));

  describe(`CiscoSpark`, () => {
    describe(`#teams`, () => {
      describe(`#create()`, () => {
        it(`creates a team`, () => spark.teams.create({
          name: `Cisco Spark Test Team (create)`
        })
          .then((team) => assert.isTeam(team)));
      });

      describe(`#get()`, () => {
        it(`retrieves a specific team`, () => spark.teams.create({
          name: `Cisco Spark Test Team (get)`
        })
          .then((team) => {
            assert.isTeam(team);
            return assert.becomes(spark.teams.get({id: team.id}), team);
          }));
      });

      describe(`#list()`, () => {
        // Reminder: we can't run the next two creates in parallel because some of
        // the tests rely on ordering.
        let team0, team1;
        before(() => spark.teams.create({name: `Cisco Spark Test Team 1`})
          .then((team) => {
            team1 = team;
          }));

        before(() => spark.teams.create({name: `Cisco Spark Test Team 0`})
          .then((team) => {
            team0 = team;
          }));

        it(`lists all of the teams to which I have access`, () => spark.teams.list()
          .then((teams) => {
            assert.isAbove(teams.length, 1);
            for (const team of teams) {
              assert.isTeam(team);
            }
          }));

        it(`lists a bounded, pageable set of teams to which I have access`, () => spark.teams.list({max: 1})
          .then((teams) => {
            assert.lengthOf(teams, 1);
            const spy = sinon.spy();
            return (function f(page) {
              for (const team of page) {
                spy(team.id);
              }

              if (page.hasNext()) {
                return page.next().then(f);
              }

              return Promise.resolve();
            }(teams))
              .then(() => {
                assert.isAbove(spy.callCount, 1);
                assert.calledWith(spy, team0.id);
                assert.calledWith(spy, team1.id);
              });
          }));
      });

      describe(`#update()`, () => {
        it(`updates a single team's name`, () => spark.teams.create({
          name: `Cisco Spark Test Team`
        })
        .then((team) => {
          assert.isTeam(team);
          return spark.teams.update(Object.assign({}, team, {name: `Cisco Spark Test Team (Updated)`}));
        })
        .then((team) => {
          assert.isTeam(team);
          assert.equal(team.name, `Cisco Spark Test Team (Updated)`);
        }));
      });
    });

    describe(`#rooms`, () => {
      let team;

      before(() => spark.teams.create({
        name: `Cisco Spark Test Team`
      })
        .then((t) => {team = t;}));

      describe(`#create()`, () => {
        // COLLAB-1104 create date don't match; Mike is working on a fix
        it.skip(`creates a room that is part of a team`, () => spark.rooms.create({
          title: `Team Room`,
          teamId: team.id
        })
          .then((room) => {
            assert.isTeamRoom(room);
            assert.equal(room.teamId, team.id);
          }));
      });

      describe(`#get()`, () => {
        it(`retrieves a specific room that is part of a team`, () => spark.rooms.create({
          title: `Team Room`,
          teamId: team.id
        })
          .then((room) => spark.rooms.get(room))
          .then((room) => {
            assert.isTeamRoom(room);
            assert.equal(room.teamId, team.id);
          }));

        describe(`when the user leaves the team's general room`, () => {
          let room, team;

          it(`no longer returns the team's rooms`, () => spark.teams.create({
            name: `Team Title`
          })
            .then((t) => {
              team = t;
              return spark.rooms.create({
                title: `Room Title`,
                teamId: team.id
              });
            })
            .then((r) => {
              room = r;
              return spark.rooms.list({teamId: team.id});
            })
            .then((teamRooms) => {
              assert.lengthOf(teamRooms, 2);
              const generalRoom = find(teamRooms.items, (r) => r.id !== room.id);
              return spark.memberships.list({roomId: generalRoom.id, personId: user.id});
            })
            .then((memberships) => {
              return spark.memberships.remove(memberships.items[0]);
            })
            .then(() => {
              return assert.isRejected(spark.rooms.get(room));
            })
            .then((reason) => {
              assert.instanceOf(reason, SparkHttpError.NotFound);
            }));
        });
      });

      describe(`#list()`, () => {
        it(`lists all rooms in a team`, () => spark.rooms.create({
          title: `Team Room`,
          teamId: team.id
        })
          .then(() => spark.rooms.list({teamId: team.id}))
          .then((rooms) => {
            assert.isAbove(rooms.length, 0);
            for (const room of rooms) {
              assert.isTeamRoom(room);
              assert.equal(room.teamId, team.id);
            }
          }));
      });
    });
  });
});


text:
// -*- C++ -*-
//
// Package:    TestBeginEndJobAnalyzer
// Class:      TestBeginEndJobAnalyzer
//

#include "art/Framework/Core/Frameworkfwd.h"
#include "art/test/Framework/Core/stubs/TestBeginEndJobAnalyzer.h"

#include <memory>

TestBeginEndJobAnalyzer::
TestBeginEndJobAnalyzer(const fhicl::ParameterSet& pset)
  : art::EDAnalyzer(pset)
{
}

TestBeginEndJobAnalyzer::~TestBeginEndJobAnalyzer() {
  destructorCalled = true;
}

bool TestBeginEndJobAnalyzer::beginJobCalled = false;
bool TestBeginEndJobAnalyzer::endJobCalled = false;
bool TestBeginEndJobAnalyzer::beginRunCalled = false;
bool TestBeginEndJobAnalyzer::endRunCalled = false;
bool TestBeginEndJobAnalyzer::beginSubRunCalled = false;
bool TestBeginEndJobAnalyzer::endSubRunCalled = false;
bool TestBeginEndJobAnalyzer::destructorCalled = false;

void
TestBeginEndJobAnalyzer::beginJob(const art::EventSetup&) {
  beginJobCalled = true;
}

void
TestBeginEndJobAnalyzer::endJob() {
  endJobCalled = true;
}

void
TestBeginEndJobAnalyzer::beginRun(art::Run const&) {
  beginRunCalled = true;
}

void
TestBeginEndJobAnalyzer::endRun(art::Run const&) {
  endRunCalled = true;
}

void
TestBeginEndJobAnalyzer::beginSubRun(art::SubRun const&) {
  beginSubRunCalled = true;
}

void
TestBeginEndJobAnalyzer::endSubRun(art::SubRun const&) {
  endSubRunCalled = true;
}

void
TestBeginEndJobAnalyzer::analyze(const art::Event& /* iEvent */, const art::EventSetup& /* iSetup */) {
}


text:
# works with a file called VERSION in the current directory,
# the contents of which should be a semantic version number
# such as "1.2.3"

# this script will display the current version, automatically
# suggest a "minor" version update, and ask for input to use
# the suggestion, or a newly entered value.

# once the new version number is determined, the script will
# pull a list of changes from git history, prepend this to
# a file called CHANGES (under the title of the new version
# number) and create a GIT tag.

if [ -f VERSION ]; then
    BASE_STRING=`cat VERSION`
    BASE_LIST=(`echo $BASE_STRING | tr '.' ' '`)
    V_MAJOR=${BASE_LIST[0]}
    V_MINOR=${BASE_LIST[1]}
    V_PATCH=${BASE_LIST[2]}
    echo "Current version : $BASE_STRING"
    V_MINOR=$((V_MINOR + 1))
    V_PATCH=0
    SUGGESTED_VERSION="$V_MAJOR.$V_MINOR.$V_PATCH"
    read -p "Enter a version number [$SUGGESTED_VERSION]: " INPUT_STRING
    if [ "$INPUT_STRING" = "" ]; then
        INPUT_STRING=$SUGGESTED_VERSION
    fi
    echo "Will set new version to be $INPUT_STRING"
    echo $INPUT_STRING > VERSION
    echo "Version $INPUT_STRING:" > tmpfile
    git log --pretty=format:" - %s" "$BASE_STRING"...HEAD >> tmpfile
    echo "" >> tmpfile
    echo "" >> tmpfile
    cat CHANGES >> tmpfile
    mv tmpfile CHANGES
    git add CHANGES VERSION
    git commit -m "Version bump to $INPUT_STRING"
    git tag -a -m "Tagging version $INPUT_STRING" "$INPUT_STRING"
    git push origin --tags
    git push
else
    echo "Could not find a VERSION file"
    read -p "Do you want to create a version file and start from scratch? [y]" RESPONSE
    if [ "$RESPONSE" = "" ]; then RESPONSE="y"; fi
    if [ "$RESPONSE" = "Y" ]; then RESPONSE="y"; fi
    if [ "$RESPONSE" = "Yes" ]; then RESPONSE="y"; fi
    if [ "$RESPONSE" = "yes" ]; then RESPONSE="y"; fi
    if [ "$RESPONSE" = "YES" ]; then RESPONSE="y"; fi
    if [ "$RESPONSE" = "y" ]; then
        echo "0.1.0" > VERSION
        echo "Version 0.1.0" > CHANGES
        git log --pretty=format:" - %s" >> CHANGES
        echo "" >> CHANGES
        echo "" >> CHANGES
        git add VERSION CHANGES
        git commit -m "Added VERSION and CHANGES files, Version bump to 0.1.0"
        git tag -a -m "Tagging version 0.1.0" "0.1.0"
        git push origin --tags
        git push
    fi

fi


text:
namespace device {

// Test double for CpuProbe that always returns a predetermined value.
class FakeCpuProbe : public CpuProbe {
 public:
  // Value returned by LastSample() if SetLastSample() is not called.
  static constexpr PressureSample kInitialSample{0.42};

  FakeCpuProbe();
  ~FakeCpuProbe() override;

  // CpuProbe implementation.
  void Update() override;
  PressureSample LastSample() override;

  // Can be called from any thread.
  void SetLastSample(PressureSample sample);

 private:
  // Bound to the sequence for Update() and LastSample().
  SEQUENCE_CHECKER(sequence_checker_);

  base::Lock lock_;
  PressureSample last_sample_ GUARDED_BY_CONTEXT(lock_);
};

}  // namespace device

#endif  // SERVICES_DEVICE_COMPUTE_PRESSURE_PRESSURE_TEST_SUPPORT_H_