text:
TOR Support in SnapCoinCoin
=======================

It is possible to run SnapCoinCoin as a Tor hidden service, and connect to such services.

The following directions assume you have a Tor proxy running on port 9050. Many distributions
default to having a SOCKS proxy listening on port 9050, but others may not.
In particular, the Tor Browser Bundle defaults to listening on a random port. See
https://www.torproject.org/docs/faq.html.en#TBBSocksPort for how to properly
configure Tor.

1. Run SnapCoinCoin behind a Tor proxy
---------------------------------

The first step is running SnapCoinCoin behind a Tor proxy. This will already make all
outgoing connections be anonimized, but more is possible.

-proxy=ip:port  Set the proxy server. If SOCKS5 is selected (default), this proxy
                server will be used to try to reach .onion addresses as well.

-tor=ip:port    Set the proxy server to use for tor hidden services. You do not
                need to set this if it's the same as -proxy. You can use -notor
                to explicitly disable access to hidden service.

-listen         When using -proxy, listening is disabled by default. If you want
                to run a hidden service (see next section), you'll need to enable
                it explicitly.

-connect=X      When behind a Tor proxy, you can specify .onion addresses instead
-addnode=X      of IP addresses or hostnames in these parameters. It requires
-seednode=X     SOCKS5. In Tor mode, such addresses can also be exchanged with
                other P2P nodes.

In a typical situation, this suffices to run behind a Tor proxy:

  ./snapcoind -proxy=127.0.0.1:9050

2. Run a SnapCoinCoin hidden server
------------------------------

If you configure your Tor system accordingly, it is possible to make your node also
reachable from the Tor network. Add these lines to your /etc/tor/torrc (or equivalent
config file):

  HiddenServiceDir /var/lib/tor/SnapCoin-service/
  HiddenServicePort 22349 127.0.0.1:22349

The directory can be different of course, but (both) port numbers should be equal to
your snapcoind's P2P listen port (22349 by default).

-externalip=X   You can tell litecoin about its publicly reachable address using
                this option, and this can be a .onion address. Given the above
                configuration, you can find your onion address in
                /var/lib/tor/SnapCoin-service/hostname. Onion addresses are given
                preference for your node to advertize itself with, for connections
                coming from unroutable addresses (such as 127.0.0.1, where the
                Tor proxy typically runs).

-listen         You'll need to enable listening for incoming connections, as this
                is off by default behind a proxy.

-discover       When -externalip is specified, no attempt is made to discover local
                IPv4 or IPv6 addresses. If you want to run a dual stack, reachable
                from both Tor and IPv4 (or IPv6), you'll need to either pass your
                other addresses using -externalip, or explicitly enable -discover.
                Note that both addresses of a dual-stack system may be easily
                linkable using traffic analysis.

In a typical situation, where you're only reachable via Tor, this should suffice:

  ./snapcoind -proxy=127.0.0.1:9050 -externalip=57qr3yd1nyntf5k.onion -listen

(obviously, replace the Onion address with your own). If you don't care too much
about hiding your node, and want to be reachable on IPv4 as well, additionally
specify:

  ./snapcoind ... -discover

and open port 22349 on your firewall (or use -upnp).

If you only want to use Tor to reach onion addresses, but not use it as a proxy
for normal IPv4/IPv6 communication, use:

  ./snapcoind -tor=127.0.0.1:9050 -externalip=57qr3yd1nyntf5k.onion -discover


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Blue Project</title>
    <meta name="description" content="Complete Site">
    <meta name="author" content="Vassilis Sponis">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link rel="stylesheet" href="css/normalize.css">
    <link rel="stylesheet" href="css/main.css">
    <link rel="stylesheet" href="css/lightbox.css">

    <link href='http://fonts.googleapis.com/css?family=Trykker|Share+Tech' rel='stylesheet' type='text/css'>

                Subscribe to:

Posts

Comments

Email

                    <form name="search" action ="" method="">
                        <input type="text" name="searchvalue" placeholder="  Search Keywords">
                        <input class="magnglass" type="Submit" value="">
                    </form>

                    Blue Masters
                    COMPLETELY UNIQUE WORDPRESS THEME

Home

About

Portfolio

Blog

Contact

Contact Us!

            <form class="contactus" name="ContactUs" method="post" action="html_form_send.php">

                        First Name *
                        <input id="first_name" type="text" name="first_name" maxlength="50" placeholder="Your First Name" tabindex="1">

                        Last Name *
                        <input id="last_name" type="text" name="last_name" maxlength="50" placeholder="Your Last Name" tabindex="2">

                        Email Address *
                        <input id="email" type="text" name="email" maxlength="80" placeholder="Your Email Address" tabindex="3">

                        Telephone Number *
                        <input id="telephone" type="text" name="telephone" maxlength="30" placeholder="Your Telephone" tabindex="4">

                        Date of Birth *
                        <input id="DoB" type="text" name="DoB" maxlength="30" placeholder="Your Date of Birth" tabindex="5">

                        Home Address
                        <input id="address" type="text" name="address" maxlength="50" placeholder="Your Home Address" tabindex="6">

                        Country *
                        <select id="country" name="country">
                            <option value="">Country</option>
                            <option value="China">CHN</option>
                            <option value="England">ENG</option>
                            <option value="France">FRA</option>
                            <option value="Germany">GER</option>
                            <option value="Greece">GRE</option>
                            <option value="Holland">HOL</option>
                            <option value="Italy">ITA</option>
                            <option value="Japan">JPN</option>
                            <option value="USA">USA</option>
                            <option value="Other">Other</option>
                        </select>

                        Comments
                        <textarea id="comments" name="comments" maxlength="1000" cols="25" rows="6" placeholder="add any comments" tabindex="7"></textarea>

                        I Accept the Terms and Conditions *
                        <input id="terms" type="checkbox" name="terms" value="terms">

                <input class="submitbutton" type="submit" value="Submit">
            </form>

About Us

Our Company

Our Blog

Submit A Site

Contact Us

Help & Terms

Read Our FAQ

Categories

Trends & Technology

Desigh Companies

Design Freelancers

Web Portfolios

Web Development

General Icons

From The Gallery

Twitter Updates

© 2010 Copyright iPadMasters Theme. All Rights Reserved.

Log In

Privacy Policy

Terms and Conditions

Contact Us

Back to Top

redpajama_set_name: RedPajamaGithub


text:
package edu.uw.zookeeper.safari.region;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.google.common.base.Optional;
import com.google.common.base.Supplier;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;

import edu.uw.zookeeper.common.Automaton;
import edu.uw.zookeeper.common.Automatons;
import edu.uw.zookeeper.common.LoggingFutureListener;

import edu.uw.zookeeper.data.Materializer;
import edu.uw.zookeeper.safari.Identifier;
import edu.uw.zookeeper.safari.control.schema.ControlZNode;

public final class LeaderProposer implements Supplier<ListenableFuture<Optional<Automaton.Transition<RegionRole>>>> {

    /**
     * Always proposes the same leader.
     */
    public static LeaderProposer fixedLeader(
            final Identifier peer,
            final Identifier region,
            final Automatons.EventfulAutomaton<RegionRole, LeaderEpoch> role,
            final Materializer<ControlZNode<?>,?> materializer) {
        return create(new Supplier<Identifier>() {
            @Override
            public Identifier get() {
                return peer;
            }
        }, region, role, materializer);
    }

    public static LeaderProposer create(
            Supplier<Identifier> leader,
            Identifier region,
            Automatons.EventfulAutomaton<RegionRole, LeaderEpoch> role,
            Materializer<ControlZNode<?>,?> materializer) {
        return new LeaderProposer(leader, region, role, materializer);
    }

    protected final Logger logger;
    protected final Automatons.EventfulAutomaton<RegionRole, LeaderEpoch> role;
    protected final Identifier region;
    protected final Supplier<Identifier> leader;
    protected final Materializer<ControlZNode<?>,?> materializer;

    protected LeaderProposer(
            Supplier<Identifier> leader,
            Identifier region,
            Automatons.EventfulAutomaton<RegionRole, LeaderEpoch> role,
            Materializer<ControlZNode<?>,?> materializer) {
        this.logger = LogManager.getLogger(this);
        this.materializer = materializer;
        this.role = role;
        this.region = region;
        this.leader = leader;
    }

    @Override
    public ListenableFuture<Optional<Automaton.Transition<RegionRole>>> get() {
        Optional<Integer> epoch = role.state().hasEpoch() ? Optional.of(role.state().getEpoch().getEpoch()) : Optional.<Integer>absent();
        ListenableFuture<LeaderEpoch> proposal =
                LoggingFutureListener.listen(logger, LeaderProposal.call(
                region, leader.get(), epoch, materializer));
        // update role before listeners see it
        return Futures.transform(proposal, role);
    }
}


