text:
=head1 NAME

Mail::SpamAssassin::AsyncLoop - scanner asynchronous event loop

=head1 DESCRIPTION

An asynchronous event loop used for long-running operations, performed "in the
background" during the Mail::SpamAssassin::check() scan operation, such as DNS
blocklist lookups.

=head1 METHODS

=over 4

=cut

package Mail::SpamAssassin::AsyncLoop;

use strict;
use warnings;
use bytes;

use Mail::SpamAssassin;
use Mail::SpamAssassin::Logger;

our @ISA = qw();

# Load Time::HiRes if it's available
BEGIN {
  use vars qw($timer_resolution);
  eval {
    require Time::HiRes or die "Error loading Time::HiRes: $@, $!";
    Time::HiRes->import( qw(time) );
    $timer_resolution = Time::HiRes->can('clock_getres')
      ? Time::HiRes::clock_getres(Time::HiRes::CLOCK_REALTIME())
      : 0.001;  # wild guess, assume resolution is better than 1s
    1;
  } or do {
    $timer_resolution = 1;  # Perl's builtin timer ticks at one second
  };
}

#############################################################################

sub new {
  my $class = shift;
  $class = ref($class) || $class;

  my ($main) = @_;
  my $self = {
    main                => $main,
    queries_started     => 0,
    queries_completed   => 0,
    total_queries_started   => 0,
    total_queries_completed => 0,
    pending_lookups     => { },
    timing_by_query     => { },
  };

  bless ($self, $class);
  $self;
}

# ---------------------------------------------------------------------------

=item $obj = $async->start_lookup($obj)

Register the start of a long-running asynchronous lookup operation. C<$obj>
is a hash reference containing the following items:

=over 4

=item key (required)

A key string, unique to this lookup.  This is what is reported in
debug messages, used as the key for C<get_lookup()>, etc.

=item id (required)

An ID string, also unique to this lookup.  Typically, this is the DNS packet ID
as returned by DnsResolver's C<bgsend> method.  Sadly, the Net::DNS
architecture forces us to keep a separate ID string for this task instead of
reusing C<key> -- if you are not using DNS lookups through DnsResolver, it
should be OK to just reuse C<key>.

=item type (required)

A string, typically one word, used to describe the type of lookup in log
messages, such as C<DNSBL>, C<MX>, C<TXT>.

=item poll_callback (optional)

A code reference, which will be called periodically during the
background-processing period.  If you will be performing an async lookup on a
non-DNS-based service, you will need to implement this so that it checks for
new responses and calls C<set_response_packet()> or C<report_id_complete()> as
appropriate.   DNS-based lookups can leave it undefined, since
DnsResolver::poll_responses() will be called automatically anyway.

The code reference will be called with one argument, the C<$ent> object.

=item completed_callback (optional)

A code reference which will be called when an asynchronous task (e.g. a
DNS lookup) is completed, either normally, or aborted, e.g. by a timeout.

When a task has been reported as completed via C<set_response_packet()>
the response (as provided to C<set_response_packet()>) is stored in
$ent->{response_packet} (possibly undef, its semantics is defined by the
caller). When completion is reported via C<report_id_complete()> or a
task was aborted, the $ent->{response_packet} is guaranteed to be undef.
If it is necessary to distinguish between the last two cases, the
$ent->{status} may be examined for a string 'ABORTING' or 'FINISHED'.

The code reference will be called with one argument, the C<$ent> object.

=item zone (optional)

A zone specification (typically a DNS zone name - e.g. host, domain, or RBL)
which may be used as a key to look up per-zone settings. No semantics on this
parameter is imposed by this module.

=item timeout_initial (optional)

An initial value of elapsed time for which we are willing to wait for a
response (time in seconds, floating point value is allowed). When elapsed
time since a query started exceeds the timeout value and there are no other
queries to wait for, the query is aborted. The actual timeout value ranges
from timeout_initial and gradually approaches timeout_min (see next parameter)
as the number of already completed queries approaches the number of all
queries started.

If a caller does not explicitly provide this parameter or its value is
undefined, a default initial timeout value is settable by a configuration
variable rbl_timeout.

If a value of the timeout_initial parameter is below timeout_min, the initial
timeout is set to timeout_min.

=item timeout_min (optional)

A lower bound (in seconds) to which the actual timeout approaches as the
number of queries completed approaches the number of all queries started.
Defaults to 0.2 * timeout_initial.

=back

C<$obj> is returned by this method.

=cut

sub start_lookup {
  my ($self, $ent) = @_;

  die "oops, no id"  unless $ent->{id};
  die "oops, no key" unless $ent->{key};
  die "oops, no type" unless $ent->{type};

  my $now = time;
  my $key = $ent->{key};
  my $id  = $ent->{id};
  $ent->{status} = 'STARTED';
  $ent->{start_time} = $now  if !defined $ent->{start_time};

  # are there any applicable per-zone settings?
  my $zone = $ent->{zone};
  my $settings;  # a ref to a by-zone or to global settings
  my $conf_by_zone = $self->{main}->{conf}->{by_zone};
  if (defined $zone && $conf_by_zone) {
  # dbg("async: searching for by_zone settings for $zone");
    $zone =~ s/^\.//;  $zone =~ s/\.\z//;  # strip leading and trailing dot
    for (;;) {  # 2.10.example.com, 10.example.com, example.com, com, ''
      if (exists $conf_by_zone->{$zone}) {
        $settings = $conf_by_zone->{$zone};
        dbg("async: applying by_zone settings for $zone");
        last;
      } elsif ($zone eq '') {
        last;
      } else {  # strip one level, careful with address literals
        $zone = ($zone =~ /^( (?: [^.] | \[ (?: \\. | [^\]\\] )* \] )* )
                            \. (.*) \z/xs) ? $2 : '';
      }
    }
  }

  my $t_init = $ent->{timeout_initial};  # application-specified has precedence
  $t_init = $settings->{rbl_timeout}  if $settings && !defined $t_init;
  $t_init = $self->{main}->{conf}->{rbl_timeout}  if !defined $t_init;
  $t_init = 0  if !defined $t_init;      # last-resort default, just in case

  my $t_end = $ent->{timeout_min};       # application-specified has precedence
  $t_end = $settings->{rbl_timeout_min}  if $settings && !defined $t_end;
  $t_end = 0.2 * $t_init  if !defined $t_end;
  $t_end = 0  if $t_end < 0;  # just in case

  $t_init = $t_end  if $t_init < $t_end;
  $ent->{timeout_initial} = $t_init;
  $ent->{timeout_min} = $t_end;

  $ent->{display_id} =  # identifies entry in debug logging and similar
    join(", ", grep { defined }
               map { ref $ent->{$_} ? @{$ent->{$_}} : $ent->{$_} }
               qw(sets rules rulename type key) );

  $self->{queries_started}++;
  $self->{total_queries_started}++;
  $self->{pending_lookups}->{$key} = $ent;

  dbg("async: starting: %s (timeout %.1fs, min %.1fs)",
      $ent->{display_id}, $ent->{timeout_initial}, $ent->{timeout_min});
  $ent;
}

# ---------------------------------------------------------------------------

=item $obj = $async->get_lookup($key)

Retrieve the pending-lookup object for the given key C<$key>.

If the lookup is complete, this will return C<undef>.

Note that a lookup is still considered "pending" until C<complete_lookups()> is
called, even if it has been reported as complete via C<set_response_packet()>
or C<report_id_complete()>.

=cut

sub get_lookup {
  my ($self, $key) = @_;
  return $self->{pending_lookups}->{$key};
}

# ---------------------------------------------------------------------------

=item @objs = $async->get_pending_lookups()

Retrieve the lookup objects for all pending lookups.

Note that a lookup is still considered "pending" until C<complete_lookups()> is
called, even if it has been reported as complete via C<set_response_packet()>
or C<report_id_complete()>.

=cut

sub get_pending_lookups {
  my ($self) = @_;
  return values %{$self->{pending_lookups}};
}

# ---------------------------------------------------------------------------

=item $async->log_lookups_timing()

Log sorted timing for all completed lookups.

=cut

sub log_lookups_timing {
  my ($self) = @_;
  my $timings = $self->{timing_by_query};
  for my $key (sort { $timings->{$a} <=> $timings->{$b} } keys %$timings) {
    dbg("async: timing: %.3f %s", $timings->{$key}, $key);
  }
}

# ---------------------------------------------------------------------------

=item $alldone = $async->complete_lookups()

Perform a poll of the pending lookups, to see if any are completed; if they
are, their <completed_callback> is called with the entry object for that
lookup.

If there are no lookups remaining, or if too long has elapsed since any results
were returned, C<1> is returned, otherwise C<0>.

=cut

sub complete_lookups {
  my ($self, $timeout, $allow_aborting_of_expired) = @_;
  my $alldone = 0;
  my $anydone = 0;
  my $waiting_time = 0;
  my $allexpired = 1;
  my %typecount;

  my $pending = $self->{pending_lookups};
  $self->{queries_started} = 0;
  $self->{queries_completed} = 0;

  my $now = time;

  if (defined $timeout && $timeout > 0 &&
      %$pending && $self->{total_queries_started} > 0)
  {
    # shrink a 'select' timeout if a caller specified unnecessarily long
    # value beyond the latest deadline of any outstanding request;
    # can save needless wait time (up to 1 second in harvest_dnsbl_queries)
    my $r = $self->{total_queries_completed} / $self->{total_queries_started};
    my $r2 = $r * $r;  # 0..1
    my $max_deadline;
    while (my($key,$ent) = each %$pending) {
      my $t_init = $ent->{timeout_initial};
      my $dt = $t_init - ($t_init - $ent->{timeout_min}) * $r2;
      my $deadline = $ent->{start_time} + $dt;
      $max_deadline = $deadline  if !defined $max_deadline ||
                                    $deadline > $max_deadline;
    }
    if (defined $max_deadline) {
      # adjust to timer resolution, only deals with 1s and with fine resolution
      $max_deadline = 1 + int $max_deadline
        if $timer_resolution == 1 && $max_deadline > int $max_deadline;
      my $sufficient_timeout = $max_deadline - $now;
      $sufficient_timeout = 0  if $sufficient_timeout < 0;
      if ($timeout > $sufficient_timeout) {
        dbg("async: reducing select timeout from %.1f to %.1f s",
            $timeout, $sufficient_timeout);
        $timeout = $sufficient_timeout;
      }
    }
  }

  # trap this loop in an eval { } block, as Net::DNS could throw
  # die()s our way; in particular, process_dnsbl_results() has
  # thrown die()s before (bug 3794).
  eval {

    if (%$pending) {  # any outstanding requests still?
      $self->{last_poll_responses_time} = $now;
      my $nfound = $self->{main}->{resolver}->poll_responses($timeout);
      dbg("async: select found %s responses ready (t.o.=%.1f)",
          !$nfound ? 'no' : $nfound,  $timeout);
    }
    $now = time;  # capture new timestamp, after possible sleep in 'select'

    while (my($key,$ent) = each %$pending) {
      my $id = $ent->{id};
      if (defined $ent->{poll_callback}) {  # call a "poll_callback" if exists
        # be nice, provide fresh info to a callback routine
        $ent->{status} = 'FINISHED'  if exists $self->{finished}->{$id};
        # a callback might call set_response_packet() or report_id_complete()
      # dbg("async: calling poll_callback on key $key");
        $ent->{poll_callback}->($ent);
      }
      my $finished = exists $self->{finished}->{$id};
      if ($finished) {
        $anydone = 1;
        delete $self->{finished}->{$id};
        $ent->{status} = 'FINISHED';
        $ent->{finish_time} = $now  if !defined $ent->{finish_time};
        my $elapsed = $ent->{finish_time} - $ent->{start_time};
        dbg("async: completed in %.3f s: %s", $elapsed, $ent->{display_id});

        # call a "completed_callback" sub, if one exists
        if (defined $ent->{completed_callback}) {
        # dbg("async: calling completed_callback on key $key");
          $ent->{completed_callback}->($ent);
        }
        $self->{timing_by_query}->{". $key"} += $elapsed;
        $self->{queries_completed}++;
        $self->{total_queries_completed}++;
        delete $pending->{$key};
      }
    }

    if (%$pending) {  # still any requests outstanding? are they expired?
      my $r =
        !$allow_aborting_of_expired || !$self->{total_queries_started} ? 1.0
        : $self->{total_queries_completed} / $self->{total_queries_started};
      my $r2 = $r * $r;  # 0..1
      while (my($key,$ent) = each %$pending) {
        $typecount{$ent->{type}}++;
        my $t_init = $ent->{timeout_initial};
        my $dt = $t_init - ($t_init - $ent->{timeout_min}) * $r2;
        # adjust to timer resolution, only deals with 1s and fine resolution
        $dt = 1 + int $dt  if $timer_resolution == 1 && $dt > int $dt;
        $allexpired = 0  if $now <= $ent->{start_time} + $dt;
      }
      dbg("async: queries completed: %d, started: %d",
          $self->{queries_completed}, $self->{queries_started});
    }

    # ensure we don't get stuck if a request gets lost in the ether.
    if (! %$pending) {
      $alldone = 1;
    }
    elsif ($allexpired && $allow_aborting_of_expired) {
      # avoid looping forever if we haven't got all results.
      dbg("async: escaping: lost or timed out requests or responses");
      $self->abort_remaining_lookups();
      $alldone = 1;
    }
    else {
      dbg("async: queries active: %s%s at %s",
          join (' ', map { "$_=$typecount{$_}" } sort keys %typecount),
          $allexpired ? ', all expired' : '', scalar(localtime(time)));
      $alldone = 0;
    }
    1;

  } or do {
    my $eval_stat = $@ ne '' ? $@ : "errno=$!";  chomp $eval_stat;
    dbg("async: caught complete_lookups death, aborting: $eval_stat");
    $alldone = 1;      # abort remaining
  };

  return wantarray ? ($alldone,$anydone,$waiting_time) : $alldone;
}

# ---------------------------------------------------------------------------

=item $async->abort_remaining_lookups()

Abort any remaining lookups.

=cut

sub abort_remaining_lookups {
  my ($self) = @_;

  my $pending = $self->{pending_lookups};
  my $foundcnt = 0;
  my $now = time;
  while (my($key,$ent) = each %$pending) {
    dbg("async: aborting after %.3f s, %s: %s",
        $now - $ent->{start_time},
        (defined $ent->{timeout_initial} &&
         $now > $ent->{start_time} + $ent->{timeout_initial}
           ? 'past original deadline' : 'deadline shrunk'),
        $ent->{display_id} );
    $foundcnt++;
    $self->{timing_by_query}->{"X $key"} = $now - $ent->{start_time};

    if (defined $ent->{completed_callback}) {
      $ent->{finish_time} = $now  if !defined $ent->{finish_time};
      $ent->{response_packet} = undef;
      $ent->{status} = 'ABORTING';
    # to avoid breaking third-party plugins which may not test for undefined
    # 'response_packet', avoid the callback on aborts for now (3.2.4);
    # the following call will be enabled for 3.3.0 :
    # $ent->{completed_callback}->($ent);
    }

    delete $pending->{$key};
  }
  dbg("async: aborted %d remaining lookups", $foundcnt)  if $foundcnt > 0;
  delete $self->{last_poll_responses_time};
  $self->{main}->{resolver}->bgabort();
  1;
}

# ---------------------------------------------------------------------------

=item $async->set_response_packet($id, $pkt, $key, $timestamp)

Register a "response packet" for a given query.  C<$id> is the ID for the
query, and must match the C<id> supplied in C<start_lookup()>. C<$pkt> is the
packet object for the response. A parameter C<$key> identifies an entry in a
hash %{$self->{pending_lookups}} where the object which spawned this query can
be found, and through which futher information about the query is accessible.

If this was called, C<$pkt> will be available in the C<completed_callback>
function as C<$ent-<gt>{response_packet}>.

One or the other of C<set_response_packet()> or C<report_id_complete()>
should be called, but not both.

=cut

sub set_response_packet {
  my ($self, $id, $pkt, $key, $timestamp) = @_;
  $self->{finished}->{$id} = 1;  # only key existence matters, any value
  $timestamp = time  if !defined $timestamp;
  my $pending = $self->{pending_lookups};
  if (!defined $key) {  # backwards compatibility with 3.2.3 and older plugins
    # a third-party plugin did not provide $key in a call, search for it:
    if ($id eq $pending->{$id}->{id}) {  # I feel lucky, key==id ?
      $key = $id;
    } else {  # then again, maybe not, be more systematic
      for my $tkey (keys %$pending) {
        if ($id eq $pending->{$tkey}->{id}) { $key = $tkey; last }
      }
    }
    dbg("async: got response on id $id, search found key $key");
  }
  if (!defined $key) {
    info("async: no key, response packet not remembered, id $id");
  } else {
    my $ent = $pending->{$key};
    if ($id ne $ent->{id}) {
      info("async: ignoring response, mismatched id $id, expected $ent->{id}");
    } else {
      $ent->{finish_time} = $timestamp;
      $ent->{response_packet} = $pkt;
    }
  }
  1;
}

=item $async->report_id_complete($id,$key,$key,$timestamp)

Register that a query has completed, and is no longer "pending". C<$id> is the
ID for the query, and must match the C<id> supplied in C<start_lookup()>.

One or the other of C<set_response_packet()> or C<report_id_complete()>
should be called, but not both.

=cut

sub report_id_complete {
  my ($self, $id, $key, $timestamp) = @_;
  $self->set_response_packet($id, undef, $key, $timestamp);
}

# ---------------------------------------------------------------------------

=item $time = $async->last_poll_responses_time()