text:
class Server < ActiveRecord::Base
  REPORT_FAULTY_VM_EVERY = 7.days

  include PublicActivity::Common
  include Billing::ServerInvoiceable
  include SiftProperties
  include Taggable
  acts_as_paranoid

  # Maximum time for server to be in states such as building, booting, etc
  MAX_TIME_FOR_INTERMEDIATE_STATES = 30.minutes

  # Maximum number of IPs that can be added to a server
  MAX_IPS = 4

  before_save :update_forecasted_revenue
  belongs_to :user
  belongs_to :unscoped_user, -> { unscope(where: :deleted_at) }, foreign_key: :user_id, class_name: "User"
  belongs_to :unscoped_location, -> { unscope(where: :deleted_at) }, foreign_key: :location_id, class_name: "Location"
  belongs_to :template
  belongs_to :location
  has_many :server_events, -> { order transaction_updated: :desc}, dependent: :destroy
  has_many :server_usages, dependent: :destroy
  has_many :server_backups, dependent: :destroy
  has_many :server_hourly_transactions, dependent: :destroy
  has_many :server_ip_addresses, dependent: :destroy
  has_many :unscoped_server_ip_addresses, -> { unscope(where: :deleted_at) }, foreign_key: :server_id, class_name: "ServerIpAddress"
  has_many :server_addons, dependent: :destroy
  has_many :addons, through: :server_addons, dependent: :destroy

  validates :identifier, :hostname, :name, :user, presence: true
  validates :template, :location, presence: true
  validate :template_should_match_location, on: :create
  validates_with HostnameValidator

  enum_field :state, allowed_values: [:pending, :building, :starting_up, :rebooting, :shutting_down, :on, :off ,:blocked, :provisioning], default: :building
  enum_field :payment_type, allowed_values: [:prepaid, :payg], default: :prepaid

  scope :prepaid, -> { where(payment_type: :prepaid) }
  scope :payg, -> { where(payment_type: :payg) }
  scope :created_this_month, -> { where('created_at > ? AND created_at < ?', Time.now.beginning_of_month, Time.now.end_of_month) }
  scope :created_last_month, -> { where('created_at > ? AND created_at < ?', (Time.now - 1.month).beginning_of_month, (Time.now - 1.month).end_of_month) }
  scope :deleted_this_month, -> { where('deleted_at > ? AND deleted_at < ?', Time.now.beginning_of_month, Time.now.end_of_month) }
  scope :deleted_last_month, -> { where('deleted_at > ? AND deleted_at < ?', (Time.now - 1.month).beginning_of_month, (Time.now - 1.month).end_of_month) }
  scope :servers_under_validation, -> { where('validation_reason > 0') }

  TYPE_PREPAID  = 'prepaid'
  TYPE_PAYG     = 'payg'

  NEW_IP_REQUESTED_CACHE = "new_ip_requested_cache"
  BACKUP_CREATED_CACHE = "backup_created_cache"

  def self.provisioner_roles
    return [] unless ENV['DOCKER_PROVISIONER'].present?
    Rails.cache.fetch("provisioner_roles", expires_in: 12.hours) do
      provisioner_roles = DockerProvisionerTasks.new.roles
      JSON.parse(provisioner_roles.body)
    end
  rescue StandardError => e
    ErrorLogging.new.track_exception(e, extra: { source: 'Server#provisioner_roles' })
    return []
  end

  def self.purchased_resources
    sums = pluck(:cpus, :memory, :disk_size)
      .inject([0,0,0]) {|sum, o| [sum,o].transpose.map {|x| x.reduce(:+)}}

    {cpu: sums[0], mem: sums[1], disc: sums[2]}
  end

  def self.clear_free_bandwidth(servers)
    servers.each { |s| s.update_attribute(:free_billing_bandwidth, 0)}
  end

  def self.clear_bandwidth_notifications(servers)
    servers.each { |s| s.update(
      exceed_bw_user_notif: 0,
      exceed_bw_value: 0,
      exceed_bw_user_last_sent: nil,
      exceed_bw_admin_notif: 0
      )
    }
  end

  def name_with_ip
    "#{name} (IP: #{primary_ip_address})"
  end

  def to_s
    "#{name}, #{hostname} (Belongs to: #{user})"
  end

  def ip_requested
    ip_requested_cache = Rails.cache.read([Server::NEW_IP_REQUESTED_CACHE, id])
    ip_requested_cache.nil? ? 0 : ip_requested_cache
  end

  def ip_requested=(count)
    if count > 0
      Rails.cache.write([Server::NEW_IP_REQUESTED_CACHE, id], count)
    else
      Rails.cache.delete([Server::NEW_IP_REQUESTED_CACHE, id])
    end
  end

  def ip_addresses
    server_ip_addresses.count + ip_requested
  end

  def primary_ip_address
    @primary_ip_address ||= begin
      server_ip_addresses.with_deleted.present? ? ((server_ip_addresses.with_deleted.find(&:primary?) || server_ip_addresses.with_deleted.first).address) : nil
    end
  end

  # Returns the primary network interface of server from Onapp, useful when assigning new IP
  def primary_network_interface
    server_task = ServerTasks.new
    interfaces = server_task.perform(:get_network_interfaces, user.id, id)
    primary = interfaces.find { |interface| interface['network_interface']['primary'] == true }
    primary['network_interface']
  rescue
    nil
  end

  def destroy_with_ip(ip)
    update!(delete_ip_address: ip)
    destroy
  end

  def prepaid?
    payment_type == Server::TYPE_PREPAID.to_sym
  end

  def payg?
    payment_type == Server::TYPE_PAYG.to_sym
  end

  def note_time_of_state_change
    update_attributes!(state_changed_at: Time.zone.now)
  end

  def last_state_change
    state_changed_at || created_at
  end

  def detect_stuck_state
    detected_stuck = false
    has_intermediate_state = !state.in?([:off, :on, :blocked])
    time_in_state = Time.zone.now - last_state_change
    if has_intermediate_state && time_in_state > MAX_TIME_FOR_INTERMEDIATE_STATES
      detected_stuck = true
      # Only respond to a stuck state the first time it is detected
      unless stuck
        AdminMailer.notify_stuck_server_state(self).deliver_now
        NotifyUsersMailer.notify_stuck_state(user, self).deliver_now
      end
    end
    update_attribute :stuck, detected_stuck if detected_stuck != stuck
  end

  # Notify admin if server has no storage attached or no IPs
  def notify_fault(no_disk, no_ip)
    add_remove_tags_by_hash(no_disk: no_disk, no_ip: no_ip)
    return unless no_disk || no_ip
    days_since_creation = ((Time.now - created_at) / 1.day).floor
    last_warning_threshold = case fault_reported_at
      when nil then 1
      else ((Time.now - fault_reported_at) / REPORT_FAULTY_VM_EVERY).floor
    end
    if days_since_creation >= 1 && last_warning_threshold >= 1
      AdminMailer.notify_faulty_server(self, no_disk, no_ip).deliver_now
      update_attribute :fault_reported_at, Time.now
      create_activity :faulty_server_report, owner: user, params: { no_disk: no_disk, no_ip: no_ip}
    end
  end

  # Change the resources for a server in our DB. Does not sync these changes to the server on the
  # Federation. It is true that, should the server be updated through the Federation API, then our
  # worker processes will eventually update the server anyway. But updating the server before the
  # Federation does, gives instant feedback to the user that their server has been updated.
  #
  # `resources` hash, new resources for server
  def edit(resources, store = true)
    resources.stringify_keys!
    editable_properties = %w(name cpus memory disk_size template_id addon_ids)
    updates = {}
    editable_properties.each do |field|
      updates[field] = resources[field] if resources.key? field
    end
    if store
      update_attributes!(updates)
    else
      assign_attributes(updates)
    end
  end

  # Check whether the current resources attributed to the server match a given package.
  # Used when editing a server, it's useful to highlight a package option if it matches the current
  # resources.
  # TODO; there is a duplicate function in ServerWizard, choose one or the other.
  #
  # `package` instance of Package model
  def matches_package?(package)
    %w(memory cpus disk_size).each do |resource|
      return false if send(resource) != package.send(resource)
    end
    true
  end

  # Blocks until server has the :on state. Used mainly during testing
  def wait_until_ready
    reload
    server_task = ServerTasks.new
    start = Time.now
    until locked == false
      sleep 60 # Too many request can fill up VCR cassettes
      server_task.perform(:refresh_server, user.id, id)
      reload
      break if Time.now - start > 10.minutes
    end
  end

  # Check temp cache of IP count is within permissible limit of IPs that can be added to a server, also check if location supports multiple IPs
  def can_add_ips?
    return false if state != :on && state != :off
    supports_multiple_ips? && (ips_chargeable? || ip_addresses < MAX_IPS)
  end

  def ips_chargeable?
    location.price_ip_address.to_f > 0
  end

  # Check if version of Onapp supports multiple IPs - should be 4.1.0+
  def supports_multiple_ips?
    Gem::Version.new(location.hv_group_version) >= Gem::Version.new('4.1.0')
  end

  # Check if version of Onapp supports manual backups - should be 4.0.0+
  def supports_manual_backups?
    Gem::Version.new(location.hv_group_version) >= Gem::Version.new('4.0.0')
  end

  def supports_root_password_reset?
    Gem::Version.new(location.hv_group_version) >= Gem::Version.new('4.2.0')
  end

  def no_auto_refresh!
    update_attribute(:no_refresh, true)
  end

  def auto_refresh_on!
    update_attribute(:no_refresh, false)
  end

  def update_forecasted_revenue
    self.forecasted_rev = forecasted_revenue
  end

  def forecasted_revenue
    return 0.0 if user.suspended?
    discount = (1 - coupon_percentage).round(3)
    (monthly_price * discount).round
  end

  def monthly_price
    (location.hourly_price(memory, cpus, disk_size) * Account::HOURS_MAX).round
  end

  def coupon_percentage
    coupon = user.account.coupon
    if coupon.present? then coupon.percentage_decimal else 0 end
  end

  def refresh_usage
    RefreshServerUsages.new.refresh_server_usages(self)
  rescue => e
    ErrorLogging.new.track_exception(e, extra: { source: 'Server#refresh_usage', server_id: id })
    # raise error - for not invoicing when user suspended at onapp or server does not exist
    raise e if e.is_a?(Faraday::ClientError) && e.to_s =~ /[401,404]/
  end

  def inform_if_bandwidth_exceeded
    BandwidthChecker.new(self).check_bandwidth
  end

  def provisioned?
    !provisioned_at.nil?
  end

  def can_provision?
    !provisioner_role.nil? && validation_reason == 0 && !provisioned?
  end

  def monitor_and_provision
    docker_provision = can_provision?
    no_auto_refresh! if docker_provision
    MonitorServer.perform_in(MonitorServer::POLL_INTERVAL.seconds, id, user_id, docker_provision)
    DockerCreation.perform_in(MonitorServer::POLL_INTERVAL.seconds, id, provisioner_role) if docker_provision
  end

  def install_ssh_keys(keys)
    InstallKeys.perform_in(MonitorServer::POLL_INTERVAL.seconds, id, keys)
  end

  def process_addons
    ProcessAddons.new(self).process
  end

  def supports_rebuild?
    !(try(:os) == "windows" || try(:provisioner_role))
  end

  private

  def template_should_match_location
    unless location && template && location.templates.where(hidden: false).exists?(template.id)
      errors.add(:server, 'Template does not match location')
      return false
    end
  end
end


text:
using System;
using Umbraco.Core.Persistence;
using Umbraco.Core.Persistence.DatabaseAnnotations;

namespace Umbraco.Core.Models.Rdbms
{
    [TableName("umbracoUserLogins")]
    [ExplicitColumns]
    internal class UserLoginDto
    {
        [Column("contextID")]
        [Index(IndexTypes.Clustered, Name = "IX_umbracoUserLogins_Index")]
        public Guid ContextId { get; set; }

        [Column("userID")]
        public int UserId { get; set; }

        [Column("timeout")]
        public long Timeout { get; set; }
    }
}


text:
import os, time
from utils import *
from fsmonitor import *
from fsmonitor.polling import FSMonitor as PollingFSMonitor

def test_2_create_not_delete():
    fsm_test = FSMonitorTest()
    w = fsm_test.add_dir_watch(tempdir)
    touch(get_testpath("x"))
    fsm_test.remove_watch(w)
    remove(get_testpath("x"))

    time.sleep(0.1)

    assert fsm_test.event_happened(FSEvent.Create, "x")
    assert not fsm_test.event_happened(FSEvent.Delete, "x")

def test_2_create_not_delete_polling():
    fsm_test = FSMonitorTest(PollingFSMonitor)
    w = fsm_test.add_dir_watch(tempdir)
    touch(get_testpath("x"))
    fsm_test.remove_watch(w)
    remove(get_testpath("x"))

    time.sleep(0.1)

    assert fsm_test.event_happened(FSEvent.Create, "x")
    assert not fsm_test.event_happened(FSEvent.Delete, "x")


text:
/**
 * library includes
 */
#include <vector>

/**
 * project includes
 */
#include "../inc/CavalcadeGlobals.h"
#include "../../../OpenGLRendering/src/inc/Rendering.h"
#include "../inc/Axon.h"
#include "../inc/LeakyIntegrator.h"
#include "../inc/Mind.h"
#include "../inc/Neuron.h"

Neuron::Neuron()
{
    //LastFireTimestamp = 0;
    S_level = 0;
    S_peak = 0;
    S_TC = DEF_SD_TC;
    ParentMind = NULL;

    ActionPotential = LeakyIntegrator(DEF_EXC_TC,10,DEF_FIRETHRESH);
}

Neuron::Neuron(int PID,RGB col)
{
    //set the default values of all variables
    fire_threshold = DEF_FIRETHRESH;
    impulses_recieved = 0;
    impulses_fired = 0;
    excitation_level = 0;
    exc_TC = DEF_EXC_TC;
    amplitude_peak = 0.0;
    refractory_countdown = 0;
    refractory_period = DEF_REFRAC_TIME;
    excitation_time = 0;
    LastFireTimestamp = 0;
    LastStimTimestamp = 0;

    ActionPotential = LeakyIntegrator(DEF_EXC_TC,10,DEF_FIRETHRESH);

    //S initialisation
    S_TC = DEF_SD_TC;
    S_level = 0;
    S_peak = 0;
    S_excitation_time = 0;

    ParentGroupID = PID;

    neuCol = col;

    ParentMind = NULL;
}