Get the time of the last call to C<poll_responses()> (which is called
from C<complete_lookups()>.  If C<poll_responses()> was never called or
C<abort_remaining_lookups()> has been called C<last_poll_responses_time()>
will return undef.

=cut

sub last_poll_responses_time {
  my ($self) = @_;
  return $self->{last_poll_responses_time};
}

1;

=back

=cut


text:
/*SETTING UP DEPENDENCIES*/
var Hapi = require('hapi');
var Good = require('good');

/*CREATE HAPI SERVER --- http://hapijs.com/
* set ejs as template system */
var port = parseInt(process.env.PORT, 10) || 3000;
var server = new Hapi.Server('0.0.0.0', port, {
    views: {
        engines: {
            html: require('ejs')
        },
        path: "./views",
        partialsPath: "./views/partials",
        isCached: false
    }
});
/*GLOBALS*/
var $ = require('./global');
$.put('test', 'OK');
$.put('server', server);

/*MODULES*/
//$.put('db', require('./modules/db')); //Load db connection, initialize model & controllers
//EVENTS
//$.put('models/event', require('./models/event'));
//$.put('controllers/fuzzy', require('./controller/fuzzy')($.get('models/event')));
//OTHER MODULES
$.put('api', require('./modules/api')($)); //
$.put('battery', require('./modules/battery')($));
$.put('fsmanager', require('./modules/fsmanager')($)); //
$.put('storify', require('./modules/server_storify')($)); //
$.put('projects', require('./modules/project_repository')($)); //

server.pack.register({
    plugin: require('hapi-socket'),
    options: {
        messageHandler: function(socket) {
            return function(message) {
                console.log("Message sent!");
                socket.send(message);
            };
        },
        logLevel: 2
    }
}, function(err) {
    server.start(function() {
        console.log("Hapi server started @ " + server.info.uri);
        $.put('garageio', require('./modules/server_garageio')(server, $)); //
        $.get('garageio').start();
    });
});

/*Load routes*/
require('./routes/client')($);
require('./routes/static')($);
require('./routes/rest')($);
require('./routes/admin')($);
require('./routes/routes_storify')($); //Project storify

/*PACKS:
- Good - A logging plugin that supports output to console, file and udp/http endpoints*/
/*server.pack.register(Good, function(err) {
    if (err) {
        throw err;
    }
    server.start(function() {
        /*$.get('battery').start()
            .job($.get('api').testMethod
                ,'asfsafsa'
               ,function(res){console.info(res);}
            );

        console.info('test method ', $.get('api').testMethod());

    });
});*/

redpajama_set_name: RedPajamaGithub


text:
"""Utilities and helper functions."""

import threading

from oslo_config import cfg
from oslo_utils import timeutils

ROOTWRAP_CONF = "/etc/ceilometer/rootwrap.conf"

OPTS = [
    cfg.StrOpt('rootwrap_config',
               default=ROOTWRAP_CONF,
               help='Path to the rootwrap configuration file to '
                    'use for running commands as root'),
]

def _get_root_helper():
    global ROOTWRAP_CONF
    return 'sudo ceilometer-rootwrap %s' % ROOTWRAP_CONF

def setup_root_helper(conf):
    global ROOTWRAP_CONF
    ROOTWRAP_CONF = conf.rootwrap_config

def spawn_thread(target, *args, **kwargs):
    t = threading.Thread(target=target, args=args, kwargs=kwargs)
    t.daemon = True
    t.start()
    return t

def isotime(at=None):
    """Current time as ISO string,

    :returns: Current time in ISO format
    """
    if not at:
        at = timeutils.utcnow()
    date_string = at.strftime("%Y-%m-%dT%H:%M:%S")
    tz = at.tzinfo.tzname(None) if at.tzinfo else 'UTC'
    date_string += ('Z' if tz == 'UTC' else tz)
    return date_string


text:
import pluginManager from '@/services/plugin-manager'
import PluginWrapper from '@/components/Plugin/PluginWrapper'

export default {
  install (Vue) {
    Vue.component('Ark', PluginWrapper)
    pluginManager.setVue(Vue.extend())
    Vue.prototype.$plugins = pluginManager
  }
}


text:
#ifndef EL_GRAPHICS_BITMAP_FRAGMENT_MAP_H_
#define EL_GRAPHICS_BITMAP_FRAGMENT_MAP_H_

#include <memory>
#include <string>
#include <vector>

#include "el/graphics/bitmap_fragment.h"

namespace el {
namespace graphics {

class BitmapFragmentManager;

// Used to pack multiple bitmaps into a single Bitmap.
// When initialized (in a size suitable for a Bitmap) is also creates a
// software buffer that will make up the Bitmap when all fragments have been
// added.
class BitmapFragmentMap {
 public:
  BitmapFragmentMap();
  ~BitmapFragmentMap();

  // Initializes the map with the given size.
  // The size should be a power of two since it will be used to create a
  // Bitmap (texture memory).
  bool Init(int bitmap_w, int bitmap_h);

  // Creates a new fragment with the given size and data in this map.
  // Returns nullptr if there is not enough room in this map or on any other
  // fail.
  std::unique_ptr<BitmapFragment> CreateNewFragment(int frag_w, int frag_h,
                                                    int data_stride,
                                                    uint32_t* frag_data,
                                                    bool add_border);

  // Frees up the space used by the given fragment, so that other fragments can
  // take its place.
  void FreeFragmentSpace(BitmapFragment* frag);

  // Returns the bitmap for this map.
  // By default, the bitmap is validated if needed before returning (See
  // Validate).
  Bitmap* GetBitmap(Validate validate_type = Validate::kAlways);

 private:
  friend class BitmapFragmentManager;
  bool ValidateBitmap();
  void DeleteBitmap();
  void CopyData(BitmapFragment* frag, int data_stride, uint32_t* frag_data,
                int border);

  std::vector<std::unique_ptr<BitmapFragmentSpaceAllocator>> m_rows;
  int m_bitmap_w = 0;
  int m_bitmap_h = 0;
  uint32_t* m_bitmap_data = nullptr;
  std::unique_ptr<Bitmap> m_bitmap;
  bool m_need_update = false;
  int m_allocated_pixels = 0;
};

}  // namespace graphics
}  // namespace el

#endif  // EL_GRAPHICS_BITMAP_FRAGMENT_MAP_H_


text:
#ifndef __TEST_SCHED_H__
#define __TEST_SCHED_H__

#include <zephyr.h>
#include <ztest.h>

#if defined(CONFIG_RISCV32)
#define STACK_SIZE 512
#else
#define STACK_SIZE (256 + CONFIG_TEST_EXTRA_STACKSIZE)
#endif

struct thread_data {
	k_tid_t tid;
	int priority;
	int executed;
};

void test_priority_cooperative(void);
void test_priority_preemptible(void);
void test_yield_cooperative(void);
void test_sleep_cooperative(void);
void test_sleep_wakeup_preemptible(void);
void test_time_slicing_preemptible(void);
void test_time_slicing_disable_preemptible(void);
void test_lock_preemptible(void);
void test_unlock_preemptible(void);
void test_sched_is_preempt_thread(void);

#endif /* __TEST_SCHED_H__ */


text:
package azureVmCustomScriptExtension

import (
	"encoding/base64"
	"fmt"
	"github.com/mitchellh/packer/packer"
	"io"
	"io/ioutil"
	"log"
	"os"
	"path/filepath"
	"time"

	"github.com/pborman/uuid"

	"github.com/Azure/packer-azure/packer/builder/azure/common"
	"github.com/Azure/packer-azure/packer/builder/azure/smapi/retry"

	"github.com/Azure/azure-sdk-for-go/management"
	vm "github.com/Azure/azure-sdk-for-go/management/virtualmachine"
	"github.com/Azure/azure-sdk-for-go/management/vmutils"
	"github.com/Azure/azure-sdk-for-go/storage"
)

const extPublisher = "Microsoft.Compute"
const extName = "CustomScriptExtension"

type comm struct {
	config Config
	uris   string
}

type Config struct {
	ServiceName               string
	VmName                    string
	StorageAccountName        string
	StorageAccountKey         string
	BlobClient                storage.BlobStorageClient
	ContainerName             string
	Ui                        packer.Ui
	ProvisionTimeoutInMinutes uint
	ManagementClient          management.Client
}

func New(config Config) (result *comm) {
	return &comm{
		config: config,
	}
}

func (c *comm) Start(cmd *packer.RemoteCmd) (err error) {
	ext, err := c.requestCustomScriptExtension()
	if err != nil {
		return
	}

	nameOfReference := fmt.Sprintf("PackerCustomScriptExtension-%s", uuid.New())
	nameOfPublisher := extPublisher
	nameOfExtension := extName
	versionOfExtension := ext.Version

	log.Println("Installing CustomScriptExtension...")
	state := "enable"
	params := c.buildParams(cmd.Command)

	err = c.updateRoleResourceExtension(nameOfReference, nameOfPublisher, nameOfExtension, versionOfExtension, state, params)
	if err != nil {
		return
	}

	stdOutBuff, stdErrBuff, err := c.pollCustomScriptExtensionIsReady()
	if err != nil {
		return
	}

	_, err = cmd.Stdout.Write([]byte(stdOutBuff))
	if err != nil {
		err = fmt.Errorf("cmd.Stdout error: %s", err.Error())
		return
	}

	_, err = cmd.Stderr.Write([]byte(stdErrBuff))
	if err != nil {
		err = fmt.Errorf("cmd.Stdout error: %s", err.Error())
		return
	}

	log.Println("Uninstalling CustomScriptExtension...")

	state = "uninstall"
	params = nil
	err = c.updateRoleResourceExtension(nameOfReference, nameOfPublisher, nameOfExtension, versionOfExtension, state, params)
	if err != nil {
		return
	}

	c.sleepSec(20)

	err = c.pollCustomScriptIsUninstalled()
	if err != nil {
		return
	}

	return
}

func (c *comm) sleepSec(d time.Duration) {
	log.Printf("Sleep for %v sec", uint(d))
	time.Sleep(time.Second * d)
}

func (c *comm) requestCustomScriptExtension() (*vm.ResourceExtension, error) {

	log.Println("Requesting resource extensions...")

	list, err := vm.NewClient(c.config.ManagementClient).GetResourceExtensions()
	if err != nil {
		return nil, err
	}

	log.Println("Searching for CustomScriptExtension...")
	for _, ext := range list {
		if ext.Name == "CustomScriptExtension" {
			log.Printf("CustomScriptExtension: %v\n\n", ext)
			return &ext, nil
		}
	}

	return nil, fmt.Errorf("Couldn't find CustomScriptExtension, am I too old or is Azure broken?")
}

func (c *comm) updateRoleResourceExtension(
	nameOfReference, nameOfPublisher, nameOfExtension, versionOfExtension, state string,
	params []vm.ResourceExtensionParameter) error {

	client := c.config.ManagementClient

	serviceName := c.config.ServiceName
	vmName := c.config.VmName

	log.Println("Updating Role Resource Extension...")

	role := vm.Role{}
	vmutils.AddAzureVMExtensionConfiguration(&role,
		nameOfExtension, nameOfPublisher, versionOfExtension, nameOfReference, state, []byte{}, []byte{})
	// HACK-paulmey: clean up later
	(*role.ResourceExtensionReferences)[0].ParameterValues = params

	if err := retry.ExecuteAsyncOperation(client, func() (management.OperationID, error) {
		return vm.NewClient(client).UpdateRole(serviceName, vmName, vmName, role)
	}); err != nil {
		return err
	}

	return nil
}

func (c *comm) buildParams(runScript string) []vm.ResourceExtensionParameter {

	scriptfile := "{\"fileUris\": [" + c.uris + "], \"commandToExecute\":\"powershell -ExecutionPolicy Unrestricted -file " + runScript + "\"}"
	account := "{\"storageAccountName\":\"" + c.config.StorageAccountName + "\",\"storageAccountKey\": \"" + c.config.StorageAccountKey + "\"}"

	return []vm.ResourceExtensionParameter{
		vm.ResourceExtensionParameter{
			Key:   "CustomScriptExtensionPublicConfigParameter",
			Value: base64.StdEncoding.EncodeToString([]byte(scriptfile)),
			Type:  "Public",
		},
		vm.ResourceExtensionParameter{
			Key:   "CustomScriptExtensionPrivateConfigParameter",
			Value: base64.StdEncoding.EncodeToString([]byte(account)),
			Type:  "Private",
		},
	}
}

func (c *comm) pollCustomScriptExtensionIsReady() (stdOutBuff, stdErrBuff string, err error) {
	client := c.config.ManagementClient
	log.Println("Polling CustomScriptExtension is ready. It may take some time...")

	var deployment vm.DeploymentResponse
	var extStatus *vm.ResourceExtensionStatus // paulmey-BUG #58: should not be pointer
	const statusSuccess = "Success"
	const statusError = "Error"

	//	needUpdateStatus := true

	serviceName := c.config.ServiceName
	vmName := c.config.VmName
	var timeout int64 = int64(c.config.ProvisionTimeoutInMinutes * 60)

	startTime := time.Now().Unix()
	timeoutState := false

	for {
		if timeout != 0 && time.Now().Unix()-startTime > timeout {
			timeoutState = true
			break
		}

		for {
			if timeout != 0 && time.Now().Unix()-startTime > timeout {
				timeoutState = true
				break
			}

			deployment, err = vm.NewClient(client).GetDeployment(serviceName, vmName)

			if err != nil {
				return
			}

			if deployment.RoleInstanceList[0].InstanceStatus == vm.InstanceStatusReadyRole {
				if len(deployment.RoleInstanceList[0].ResourceExtensionStatusList) > 0 {
					break
				}
			}

			c.sleepSec(45)
		}

		if timeoutState {
			err = fmt.Errorf("InstanceStatus is not 'ReadyRole' or CustomScriptExtension ResourceExtensionStatusList is empty after %d minutes", c.config.ProvisionTimeoutInMinutes)
			return
		}

		extHandlerName := extPublisher + "." + extName

		for _, s := range deployment.RoleInstanceList[0].ResourceExtensionStatusList {
			if s.HandlerName == extHandlerName {
				extStatus = &s
			}
		}

		if extStatus == nil {
			err = fmt.Errorf("CustomScriptExtension status not found")
			return
		}

		log.Printf("CustomScriptExtension status: %v", extStatus)

		extensionSettingStatus := extStatus.ExtensionSettingStatus

		if extensionSettingStatus.Status == statusError {
			err = fmt.Errorf("CustomScriptExtension operation '%s' status: %s", extensionSettingStatus.Operation, extensionSettingStatus.FormattedMessage.Message)
			return
		}

		log.Printf("CustomScriptExtension INFO: operation '%s' status: %s", extensionSettingStatus.Operation, extensionSettingStatus.Status)

		var stdOut, stdErr string

		for _, subStatus := range extStatus.ExtensionSettingStatus.SubStatusList {
			if subStatus.Name == "StdOut" {
				if subStatus.Status != statusSuccess {
					stdOut = fmt.Sprintf("StdOut failed with message: '%s'", subStatus.FormattedMessage.Message)
				} else {
					stdOut = subStatus.FormattedMessage.Message
				}
				continue
			}

			if subStatus.Name == "StdErr" {
				if subStatus.Status != statusSuccess {
					stdErr = fmt.Sprintf("StdErr failed with message: '%s'", subStatus.FormattedMessage.Message)
				} else {
					stdErr = subStatus.FormattedMessage.Message
				}
				continue
			}
		}

		log.Printf("StdOut: '%s'\n", stdOut)

		if len(stdOutBuff) == 0 {
			stdOutBuff = stdOut
		} else {
			stdOutBuff = common.GlueStrings(stdOutBuff, stdOut)
		}

		if len(stdErrBuff) == 0 {
			stdErrBuff = stdErr
		} else {
			stdErrBuff = common.GlueStrings(stdErrBuff, stdErr)
		}

		if extensionSettingStatus.Status == statusSuccess {
			break
		}

		c.sleepSec(40)
	}

	if timeoutState {
		err = fmt.Errorf("extensionSettingStatus.Status in not 'Success' after %d minutes", c.config.ProvisionTimeoutInMinutes)
		return
	}

	return
}

func (c *comm) pollCustomScriptIsUninstalled() error {
	client := c.config.ManagementClient
	log.Println("Polling CustomScript is uninstalled. It may take some time...")

	serviceName := c.config.ServiceName
	vmName := c.config.VmName

	const attemptLimit uint = 30
	repeatCount := attemptLimit
	for ; repeatCount > 0; repeatCount-- {
		deployment, err := vm.NewClient(client).GetDeployment(serviceName, vmName)
		if err != nil {
			return err
		}

		if deployment.RoleInstanceList[0].InstanceStatus == vm.InstanceStatusReadyRole {
			if len(deployment.RoleInstanceList[0].ResourceExtensionStatusList) == 0 {
				break
			}
		}

		c.sleepSec(45)
	}

	if repeatCount == 0 {
		err := fmt.Errorf("InstanceStatus is not 'ReadyRole' or ResourceExtensionStatusList is not empty after %d attempts", attemptLimit)
		return err
	}

	return nil
}

func (c *comm) Upload(string, io.Reader, *os.FileInfo) error {
	return fmt.Errorf("Upload is not supported for azureVmCustomScriptExtension")
}

func (c *comm) UploadDir(skipped string, src string, excl []string) error {

	src = filepath.FromSlash(src)
	info, err := os.Stat(src)
	if err != nil {
		return err
	}

	containerName := c.config.ContainerName

	if info.IsDir() {
		log.Println(fmt.Sprintf("Uploading files (only!) in the folder to Azure storage container '%s' => '%s'...", src, containerName))
		err := c.uploadFolder("", src)
		if err != nil {
			return err
		}
	} else {
		err := c.uploadFile("", src)
		if err != nil {
			return err
		}
	}

	return err
}

func (c *comm) Download(string, io.Writer) error {
	return fmt.Errorf("Download is not supported for azureVmCustomScriptExtension")
}

// region private helpers

// Helper method to upload a blob, removed from azure-sdk (and not added back as util)
// See https://github.com/Azure/azure-sdk-for-go/commit/bf6723e87ca7c26e523b13c18f29383da60ab64f

// PutBlockBlob uploads given stream into a block blob by splitting
// data stream into chunks and uploading as blocks. Commits the block
// list at the end. This is a helper method built on top of PutBlock
// and PutBlockList methods with sequential block ID counting logic.
func putBlockBlob(b storage.BlobStorageClient, container, name string, blob io.Reader, chunkSize int) error {
	if chunkSize <= 0 || chunkSize > storage.MaxBlobBlockSize {
		chunkSize = storage.MaxBlobBlockSize
	}

	chunk := make([]byte, chunkSize)
	n, err := blob.Read(chunk)
	if err != nil && err != io.EOF {
		return err
	}

	blockList := []storage.Block{}

	for blockNum := 0; ; blockNum++ {
		id := base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("%011d", blockNum)))
		data := chunk[:n]
		err = b.PutBlock(container, name, id, data)
		if err != nil {
			return err
		}

		blockList = append(blockList, storage.Block{ID: id, Status: storage.BlockStatusLatest})

		// Read next block
		n, err = blob.Read(chunk)
		if err != nil && err != io.EOF {
			return err
		}
		if err == io.EOF {
			break
		}
	}

	return b.PutBlockList(container, name, blockList)
}