Neuron::Neuron(int PID, PlotPoint neuPos, double firethresh, double epsilon, double refrac,RGB col)
{
    ParentGroupID = PID;
    position = neuPos;
    fire_threshold = firethresh;
    exc_TC = epsilon;
    if(refrac!=0)
            refractory_period = refrac;
    else
            refractory_period = DEF_REFRAC_TIME;
    refractory_countdown = 0;

    LastFireTimestamp = 0;
    LastStimTimestamp = 0;

    ActionPotential = LeakyIntegrator(DEF_EXC_TC,10,DEF_FIRETHRESH);

    impulses_recieved = 0;
    impulses_fired = 0;
    excitation_level = 0;
    excitation_time = 0;
    amplitude_peak = 0.0;

    S_TC = DEF_SD_TC;
    S_level = 0;
    S_peak = 0;
    S_excitation_time = 0;

    neuCol = col;

    ParentMind = NULL;
}

void Neuron::Stimulate_TW(double amplitude)
{
    //**DELETE AFTER OXFORD INTERVIEW**//
    if(ParentMind->_t_Window == NULL) Stimulate(amplitude);

    if(ActionPotential.Stimulate(amplitude))
    {
        Fire_TW();
    }

    impulses_recieved++;
}

void Neuron::Fire_TW()
{
    for(int x=0;x<outgoingAxons.size();x++) {
    	Axon* a = outgoingAxons[x];
    	a->AcceptFire();
    }

    refractory_countdown = refractory_period; //only here to make visualisation cool

    S_peak = S_level + DEF_SD_MAG; //add the spike to the current SDPD excitation level
    S_level = S_peak;

    ActionPotential.Reset();

}

//called to stimulate the current neuron
void Neuron::Stimulate(double amplitude)
{

    if(refractory_countdown == 0)
    {

        excitation_level = amplitude_peak*exp(-(excitation_time)/exc_TC); //calculate the excitation level

        if(excitation_level<0.01f) amplitude_peak = 0; //if the potential has dropped below certain value since last stimulus, reset the running sum of consecutive pulses

        excitation_time = 0; //reset the time between stimulations
        amplitude_peak = excitation_level + amplitude; //add the stimulated response onto the potential
        excitation_level = amplitude_peak; //set the excitation level of the neuron after the fire

        impulses_recieved++;
    }
}

//called to fire the current neuron
void Neuron::Fire()
{
    //cause a spike in SDPD of this neuron to denote 'suppy'
    S_excitation_time  = 0; //reset the time between fires
    S_peak = S_level + DEF_SD_MAG; //add the spike to the current SDPD excitation level
    S_level = S_peak;
    //reset the excitation levels to refractory period and peak to 0
    excitation_level = DEF_REFRAC_LEV;
    amplitude_peak = 0;
    refractory_countdown = refractory_period;

    //raise the event of the neuron firing
    for(int x=0;x<outgoingAxons.size();x++) {
    	Axon* a = outgoingAxons[x];
    	a->AcceptFire();
    }

    impulses_fired++;
}

//updates the potentials
void Neuron::UpdatePotentials()
{

    if(refractory_countdown != 0)
    {
        refractory_countdown--;
    }
    else
    {
        //excitation_time++;
        if(amplitude_peak<0)amplitude_peak = 0;
        excitation_time++;
        //excitation_level = amplitude_peak*exp(-(++excitation_time)/exc_TC);

        //update the neuron potential
        if(amplitude_peak>fire_threshold) //if the excitation level is above the threshold value then fire the neuron
        {
            Fire();
        }
    }

    //update the Supply and demand
    S_level = S_peak*exp(-(++S_excitation_time)/S_TC);
    if(S_level<0.01) S_peak = 0; //don't let peaks float if neuron suddenly stops firing
}

Neuron* Neuron::FindNeuronByID(int id, std::vector<Neuron*>* neuronList) //returns a pointer to the neuron with ID==ID in a group
{
    if(neuronList!=NULL)
    {
		for(int n_c = 0; n_c<neuronList->size(); n_c++)
		{
			Neuron* n = neuronList->at(n_c);
			if(n->id == id) return n;
		}
    }
	return NULL;
}

double Neuron::calcSLevel_TW()
{
//    if(ParentMind!=NULL) S_level = S_peak*exp(-(double)((int)(ParentMind->CurTime-LastFireTimestamp))/S_TC);
//    else S_level = S_peak;
    return S_level;
}

Neuron::~Neuron(void)
{
    outgoingAxons.clear();
}


text:
package org.drools.gorm.session;

import java.io.ByteArrayInputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Collections;
import java.util.Date;
import java.util.IdentityHashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;

import org.drools.KnowledgeBase;
import org.drools.RuleBase;
import org.drools.SessionConfiguration;
import org.drools.command.Command;
import org.drools.command.Context;
import org.drools.command.impl.ContextImpl;
import org.drools.command.impl.GenericCommand;
import org.drools.command.impl.KnowledgeCommandContext;
import org.drools.command.runtime.DisposeCommand;
import org.drools.common.EndOperationListener;
import org.drools.common.InternalKnowledgeRuntime;
import org.drools.gorm.GrailsIntegration;
import org.drools.gorm.session.marshalling.GormSessionMarshallingHelper;
import org.drools.impl.KnowledgeBaseImpl;
import org.drools.persistence.jpa.JpaJDKTimerService;
import org.drools.process.instance.WorkItemManager;
import org.drools.runtime.Environment;
import org.drools.runtime.KnowledgeSessionConfiguration;
import org.drools.runtime.StatefulKnowledgeSession;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.jdbc.Work;
import org.hibernate.metadata.ClassMetadata;
import org.hibernate.persister.entity.SingleTableEntityPersister;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;

public class SingleSessionCommandService implements
        org.drools.command.SingleSessionCommandService {

    private final static Map<Class<?>, String> entitiesTablenames = new ConcurrentHashMap<Class<?>, String>();

    private SessionInfo sessionInfo;
    private GormSessionMarshallingHelper marshallingHelper;

    private StatefulKnowledgeSession ksession;
    private Environment env;
    private KnowledgeCommandContext kContext;
    private volatile boolean doRollback;

    public void checkEnvironment(Environment env) {
        configureEnvironment();
    }

    private void configureEnvironment() {
        env.set(HasBlob.GORM_UPDATE_SET, new CopyOnWriteArraySet<HasBlob<?>>());
    }

    public SingleSessionCommandService(RuleBase ruleBase,
                                       SessionConfiguration conf,
                                       Environment env) {
        this( new KnowledgeBaseImpl( ruleBase ),
              conf,
              env );
    }

    public SingleSessionCommandService(int sessionId,
                                       RuleBase ruleBase,
                                       SessionConfiguration conf,
                                       Environment env) {
        this( sessionId,
              new KnowledgeBaseImpl( ruleBase ),
              conf,
              env );
    }

    public SingleSessionCommandService(KnowledgeBase kbase,
                                       KnowledgeSessionConfiguration conf,
                                       Environment env) {
        if ( conf == null ) {
            conf = new SessionConfiguration();
        }
        this.env = env;

        checkEnvironment( this.env );

        this.sessionInfo = GrailsIntegration.getGormDomainService().getNewSessionInfo(env);

        // create session but bypass command service
        this.ksession = kbase.newStatefulKnowledgeSession(conf, this.env);

        this.kContext = new KnowledgeCommandContext( new ContextImpl( "ksession",
                                                                      null ),
                                                     null,
                                                     null,
                                                     this.ksession,
                                                     null );

        ((JpaJDKTimerService) ((InternalKnowledgeRuntime) ksession).getTimerService()).setCommandService( this );

        this.marshallingHelper = new GormSessionMarshallingHelper( this.ksession,
                                                                  conf );
        this.sessionInfo.setMarshallingHelper( this.marshallingHelper );
        ((InternalKnowledgeRuntime) this.ksession).setEndOperationListener( new EndOperationListenerImpl() );

        // Use the App scoped EntityManager if the user has provided it, and it is open.

        PlatformTransactionManager txManager = GrailsIntegration.getTransactionManager();
        DefaultTransactionDefinition txDef = new DefaultTransactionDefinition();
        txDef.setPropagationBehavior(DefaultTransactionDefinition.PROPAGATION_REQUIRED);
        TransactionStatus status = txManager.getTransaction(txDef);
        try {
            registerRollbackSync();

            GrailsIntegration.getGormDomainService().saveDomain(this.sessionInfo);
            updateBlobs(false);
            txManager.commit(status);
        } catch ( Exception t1 ) {
            try {
                txManager.rollback(status);
            } catch ( Throwable t2 ) {
                throw new RuntimeException( "Could not commit session or rollback",
                                            t2 );
            }
            throw new RuntimeException( "Could not commit session",
                                        t1 );
        }

        // update the session id to be the same as the session info id
        ((InternalKnowledgeRuntime) ksession).setId( this.sessionInfo.getId() );

    }

    public SingleSessionCommandService(int sessionId,
                                       KnowledgeBase kbase,
                                       KnowledgeSessionConfiguration conf,
                                       Environment env) {
        if ( conf == null ) {
            conf = new SessionConfiguration();
        }

        this.env = env;

        checkEnvironment( this.env );

        initKsession( sessionId,
                      kbase,
                      conf );
    }

    public void initKsession(int sessionId,
                             KnowledgeBase kbase,
                             KnowledgeSessionConfiguration conf) {
        if ( !doRollback && this.ksession != null ) {
            return;
            // nothing to initialise
        }

        this.doRollback = false;

        try {
            this.sessionInfo = GrailsIntegration.getGormDomainService().getSessionInfo(sessionId, env);
        } catch ( Exception e ) {
            throw new RuntimeException( "Could not find session data for id " + sessionId,
                                        e );
        }

        if ( sessionInfo == null ) {
            throw new RuntimeException( "Could not find session data for id " + sessionId );
        }

        if ( this.marshallingHelper == null ) {
            // this should only happen when this class is first constructed
            this.marshallingHelper = new GormSessionMarshallingHelper( kbase,
                                                                      conf,
                                                                      env );
        }

        this.sessionInfo.setMarshallingHelper( this.marshallingHelper );

        // if this.ksession is null, it'll create a new one, else it'll use the existing one
        this.ksession = this.marshallingHelper.loadSnapshot( this.sessionInfo.getData(),
                                                             this.ksession );

        // update the session id to be the same as the session info id
        ((InternalKnowledgeRuntime) ksession).setId( this.sessionInfo.getId() );

        ((InternalKnowledgeRuntime) this.ksession).setEndOperationListener( new EndOperationListenerImpl() );

        ((JpaJDKTimerService) ((InternalKnowledgeRuntime) ksession).getTimerService()).setCommandService( this );

        if ( this.kContext == null ) {
            // this should only happen when this class is first constructed
            this.kContext = new KnowledgeCommandContext( new ContextImpl( "ksession",
                        null ),
                    null,
                    null,
                    this.ksession,
                    null );
        }

    }

    public class EndOperationListenerImpl implements EndOperationListener {

        public void endOperation(InternalKnowledgeRuntime kruntime) {
            SingleSessionCommandService.this.sessionInfo.setLastModificationDate( new Date( kruntime.getLastIdleTimestamp() ) );
        }
    }

    public Context getContext() {
        return this.kContext;
    }

    public synchronized <T> T execute(Command<T> command) {
        PlatformTransactionManager txManager = GrailsIntegration.getTransactionManager();
        DefaultTransactionDefinition txDef = new DefaultTransactionDefinition();
        txDef.setPropagationBehavior(DefaultTransactionDefinition.PROPAGATION_REQUIRED);
        TransactionStatus status = txManager.getTransaction(txDef);

        try {
            initKsession( this.sessionInfo.getId(),
                          this.marshallingHelper.getKbase(),
                          this.marshallingHelper.getConf() );

            registerRollbackSync();
            configureEnvironment();

            T result = ((GenericCommand<T>) command).execute( this.kContext );

            updateBlobs(command instanceof DisposeCommand);
            txManager.commit(status);

            return result;
        } catch (RuntimeException e){
            status.setRollbackOnly();
            throw e;
        } catch ( Exception e ) {
            status.setRollbackOnly();
            throw new RuntimeException("Wrapped exception see cause", e);
        }
    }

    private void updateBlobs(final boolean isDispose) {
        final Set<HasBlob<?>> updates = (Set<HasBlob<?>>) env.get(HasBlob.GORM_UPDATE_SET);
        configureEnvironment();
        Session session = GrailsIntegration.getCurrentSession();

        session.doWork(new Work() {
            @Override
            public void execute(Connection conn) throws SQLException {
                boolean hasStoredKSession = false;
                for (final HasBlob<?> hasBlob : updates) {
                    if (!hasBlob.isDeleted()) {
                        persistBlob(isDispose, conn, hasBlob);
                    }
                    hasStoredKSession |= SingleSessionCommandService.this.sessionInfo == hasBlob;
                }
                if (!hasStoredKSession) {
                    persistBlob(isDispose, conn, SingleSessionCommandService.this.sessionInfo);
                }
            }

            private void persistBlob(boolean isDispose, Connection conn,
                    HasBlob<?> hasBlob) throws SQLException {
                byte[] blob = null;
                try {
                    blob = hasBlob.generateBlob();
                } catch (RuntimeException e) {
                    if (!isDispose) {
                        throw e;
                    }
                }
                if (blob != null && blob.length > 0) {
                    PreparedStatement ps = conn.prepareStatement("update "
                            + getTablename(hasBlob)
                            + " set data = ? where id = ?");
                    try {
                        int i = 1;
                        ps.setBinaryStream(i++, new ByteArrayInputStream(blob), blob.length);
                        ps.setLong(i++, hasBlob.getId().longValue());
                        int count = ps.executeUpdate();
                        if (count != 1) {
                            throw new IllegalStateException("update blob for id:  " + hasBlob
                                    + " has failed, count: " + count);
                        }
                    } finally {
                        ps.close();
                    }
                }
            }
        });
    }

    public void dispose() {
        if ( ksession != null ) {
            ksession.dispose();
        }
    }

    public int getSessionId() {
        return sessionInfo.getId();
    }

    @SuppressWarnings("unchecked")
    private Map<Object, Object> getSyncronizationMap() {
        Map<Object, Object> map = (Map<Object, Object>) env.get("synchronizations");
        if ( map == null ) {
            map = Collections.synchronizedMap( new IdentityHashMap<Object, Object>() );
            env.set("synchronizations", map);
        }
        return map;
    }

    private void registerRollbackSync() throws IllegalStateException {
        Map<Object, Object> map = getSyncronizationMap();

        if (!map.containsKey( this )) {
            TransactionSynchronizationManager.registerSynchronization(new SynchronizationImpl());
            map.put(this, this);
        }
    }

    private class SynchronizationImpl
        implements TransactionSynchronization {

        @Override
        public void suspend() {}

        @Override
        public void resume() {}

        @Override
        public void flush() {}

        @Override
        public void beforeCommit(boolean readOnly) {}

        @Override
        public void beforeCompletion() {}

        @Override
        public void afterCommit() {}

        @Override
        public void afterCompletion(int status) {
            try {
                if (status != TransactionSynchronization.STATUS_COMMITTED) {
                    SingleSessionCommandService.this.rollback();
                }
                // clean up cached process and work item instances
                StatefulKnowledgeSession ksession = SingleSessionCommandService.this.ksession;
                if (ksession != null) {
                    ((InternalKnowledgeRuntime) ksession).getProcessRuntime().clearProcessInstances();
                    ((WorkItemManager) ksession.getWorkItemManager()).clear();
                }
            } finally {
                SingleSessionCommandService.this.getSyncronizationMap().remove(SingleSessionCommandService.this);
            }
        }
    }

    private void rollback() {
        this.doRollback = true;
    }

    private String getTablename(HasBlob<?> hasBlob) {
        String tablename = entitiesTablenames.get(hasBlob.getClass());
        if (tablename == null) {
            SessionFactory sf = GrailsIntegration.getCurrentSessionFactory();
            ClassMetadata classMetadata = sf.getClassMetadata(hasBlob.getClass());
            if (classMetadata instanceof SingleTableEntityPersister) {
                SingleTableEntityPersister step = (SingleTableEntityPersister) classMetadata;
                tablename = step.getTableName();
                entitiesTablenames.put(hasBlob.getClass(), tablename);
            }
        }
        return tablename;

    }
}


text:
package com.khipu.lib.java.response;

/**
 * Objeto que representa la respuesta a que el cobrador declare un pago como
 * pagado
 *
 * @author Alejandro Vera (alejandro.vera@khipu.com)
 * @version 1.2
 * @since 2013-05-24
 */
public class KhipuSetPayedByReceiverResponse implements KhipuResponse {
    // no hay métodos públicos
}


text:
using System;
using Elastic.Clients.Elasticsearch.Aggregations;
using Tests.Core.Extensions;
using Tests.Core.ManagedElasticsearch.Clusters;
using Tests.Domain;
using Tests.Framework.EndpointTests.TestState;
using static Elastic.Clients.Elasticsearch.Infer;

namespace Tests.Aggregations.Metric;

public class CardinalityAggregationUsageTests : AggregationUsageTestBase<ReadOnlyCluster>
{
	public CardinalityAggregationUsageTests(ReadOnlyCluster i, EndpointUsage usage) : base(i, usage) { }

	protected override object AggregationJson => new
	{
		state_count = new
		{
			cardinality = new
			{
				field = "state",
				precision_threshold = 100
			}
		}
	};

	protected override Action<AggregationDescriptor<Project>> FluentAggs => a => a
		.Cardinality("state_count", c => c
			.Field(p => p.State)
			.PrecisionThreshold(100)
		);

	protected override AggregationDictionary InitializerAggs =>
		new CardinalityAggregation("state_count", Field<Project>(p => p.State))
		{
			PrecisionThreshold = 100
		};

	protected override void ExpectResponse(SearchResponse<Project> response)
	{
		response.ShouldBeValid();
		var projectCount = response.Aggregations.GetCardinality("state_count");
		projectCount.Should().NotBeNull();
		projectCount.Value.Should().BeGreaterOrEqualTo(1);
	}
}


text:
package org.opencb.opencga.app.cli.internal.executors;

import org.opencb.commons.datastore.core.ObjectMap;
import org.opencb.opencga.analysis.individual.IndividualIndexTask;
import org.opencb.opencga.analysis.individual.IndividualTsvAnnotationLoader;
import org.opencb.opencga.app.cli.internal.options.IndividualCommandOptions;
import org.opencb.opencga.core.exceptions.ToolException;

import java.nio.file.Path;
import java.nio.file.Paths;

public class IndividualCommandExecutor extends InternalCommandExecutor {

    private final IndividualCommandOptions individualCommandOptions;

    public IndividualCommandExecutor(IndividualCommandOptions options) {
        super(options.individualCommandOptions);
        individualCommandOptions = options;
    }

    @Override
    public void execute() throws Exception {
        logger.debug("Executing individual command line");

        String subCommandString = getParsedSubCommand(individualCommandOptions.jCommander);
        configure();
        switch (subCommandString) {
            case "secondary-index":
                secondaryIndex();
                break;
            case "tsv-load":
                tsvLoad();
                break;
            default:
                logger.error("Subcommand not valid");
                break;

        }
    }

    private void secondaryIndex() throws ToolException {
        IndividualCommandOptions.SecondaryIndex options = individualCommandOptions.secondaryIndex;
        Path outDir = Paths.get(options.outDir);
        toolRunner.execute(IndividualIndexTask.class, new ObjectMap(), outDir, options.jobOptions.jobId, options.commonOptions.token);
    }

    private void tsvLoad() throws ToolException {
        IndividualCommandOptions.TsvLoad options = individualCommandOptions.tsvLoad;

        Path outDir = Paths.get(options.outDir);
        Path opencgaHome = Paths.get(configuration.getWorkspace()).getParent();

        IndividualTsvAnnotationLoader annotationLoader = new IndividualTsvAnnotationLoader();
        annotationLoader.setAnnotationSetId(options.annotationSetId);
        annotationLoader.setVariableSetId(options.variableSetId);
        annotationLoader.setPath(options.filePath);
        annotationLoader.setStudy(options.studyId);

        annotationLoader.setUp(opencgaHome.toString(), new ObjectMap(), outDir, options.commonOptions.token);
        annotationLoader.start();
    }

}


text:
package shms.dao.sensorManage;

import java.util.List;
import java.util.Map;

import org.springframework.orm.ibatis.SqlMapClientTemplate;

public class sensorListDao {

	private SqlMapClientTemplate sqlMapClientTemplate;

	public void setSqlMapClientTemplate(SqlMapClientTemplate sqlMapClientTemplate) {
		this.sqlMapClientTemplate = sqlMapClientTemplate;
	}

	// ¼¾¼ ¸®½ºÆ®
	public List senSensorList_Sensor(Map map) {
		return sqlMapClientTemplate.queryForList("senSensorList_SensorSql", map);
	}

	// ¼¾¼ ¸®½ºÆ® °Ç¼ö
	public int countSenSensorList_Sensor(Map map) {
		return (Integer) sqlMapClientTemplate.queryForObject("countSenSensorList_SensorSql", map);
	}

	// ¼¾¼ »ó¼¼º¸±â
	public Object senSensorList_Detail(Map map) {
		return sqlMapClientTemplate.queryForObject("senSensorList_DetailSql", map);
	}

	// ¼¾¼(¼ºê¸ÞÀÎ)¸®½ºÆ®
	public List senSensorList_SubMain(Map map) {
		return sqlMapClientTemplate.queryForList("senSensorTrouble_SubMainSql", map);
	}

	// ¼¾¼(¼ºê¸ÞÀÎ)  ¸®½ºÆ® °Ç¼ö
	public int countsenSensorList_SubMain(Map map) {
		return (Integer) sqlMapClientTemplate.queryForObject("countSenSensorTrouble_SubMainSql", map);
	}

	// Á¶Ä¡»çÀ¯ ¸®½ºÆ®
	public List troubleCancel_SubMain(Map map) {
		return sqlMapClientTemplate.queryForList("troubleCancel_SubMainSql", map);
	}

	// Á¶Ä¡»çÀ¯  ¸®½ºÆ® °Ç¼ö
	public int counttroubleCancel_Sensor(Map map) {
		return (Integer) sqlMapClientTemplate.queryForObject("countTroubleCancel_SensorSql", map);
	}