func (c *comm) uploadFile(dscPath string, srcPath string) error {

	srcPath = filepath.FromSlash(srcPath)

	_, err := os.Stat(srcPath)
	if err != nil {
		return fmt.Errorf("Check file path is correct: %s", srcPath)
	}

	ui := c.config.Ui
	sa := c.config.BlobClient

	containerName := c.config.ContainerName

	fileName := filepath.Base(srcPath)
	uri := sa.GetBlobURL(containerName, fileName)

	if len(c.uris) == 0 {
		c.uris = fmt.Sprintf("\"%s\"", uri)
	} else {
		c.uris += fmt.Sprintf(", \"%s\"", uri)
	}

	log.Println("uris: '" + c.uris + "'")

	ui.Message(fmt.Sprintf("Uploading file to to Azure storage container '%s' => '%s'...", srcPath, containerName))

	f, err := os.Open(srcPath)
	if err != nil {
		return fmt.Errorf("Error reading file %s: %v", srcPath, err)
	}

	defer f.Close()

	err = sa.CreateBlockBlob(containerName, fileName)
	if err != nil {
		return fmt.Errorf("Error creating block blob in container %s for file %s: %v", containerName, fileName, err)
	}

	err = putBlockBlob(sa, containerName, fileName, f, storage.MaxBlobBlockSize)
	if err != nil {
		return fmt.Errorf("Error uploading block blob in container %s for file %s: %v", containerName, fileName, err)
	}

	return nil
}

func (c *comm) uploadFolder(dscPath string, srcPath string) error {

	srcPath = filepath.FromSlash(srcPath)

	files, err := ioutil.ReadDir(srcPath)
	if err != nil {
		return err
	}

	for _, f := range files {
		if f.IsDir() {
			continue
		}

		err := c.uploadFile("", filepath.Join(srcPath, f.Name()))
		if err != nil {
			return err
		}
	}

	return err
}

func (*comm) DownloadDir(string, string, []string) error {
	return fmt.Errorf("Not implemented")
}


text:
package com.amazonaws.services.connectwisdom.model;

import javax.annotation.Generated;

/**
 *

 * The provided revisionId does not match, indicating the content has been modified since it was last read.
 *

 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class PreconditionFailedException extends com.amazonaws.services.connectwisdom.model.AmazonConnectWisdomException {
    private static final long serialVersionUID = 1L;

    /**
     * Constructs a new PreconditionFailedException with the specified error message.
     *
     * @param message
     *        Describes the error encountered.
     */
    public PreconditionFailedException(String message) {
        super(message);
    }

}


text:
using System.Diagnostics;
using js.net.Util;

namespace js.net.Engine
{
  public abstract class AbstractEngine : IEngine
  {
    static AbstractEngine()
    {
      Trace.Listeners.Clear();
      Trace.Listeners.Add(new ExceptionTraceListener());
    }

    public abstract object Run(string script, string fileName);
    public abstract void SetGlobal(string name, object value);
    public abstract object GetGlobal(string name);
    public abstract void Dispose();
  }
}


text:
"""Python Soundcloud API Wrapper."""

__version__ = '0.4.1'
__all__ = ['Client']

USER_AGENT = 'SoundCloud Python API Wrapper %s' % __version__

from soundcloud.client import Client


text:
title: Supplier registration
permalink: /supplier-registration/
published: true
---

# Supplier registration
To participate in any bid processes with the City, please complete the online Supplier Registration Form. To ensure your application is complete, the City requires a complete IRS W-9 form to be on file. Please print, sign and email or fax on the same day to [supplierregistration@atlantaga.gov](mailto:supplierregistration@atlantaga.gov) or 404-546-2086. Note that all forms must be fully completed.