	//  DTREE
	public List getSensorTree(Map map){
		return sqlMapClientTemplate.queryForList("listSensorTree",map);
	}

	// ´ë½Ãº¸µå À§Çè/°æ°í/Á¶Ä¡/¹ÌÁ¶Ä¡ º¸¿©ÁÖ±â
	public Object dashboardList_Detail(Map map) {
		return sqlMapClientTemplate.queryForObject("countDASHBORDTroubleSql", map);
	}
}


text:
package org.apache.skywalking.oap.server.storage.plugin.jdbc.h2.dao;

import org.apache.skywalking.oap.server.core.analysis.config.NoneStream;
import org.apache.skywalking.oap.server.core.storage.INoneStreamDAO;
import org.apache.skywalking.oap.server.core.storage.StorageBuilder;
import org.apache.skywalking.oap.server.core.storage.model.Model;
import org.apache.skywalking.oap.server.library.client.jdbc.hikaricp.JDBCHikariCPClient;
import org.apache.skywalking.oap.server.storage.plugin.jdbc.SQLExecutor;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * Synchronize storage H2 implements
 */
public class H2NoneStreamDAO extends H2SQLExecutor implements INoneStreamDAO {

    private JDBCHikariCPClient h2Client;
    private StorageBuilder<NoneStream> storageBuilder;

    public H2NoneStreamDAO(JDBCHikariCPClient h2Client, StorageBuilder<NoneStream> storageBuilder) {
        this.h2Client = h2Client;
        this.storageBuilder = storageBuilder;
    }

    @Override
    public void insert(Model model, NoneStream noneStream) throws IOException {
        try (Connection connection = h2Client.getConnection()) {
            SQLExecutor insertExecutor = getInsertExecutor(model.getName(), noneStream, storageBuilder);
            insertExecutor.invoke(connection);
        } catch (IOException | SQLException e) {
            throw new IOException(e.getMessage(), e);
        }
    }
}


text:
require 'twopence'

# Initialize SSH targets from environment variables
raise 'Server IP address or domain name variable empty' if ENV['TESTHOST'].nil?
raise 'Client IP address or domain name variable empty' if ENV['CLIENT'].nil?
raise 'Minion IP address or domain name variable empty' if ENV['MINION'].nil?
raise 'CentOS minion IP address or domain name variable empty' if ENV['CENTOSMINION'].nil?
raise 'SSH minion IP address or domain name variable empty' if ENV['SSHMINION'].nil?

$server_ip = ENV['TESTHOST']
$client_ip = ENV['CLIENT']
$minion_ip = ENV['MINION']
$ceos_minion_ip = ENV['CENTOSMINION']
$ssh_minion_ip = ENV['SSHMINION']

# Define twopence objects
$client = Twopence.init("ssh:#{$client_ip}")
$server = Twopence.init("ssh:#{$server_ip}")
$minion = Twopence.init("ssh:#{$minion_ip}")
$ceos_minion = Twopence.init("ssh:#{$ceos_minion_ip}")
$ssh_minion = Twopence.init("ssh:#{$ssh_minion_ip}")

# Lavanda library module extension
# Look at support/lavanda.rb for more details
$server.extend(LavandaBasic)
$client.extend(LavandaBasic)
$minion.extend(LavandaBasic)
$ceos_minion.extend(LavandaBasic)
$ssh_minion.extend(LavandaBasic)

# Initialize hostname
nodes = [$server, $client, $minion, $ceos_minion, $ssh_minion]
nodes.each do |node|
  hostname, _local, _remote, code = node.test_and_store_results_together('hostname', 'root', 500)
  raise 'Cannot get hostname for node' if code.nonzero?
  node.init_hostname(hostname)
  fqdn, _local, _remote, code = node.test_and_store_results_together('hostname -f', 'root', 500)
  raise 'No fully qualified domain name for node' if code.nonzero?
  node.init_full_hostname(fqdn)
end

# This function is used to get one of the nodes based on its type
def get_target(host)
  case host
  when 'server'
    node = $server
  when 'ceos-minion'
    node = $ceos_minion
  when 'ssh-minion'
    node = $ssh_minion
  when 'sle-minion'
    node = $minion
  when 'sle-client'
    node = $client
  when 'sle-migrated-minion'
    node = $client
  else
    raise 'Invalid target.'
  end
  node
end

# This function tests whether a file exists on a node
def file_exists?(node, file)
  _out, _local, _remote, code = node.test_and_store_results_together("test -f #{file}", 'root', 500)
  code.zero?
end

# This function deletes a file from a node
def file_delete(node, file)
  _out, _local, _remote, code = node.test_and_store_results_together("rm  #{file}", 'root', 500)
  code
end


text:
package app;

import java.util.HashMap;
import java.util.Map;
import javax.swing.JOptionPane;
import modelo.Pessoa;

public class AppFormularioPessoas {

    public static void main(String[] args) {

        Map<String, Pessoa> formPessoas = new HashMap<>();

        formPessoas.put("Chefe", new Pessoa("Hommer", 40));
        formPessoas.put("Gerente", new Pessoa("Maria", 42));
        formPessoas.put("Estagiario", new Pessoa("Bob", 22));

        JOptionPane.showMessageDialog(null, formPessoas);
    }
}


text: ALTER TABLE ProgramStage ADD COLUMN dueDateLabel TEXT;


text:
package org.beanmaker;

/**
 * This class gives information about the VERSION of this library.
 */
public class Version {
    private static final String  PREFIX  = "";
    private static final int     MAJOR   = 0;
    private static final int     MINOR   = 9;
    private static final int     PATCH   = 15;
    private static final String  POSTFIX = "-beta";

    private static final String VERSION = PREFIX + MAJOR + "." + MINOR + "." + PATCH + POSTFIX;

    /**
     * @return the version number of this library
     */
    public static String get() {
        return VERSION;
    }

    /**
     * To be used in build scripts.
     */
    public static void main (String[] args) {
        System.out.println(get());
    }
}


text:
#ifndef NACL_SPAWN_NACL_MAIN_H_
#define NACL_SPAWN_NACL_MAIN_H_

#include <spawn.h>

#ifdef __cplusplus
extern "C" {
#endif

/*
 * Entry point expected by libcli_main.a
 */
extern int nacl_main(int argc, char* argv[]);

/*
 * Untar a startup bundle to a particular root.
 *
 * NOTE: This lives in libcli_main.a
 * Args:
 *   arg0: The contents of argv[0], used to determine relative tar location.
 *   tarfile: The name of a tarfile to extract.
 *   root: The absolute path to extract the startup tar file to.
 */
extern int nacl_startup_untar(
    const char* argv0, const char* tarfile, const char* root);

#ifdef __cplusplus
}
#endif

#endif /* NACL_SPAWN_NACL_MAIN_H_ */


text:
package com.github.pixelstuermer.littleNotes.configurations;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.github.pixelstuermer.littleNotes.models.Collection;

@Configuration
public class CollectionConfig {

   @Bean
   public Collection setNotesCollection( @Value( "${collection.name}" ) String collectionName ) {
      return Collection.builder().collectionName( collectionName ).build();
   }

}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

    <TITLE>Class Template symmetric_filter</TITLE>
    <LINK REL="stylesheet" HREF="../../../../boost.css">
    <LINK REL="stylesheet" HREF="../theme/iostreams.css">

Class Template symmetric_filter

Description

Headers

Reference

Examples

Description

    The class template symmetric_filter is tool for generating models of DualUseFilter from models of SymmetricFilter. It is useful for defining filters based on C language APIs.

    The Iostreams library uses symmetric_filter to implement the Zlib and Bzip2 Filters.

Headers

<boost/iostreams/filter/symmetric.hpp>

Reference

Synopsis

namespace boost { namespace iostreams {

template< typename SymmetricFilter,
          typename Alloc = std::allocator<...> >
class symmetric_filter {
public:
    typedef typename char_type_of<SymmetricFilter>::type  char_type;
    typedef implementation-defined                        category;

    explicit symmetric_filter(int buffer_size);

    template<typename T0>
    symmetric_filter(int buffer_size, const T0& t0);

    template<typename T0, typename T1>
    symmetric_filter(int buffer_size, const T0& t0, const T1& t1);

    template<typename T0, ..., typename TN>
    symmetric_filter( int buffer_size, const T0& t0,
                      const T1& t1, ..., const TN& tN );

    ...
protected:
    SymmetricFilter& filter();
    std::basic_string<char_type, Alloc> unconsumed_input() const;
};

} } // End namespace boost::io

Template parameters

        SymmetricFilter	-
        A model of SymmetricFilter

        Alloc	-
        A standard library allocator type ([ISO], 20.1.5), used to allocate a character buffer

symmetric_filter::symmetric_filter

    explicit symmetric_filter(int buffer_size);

Constructs an instance of symmetric_filter based on a default-constructed instance of the template parameter SymmetricFilter and having an internal buffer of size buffer_size.

symmetric_filter::symmetric_filter

    template<typename T0>
    symmetric_filter(int buffer_size, const T0& t0);

    template<typename T0, typename T1>
    symmetric_filter(int buffer_size, const T0& t0, const T1& t1);

    template<typename T0, ..., typename TN>
    symmetric_filter( int buffer_size, const T0& t0,
                              const T1& t1, ..., const TN& tN );

Each member constructs an instance of symmetric_filter based on an instance of the template parameter SymmetricFilter constructed with the given sequence of arguments and having an internal buffer of size buffer_size.

symmetric_filter::filter

    SymmetricFilter& filter();

Returns a reference to the underlying instance of SymmetricFilter.

symmetric_filter::unconsumed_input

    std::basic_string<char_type, Alloc> unconsumed_input() const;

Returns any uncomsumed data remaining in the internal buffer as a standard string. Valid from the time the end of a stream is reached — that is, from the time SymmetricFilter::filter returns false — until filter is invoked to begin processing a new sequence of data.

Examples

For example uses of symmetric_filter, see the headers <boost/iostreams/filter/zlib.hpp> and <boost/iostreams/filter/bzip2.hpp> and the corresponding implementation files <libs/iostreams/src/zlib.cpp> and <libs/iostreams/src/bzip2.cpp>.

© Copyright 2008 CodeRage, LLC
© Copyright 2004-2007 Jonathan Turkanis

    Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)


text:
#pragma once
#include <aws/devicefarm/DeviceFarm_EXPORTS.h>
#include <aws/devicefarm/model/NetworkProfile.h>
#include <utility>

namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;

namespace Utils
{
namespace Json
{
  class JsonValue;
} // namespace Json
} // namespace Utils
namespace DeviceFarm
{
namespace Model
{
  class AWS_DEVICEFARM_API GetNetworkProfileResult
  {
  public:
    GetNetworkProfileResult();
    GetNetworkProfileResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
    GetNetworkProfileResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);

    /**
     *
The network profile.

     */
    inline const NetworkProfile& GetNetworkProfile() const{ return m_networkProfile; }

    /**
     *
The network profile.

     */
    inline void SetNetworkProfile(const NetworkProfile& value) { m_networkProfile = value; }

    /**
     *
The network profile.

     */
    inline void SetNetworkProfile(NetworkProfile&& value) { m_networkProfile = std::move(value); }

    /**
     *
The network profile.

     */
    inline GetNetworkProfileResult& WithNetworkProfile(const NetworkProfile& value) { SetNetworkProfile(value); return *this;}

    /**
     *
The network profile.

     */
    inline GetNetworkProfileResult& WithNetworkProfile(NetworkProfile&& value) { SetNetworkProfile(std::move(value)); return *this;}

  private:

    NetworkProfile m_networkProfile;
  };

} // namespace Model
} // namespace DeviceFarm
} // namespace Aws


text:
<?xml version="1.0" encoding="utf-8"?>

<resources>

    <!-- DynamicGrid -->
    <dimen name="dgv_overlap_if_switch_straight_line">16dp</dimen>

    <dimen name="layout_width_225dp">210dp</dimen>
    <dimen name="layout_width_156dp">156dp</dimen>
    <dimen name="layout_width_144dp">144dp</dimen>

    <dimen name="layout_height_320dp">320dp</dimen>
    <dimen name="layout_height_141dp">141dp</dimen>
    <dimen name="layout_height_117dp">117dp</dimen>
    <dimen name="layout_height_108dp">108dp</dimen>
    <dimen name="layout_height_48dp">48dp</dimen>
    <dimen name="layout_height_36dp">36dp</dimen>
    <dimen name="layout_height_32dp">32dp</dimen>
    <dimen name="layout_height_25dp">25dp</dimen>
    <dimen name="layout_height_12dp">12dp</dimen>
    <dimen name="layout_height_6dp">6dp</dimen>
    <dimen name="layout_height_2dp">2dp</dimen>
    <dimen name="layout_height_1dp">1dp</dimen>

    <dimen name="layout_margin_48dp">48dp</dimen>
    <dimen name="layout_margin_20dp">20dp</dimen>
    <dimen name="layout_margin_16dp">16dp</dimen>
    <dimen name="layout_margin_14dp">14dp</dimen>
    <dimen name="layout_margin_12dp">12dp</dimen>
    <dimen name="layout_margin_8dp">8dp</dimen>
    <dimen name="layout_margin_4dp">4dp</dimen>
    <dimen name="layout_margin_2dp">2dp</dimen>

    <dimen name="padding_16dp">16dp</dimen>
    <dimen name="padding_8dp">8dp</dimen>
    <dimen name="padding_4dp">4dp</dimen>

    <dimen name="text_size_18sp">18sp</dimen>
    <dimen name="text_size_16sp">16sp</dimen>
    <dimen name="text_size_14sp">14sp</dimen>
    <dimen name="text_size_12sp">12sp</dimen>

    <dimen name="divider_height_1dp">1dp</dimen>
    <dimen name="divider_height_0dp">0dp</dimen>
    <dimen name="elevation_2dp">2dp</dimen>
    <dimen name="elevation_1dp">1dp</dimen>
    <dimen name="elevation_0dp">0dp</dimen>
    <dimen name="radius_2dp">2dp</dimen>
    <dimen name="radius_1dp">1dp</dimen>

</resources>


text:
package io.debezium.connector.mongodb;

import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

import org.apache.kafka.connect.data.Struct;
import org.apache.kafka.connect.errors.ConnectException;
import org.bson.BsonDocument;
import org.bson.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;

import io.debezium.DebeziumException;
import io.debezium.annotation.NotThreadSafe;
import io.debezium.connector.mongodb.ConnectionContext.MongoPrimary;
import io.debezium.pipeline.EventDispatcher;
import io.debezium.pipeline.source.AbstractSnapshotChangeEventSource;
import io.debezium.pipeline.source.snapshot.incremental.CloseIncrementalSnapshotWindow;
import io.debezium.pipeline.source.snapshot.incremental.DataCollection;
import io.debezium.pipeline.source.snapshot.incremental.IncrementalSnapshotChangeEventSource;
import io.debezium.pipeline.source.snapshot.incremental.IncrementalSnapshotContext;
import io.debezium.pipeline.source.snapshot.incremental.OpenIncrementalSnapshotWindow;
import io.debezium.pipeline.source.spi.DataChangeEventListener;
import io.debezium.pipeline.source.spi.SnapshotProgressListener;
import io.debezium.pipeline.spi.ChangeRecordEmitter;
import io.debezium.pipeline.spi.OffsetContext;
import io.debezium.spi.schema.DataCollectionId;
import io.debezium.util.Clock;
import io.debezium.util.Strings;
import io.debezium.util.Threads;
import io.debezium.util.Threads.Timer;

/**
 * An incremental snapshot change event source that emits events from a MongoDB change stream interleaved with snapshot events.
 */