[Online supplier registration form](https://catsprod.atlantaga.gov/OA_HTML/OA.jsp?page=/oracle/apps/pos/suppreg/webui/PosSRegPG&OAHP=POS_GUEST_REG_HP&OASF=POS_SUPPREG_REGISTER&OAPB=POS_ISP_BRAND&ouid=5CDE34D24B087C20)

[IRS Form W-9 (PDF)](http://www.irs.gov/pub/irs-pdf/fw9.pdf)

After you have submitted the Online Supplier's registration form and emailed or faxed the completed IRS Form W-9 to the City's Department of Procurement, then you will receive an email with your access details to the City's iSupplier system. Using those details, you should access the City's iSupplier system and update your additional address & contact information, product & services information and business classification (minority, woman owned, etc) information.

[iSupplier User Guide](http://atlantaga.gov/modules/showdocument.aspx?documentid=5545)


text:
package demo.service;

import demo.model.Cart;
import demo.model.CartItem;
import demo.model.Product;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class CartService {

  @Autowired private HttpSession session;
  @Autowired private ProductService productService;

  public Cart getCart() {
    return (Cart) Optional.ofNullable(session.getAttribute("cart")).orElseGet(Cart::new);
  }

  // Empty cart and reset values in session
  public Cart emptyCart() {
    Cart cart = new Cart();
    List<CartItem> items = new ArrayList<CartItem>();
    cart.setCartItems(items);
    return cart;
  }

  /**
   * Check if a product is already added to the cart
   *
   * @param id
   * @param cart
   */
  public Optional<CartItem> exists(String id, List<CartItem> cart) {
    return cart.stream().filter(c -> c.getProductId().equals(id)).findAny();
  }

  /**
   * Create list of products from the cart items. This is more of a workaround to cater to what's
   * expected to show up in the ftl templates
   *
   * @param session
   * @param cart
   */
  public List<Product> getSelectedProducts(HttpSession session, Cart cart) {
    List<Product> selectedProducts = new ArrayList<>();
    for (CartItem item : cart.getCartItems()) {
      selectedProducts.add(productService.findProductById(item.getProductId()).get());
    }
    return selectedProducts;
  }

  /**
   * Create new cart item based on the user selection
   *
   * @param selectedProduct
   * @param selectedQty
   * @param cart
   */
  public CartItem newCartItem(String selectedProduct, int selectedQty, Cart cart) {
    CartItem cartItem = new CartItem();
    cartItem.setProductId(selectedProduct);
    cartItem.setQuantity(selectedQty);
    cartItem.setCart(cart);
    return cartItem;
  }
}


text:
package org.springframework.boot.autoconfigure.webflux;

import java.net.InetAddress;

import org.junit.Before;
import org.junit.Test;

import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.boot.web.reactive.server.ConfigurableReactiveWebServerFactory;

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;

/**
 * Tests for {@link DefaultReactiveWebServerCustomizer}.
 *
 * @author Brian Clozel
 */
public class DefaultReactiveWebServerCustomizerTests {

	private final ServerProperties properties = new ServerProperties();

	private DefaultReactiveWebServerCustomizer customizer;

	@Before
	public void setup() throws Exception {
		this.customizer = new DefaultReactiveWebServerCustomizer(this.properties);
	}

	@Test
	public void testCustomizeServerPort() throws Exception {
		ConfigurableReactiveWebServerFactory factory = mock(ConfigurableReactiveWebServerFactory.class);
		this.properties.setPort(9000);
		this.customizer.customize(factory);
		verify(factory).setPort(9000);
	}

	@Test
	public void testCustomizeServerAddress() throws Exception {
		ConfigurableReactiveWebServerFactory factory = mock(ConfigurableReactiveWebServerFactory.class);
		InetAddress address = mock(InetAddress.class);
		this.properties.setAddress(address);
		this.customizer.customize(factory);
		verify(factory).setAddress(address);
	}

}


text:
package org.apache.hadoop.hdds.scm.pipelines.ratis;

import com.google.common.base.Preconditions;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hdds.scm.XceiverClientRatis;
import org.apache.hadoop.hdds.scm.container.common.helpers.Pipeline;
import org.apache.hadoop.hdds.scm.container.common.helpers.PipelineChannel;
import org.apache.hadoop.hdds.scm.container.placement.algorithms
    .ContainerPlacementPolicy;
import org.apache.hadoop.hdds.scm.node.NodeManager;
import org.apache.hadoop.hdds.scm.pipelines.PipelineManager;
import org.apache.hadoop.hdds.scm.pipelines.PipelineSelector;
import org.apache.hadoop.hdds.protocol.DatanodeDetails;
import org.apache.hadoop.hdds.protocol.proto.HddsProtos.LifeCycleState;
import org.apache.hadoop.hdds.protocol.proto.HddsProtos.NodeState;
import org.apache.hadoop.hdds.protocol.proto.HddsProtos.ReplicationFactor;
import org.apache.hadoop.hdds.protocol.proto.HddsProtos.ReplicationType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.UUID;

/**
 * Implementation of {@link PipelineManager}.
 *
 * TODO : Introduce a state machine.
 */
public class RatisManagerImpl extends PipelineManager {
  private static final Logger LOG =
      LoggerFactory.getLogger(RatisManagerImpl.class);
  private static final String PREFIX = "Ratis-";
  private final Configuration conf;
  private final NodeManager nodeManager;
  private final Set<DatanodeDetails> ratisMembers;

  /**
   * Constructs a Ratis Pipeline Manager.
   *
   * @param nodeManager
   */
  public RatisManagerImpl(NodeManager nodeManager,
      ContainerPlacementPolicy placementPolicy, long size, Configuration conf) {
    super();
    this.conf = conf;
    this.nodeManager = nodeManager;
    ratisMembers = new HashSet<>();
  }

  /**
   * Allocates a new ratis PipelineChannel from the free nodes.
   *
   * @param factor - One or Three
   * @return PipelineChannel.
   */
  public PipelineChannel allocatePipelineChannel(ReplicationFactor factor) {
    List<DatanodeDetails> newNodesList = new LinkedList<>();
    List<DatanodeDetails> datanodes = nodeManager.getNodes(NodeState.HEALTHY);
    int count = getReplicationCount(factor);
    //TODO: Add Raft State to the Nodes, so we can query and skip nodes from
    // data from datanode instead of maintaining a set.
    for (DatanodeDetails datanode : datanodes) {
      Preconditions.checkNotNull(datanode);
      if (!ratisMembers.contains(datanode)) {
        newNodesList.add(datanode);
        if (newNodesList.size() == count) {
          // once a datanode has been added to a pipeline, exclude it from
          // further allocations
          ratisMembers.addAll(newNodesList);
          LOG.info("Allocating a new ratis pipelineChannel of size: {}", count);
          // Start all channel names with "Ratis", easy to grep the logs.
          String conduitName = PREFIX +
              UUID.randomUUID().toString().substring(PREFIX.length());
          PipelineChannel pipelineChannel =
              PipelineSelector.newPipelineFromNodes(newNodesList,
              LifeCycleState.OPEN, ReplicationType.RATIS, factor, conduitName);
          Pipeline pipeline =
              new Pipeline("setup", pipelineChannel);
          try (XceiverClientRatis client =
              XceiverClientRatis.newXceiverClientRatis(pipeline, conf)) {
            client.createPipeline(pipeline.getPipelineName(), newNodesList);
          } catch (IOException e) {
            return null;
          }
          return pipelineChannel;
        }
      }
    }
    return null;
  }

  /**
   * Creates a pipeline from a specified set of Nodes.
   *
   * @param pipelineID - Name of the pipeline
   * @param datanodes - The list of datanodes that make this pipeline.
   */
  @Override
  public void createPipeline(String pipelineID,
                             List<DatanodeDetails> datanodes) {

  }

  /**
   * Close the  pipeline with the given clusterId.
   *
   * @param pipelineID
   */
  @Override
  public void closePipeline(String pipelineID) throws IOException {

  }

  /**
   * list members in the pipeline .
   *
   * @param pipelineID
   * @return the datanode
   */
  @Override
  public List<DatanodeDetails> getMembers(String pipelineID)
      throws IOException {
    return null;
  }

  /**
   * Update the datanode list of the pipeline.
   *
   * @param pipelineID
   * @param newDatanodes
   */
  @Override
  public void updatePipeline(String pipelineID,
                             List<DatanodeDetails> newDatanodes)
      throws IOException {

  }
}


text:
pynrc.obs\_hci.multiaccum\_times
================================

.. currentmodule:: pynrc

.. autoproperty:: obs_hci.multiaccum_times


text:
module('baidu.dom.empty')

/**
 * 删除一个节点下面的所有子节点。会包含文本?
 */
test('innerHTML is blank', function(){
	var div = document.createElement('div');
	var a = document.createElement('a');
	document.body.appendChild(div);
	document.body.appendChild(a);
	a.innerHTML = "test_a";            //son of a
	var img = document.createElement('img')//son of div
	div.appendChild(img);
	var txt=document.createTextNode("textNode");//son of p
	var p=document.createElement('p');
	document.body.appendChild(p);
	p.appendChild(txt);

	baidu.dom.empty(div);
	baidu.dom.empty(p);
	baidu.dom.empty(a);
	ok(div.childNodes.length==0,"div is empty;");
	ok(p.childNodes.length==0,"p is empty");
	ok(a.childNodes.length==0,"a is empty");
	document.body.removeChild(div);
	document.body.removeChild(a);
	document.body.removeChild(p);
})


text:
body {
    font-family: Arial;
}

#reportManagerDisplay .reportName {
    font: normal normal bold 19pt;
    color: #333333;
}

#reportManagerDisplay .timestamp {
    margin-top: 15px;
    font: normal normal 8pt;
    color: #333333;
    float: left;
    clear: both;
}

#reportManagerDisplay .report
{
    margin: 0px;
    padding: 0px;
    border-top-width: 0px;
    border-bottom-width: 1px;
    border-left-width: 1px;
    border-right-width: 1px;
    border-style: solid;
    border-color: #cccccc;
    border-collapse: collapse;
    font: normal normal bold 11pt;
    color: #ffffff;
}

#reportManagerDisplay .report tr.header th
{
    background: #333333;
    border-top-width: 0px;
    border-bottom-width: 1px;
    border-left-width: 0px;
    border-right-width: 0px;
    border-style: solid;
    border-color: #eeeeee;
    font: normal normal 10pt;
    color: #ffffff;
    text-align: left;
}

#reportManagerDisplay .report tr.body td
{
    background: #FFFFFF;
    border-top-width: 0px;
    border-bottom-width: 1px;
    border-left-width: 1px;
    border-right-width: 1px;
    border-style: solid;
    border-color: #CCCCCC;
    text-align: left;
    font: normal normal 9pt;
    color: #555555;
}

#reportManagerDisplay .report tr.footer td
{
    background: #FFFFFF;
    border-top-width: 0px;
    border-bottom-width: 1px;
    border-left-width: 1px;
    border-right-width: 1px;
    border-style: solid;
    border-color: #CCCCCC;
    font: normal normal 9pt;
    color: #555555;
    text-align: left;
}


text:
module RiotSetBuilder
  module Configuration
    CONFIG_KEYS = [
      :league_path
    ].freeze

    DEFAULT_KEYS = {
      league_path: './'
    }

    attr_accessor *CONFIG_KEYS

    def configure
      yield self
    end

    def options
      CONFIG_KEYS.inject({}) do |option, key|
        option.merge!(key => send(key))
      end
    end

    def self.extended(base)
      base.reset_config
    end

    def reset_config
      CONFIG_KEYS.each do |key|
        if DEFAULT_KEYS[key]
          self.send("#{key}=", DEFAULT_KEYS[key])
        else
          self.send("#{key}=", nil)
        end
      end
    end
  end
end


text:
package org.gluu.oxauth.model.common;

import org.gluu.oxauth.model.registration.Client;

import java.util.Date;

/**
 *

 * The implicit grant is a simplified authorization code flow optimized for
 * clients implemented in a browser using a scripting language such as
 * JavaScript. In the implicit flow, instead of issuing the client an
 * authorization code, the client is issued an access token directly (as the
 * result of the resource owner authorization). The grant type is implicit as no
 * intermediate credentials (such as an authorization code) are issued (and
 * later used to obtain an access token).
 *

 *

 * When issuing an implicit grant, the authorization server does not
 * authenticate the client. In some cases, the client identity can be verified
 * via the redirection URI used to deliver the access token to the client. The
 * access token may be exposed to the resource owner or other applications with
 * access to the resource owner's user-agent.
 *

 *

 * Implicit grants improve the responsiveness and efficiency of some clients
 * (such as a client implemented as an in-browser application) since it reduces
 * the number of round trips required to obtain an access token. However, this
 * convenience should be weighed against the security implications of using
 * implicit grants, especially when the authorization code grant type is
 * available.
 *

 *
 * @author Javier Rojas Blum Date: 09.29.2011
 * @author Yuriy Movchan
 */
public class ImplicitGrant extends AuthorizationGrant {

	public ImplicitGrant() {}

    /**
     * Constructs an implicit grant.
     *
     * @param user               The resource owner.
     * @param client             An application making protected resource requests on behalf of the resource owner and
     *                           with its authorization.
     * @param authenticationTime The Claim Value is the number of seconds from 1970-01-01T0:0:0Z as measured in UTC
     *                           until the date/time that the End-User authentication occurred.
     */
    public ImplicitGrant(User user, Client client, Date authenticationTime) {
        init(user, client, authenticationTime);
    }

    @Override
    public GrantType getGrantType() {
        return GrantType.IMPLICIT;
    }

    public void init(User user, Client client, Date authenticationTime) {
        super.init(user, AuthorizationGrantType.IMPLICIT, client, authenticationTime);
    }

    /**
     * The authorization server MUST NOT issue a refresh token.
     */
    @Override
    public RefreshToken createRefreshToken() {
        throw new UnsupportedOperationException(
                "The authorization server MUST NOT issue a refresh token.");
    }
}


text:
#ifndef CXXLAPACK_INTERFACE_HEGST_H
#define CXXLAPACK_INTERFACE_HEGST_H 1

#include <cxxstd/complex.h>

namespace cxxlapack {

template <typename IndexType>
    IndexType
    hegst(IndexType                  itype,
          char                       uplo,
          IndexType                  n,
          std::complex<float >       *A,
          IndexType                  ldA,
          const std::complex<float > *B,
          IndexType                  ldB);

template <typename IndexType>
    IndexType
    hegst(IndexType                  itype,
          char                       uplo,
          IndexType                  n,
          std::complex<double>       *A,
          IndexType                  ldA,
          const std::complex<double> *B,
          IndexType                  ldB);

} // namespace cxxlapack

#endif // CXXLAPACK_INTERFACE_HEGST_H


text:
//
//  NSDate+JS.h
//  timeboy
//
//  Created by wenghengcong on 15/5/5.
//  Copyright (c) 2015年 JungleSong. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface NSDate(JS)

-(NSString *)getNSDateDay;
-(NSString *)getNSDateTime;
-(NSString *)getNSDate;

/**
 *  从字符串构造日期;格式为:yyyy-MM-dd HH:mm
 */
+ (NSDate*)DateFromString:(NSString *)string;

///-----------------------------------------
/// @name Calculating Beginning / End of Day
///-----------------------------------------

/**
 Returns a new date with first second of the day of the receiver.
 */
- (NSDate *)beginningOfDay;

/**
 Returns a new date with the last second of the day of the receiver.
 */
- (NSDate *)endOfDay;

///------------------------------------------
/// @name Calculating Beginning / End of Week
///------------------------------------------

/**
 Returns a new date with first second of the first weekday of the receiver, taking into account the current calendar's `firstWeekday` property.
 */
- (NSDate *)beginningOfWeek;

/**
 Returns a new date with last second of the last weekday of the receiver, taking into account the current calendar's `firstWeekday` property.
 */
- (NSDate *)endOfWeek;

///-------------------------------------------
/// @name Calculating Beginning / End of Month
///-------------------------------------------

/**
 Returns a new date with the first second of the first day of the month of the receiver.
 */
- (NSDate *)beginningOfMonth;

/**
 Returns a new date with the last second of the last day of the month of the receiver.
 */
- (NSDate *)endOfMonth;

///------------------------------------------
/// @name Calculating Beginning / End of Year
///------------------------------------------

/**
 Returns a new date with the first second of the first day of the year of the receiver.
 */
- (NSDate *)beginningOfYear;

/**
 Returns a new date with the last second of the last day of the year of the receiver.
 */
- (NSDate *)endOfYear;

/**
 *  判断当前时间是否在某一天
 */
- (BOOL)isInDate:(NSDate *)date;

@end


text:
package logs

import (
	"bytes"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"os"
	"path/filepath"
	"strings"
	"sync"
	"time"
)

// fileLogWriter implements LoggerInterface.
// It writes messages by lines limit, file size limit, or time frequency.
type fileLogWriter struct {
	sync.Mutex // write log order by order and  atomic incr maxLinesCurLines and maxSizeCurSize
	// The opened file
	Filename   string `json:"filename"`
	fileWriter *os.File

	// Rotate at line
	MaxLines         int `json:"maxlines"`
	maxLinesCurLines int

	// Rotate at size
	MaxSize        int `json:"maxsize"`
	maxSizeCurSize int

	// Rotate daily
	Daily         bool  `json:"daily"`
	MaxDays       int64 `json:"maxdays"`
	dailyOpenDate int

	Rotate bool `json:"rotate"`

	Level int `json:"level"`

	Perm os.FileMode `json:"perm"`
}

// NewFileWriter create a FileLogWriter returning as LoggerInterface.
func newFileWriter() Logger {
	w := &fileLogWriter{
		Filename: "",
		MaxLines: 1000000,
		MaxSize:  1 << 28, //256 MB
		Daily:    true,
		MaxDays:  7,
		Rotate:   true,
		Level:    LevelTrace,
		Perm:     0660,
	}
	return w
}

// Init file logger with json config.
// jsonConfig like:
//	{
//	"filename":"logs/beego.log",
//	"maxLines":10000,
//	"maxsize":1<<30,
//	"daily":true,
//	"maxDays":15,
//	"rotate":true,
//  	"perm":0600
//	}
func (w *fileLogWriter) Init(jsonConfig string) error {
	err := json.Unmarshal([]byte(jsonConfig), w)
	if err != nil {
		return err
	}
	if len(w.Filename) == 0 {
		return errors.New("jsonconfig must have filename")
	}
	err = w.startLogger()
	return err
}

// start file logger. create log file and set to locker-inside file writer.
func (w *fileLogWriter) startLogger() error {
	file, err := w.createLogFile()
	if err != nil {
		return err
	}
	if w.fileWriter != nil {
		w.fileWriter.Close()
	}
	w.fileWriter = file
	return w.initFd()
}

func (w *fileLogWriter) needRotate(size int, day int) bool {
	return (w.MaxLines > 0 && w.maxLinesCurLines >= w.MaxLines) ||
		(w.MaxSize > 0 && w.maxSizeCurSize >= w.MaxSize) ||
		(w.Daily && day != w.dailyOpenDate)

}

// WriteMsg write logger message into file.
func (w *fileLogWriter) WriteMsg(msg string, level int) error {
	if level > w.Level {
		return nil
	}
	//2016/01/12 21:34:33
	now := time.Now()
	y, mo, d := now.Date()
	h, mi, s := now.Clock()
	//len(2006/01/02 15:03:04)==19
	var buf [20]byte
	t := 3
	for y >= 10 {
		p := y / 10
		buf[t] = byte('0' + y - p*10)
		y = p
		t--
	}
	buf[0] = byte('0' + y)
	buf[4] = '/'
	if mo > 9 {
		buf[5] = '1'
		buf[6] = byte('0' + mo - 9)
	} else {
		buf[5] = '0'
		buf[6] = byte('0' + mo)
	}
	buf[7] = '/'
	t = d / 10
	buf[8] = byte('0' + t)
	buf[9] = byte('0' + d - t*10)
	buf[10] = ' '
	t = h / 10
	buf[11] = byte('0' + t)
	buf[12] = byte('0' + h - t*10)
	buf[13] = ':'
	t = mi / 10
	buf[14] = byte('0' + t)
	buf[15] = byte('0' + mi - t*10)
	buf[16] = ':'
	t = s / 10
	buf[17] = byte('0' + t)
	buf[18] = byte('0' + s - t*10)
	buf[19] = ' '
	msg = string(buf[0:]) + msg + "\n"

	if w.Rotate {
		if w.needRotate(len(msg), d) {
			w.Lock()
			if w.needRotate(len(msg), d) {
				if err := w.doRotate(); err != nil {
					fmt.Fprintf(os.Stderr, "FileLogWriter(%q): %s\n", w.Filename, err)
				}

			}
			w.Unlock()
		}
	}

	w.Lock()
	_, err := w.fileWriter.Write([]byte(msg))
	if err == nil {
		w.maxLinesCurLines++
		w.maxSizeCurSize += len(msg)
	}
	w.Unlock()
	return err
}

func (w *fileLogWriter) createLogFile() (*os.File, error) {
	// Open the log file
	fd, err := os.OpenFile(w.Filename, os.O_WRONLY|os.O_APPEND|os.O_CREATE, w.Perm)
	return fd, err
}

func (w *fileLogWriter) initFd() error {
	fd := w.fileWriter
	fInfo, err := fd.Stat()
	if err != nil {
		return fmt.Errorf("get stat err: %s\n", err)
	}
	w.maxSizeCurSize = int(fInfo.Size())
	w.dailyOpenDate = time.Now().Day()
	w.maxLinesCurLines = 0
	if fInfo.Size() > 0 {
		count, err := w.lines()
		if err != nil {
			return err
		}
		w.maxLinesCurLines = count
	}
	return nil
}

func (w *fileLogWriter) lines() (int, error) {
	fd, err := os.Open(w.Filename)
	if err != nil {
		return 0, err
	}
	defer fd.Close()

	buf := make([]byte, 32768) // 32k
	count := 0
	lineSep := []byte{'\n'}

	for {
		c, err := fd.Read(buf)
		if err != nil && err != io.EOF {
			return count, err
		}

		count += bytes.Count(buf[:c], lineSep)

		if err == io.EOF {
			break
		}
	}

	return count, nil
}

// DoRotate means it need to write file in new file.
// new file name like xx.2013-01-01.2.log
func (w *fileLogWriter) doRotate() error {
	_, err := os.Lstat(w.Filename)
	if err != nil {
		return err
	}
	// file exists
	// Find the next available number
	num := 1
	fName := ""
	suffix := filepath.Ext(w.Filename)
	filenameOnly := strings.TrimSuffix(w.Filename, suffix)
	if suffix == "" {
		suffix = ".log"
	}
	for ; err == nil && num <= 999; num++ {
		fName = filenameOnly + fmt.Sprintf(".%s.%03d%s", time.Now().Format("2006-01-02"), num, suffix)
		_, err = os.Lstat(fName)
	}
	// return error if the last file checked still existed
	if err == nil {
		return fmt.Errorf("Rotate: Cannot find free log number to rename %s\n", w.Filename)
	}

	// close fileWriter before rename
	w.fileWriter.Close()

	// Rename the file to its new found name
	// even if occurs error,we MUST guarantee to  restart new logger
	renameErr := os.Rename(w.Filename, fName)
	// re-start logger
	startLoggerErr := w.startLogger()
	go w.deleteOldLog()

	if startLoggerErr != nil {
		return fmt.Errorf("Rotate StartLogger: %s\n", startLoggerErr)
	}
	if renameErr != nil {
		return fmt.Errorf("Rotate: %s\n", renameErr)
	}
	return nil

}

func (w *fileLogWriter) deleteOldLog() {
	dir := filepath.Dir(w.Filename)
	filepath.Walk(dir, func(path string, info os.FileInfo, err error) (returnErr error) {
		defer func() {
			if r := recover(); r != nil {
				fmt.Fprintf(os.Stderr, "Unable to delete old log '%s', error: %v\n", path, r)
			}
		}()

		if !info.IsDir() && info.ModTime().Unix() < (time.Now().Unix()-60*60*24*w.MaxDays) {
			if strings.HasPrefix(filepath.Base(path), filepath.Base(w.Filename)) {
				os.Remove(path)
			}
		}
		return
	})
}

// Destroy close the file description, close file writer.
func (w *fileLogWriter) Destroy() {
	w.fileWriter.Close()
}

// Flush flush file logger.
// there are no buffering messages in file logger in memory.
// flush file means sync file from disk.
func (w *fileLogWriter) Flush() {
	w.fileWriter.Sync()
}

func init() {
	Register("file", newFileWriter)
}


text:
namespace mdsearch { namespace tests
{

	static const unsigned int NUM_KDTREE_DIMENSIONS = 3;

	class KDTreeTests : public ::testing::Test
	{

	};

	TEST_F(KDTreeTests, Construction)
	{
		KDTree structure(NUM_KDTREE_DIMENSIONS);
		ASSERT_EQ(NUM_PYRAMIDTREE_DIMENSIONS, structure.dimensionality());
	}

	TEST_F(KDTreeTests, Clear)
	{
		KDTree structure(NUM_KDTREE_DIMENSIONS);
		IndexStructureTester tester;
		const PointList& testPoints = tester.getTestPoints();
		structure.loadPoints(testPoints);
		// Ensure all points loaded exist
		for (unsigned int i = 0; (i < testPoints.size()); i++)
			ASSERT_TRUE(structure.pointExists(testPoints[i]));
		// Clear the entire structure
		structure.clear();
		// Ensure all points are no longer stored in structure
		for (unsigned int i = 0; (i < testPoints.size()); i++)
			ASSERT_FALSE(structure.pointExists(testPoints[i]));
	}

	TEST_F(KDTreeTests, InsertionAndRemoval)
	{
		KDTree structure(NUM_KDTREE_DIMENSIONS);
		IndexStructureTester tester;
		const PointList& testPoints = tester.getTestPoints();

		// Insert each point, ensuring that point and the points
		// previously inserted can be accessed
		for (unsigned int i = 0; (i < testPoints.size()); i++)
		{
			ASSERT_TRUE(structure.insert(testPoints[i]));
			for (unsigned int j = 0; (j <= i); j++)
				ASSERT_TRUE(structure.pointExists(testPoints[j]));
			for (unsigned int j = i + 1; (j < testPoints.size()); j++)
				ASSERT_FALSE(structure.pointExists(testPoints[j]));
		}

		// Now do the same for remove()
		for (unsigned int i = 0; (i < testPoints.size()); i++)
		{
			ASSERT_TRUE(structure.remove(testPoints[i]));
			for (unsigned int j = 0; (j <= i); j++)
				ASSERT_FALSE(structure.pointExists(testPoints[j]));
			for (unsigned int j = i + 1; (j < testPoints.size()); j++)
				ASSERT_TRUE(structure.pointExists(testPoints[j]));
		}
	}

	TEST_F(KDTreeTests, Updating)
	{
		KDTree structure(IndexStructureTester::NUM_TEST_DIMENSIONS);
		IndexStructureTester tester;
		tester.testUpdates(&structure);
	}

	TEST_F(KDTreeTests, PointQueries)
	{
		KDTree structure(IndexStructureTester::NUM_TEST_DIMENSIONS);
		IndexStructureTester tester;
		tester.testPointQueries(&structure);
	}

	TEST_F(KDTreeTests, FindMinimum)
	{
		KDTree structure(NUM_KDTREE_DIMENSIONS);
		IndexStructureTester tester;
		const PointList& testPoints = tester.getTestPoints();

		// Test on empty structure
		EXPECT_EQ(NULL, structure.findMinimum(structure.rootNode(), 0));

		// Test on filled structure
		structure.loadPoints(testPoints);
		const Point* returnedPoint = structure.findMinimum(structure.rootNode(), 0);
		ASSERT_TRUE(returnedPoint);
		EXPECT_EQ(testPoints[5], *returnedPoint);
		returnedPoint = structure.findMinimum(structure.rootNode(), 1);
		ASSERT_TRUE(returnedPoint);
		EXPECT_EQ(testPoints[2], *returnedPoint);
		// Case where there are MULTIPLE minimum points
		// Doesn't matter which is returned, as long one of them is
		returnedPoint = structure.findMinimum(structure.rootNode(), 2);
		ASSERT_TRUE(returnedPoint);
		EXPECT_TRUE(testPoints[0] == *returnedPoint
			|| testPoints[5] == *returnedPoint
			|| testPoints[6] == *returnedPoint
			|| testPoints[9] == *returnedPoint);
	}

	#ifdef TRACK_OPERATION_COSTS
	TEST_F(KDTreeTests, OpCostComputation)
	{
		KDTree structure(NUM_KDTREE_DIMENSIONS);
		IndexStructureTester tester;
		const PointList& testPoints = tester.getTestPoints();

		// Insertion count
		EXPECT_EQ(0.0, structure.averageInsertionCost()); // test initialisation
		EXPECT_EQ(0, structure.totalInsertionOps());
		structure.insert(testPoints[0]);
		EXPECT_EQ(0.0, structure.averageInsertionCost());
		EXPECT_EQ(1, structure.totalInsertionOps());
		structure.insert(testPoints[1]);
		EXPECT_EQ(0.5, structure.averageInsertionCost());
		EXPECT_EQ(2, structure.totalInsertionOps());
		structure.insert(testPoints[2]); // point will be left child of left child of root
		EXPECT_EQ(1.0, structure.averageInsertionCost());
		EXPECT_EQ(3.0, structure.totalInsertionOps());

		// Query count
		EXPECT_EQ(0.0, structure.averageQueryCost());
		EXPECT_EQ(0, structure.totalQueryOps());
		structure.pointExists(testPoints[2]);
		EXPECT_EQ(3.0, structure.averageQueryCost());
		EXPECT_EQ(1, structure.totalQueryOps());
		structure.pointExists(testPoints[3]);
		EXPECT_EQ(3.0, structure.averageQueryCost());
		EXPECT_EQ(2, structure.totalQueryOps());
		structure.pointExists(testPoints[0]);
		EXPECT_EQ((3.0 + 3.0 + 1.0) / 3.0, structure.averageQueryCost());
		EXPECT_EQ(3, structure.totalQueryOps());

		// Delete count
		EXPECT_EQ(0.0, structure.averageDeletionCost());
		EXPECT_EQ(0, structure.totalDeletionOps());
		structure.remove(testPoints[0]);
		EXPECT_EQ(6.0, structure.averageDeletionCost());
		EXPECT_EQ(1, structure.totalDeletionOps());
		structure.remove(testPoints[0]);
		EXPECT_EQ(4.0, structure.averageDeletionCost());
		EXPECT_EQ(2, structure.totalDeletionOps());

	}
	#endif

	TEST_F(KDTreeTests, Stats)
	{
		KDTree structure(NUM_KDTREE_DIMENSIONS);
		IndexStructureTester tester;
		const PointList& testPoints = tester.getTestPoints();
		structure.loadPoints(testPoints);

		KDTreeStats stats = structure.computeStats();
		EXPECT_EQ(4.0, stats.balanceFactor);
		EXPECT_EQ(5, stats.maxPathLength);

		const Real vals[] = { 6, 5.5, 2 };
		Point newPoint(3, vals);
		ASSERT_TRUE(structure.insert(newPoint));
		stats = structure.computeStats();
		EXPECT_EQ(((5.0 + 4.0 + 4.0) / 3.0), stats.balanceFactor); // 4.33r
		EXPECT_EQ(5, stats.maxPathLength);
	}

} }

#endif


text:
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft 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.
// ----------------------------------------------------------------------------------

using System;
using System.Diagnostics;
using System.Management.Automation;
using System.Threading;
using Microsoft.Azure.Commands.RecoveryServices.SiteRecovery;
using Microsoft.WindowsAzure.Management.SiteRecovery.Models;

namespace Microsoft.Azure.Commands.RecoveryServices
{
    /// <summary>
    /// Remove a Recovery Plan from the current Azure Site Recovery Vault.
    /// </summary>
    [Cmdlet(VerbsCommon.Remove, "AzureSiteRecoveryRecoveryPlan", DefaultParameterSetName = ASRParameterSets.ByRPObject, SupportsShouldProcess = true)]
    [OutputType(typeof(ASRJob))]
    [Obsolete("This cmdlet has been marked for deprecation in an upcoming release. Please use the " +
        "equivalent cmdlet from the AzureRm.RecoveryServices.SiteRecovery module instead.",
        false)]
    public class RemoveAzureSiteRecoveryRecoveryPlan : RecoveryServicesCmdletBase
    {
        #region Parameters
        /// <summary>
        /// Job response.
        /// </summary>
        private JobResponse jobResponse = null;

        /// <summary>
        /// Holds either Name (if object is passed) or ID (if IDs are passed) of the PE.
        /// </summary>
        private string targetNameOrId = string.Empty;

        /// <summary>
        /// Gets or sets ID of the Recovery Plan.
        /// </summary>
        [Parameter(ParameterSetName = ASRParameterSets.ById, Mandatory = true)]
        [ValidateNotNullOrEmpty]
        public string Id { get; set; }

        /// <summary>
        /// Gets or sets Recovery Plan object.
        /// </summary>
        [Parameter(ParameterSetName = ASRParameterSets.ByRPObject, Mandatory = true, ValueFromPipeline = true)]
        [ValidateNotNullOrEmpty]
        public ASRRecoveryPlan RecoveryPlan { get; set; }

        /// <summary>
        /// Gets or sets switch parameter. This is required to wait for job completion.
        /// </summary>
        [Parameter]
        public SwitchParameter WaitForCompletion { get; set; }

        /// <summary>
        /// Gets or sets switch parameter. On passing, command does not ask for confirmation.
        /// </summary>
        [Parameter(Mandatory = false)]
        public SwitchParameter Force { get; set; }
        #endregion Parameters

        /// <summary>
        /// ProcessRecord of the command.
        /// </summary>
        public override void ExecuteCmdlet()
        {
            this.WriteWarningWithTimestamp(
                string.Format(
                    Properties.Resources.CmdletWillBeDeprecatedSoon,
                    this.MyInvocation.MyCommand.Name));

            switch (this.ParameterSetName)
            {
                case ASRParameterSets.ByRPObject:
                    this.Id = this.RecoveryPlan.ID;
                    this.targetNameOrId = this.RecoveryPlan.Name;
                    break;
                case ASRParameterSets.ById:
                    this.targetNameOrId = this.Id;
                    break;
            }

            this.ConfirmAction(
                this.Force.IsPresent,
                string.Format(Properties.Resources.RemoveRPWarning, this.targetNameOrId),
                Properties.Resources.RemoveRPWhatIfMessage,
                this.targetNameOrId,
                () =>
                {
                    try
                    {
                        this.jobResponse = RecoveryServicesClient.RemoveAzureSiteRecoveryRecoveryPlan(
                           this.Id);
                        this.WriteJob(this.jobResponse.Job);

                        string jobId = this.jobResponse.Job.ID;
                        if (this.WaitForCompletion.IsPresent)
                        {
                            this.WaitForJobCompletion(this.jobResponse.Job.ID);
                        }
                    }
                    catch (Exception exception)
                    {
                        this.HandleException(exception);
                    }
                });
        }

        /// <summary>
        /// Writes Job
        /// </summary>
        /// <param name="job">Job object</param>
        private void WriteJob(Microsoft.WindowsAzure.Management.SiteRecovery.Models.Job job)
        {
            this.WriteObject(new ASRJob(job));
        }
    }
}


text:
/*
 * PreferencesWindowController.h
 *
 * Created by Sajid Anwar.
 *
 * Subject to terms and conditions in LICENSE.md.
 *
 */

#import <MASPreferences/MASPreferencesWindowController.h>
#import "GeneralPreferencesViewController.h"
#import "NavigationPreferencesViewController.h"
#import "LastFmPreferencesViewController.h"

@interface PreferencesWindowController : MASPreferencesWindowController

@property (assign) IBOutlet GeneralPreferencesViewController *generalController;
@property (assign) IBOutlet NavigationPreferencesViewController *navigationController;
@property (assign) IBOutlet LastFmPreferencesViewController *lastFmController;

- (void)loadControllers;

@end


text:
goog.setTestOnly();
goog.require('goog.testing.AsyncTestCase');
goog.require('goog.testing.jsunit');
goog.require('lf.Global');
goog.require('lf.backstore.Memory');
goog.require('lf.cache.DefaultCache');
goog.require('lf.index.MemoryIndexStore');
goog.require('lf.service');
goog.require('lf.testing.backstore.ScudTester');
goog.require('lf.testing.getSchemaBuilder');

/** @type {!goog.testing.AsyncTestCase} */
var asyncTestCase = goog.testing.AsyncTestCase.createAndInstall(
    'MemoryBackStore');

/** @type {!lf.backstore.Memory} */
var db;

/** @type {!lf.cache.Cache} */
var cache;

/** @type {!lf.schema.Database} */
var schema;

function setUp() {
  asyncTestCase.waitForAsync('setUp');

  var indexStore = new lf.index.MemoryIndexStore();
  schema = lf.testing.getSchemaBuilder().getSchema();
  cache = new lf.cache.DefaultCache(schema);

  var global = lf.Global.get();
  global.registerService(lf.service.CACHE, cache);
  global.registerService(lf.service.INDEX_STORE, indexStore);
  global.registerService(lf.service.SCHEMA, schema);

  db = new lf.backstore.Memory(schema);

  db.init().then(function() {
    asyncTestCase.continueTesting();
  }, fail);
}

/**
 * Tests that the backstore.Memory is instantiated according to the schema
 * instance that is passed into its constructor.
 */
function testConstruction() {
  assertTrue(schema.tables().length > 0);

  schema.tables().forEach(
      function(table) {
        assertNotNull(db.getTableInternal(table.getName()));
      });
}

function testGetTable_NonExisting() {
  assertThrows(
      goog.bind(db.getTableInternal, db, 'nonExistingTableName'));
}

function testSCUD() {
  var scudTester = new lf.testing.backstore.ScudTester(db, lf.Global.get());

  scudTester.run().then(function() {
    asyncTestCase.continueTesting();
  });

  asyncTestCase.waitForAsync('testSCUD');
}


text:
#include "stdafx.h"
#include "resource.h"
#include "IntelMediaServerService.h"
#include "MediaServer.h"
#include <stdio.h>

MediaServer *g_MediaServer = NULL;

class CIntelMediaServerServiceModule : public CAtlServiceModuleT< CIntelMediaServerServiceModule, IDS_SERVICENAME >
{
public :
	DECLARE_LIBID(LIBID_IntelMediaServerServiceLib)
	DECLARE_REGISTRY_APPID_RESOURCEID(IDR_INTELMEDIASERVERSERVICE, "{91556716-97AA-4787-8EE7-D8D648886E24}")

	static DWORD WINAPI MediaServerInitThread(LPVOID args)
	{
		Sleep(50);
		CoInitializeEx(0,COINIT_MULTITHREADED);
		g_MediaServer = new MediaServer();

		// Fetch path of this service
		TCHAR szFilePath[MAX_PATH];
		DWORD dwFLen = ::GetModuleFileName(NULL, szFilePath, MAX_PATH);
		if( dwFLen == 0 || dwFLen == MAX_PATH ) return E_FAIL;

		g_MediaServer->Init(szFilePath);

		return 0;
	}

	HRESULT Run(int nShowCmd = SW_HIDE)
	{
		CreateThread(NULL,0,&MediaServerInitThread,this,0,NULL);

		HRESULT r = CAtlServiceModuleT< CIntelMediaServerServiceModule, IDS_SERVICENAME >::Run(nShowCmd);

		if (g_MediaServer != NULL)
		{
			delete g_MediaServer;
			g_MediaServer = NULL;
		}

		return r;
	}

	void OnStop() throw()
	{
		if (g_MediaServer != NULL)
		{
			delete g_MediaServer;
			g_MediaServer = NULL;
		}
		CAtlServiceModuleT< CIntelMediaServerServiceModule, IDS_SERVICENAME >::OnStop();
	}

	void OnPause() throw()
	{
		if (g_MediaServer != NULL)
		{
			delete g_MediaServer;
			g_MediaServer = NULL;
		}
		CAtlServiceModuleT< CIntelMediaServerServiceModule, IDS_SERVICENAME >::OnPause();
	}

	void OnContinue() throw()
	{
		if (g_MediaServer == NULL)
		{
			// Fetch path of this service
			TCHAR szFilePath[MAX_PATH];
			DWORD dwFLen = ::GetModuleFileName(NULL, szFilePath, MAX_PATH);
			if( dwFLen == 0 || dwFLen == MAX_PATH ) return;

			g_MediaServer = new MediaServer();
			HRESULT r = g_MediaServer->Init(szFilePath);
		}
		CAtlServiceModuleT< CIntelMediaServerServiceModule, IDS_SERVICENAME >::OnContinue();
	}

	void OnShutdown() throw()
	{
		if (g_MediaServer != NULL)
		{
			delete g_MediaServer;
			g_MediaServer = NULL;
		}

		CAtlServiceModuleT< CIntelMediaServerServiceModule, IDS_SERVICENAME >::OnShutdown();
	}

};

CIntelMediaServerServiceModule _AtlModule;

//
extern "C" int WINAPI _tWinMain(HINSTANCE /*hInstance*/, HINSTANCE /*hPrevInstance*/,
                                LPTSTR /*lpCmdLine*/, int nShowCmd)
{
    return _AtlModule.WinMain(nShowCmd);
}