@NotThreadSafe
public class MongoDbIncrementalSnapshotChangeEventSource
        implements IncrementalSnapshotChangeEventSource<MongoDbPartition, CollectionId> {

    private static final String DOCUMENT_ID = "_id";
    private static final Logger LOGGER = LoggerFactory.getLogger(MongoDbIncrementalSnapshotChangeEventSource.class);
    private static final String AUTHORIZATION_FAILURE_MESSAGE = "Command failed with error 13";

    private final MongoDbConnectorConfig connectorConfig;
    private final Clock clock;
    private final MongoDbSchema collectionSchema;
    private final SnapshotProgressListener<MongoDbPartition> progressListener;
    private final DataChangeEventListener<MongoDbPartition> dataListener;
    private long totalRowsScanned = 0;
    private final ReplicaSets replicaSets;
    private final ConnectionContext connectionContext;
    private final MongoDbTaskContext taskContext;

    private MongoDbCollectionSchema currentCollection;

    protected EventDispatcher<MongoDbPartition, CollectionId> dispatcher;
    protected IncrementalSnapshotContext<CollectionId> context = null;
    protected final Map<Struct, Object[]> window = new LinkedHashMap<>();
    private MongoPrimary primary;
    private CollectionId signallingCollectionId;

    public MongoDbIncrementalSnapshotChangeEventSource(MongoDbConnectorConfig config,
                                                       MongoDbTaskContext taskContext,
                                                       ReplicaSets replicaSets,
                                                       EventDispatcher<MongoDbPartition, CollectionId> dispatcher,
                                                       MongoDbSchema collectionSchema,
                                                       Clock clock,
                                                       SnapshotProgressListener<MongoDbPartition> progressListener,
                                                       DataChangeEventListener<MongoDbPartition> dataChangeEventListener) {
        this.connectorConfig = config;
        this.replicaSets = replicaSets;
        this.taskContext = taskContext;
        this.connectionContext = taskContext.getConnectionContext();
        this.dispatcher = dispatcher;
        this.collectionSchema = collectionSchema;
        this.clock = clock;
        this.progressListener = progressListener;
        this.dataListener = dataChangeEventListener;
        this.signallingCollectionId = connectorConfig.getSignalingDataCollectionId() == null ? null
                : CollectionId.parse("UNUSED", connectorConfig.getSignalingDataCollectionId());
    }

    @Override
    @SuppressWarnings("unchecked")
    public void closeWindow(MongoDbPartition partition, String id, OffsetContext offsetContext) throws InterruptedException {
        context = (IncrementalSnapshotContext<CollectionId>) offsetContext.getIncrementalSnapshotContext();
        if (!context.closeWindow(id)) {
            return;
        }
        sendWindowEvents(partition, offsetContext);
        readChunk(partition);
    }

    @Override
    public void pauseSnapshot(MongoDbPartition partition, OffsetContext offsetContext) throws InterruptedException {
        context = (IncrementalSnapshotContext<CollectionId>) offsetContext.getIncrementalSnapshotContext();
        if (context.snapshotRunning() && !context.isSnapshotPaused()) {
            context.pauseSnapshot();
            progressListener.snapshotPaused(partition);
        }
    }

    @Override
    public void resumeSnapshot(MongoDbPartition partition, OffsetContext offsetContext) throws InterruptedException {
        context = (IncrementalSnapshotContext<CollectionId>) offsetContext.getIncrementalSnapshotContext();
        if (context.snapshotRunning() && context.isSnapshotPaused()) {
            context.resumeSnapshot();
            progressListener.snapshotResumed(partition);
            window.clear();
            context.revertChunk();
            readChunk(partition);
        }
    }

    protected String getSignalCollectionName(String dataCollectionId) {
        return dataCollectionId;
    }

    protected void sendWindowEvents(MongoDbPartition partition, OffsetContext offsetContext) throws InterruptedException {
        LOGGER.debug("Sending {} events from window buffer", window.size());
        offsetContext.incrementalSnapshotEvents();
        for (Object[] row : window.values()) {
            sendEvent(partition, dispatcher, offsetContext, row);
        }
        offsetContext.postSnapshotCompletion();
        window.clear();
    }

    // TODO Used typed dispatcher and offset context
    protected void sendEvent(MongoDbPartition partition, EventDispatcher<MongoDbPartition, CollectionId> dispatcher, OffsetContext offsetContext, Object[] row)
            throws InterruptedException {
        context.sendEvent(keyFromRow(row));
        ((ReplicaSetOffsetContext) offsetContext).readEvent(context.currentDataCollectionId().getId(), clock.currentTimeAsInstant());
        dispatcher.dispatchSnapshotEvent(partition, context.currentDataCollectionId().getId(),
                getChangeRecordEmitter(partition, offsetContext, row),
                dispatcher.getIncrementalSnapshotChangeEventReceiver(dataListener));
    }

    /**
     * Returns a {@link ChangeRecordEmitter} producing the change records for
     * the given table row.
     */
    protected ChangeRecordEmitter<MongoDbPartition> getChangeRecordEmitter(MongoDbPartition partition,
                                                                           OffsetContext offsetContext, Object[] row) {
        return new MongoDbChangeSnapshotOplogRecordEmitter(partition, offsetContext, clock, (BsonDocument) row[0], true);
    }

    protected void deduplicateWindow(DataCollectionId dataCollectionId, Object key) {
        if (context.currentDataCollectionId() == null || !context.currentDataCollectionId().getId().equals(dataCollectionId)) {
            return;
        }
        if (key instanceof Struct) {
            if (window.remove((Struct) key) != null) {
                LOGGER.info("Removed '{}' from window", key);
            }
        }
    }

    /**
     * Update low watermark for the incremental snapshot chunk
     */
    protected void emitWindowOpen() throws InterruptedException {
        final CollectionId collectionId = signallingCollectionId;
        final String id = context.currentChunkId() + "-open";
        primary.executeBlocking(
                "emit window open for chunk '" + context.currentChunkId() + "'",
                primary -> {
                    final MongoDatabase database = primary.getDatabase(collectionId.dbName());
                    final MongoCollection<Document> collection = database.getCollection(collectionId.name());

                    LOGGER.trace("Emitting open window for chunk = '{}'", context.currentChunkId());
                    final Document signal = new Document();
                    signal.put(DOCUMENT_ID, id);
                    signal.put("type", OpenIncrementalSnapshotWindow.NAME);
                    signal.put("payload", "");
                    collection.insertOne(signal);
                });
    }

    /**
     * Update high watermark for the incremental snapshot chunk
     */
    protected void emitWindowClose() throws InterruptedException {
        final CollectionId collectionId = signallingCollectionId;
        final String id = context.currentChunkId() + "-close";
        primary.executeBlocking(
                "emit window close for chunk '" + context.currentChunkId() + "'",
                primary -> {
                    final MongoDatabase database = primary.getDatabase(collectionId.dbName());
                    final MongoCollection<Document> collection = database.getCollection(collectionId.name());

                    LOGGER.trace("Emitting close window for chunk = '{}'", context.currentChunkId());
                    final Document signal = new Document();
                    signal.put(DOCUMENT_ID, id);
                    signal.put("type", CloseIncrementalSnapshotWindow.NAME);
                    signal.put("payload", "");
                    collection.insertOne(signal);
                });
    }

    @Override
    @SuppressWarnings("unchecked")
    public void init(MongoDbPartition partition, OffsetContext offsetContext) {
        primary = establishConnectionToPrimary(partition, replicaSets.all().get(0));
        if (offsetContext == null) {
            LOGGER.info("Empty incremental snapshot change event source started, no action needed");
            postIncrementalSnapshotCompleted();
            return;
        }
        context = (IncrementalSnapshotContext<CollectionId>) offsetContext.getIncrementalSnapshotContext();
        if (!context.snapshotRunning()) {
            LOGGER.info("No incremental snapshot in progress, no action needed on start");
            postIncrementalSnapshotCompleted();
            return;
        }
        LOGGER.info("Incremental snapshot in progress, need to read new chunk on start");
        try {
            progressListener.snapshotStarted(partition);
            readChunk(partition);
        }
        catch (InterruptedException e) {
            throw new DebeziumException("Reading of an initial chunk after connector restart has been interrupted");
        }
        LOGGER.info("Incremental snapshot in progress, loading of initial chunk completed");
    }

    protected void readChunk(MongoDbPartition partition) throws InterruptedException {
        if (!context.snapshotRunning()) {
            LOGGER.info("Skipping read chunk because snapshot is not running");
            postIncrementalSnapshotCompleted();
            return;
        }
        if (context.isSnapshotPaused()) {
            LOGGER.info("Incremental snapshot was paused.");
            return;
        }
        try {
            preReadChunk(context);
            context.startNewChunk();
            emitWindowOpen();
            while (context.snapshotRunning()) {
                final CollectionId currentDataCollectionId = context.currentDataCollectionId().getId();
                currentCollection = (MongoDbCollectionSchema) collectionSchema.schemaFor(currentDataCollectionId);
                if (replicaSets.all().size() > 1) {
                    LOGGER.warn("Incremental snapshotting supported only for single result set topology, skipping collection '{}', known collections {}",
                            currentDataCollectionId);
                    nextDataCollection(partition);
                    continue;
                }
                // TODO Collection schema is calculated dynamically, it is necessary to use a different check
                if (currentCollection == null) {
                    LOGGER.warn("Schema not found for collection '{}', known collections {}", currentDataCollectionId, collectionSchema);
                    nextDataCollection(partition);
                    continue;
                }
                // MongoDB collection has always key so it is not necessary to check if it is available
                if (!context.maximumKey().isPresent()) {
                    context.maximumKey(readMaximumKey());
                    if (!context.maximumKey().isPresent()) {
                        LOGGER.info(
                                "No maximum key returned by the query, incremental snapshotting of collection '{}' finished as it is empty",
                                currentDataCollectionId);
                        nextDataCollection(partition);
                        continue;
                    }
                    if (LOGGER.isInfoEnabled()) {
                        LOGGER.info("Incremental snapshot for collection '{}' will end at position {}", currentDataCollectionId,
                                context.maximumKey().orElse(new Object[0]));
                    }
                }
                createDataEventsForDataCollection(partition);
                if (window.isEmpty()) {
                    LOGGER.info("No data returned by the query, incremental snapshotting of table '{}' finished",
                            currentDataCollectionId);
                    collectionScanCompleted(partition);
                    nextDataCollection(partition);
                }
                else {
                    break;
                }
            }
            emitWindowClose();
        }
        // catch (InterruptedException e) {
        // throw new DebeziumException(String.format("Database error while executing incremental snapshot for table '%s'", context.currentDataCollectionId()), e);
        // }
        finally {
            postReadChunk(context);
            if (!context.snapshotRunning()) {
                postIncrementalSnapshotCompleted();
            }
        }
    }

    private void nextDataCollection(MongoDbPartition partition) {
        context.nextDataCollection();
        if (!context.snapshotRunning()) {
            progressListener.snapshotCompleted(partition);
        }
    }

    private Object[] readMaximumKey() throws InterruptedException {
        final CollectionId collectionId = (CollectionId) currentCollection.id();
        final AtomicReference<Object> key = new AtomicReference<>();
        primary.executeBlocking("maximum key for '" + collectionId + "'", primary -> {
            final MongoDatabase database = primary.getDatabase(collectionId.dbName());
            final MongoCollection<Document> collection = database.getCollection(collectionId.name());

            final Document lastDocument = collection.find().sort(new Document(DOCUMENT_ID, -1)).limit(1).first();
            if (lastDocument != null) {
                key.set(lastDocument.get(DOCUMENT_ID));
            }
        });
        return key.get() != null ? new Object[]{ key.get() } : null;
    }

    @Override
    @SuppressWarnings("unchecked")
    public void addDataCollectionNamesToSnapshot(MongoDbPartition partition, List<String> dataCollectionIds,
                                                 Optional<String> additionalCondition, OffsetContext offsetContext)
            throws InterruptedException {
        if (additionalCondition != null && additionalCondition.isPresent()) {
            throw new UnsupportedOperationException("Additional condition not supported for MongoDB");
        }
        context = (IncrementalSnapshotContext<CollectionId>) offsetContext.getIncrementalSnapshotContext();
        final boolean shouldReadChunk = !context.snapshotRunning();
        final String rsName = replicaSets.all().get(0).replicaSetName();
        dataCollectionIds = dataCollectionIds
                .stream()
                .map(x -> rsName + "." + x)
                .collect(Collectors.toList());
        final List<DataCollection<CollectionId>> newDataCollectionIds = context.addDataCollectionNamesToSnapshot(dataCollectionIds, null);
        if (shouldReadChunk) {
            progressListener.snapshotStarted(partition);
            progressListener.monitoredDataCollectionsDetermined(partition, newDataCollectionIds.stream()
                    .map(x -> x.getId()).collect(Collectors.toList()));
            readChunk(partition);
        }
    }

    @Override
    @SuppressWarnings("unchecked")
    public void stopSnapshot(MongoDbPartition partition, List<String> dataCollectionIds, OffsetContext offsetContext) {
        context = (IncrementalSnapshotContext<CollectionId>) offsetContext.getIncrementalSnapshotContext();
        if (context.snapshotRunning()) {
            if (dataCollectionIds == null || dataCollectionIds.isEmpty()) {
                LOGGER.info("Stopping incremental snapshot.");
                try {
                    // This must be called prior to closeWindow to ensure that the correct state is set
                    // to prevent chunk rads from triggering additional open/close events.
                    context.stopSnapshot();

                    // Clear the state
                    window.clear();
                    closeWindow(partition, context.currentChunkId(), offsetContext);

                    progressListener.snapshotAborted(partition);
                }
                catch (InterruptedException e) {
                    LOGGER.warn("Failed to stop snapshot successfully.", e);
                }
            }
            else {
                LOGGER.info("Removing '{}' collections from incremental snapshot", dataCollectionIds);
                final String rsName = replicaSets.all().get(0).replicaSetName();
                dataCollectionIds = dataCollectionIds.stream().map(x -> rsName + "." + x).collect(Collectors.toList());
                for (String dataCollectionId : dataCollectionIds) {
                    final CollectionId collectionId = CollectionId.parse(dataCollectionId);
                    if (currentCollection != null && currentCollection.id().equals(collectionId)) {
                        window.clear();
                        LOGGER.info("Removed '{}' from incremental snapshot collection list.", collectionId);

                        collectionScanCompleted(partition);
                        nextDataCollection(partition);
                    }
                    else {
                        if (context.removeDataCollectionFromSnapshot(dataCollectionId)) {
                            LOGGER.info("Removed '{}' from incremental snapshot collection list.", collectionId);
                        }
                        else {
                            LOGGER.warn("Could not remove '{}', collection is not part of the incremental snapshot.", collectionId);
                        }
                    }
                }
            }
        }
        else {
            LOGGER.warn("No active incremental snapshot, stop ignored");
        }
    }

    /**
     * Dispatches the data change events for the records of a single table.
     */
    private void createDataEventsForDataCollection(MongoDbPartition partition) throws InterruptedException {
        final CollectionId collectionId = (CollectionId) currentCollection.id();
        long exportStart = clock.currentTimeInMillis();
        LOGGER.debug("Exporting data chunk from collection '{}' (total {} collections)", currentCollection.id(), context.dataCollectionsToBeSnapshottedCount());

        primary.executeBlocking("chunk query key for '" + currentCollection.id() + "'", primary -> {
            final MongoDatabase database = primary.getDatabase(collectionId.dbName());
            final MongoCollection<BsonDocument> collection = database.getCollection(collectionId.name(), BsonDocument.class);

            final Document maxKeyPredicate = new Document();
            final Document maxKeyOp = new Document();
            maxKeyOp.put("$lte", context.maximumKey().get()[0]);
            maxKeyPredicate.put(DOCUMENT_ID, maxKeyOp);

            Document predicate = maxKeyPredicate;

            if (context.chunkEndPosititon() != null) {
                final Document chunkEndPredicate = new Document();
                final Document chunkEndOp = new Document();
                chunkEndOp.put("$gt", context.chunkEndPosititon()[0]);
                chunkEndPredicate.put(DOCUMENT_ID, chunkEndOp);
                predicate = new Document();
                predicate.put("$and", Arrays.asList(chunkEndPredicate, maxKeyPredicate));
            }

            LOGGER.debug("\t For collection '{}' using query: '{}', key: '{}', maximum key: '{}'", currentCollection.id(),
                    predicate.toJson(), context.chunkEndPosititon(), context.maximumKey().get());

            long rows = 0;
            Timer logTimer = getTableScanLogTimer();

            Object[] lastRow = null;
            Object[] firstRow = null;

            for (BsonDocument doc : collection.find(predicate).sort(new Document(DOCUMENT_ID, 1))
                    .limit(connectorConfig.getIncrementalSnashotChunkSize())) {
                rows++;
                final Object[] row = new Object[]{ doc };
                if (firstRow == null) {
                    firstRow = row;
                }
                final Struct keyStruct = currentCollection.keyFromDocumentOplog(doc);
                window.put(keyStruct, row);
                if (logTimer.expired()) {
                    long stop = clock.currentTimeInMillis();
                    LOGGER.debug("\t Exported {} records for collection '{}' after {}", rows, currentCollection.id(),
                            Strings.duration(stop - exportStart));
                    logTimer = getTableScanLogTimer();
                }

                lastRow = row;
            }
            final Object[] firstKey = keyFromRow(firstRow);
            final Object[] lastKey = keyFromRow(lastRow);
            if (context.isNonInitialChunk()) {
                progressListener.currentChunk(partition, context.currentChunkId(), firstKey, lastKey);
            }
            else {
                progressListener.currentChunk(partition, context.currentChunkId(), firstKey, lastKey, context.maximumKey().orElse(null));
            }
            context.nextChunkPosition(lastKey);
            if (lastRow != null) {
                LOGGER.debug("\t Next window will resume from {}", (Object) context.chunkEndPosititon());
            }

            LOGGER.debug("\t Finished exporting {} records for window of collection '{}'; total duration '{}'", rows,
                    currentCollection.id(), Strings.duration(clock.currentTimeInMillis() - exportStart));
            incrementTableRowsScanned(rows);
        });
    }

    private void incrementTableRowsScanned(long rows) {
        totalRowsScanned += rows;
        // TODO This metric is not provided by MongoDB
        // progressListener.rowsScanned(currentCollection.id(), totalRowsScanned);
    }

    private void collectionScanCompleted(MongoDbPartition partition) {
        progressListener.dataCollectionSnapshotCompleted(partition, currentCollection.id(), totalRowsScanned);
        totalRowsScanned = 0;
        // Reset chunk/table information in metrics
        progressListener.currentChunk(null, null, null, null);
    }

    private Timer getTableScanLogTimer() {
        return Threads.timer(clock, AbstractSnapshotChangeEventSource.LOG_INTERVAL);
    }

    private Object[] keyFromRow(Object[] row) {
        if (row == null) {
            return null;
        }
        return new Object[]{ ((BsonDocument) row[0]).getInt32(DOCUMENT_ID).getValue() };
    }

    protected void setContext(IncrementalSnapshotContext<CollectionId> context) {
        this.context = context;
    }

    protected void preReadChunk(IncrementalSnapshotContext<CollectionId> context) {
    }

    protected void postReadChunk(IncrementalSnapshotContext<CollectionId> context) {
        // no-op
    }

    protected void postIncrementalSnapshotCompleted() {
        // no-op
    }

    @Override
    public void processMessage(MongoDbPartition partition, DataCollectionId dataCollectionId, Object key,
                               OffsetContext offsetContext)
            throws InterruptedException {
        context = (IncrementalSnapshotContext<CollectionId>) offsetContext.getIncrementalSnapshotContext();
        if (context == null) {
            LOGGER.warn("Context is null, skipping message processing");
            return;
        }
        LOGGER.trace("Checking window for table '{}', key '{}', window contains '{}'", dataCollectionId, key, window);
        if (!window.isEmpty() && context.deduplicationNeeded()) {
            deduplicateWindow(dataCollectionId, key);
        }
    }

    private MongoPrimary establishConnectionToPrimary(MongoDbPartition partition, ReplicaSet replicaSet) {
        return connectionContext.primaryFor(replicaSet, taskContext.filters(), (desc, error) -> {
            // propagate authorization failures
            if (error.getMessage() != null && error.getMessage().startsWith(AUTHORIZATION_FAILURE_MESSAGE)) {
                throw new ConnectException("Error while attempting to " + desc, error);
            }
            else {
                dispatcher.dispatchConnectorEvent(partition, new DisconnectEvent());
                LOGGER.error("Error while attempting to {}: {}", desc, error.getMessage(), error);
                throw new ConnectException("Error while attempting to " + desc, error);
            }
        });
    }
}


text:
jQuery(document).ready(function($) {
	// Hide all by default
	$('.group').hide();

	// Display active group
	var activetab = '';
	if (typeof(localStorage) != 'undefined') {
		activetab = localStorage.getItem("activetab");
	}
	if (activetab != '' && $(activetab).length) {
		$(activetab).fadeIn();
	} else {
		$('.group:first').fadeIn();
	}
	console.log(activetab);

	if (activetab != '' && $(activetab + '-tab').length) {
		$(activetab + '-tab').addClass('nav-tab-active');
	} else {
		$('.nav-tab-wrapper a:first').addClass('nav-tab-active');
	}

	$('.nav-tab-wrapper a').click(function(evt) {
		$('.nav-tab-wrapper a').removeClass('nav-tab-active');
		$(this).addClass('nav-tab-active').blur();
		var clicked_group = $(this).attr('href');
		if (typeof(localStorage) != 'undefined') {
			localStorage.setItem("activetab", $(this).attr('href'));
		}
		$('.group').hide();
		$(clicked_group).fadeIn();
		evt.preventDefault();
	});
});

jQuery(document).ready(function() {
	jQuery('input#cloud_max_color')
		.ready(function() {
		cloudMaxColor()
	})
		.click(function() {
		cloudMaxColor()
	})
		.blur(function() {
		cloudMaxColor()
	})
		.change(function() {
		cloudMaxColor()
	})
		.focus(function() {
		cloudMaxColor()
	});

	jQuery('input#cloud_min_color')
		.ready(function() {
		cloudMinColor()
	})
		.click(function() {
		cloudMinColor()
	})
		.blur(function() {
		cloudMinColor()
	})
		.change(function() {
		cloudMinColor()
	})
		.focus(function() {
		cloudMinColor()
	});
});

function cloudMaxColor() {
	jQuery('div.cloud_max_color').css({
		backgroundColor: jQuery('input#cloud_max_color').val()
	});
}

function cloudMinColor() {
	jQuery('div.cloud_min_color').css({
		backgroundColor: jQuery('input#cloud_min_color').val()
	});
}


text:
<?php

namespace Google\Service\DisplayVideo;

class GeoRegionTargetingOptionDetails extends \Google\Model
{
  /**
   * @var string
   */
  public $displayName;
  /**
   * @var string
   */
  public $geoRegionType;

  /**
   * @param string
   */
  public function setDisplayName($displayName)
  {
    $this->displayName = $displayName;
  }
  /**
   * @return string
   */
  public function getDisplayName()
  {
    return $this->displayName;
  }
  /**
   * @param string
   */
  public function setGeoRegionType($geoRegionType)
  {
    $this->geoRegionType = $geoRegionType;
  }
  /**
   * @return string
   */
  public function getGeoRegionType()
  {
    return $this->geoRegionType;
  }
}

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


text:
<!doctype html>
<title>different origin</title>


text:
package com.speedment.generator.translator;

import com.speedment.runtime.application.AbstractApplicationMetadata;
import com.speedment.runtime.config.*;
import com.speedment.runtime.config.trait.HasNameUtil;
import com.speedment.runtime.config.trait.HasTypeMapperUtil;
import com.speedment.runtime.core.Speedment;
import org.junit.jupiter.api.BeforeEach;

import java.util.NoSuchElementException;
import java.util.Optional;
import java.util.stream.Stream;

import static java.util.stream.Collectors.joining;

/**
 *
 * @author Per Minborg
 */
public abstract class SimpleModel {

    protected static final String TABLE_NAME = "user";
    protected static final String TABLE_NAME2 = "S_P";
    protected static final String SCHEMA_NAME = "mySchema";
    protected static final String COLUMN_NAME = "first_name";
    protected static final String COLUMN_NAME2 = "item";

    protected Speedment speedment;
    protected Project project;
    protected Dbms dbms;
    protected Schema schema;
    protected Table table;
    protected Column column;
    protected PrimaryKeyColumn pkColumn;
    protected Table table2;
    protected Column column2;

 /*   public final static class SilentTranslatorManager extends AbstractTranslatorManager {

        public SilentTranslatorManager(
            final InfoComponent info,
            final PathComponent paths,
            final EventComponent events,
            final ProjectComponent projects,
            final CodeGenerationComponent codeGenerationComponent,
            final @Config(name="skipClear", value="false") boolean skipClear
        ) {
            super(info, paths, events, projects, codeGenerationComponent, skipClear);
        }

        @Override
        public void clearExistingFiles() {}

        @Override
        public void writeToFile(Project project, Meta<File, String> meta, boolean overwriteExisting) {}

        @Override
        public void writeToFile(Project project, String filename, String content, boolean overwriteExisting) {}

        @Override
        public void writeToFile(Path location, String content, boolean overwriteExisting) {}

        @Override
        public int getFilesCreated() {return 0;}
    }*/

    @BeforeEach
    public void simpleModelTestSetUp() {

        /*speedment = new DefaultApplicationBuilder(SimpleMetadata.class)
            .withBundle(GeneratorBundle.class)
            .withComponent(SilentTranslatorManager.class)
            // .withLogging(ApplicationBuilder.LogType.APPLICATION_BUILDER)
            .withSkipCheckDatabaseConnectivity()
            .withSkipValidateRuntimeConfig()
            .build();*/

        project = new SimpleMetadata().makeProject();

/*        project  = speedment.getOrThrow(ProjectComponent.class).getProject();*/
        dbms     = project.dbmses().findAny().orElseThrow(NoSuchElementException::new);
        schema   = dbms.schemas().findAny().orElseThrow(NoSuchElementException::new);
        table    = schema.tables().filter(t -> TABLE_NAME.equals(t.getId())).findAny().orElseThrow(NoSuchElementException::new);
        column   = table.columns().findAny().orElseThrow(NoSuchElementException::new);
        pkColumn = table.primaryKeyColumns().findAny().orElseThrow(NoSuchElementException::new);

        table2  = schema.tables().filter(t -> TABLE_NAME2.equals(t.getId())).findAny().orElseThrow(NoSuchElementException::new);
        column2 = table2.columns().findAny().orElseThrow(NoSuchElementException::new);
    }

    public final static class SimpleMetadata extends AbstractApplicationMetadata {

        private String quote(String s) {
            return "\"" + s + "\"";
        }

        private String name(String s) {
            return quote(HasNameUtil.NAME) + " : " + quote(s);
        }

        private String dbTypeName(String dbmsTypeName) {
            return quote(DbmsUtil.TYPE_NAME) + " : " + quote(dbmsTypeName);
        }

        private String columnDatabaseType(String typeName) {
            return quote(HasTypeMapperUtil.DATABASE_TYPE) + " : " + quote(typeName);
        }

        private String array(String name, String... s) {
            return quote(name) + " : [\n" + Stream.of(s)
                .map(line -> line.replace("\n", "\n    "))
                .collect(joining(",\n    ")
            ) + "\n]";
        }

        private String objectWithKey(String name, String... s) {
            return quote(name) + " : " + object(s);
        }

        private String object(String... s) {
            return "{\n" + Stream.of(s)
                .map(line -> line.replace("\n", "\n    "))
                .collect(joining(",\n    ")) + "\n}";
        }

        @Override
        public Optional<String> getMetadata() {
            return Optional.of("{"
                + objectWithKey("config",
                    name("myProject"),
                    array(ProjectUtil.DBMSES,
                        object(name("myDbms"),
                            dbTypeName("MySQL"),
                            array(DbmsUtil.SCHEMAS,
                                object(
                                    name(SCHEMA_NAME),
                                    array(SchemaUtil.TABLES,
                                        object(
                                            name(TABLE_NAME),
                                            array(TableUtil.COLUMNS,
                                                object(
                                                    name(COLUMN_NAME),
                                                    columnDatabaseType(String.class.getName())
                                                )
                                            ),
                                            array(TableUtil.PRIMARY_KEY_COLUMNS,
                                                object(
                                                    name(COLUMN_NAME)
                                                )
                                            )
                                        ),
                                        object(
                                            name(TABLE_NAME2),
                                            array(TableUtil.COLUMNS,
                                                object(
                                                    name(COLUMN_NAME2),
                                                    columnDatabaseType(String.class.getName())
                                                )
                                            ),
                                            array(TableUtil.PRIMARY_KEY_COLUMNS,
                                                object(
                                                    name(COLUMN_NAME2)
                                                )
                                            )
                                        )
                                    )
                                )
                            )
                        )
                    )
                )
                + "}"
            );
        }
    }
}


text:
<?php

namespace Zff\Base\Form\Element;

use Zend\Form\Element\Checkbox;

/**
 * Bs Checkbox Element
 *
 * @package ZffBase
 * @subpackage ZffBase_Form
 */
class BsCheckbox extends Checkbox implements BsElementInterface
{

    /**
     * Seed label attributes
     *
     * @var array
     */
    protected $labelAttributes = [
        'class' => 'c-input c-checkbox',
    ];
    protected $labelOptions    = [
        'always_wrap'         => true,
        'label_position'      => 'append',
    ];

    public function __construct($name = null, $options = [])
    {
        $this->attributes['id'] = uniqid();
        parent::__construct($name, $options);
    }
}


text: pytest --cov-report xml:cov.xml --cov keras_tuner $1