text:
//
//  FlipsideViewController.m
//  Coniglio
//
//  Created by Giacomo Tufano on 02/02/09.
//
//  Copyright 2011, Giacomo Tufano (gt@ilTofa.it)
//  Licensed under MIT license. See LICENSE file or http://www.opensource.org/licenses/mit-license.php
//

#import "FlipsideViewController.h"
#import "RootViewController.h"

@implementation FlipsideViewController

@synthesize fieldSN;
@synthesize fieldToken;
@synthesize labelBunny;
@synthesize tableVoices;
@synthesize laRuota;
@synthesize buttonServersList;
@synthesize theFBSession;
@synthesize fbLogged;
@synthesize fbButton, checkButton, helpButton;
@synthesize labelVersion;

// Get help page on safari
- (IBAction)getHelp:(id)sender
{
	[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://www.ilTofa.com/Coniglio/help.html"]];
}

// Check data
- (IBAction)checkBunnyInfo:(id)sender
{
	NSString *temp;

	[laRuota startAnimating];
	DLog(@"Check Button pressed, starting nabaztag verification");
	theBunny = [Nabaztag sharedInstance];
	if([theBunny validateBunny:fieldSN.text:fieldToken.text])
	{
		DLog(@"Bunny validated! Name is: %@", [theBunny rabbitName]);
		// Set defaults
		NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
		[defaults setObject:fieldSN.text forKey:@"SerialNumber"];
		[defaults setObject:fieldToken.text forKey:@"Token"];
		[defaults setObject:[NSString stringWithFormat:@"%d", selectedVoice] forKey:@"Voice"];
		DLog(@"Default set. SN: %@, token: %@, voice: %d",
			 fieldSN.text, fieldToken.text, selectedVoice);
		// if no voices loaded already, load them
		if([theBunny.voices count] == 0)
		{
			[theBunny getVoices];
			// and reload table data...
			[tableVoices reloadData];
			[tableVoices scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:selectedVoice inSection:0]
							   atScrollPosition:UITableViewScrollPositionMiddle
									   animated:NO];
		}

		temp = [NSString stringWithFormat:NSLocalizedString(@"Nabaztag%@ %@ is %@.", @""),
				(theBunny.isTagTag) ? @"/tag" : @"",
				theBunny.rabbitName,
				(theBunny.isSleeping) ? NSLocalizedString(@"sleeping", @"") : NSLocalizedString(@"awake", @"")];
	}
	else
	{
		DLog(@"Bunny validation failed!");
		temp = [NSString stringWithFormat:NSLocalizedString(@"Error: %@", @""), theBunny.lastMessage];
	}
	labelBunny.text = temp;
	[laRuota stopAnimating];
}

// dismiss keyboard
- (BOOL)textFieldShouldReturn:(UITextField *)theTextField
{
	DLog(@"textFieldShouldReturn called");
    if (theTextField == fieldSN)
        [fieldSN resignFirstResponder];
    if (theTextField == fieldToken)
        [fieldToken resignFirstResponder];
    return YES;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	//    self.view.backgroundColor = [UIColor viewFlipsideBackgroundColor];
	theBunny = [Nabaztag sharedInstance];
	// Get defaults
	DLog(@"FlipsideViewController viewDidLoad");
	NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
	self.fieldSN.placeholder = NSLocalizedString(@"Serial Number: ", @"");
	self.fieldToken.placeholder = NSLocalizedString(@"Token: ", @"");
	self.labelVersion.text = [NSString stringWithFormat:@"Coniglio %@",
							  [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"]];
    [self.buttonServersList setTitle:NSLocalizedString(@"Choose a server for your nabaztag", @"") forState:UIControlStateNormal];
    [self.buttonServersList setTitle:NSLocalizedString(@"Choose a server for your nabaztag", @"") forState:UIControlStateHighlighted];
    [self.buttonServersList setTitle:NSLocalizedString(@"Choose a server for your nabaztag", @"") forState:UIControlStateHighlighted];

	[checkButton setTitle:NSLocalizedString(@"Check", @"") forState:UIControlStateNormal];
	[checkButton setTitle:NSLocalizedString(@"Check", @"") forState:UIControlStateHighlighted];
	[checkButton setTitle:NSLocalizedString(@"Check", @"") forState:UIControlStateSelected];
	[helpButton setTitle:NSLocalizedString(@"Help", @"") forState:UIControlStateNormal];
	[helpButton setTitle:NSLocalizedString(@"Help", @"") forState:UIControlStateHighlighted];
	[helpButton setTitle:NSLocalizedString(@"Help", @"") forState:UIControlStateSelected];

	fieldSN.text = [defaults stringForKey:@"SerialNumber"];
	fieldToken.text = [defaults stringForKey:@"Token"];
	selectedVoice = [[defaults stringForKey:@"Voice"] integerValue];
	DLog(@"Default loaded. SN: %@, token: %@, voice: %d", fieldSN.text, fieldToken.text, selectedVoice);
	// validate bunny on default (IF there is a default)
	if([fieldSN.text length] == 0 || [fieldToken.text length] == 0)
		// No default set
		labelBunny.text = NSLocalizedString(@"No bunny setup", @"");
	else
	{ // we have a default...
		[self checkBunnyInfo:nil];
		// set voices table view. Load voices...
		[theBunny getVoices];
	}
}

- (void)viewDidAppear:(BOOL)animated
{
	DLog(@"FlipsideViewController viewDidAppear");
	[super viewWillAppear:animated];

	// load data and scroll to default row in TableView ...if the bunny is valid...
	if(theBunny.isValid)
	{
		[tableVoices reloadData];
        if(selectedVoice > [tableVoices numberOfRowsInSection:0])
            selectedVoice = 0;
		[tableVoices scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:selectedVoice inSection:0]
						   atScrollPosition:UITableViewScrollPositionMiddle
								   animated:NO];
	}
	// Setup FB button...
	[self FBButtonSetup];
}

// TableView delegate rows
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
	return theBunny.voices.count;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	DLog(@"Cell for row %d (selected: %d)", indexPath.row, selectedVoice);

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Normal"];
    if (cell == nil)
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Normal"] autorelease];

    cell.textLabel.text = [theBunny.voices objectAtIndex:indexPath.row];
	if(indexPath.row != selectedVoice)
		cell.accessoryType = UITableViewCellAccessoryNone;
	else
		cell.accessoryType = UITableViewCellAccessoryCheckmark;
    return cell;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    return NSLocalizedString(@"Voice", @"");
}

// Table Row selected
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
	DLog(@"Selected row %i", indexPath.row);
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
	// Is the same row as before?
    if (selectedVoice == indexPath.row)
        return;

    NSIndexPath *oldIndexPath = [NSIndexPath indexPathForRow:selectedVoice inSection:0];

    UITableViewCell *newCell = [tableView cellForRowAtIndexPath:indexPath];
    if (newCell.accessoryType == UITableViewCellAccessoryNone)
	{
        newCell.accessoryType = UITableViewCellAccessoryCheckmark;
        selectedVoice = indexPath.row;
		[[NSUserDefaults standardUserDefaults] setObject:[NSString stringWithFormat:@"%d", selectedVoice] forKey:@"Voice"];
    }

    UITableViewCell *oldCell = [tableView cellForRowAtIndexPath:oldIndexPath];
    if (oldCell.accessoryType == UITableViewCellAccessoryCheckmark)
	{
        oldCell.accessoryType = UITableViewCellAccessoryNone;
    }
}

/*
 // Override to allow orientations other than the default portrait orientation.
 - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
 // Return YES for supported orientations
 return (interfaceOrientation == UIInterfaceOrientationPortrait);
 }
 */

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
    // Release anything that's not essential, such as cached data
}

- (void)dealloc {
    [buttonServersList release];
    [super dealloc];
}

// Facebook login
- (IBAction)facebookLogInOut:(id)sender
{
	if([Facebook sharedInstance].isLogged)
		[[Facebook sharedInstance] fbLogout:self];
	else
		[[Facebook sharedInstance] fbLogin:self];
	// in any case, reset time for reading statuses
	NSDate *lastDay = [NSDate dateWithTimeIntervalSinceNow:-86400.0];
	NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
	[defaults setObject:lastDay forKey:@"lastFBReading"];
}

- (void)FBButtonSetup
{
	NSBundle *thisBundle = [NSBundle bundleForClass:[self class]];
	NSString *theImageName = [NSString stringWithString:([Facebook sharedInstance].isLogged) ? @"Logout_iphone" : @"Connect_iphone"];
	[fbButton setImage:[UIImage imageWithContentsOfFile:[thisBundle pathForResource:theImageName ofType:@"png"]]
			  forState:UIControlStateNormal];
}

- (IBAction)sendToServerList:(id)sender
{
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://ojn.psnet.fr/ojn_admin/"]];
}

#pragma mark FacebookDelegate

- (void)loggedInOut
{
	// Only react setting up the right button
	[self FBButtonSetup];
}

- (void)viewDidUnload {
    [self setButtonServersList:nil];
    [super viewDidUnload];
}
@end


text:
"""Training code for baseline model."""

from absl import app
from absl import flags
from absl import logging

import os
import numpy as np
from tqdm import trange

import common.data as data
from common.networks import AllConvModel

from training.train_baseline import TrainLoop

import training.utils as utils

FLAGS = flags.FLAGS

def encode(xs):
    thresholds = np.arange(0, 1, .05)+.05
    shape = xs.shape
    less_than_threshold = xs[:,:,:,:,None] < thresholds
    xs = np.array(less_than_threshold, dtype=np.float32)
    xs = np.reshape(xs, [-1, shape[1], shape[2], shape[3]*len(thresholds)])
    return xs

def main(argv):
    del argv

    dataset = data.load_dataset(FLAGS.dataset)

    (x_train, y_train), (x_test, y_test), num_classes = dataset

    x_train = encode(x_train)
    x_test = encode(x_test)
    print(x_train.shape)

    dataset = (x_train, y_train), (x_test, y_test), num_classes

    input_shape = x_train[0].shape

    loop = TrainLoop(FLAGS.num_filters,
                     num_classes, input_shape)
    loop.train(dataset=dataset,
               batch_size=FLAGS.batch_size,
               num_epochs=FLAGS.num_epochs,
               model_dir=os.path.join(FLAGS.model_dir, "discretize/"))

if __name__ == '__main__':
    logging.set_verbosity(logging.INFO)
    app.run(main)

redpajama_set_name: RedPajamaGithub


text:
<?php

declare(strict_types=1);

namespace GoetasWebservices\SoapServices\SoapClient\Result;

interface ResultCreatorInterface
{
    /**
     * @return mixed
     */
    public function prepareResult(object $object, array $output);
}


text:
package io.atomix.protocols.raft.session.impl;

import static com.google.common.base.Preconditions.checkNotNull;

import io.atomix.primitive.PrimitiveException;
import io.atomix.primitive.PrimitiveState;
import io.atomix.primitive.operation.PrimitiveOperation;
import io.atomix.protocols.raft.RaftError;
import io.atomix.protocols.raft.RaftException;
import io.atomix.protocols.raft.protocol.CommandRequest;
import io.atomix.protocols.raft.protocol.CommandResponse;
import io.atomix.protocols.raft.protocol.OperationRequest;
import io.atomix.protocols.raft.protocol.OperationResponse;
import io.atomix.protocols.raft.protocol.QueryRequest;
import io.atomix.protocols.raft.protocol.QueryResponse;
import io.atomix.protocols.raft.protocol.RaftResponse;
import io.atomix.utils.concurrent.ThreadContext;
import java.net.ConnectException;
import java.nio.channels.ClosedChannelException;
import java.time.Duration;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.BiConsumer;
import java.util.function.Predicate;

/**
 * Session operation submitter.
 */
final class RaftSessionInvoker {
  private static final int[] FIBONACCI = new int[]{1, 1, 2, 3, 5};
  private static final Predicate<Throwable> EXCEPTION_PREDICATE = e ->
      e instanceof ConnectException
          || e instanceof TimeoutException
          || e instanceof ClosedChannelException;
  private static final Predicate<Throwable> EXPIRED_PREDICATE = e ->
      e instanceof RaftException.UnknownClient
          || e instanceof RaftException.UnknownSession;
  private static final Predicate<Throwable> CLOSED_PREDICATE = e ->
      e instanceof RaftException.ClosedSession
          || e instanceof RaftException.UnknownService;

  private final RaftSessionConnection leaderConnection;
  private final RaftSessionConnection sessionConnection;
  private final RaftSessionState state;
  private final RaftSessionSequencer sequencer;
  private final RaftSessionManager manager;
  private final ThreadContext context;
  private final Map<Long, OperationAttempt> attempts = new LinkedHashMap<>();
  private final AtomicLong keepAliveIndex = new AtomicLong();

  RaftSessionInvoker(
      RaftSessionConnection leaderConnection,
      RaftSessionConnection sessionConnection,
      RaftSessionState state,
      RaftSessionSequencer sequencer,
      RaftSessionManager manager,
      ThreadContext context) {
    this.leaderConnection = checkNotNull(leaderConnection, "leaderConnection");
    this.sessionConnection = checkNotNull(sessionConnection, "sessionConnection");
    this.state = checkNotNull(state, "state");
    this.sequencer = checkNotNull(sequencer, "sequencer");
    this.manager = checkNotNull(manager, "manager");
    this.context = checkNotNull(context, "context cannot be null");
  }

  /**
   * Submits a operation to the cluster.
   *
   * @param operation The operation to submit.
   * @return A completable future to be completed once the command has been submitted.
   */
  public CompletableFuture<byte[]> invoke(PrimitiveOperation operation) {
    CompletableFuture<byte[]> future = new CompletableFuture<>();
    switch (operation.id().type()) {
      case COMMAND:
        context.execute(() -> invokeCommand(operation, future));
        break;
      case QUERY:
        context.execute(() -> invokeQuery(operation, future));
        break;
      default:
        throw new IllegalArgumentException("Unknown operation type " + operation.id().type());
    }
    return future;
  }

  /**
   * Submits a command to the cluster.
   */
  private void invokeCommand(PrimitiveOperation operation, CompletableFuture<byte[]> future) {
    CommandRequest request = CommandRequest.builder()
        .withSession(state.getSessionId().id())
        .withSequence(state.nextCommandRequest())
        .withOperation(operation)
        .build();
    invokeCommand(request, future);
  }

  /**
   * Submits a command request to the cluster.
   */
  private void invokeCommand(CommandRequest request, CompletableFuture<byte[]> future) {
    invoke(new CommandAttempt(sequencer.nextRequest(), request, future));
  }

  /**
   * Submits a query to the cluster.
   */
  private void invokeQuery(PrimitiveOperation operation, CompletableFuture<byte[]> future) {
    QueryRequest request = QueryRequest.builder()
        .withSession(state.getSessionId().id())
        .withSequence(state.getCommandRequest())
        .withOperation(operation)
        .withIndex(Math.max(state.getResponseIndex(), state.getEventIndex()))
        .build();
    invokeQuery(request, future);
  }

  /**
   * Submits a query request to the cluster.
   */
  private void invokeQuery(QueryRequest request, CompletableFuture<byte[]> future) {
    invoke(new QueryAttempt(sequencer.nextRequest(), request, future));
  }

  /**
   * Submits an operation attempt.
   *
   * @param attempt The attempt to submit.
   */
  private <T extends OperationRequest, U extends OperationResponse> void invoke(OperationAttempt<T, U> attempt) {
    if (state.getState() == PrimitiveState.CLOSED) {
      attempt.fail(new PrimitiveException.ClosedSession("session closed"));
    } else {
      attempts.put(attempt.sequence, attempt);
      attempt.send();
      attempt.future.whenComplete((r, e) -> attempts.remove(attempt.sequence));
    }
  }

  /**
   * Resubmits commands starting after the given sequence number.
   *

   * The sequence number from which to resend commands is the request sequence number, not the client-side
   * sequence number. We resend only commands since queries cannot be reliably resent without losing linearizable
   * semantics. Commands are resent by iterating through all pending operation attempts and retrying commands where the
   * sequence number is greater than the given {@code commandSequence} number and the attempt number is less than or
   * equal to the version.
   */
  private void resubmit(long commandSequence, OperationAttempt<?, ?> attempt) {
    // If the client's response sequence number is greater than the given command sequence number,
    // the cluster likely has a new leader, and we need to reset the sequencing in the leader by
    // sending a keep-alive request.
    // Ensure that the client doesn't resubmit many concurrent KeepAliveRequests by tracking the last
    // keep-alive response sequence number and only resubmitting if the sequence number has changed.
    long responseSequence = state.getCommandResponse();
    if (commandSequence < responseSequence && keepAliveIndex.get() != responseSequence) {
      keepAliveIndex.set(responseSequence);
      manager.resetIndexes(state.getSessionId()).whenCompleteAsync((result, error) -> {
        if (error == null) {
          resubmit(responseSequence, attempt);
        } else {
          keepAliveIndex.set(0);
          attempt.retry(Duration.ofSeconds(FIBONACCI[Math.min(attempt.attempt - 1, FIBONACCI.length - 1)]));
        }
      }, context);
    } else {
      for (Map.Entry<Long, OperationAttempt> entry : attempts.entrySet()) {
        OperationAttempt operation = entry.getValue();
        if (operation instanceof CommandAttempt && operation.request.sequenceNumber() > commandSequence && operation.attempt <= attempt.attempt) {
          operation.retry();
        }
      }
    }
  }

  /**
   * Resubmits pending commands.
   */
  public void reset() {
    context.execute(() -> {
      for (OperationAttempt attempt : attempts.values()) {
        attempt.retry();
      }
    });
  }

  /**
   * Closes the submitter.
   *
   * @return A completable future to be completed with a list of pending operations.
   */
  public CompletableFuture<Void> close() {
    for (OperationAttempt attempt : new ArrayList<>(attempts.values())) {
      attempt.fail(new PrimitiveException.ClosedSession("session closed"));
    }
    attempts.clear();
    sessionConnection.close();
    leaderConnection.close();
    return CompletableFuture.completedFuture(null);
  }

  /**
   * Operation attempt.
   */
  private abstract class OperationAttempt<T extends OperationRequest, U extends OperationResponse> implements BiConsumer {
    protected final long sequence;
    protected final int attempt;
    protected final T request;
    protected final CompletableFuture<byte[]> future;

    protected OperationAttempt(long sequence, int attempt, T request, CompletableFuture<byte[]> future) {
      this.sequence = sequence;
      this.attempt = attempt;
      this.request = request;
      this.future = future;
    }

    /**
     * Sends the attempt.
     */
    protected abstract void send();

    /**
     * Returns the next instance of the attempt.
     *
     * @return The next instance of the attempt.
     */
    protected abstract OperationAttempt<T, U> next();

    /**
     * Returns a new instance of the default exception for the operation.
     *
     * @return A default exception for the operation.
     */
    protected abstract Throwable defaultException();

    /**
     * Completes the operation successfully.
     *
     * @param response The operation response.
     */
    protected abstract void complete(U response);

    /**
     * Completes the operation with an exception.
     *
     * @param error The completion exception.
     */
    protected void complete(Throwable error) {
      sequence(null, () -> future.completeExceptionally(error));
    }

    /**
     * Runs the given callback in proper sequence.
     *
     * @param response The operation response.
     * @param callback The callback to run in sequence.
     */
    protected final void sequence(OperationResponse response, Runnable callback) {
      sequencer.sequenceResponse(sequence, response, callback);
    }

    /**
     * Fails the attempt.
     */
    public void fail() {
      fail(defaultException());
    }

    /**
     * Fails the attempt with the given exception.
     *
     * @param t The exception with which to fail the attempt.
     */
    public void fail(Throwable t) {
      sequence(null, () -> {
        state.setCommandResponse(request.sequenceNumber());
        future.completeExceptionally(t);
      });

      // If the session has been expired or closed, update the client's state.
      if (EXPIRED_PREDICATE.test(t)) {
        state.setState(PrimitiveState.EXPIRED);
      } else if (CLOSED_PREDICATE.test(t)) {
        state.setState(PrimitiveState.CLOSED);
      }
    }

    /**
     * Immediately retries the attempt.
     */
    public void retry() {
      context.checkThread();
      invoke(next());
    }

    /**
     * Retries the attempt after the given duration.
     *
     * @param after The duration after which to retry the attempt.
     */
    public void retry(Duration after) {
      context.schedule(after, () -> invoke(next()));
    }
  }

  /**
   * Command operation attempt.
   */
  private final class CommandAttempt extends OperationAttempt<CommandRequest, CommandResponse> {
    CommandAttempt(long sequence, CommandRequest request, CompletableFuture<byte[]> future) {
      super(sequence, 1, request, future);
    }

    CommandAttempt(long sequence, int attempt, CommandRequest request, CompletableFuture<byte[]> future) {
      super(sequence, attempt, request, future);
    }

    @Override
    protected void send() {
      leaderConnection.command(request).whenCompleteAsync(this, context);
    }

    @Override
    protected OperationAttempt<CommandRequest, CommandResponse> next() {
      return new CommandAttempt(sequence, this.attempt + 1, request, future);
    }

    @Override
    protected Throwable defaultException() {
      return new PrimitiveException.CommandFailure("failed to complete command");
    }

    @Override
    public void accept(CommandResponse response, Throwable error) {
      if (error == null) {
        if (response.status() == RaftResponse.Status.OK) {
          complete(response);
        }
        // COMMAND_ERROR indicates that the command was received by the leader out of sequential order.
        // We need to resend commands starting at the provided lastSequence number.
        else if (response.error().type() == RaftError.Type.COMMAND_FAILURE) {
          resubmit(response.lastSequenceNumber(), this);
        }
        // If a PROTOCOL_ERROR or APPLICATION_ERROR occurred, complete the request exceptionally with the error message.
        else if (response.error().type() == RaftError.Type.PROTOCOL_ERROR
            || response.error().type() == RaftError.Type.APPLICATION_ERROR) {
          complete(response.error().createException());
        }
        // If the client is unknown by the cluster, close the session and complete the operation exceptionally.
        else if (response.error().type() == RaftError.Type.UNKNOWN_CLIENT
            || response.error().type() == RaftError.Type.UNKNOWN_SESSION) {
          complete(response.error().createException());
          state.setState(PrimitiveState.EXPIRED);
        }
        // If the service is unknown by the cluster or the session was explicitly closed, set the session state to CLOSED.
        else if (response.error().type() == RaftError.Type.UNKNOWN_SERVICE
            || response.error().type() == RaftError.Type.CLOSED_SESSION) {
          complete(response.error().createException());
          state.setState(PrimitiveState.CLOSED);
        }
        // For all other errors, use fibonacci backoff to resubmit the command.
        else {
          retry(Duration.ofSeconds(FIBONACCI[Math.min(attempt - 1, FIBONACCI.length - 1)]));
        }
      } else if (EXCEPTION_PREDICATE.test(error) || (error instanceof CompletionException && EXCEPTION_PREDICATE.test(error.getCause()))) {
        if (error instanceof ConnectException || error.getCause() instanceof ConnectException) {
          leaderConnection.reset(null, leaderConnection.members());
        }
        retry(Duration.ofSeconds(FIBONACCI[Math.min(attempt - 1, FIBONACCI.length - 1)]));
      } else {
        fail(error);
      }
    }

    @Override
    @SuppressWarnings("unchecked")
    protected void complete(CommandResponse response) {
      sequence(response, () -> {
        state.setCommandResponse(request.sequenceNumber());
        state.setResponseIndex(response.index());
        future.complete(response.result());
      });
    }
  }

  /**
   * Query operation attempt.
   */
  private final class QueryAttempt extends OperationAttempt<QueryRequest, QueryResponse> {
    QueryAttempt(long sequence, QueryRequest request, CompletableFuture<byte[]> future) {
      super(sequence, 1, request, future);
    }

    QueryAttempt(long sequence, int attempt, QueryRequest request, CompletableFuture<byte[]> future) {
      super(sequence, attempt, request, future);
    }

    @Override
    protected void send() {
      sessionConnection.query(request).whenComplete(this);
    }

    @Override
    protected OperationAttempt<QueryRequest, QueryResponse> next() {
      return new QueryAttempt(sequence, this.attempt + 1, request, future);
    }

    @Override
    protected Throwable defaultException() {
      return new PrimitiveException.QueryFailure("failed to complete query");
    }

    @Override
    public void accept(QueryResponse response, Throwable error) {
      if (error == null) {
        if (response.status() == RaftResponse.Status.OK) {
          complete(response);
        } else if (response.error().type() == RaftError.Type.UNKNOWN_CLIENT
            || response.error().type() == RaftError.Type.UNKNOWN_SESSION) {
          complete(response.error().createException());
          state.setState(PrimitiveState.EXPIRED);
        } else if (response.error().type() == RaftError.Type.UNKNOWN_SERVICE
            || response.error().type() == RaftError.Type.CLOSED_SESSION) {
          complete(response.error().createException());
          state.setState(PrimitiveState.CLOSED);
        } else {
          complete(response.error().createException());
        }
      } else {
        fail(error);
      }
    }

    @Override
    @SuppressWarnings("unchecked")
    protected void complete(QueryResponse response) {
      sequence(response, () -> {
        state.setResponseIndex(response.index());
        future.complete(response.result());
      });
    }
  }

}


text:
"""Support for ESPHome climate devices."""
import logging
from typing import List, Optional

from aioesphomeapi import ClimateInfo, ClimateMode, ClimateState

from homeassistant.components.climate import ClimateDevice
from homeassistant.components.climate.const import (
    ATTR_HVAC_MODE,
    ATTR_TARGET_TEMP_HIGH,
    ATTR_TARGET_TEMP_LOW,
    HVAC_MODE_HEAT_COOL,
    HVAC_MODE_COOL,
    HVAC_MODE_HEAT,
    SUPPORT_TARGET_TEMPERATURE,
    SUPPORT_PRESET_MODE,
    SUPPORT_TARGET_TEMPERATURE_RANGE,
    PRESET_AWAY,
    HVAC_MODE_OFF,
)
from homeassistant.const import (
    ATTR_TEMPERATURE,
    PRECISION_HALVES,
    PRECISION_TENTHS,
    PRECISION_WHOLE,
    TEMP_CELSIUS,
)

from . import (
    EsphomeEntity,
    esphome_map_enum,
    esphome_state_property,
    platform_async_setup_entry,
)

_LOGGER = logging.getLogger(__name__)

async def async_setup_entry(hass, entry, async_add_entities):
    """Set up ESPHome climate devices based on a config entry."""
    await platform_async_setup_entry(
        hass,
        entry,
        async_add_entities,
        component_key="climate",
        info_type=ClimateInfo,
        entity_type=EsphomeClimateDevice,
        state_type=ClimateState,
    )

@esphome_map_enum
def _climate_modes():
    return {
        ClimateMode.OFF: HVAC_MODE_OFF,
        ClimateMode.AUTO: HVAC_MODE_HEAT_COOL,
        ClimateMode.COOL: HVAC_MODE_COOL,
        ClimateMode.HEAT: HVAC_MODE_HEAT,
    }

class EsphomeClimateDevice(EsphomeEntity, ClimateDevice):
    """A climate implementation for ESPHome."""

    @property
    def _static_info(self) -> ClimateInfo:
        return super()._static_info

    @property
    def _state(self) -> Optional[ClimateState]:
        return super()._state

    @property
    def precision(self) -> float:
        """Return the precision of the climate device."""
        precicions = [PRECISION_WHOLE, PRECISION_HALVES, PRECISION_TENTHS]
        for prec in precicions:
            if self._static_info.visual_temperature_step >= prec:
                return prec
        # Fall back to highest precision, tenths
        return PRECISION_TENTHS

    @property
    def temperature_unit(self) -> str:
        """Return the unit of measurement used by the platform."""
        return TEMP_CELSIUS

    @property
    def hvac_modes(self) -> List[str]:
        """Return the list of available operation modes."""
        return [
            _climate_modes.from_esphome(mode)
            for mode in self._static_info.supported_modes
        ]

    @property
    def preset_modes(self):
        """Return preset modes."""
        return [PRESET_AWAY] if self._static_info.supports_away else []

    @property
    def target_temperature_step(self) -> float:
        """Return the supported step of target temperature."""
        # Round to one digit because of floating point math
        return round(self._static_info.visual_temperature_step, 1)

    @property
    def min_temp(self) -> float:
        """Return the minimum temperature."""
        return self._static_info.visual_min_temperature

    @property
    def max_temp(self) -> float:
        """Return the maximum temperature."""
        return self._static_info.visual_max_temperature

    @property
    def supported_features(self) -> int:
        """Return the list of supported features."""
        features = 0
        if self._static_info.supports_two_point_target_temperature:
            features |= SUPPORT_TARGET_TEMPERATURE_RANGE
        else:
            features |= SUPPORT_TARGET_TEMPERATURE
        if self._static_info.supports_away:
            features |= SUPPORT_PRESET_MODE
        return features

    @esphome_state_property
    def hvac_mode(self) -> Optional[str]:
        """Return current operation ie. heat, cool, idle."""
        return _climate_modes.from_esphome(self._state.mode)

    @esphome_state_property
    def preset_mode(self):
        """Return current preset mode."""
        return PRESET_AWAY if self._state.away else None

    @esphome_state_property
    def current_temperature(self) -> Optional[float]:
        """Return the current temperature."""
        return self._state.current_temperature

    @esphome_state_property
    def target_temperature(self) -> Optional[float]:
        """Return the temperature we try to reach."""
        return self._state.target_temperature

    @esphome_state_property
    def target_temperature_low(self) -> Optional[float]:
        """Return the lowbound target temperature we try to reach."""
        return self._state.target_temperature_low

    @esphome_state_property
    def target_temperature_high(self) -> Optional[float]:
        """Return the highbound target temperature we try to reach."""
        return self._state.target_temperature_high

    async def async_set_temperature(self, **kwargs) -> None:
        """Set new target temperature (and operation mode if set)."""
        data = {"key": self._static_info.key}
        if ATTR_HVAC_MODE in kwargs:
            data["mode"] = _climate_modes.from_hass(kwargs[ATTR_HVAC_MODE])
        if ATTR_TEMPERATURE in kwargs:
            data["target_temperature"] = kwargs[ATTR_TEMPERATURE]
        if ATTR_TARGET_TEMP_LOW in kwargs:
            data["target_temperature_low"] = kwargs[ATTR_TARGET_TEMP_LOW]
        if ATTR_TARGET_TEMP_HIGH in kwargs:
            data["target_temperature_high"] = kwargs[ATTR_TARGET_TEMP_HIGH]
        await self._client.climate_command(**data)

    async def async_set_hvac_mode(self, hvac_mode: str) -> None:
        """Set new target operation mode."""
        await self._client.climate_command(
            key=self._static_info.key, mode=_climate_modes.from_hass(hvac_mode)
        )

    async def async_set_preset_mode(self, preset_mode):
        """Set preset mode."""
        away = preset_mode == PRESET_AWAY
        await self._client.climate_command(key=self._static_info.key, away=away)


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

using System;
using Microsoft.WindowsAzure.Management.SiteRecovery;
using Microsoft.WindowsAzure.Management.SiteRecovery.Models;

namespace Microsoft.Azure.Commands.RecoveryServices
{
    /// <summary>
    /// Recovery services convenience client.
    /// </summary>
    public partial class PSRecoveryServicesClient
    {
        /// <summary>
        /// Gets Azure Site Recovery Servers.
        /// </summary>
        /// <param name="shouldSignRequest">Boolean indicating if the request should be signed ACIK</param>
        /// <returns>Server list response</returns>
        public ServerListResponse GetAzureSiteRecoveryServer(bool shouldSignRequest = true)
        {
            return this.GetSiteRecoveryClient().Servers.List(this.GetRequestHeaders(shouldSignRequest));
        }

        /// <summary>
        /// Gets Azure Site Recovery Server.
        /// </summary>
        /// <param name="serverId">Server ID</param>
        /// <returns>Server response</returns>
        public ServerResponse GetAzureSiteRecoveryServer(string serverId)
        {
            return this.GetSiteRecoveryClient().Servers.Get(serverId, this.GetRequestHeaders());
        }
    }
}


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

import com.amazonaws.AmazonServiceException;

/**
 * <p>
 * You cannot create anymore cache behaviors for the distribution.
 * </p>
 */
public class TooManyCacheBehaviorsException extends AmazonServiceException {
    private static final long serialVersionUID = 1L;

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

}


text:
/**
 * Created with JetBrains WebStorm.
 * User: asiebert
 * Date: 18.01.14
 * Time: 17:22
 * To change this template use File | Settings | File Templates.
 */


text:
var express = require('express');
var stripe = require('stripe')("sk_test_Ec1UzFOy7ATlFhS7hXSIAFKc");
var bodyParser = require ('body-parser');
var port = 9555;

var app = express();

app.use(express.static(__dirname+'/public'));
app.use(bodyParser());

app.post('/charge', function(req, res) {
  var stripeToken = req.body.stripeToken;
  var charge = stripe.charges.create({
    amount: 1000,
    currency: 'usd',
    card: stripeToken,
    description: 'charge from site'
  }, function(err, charge) {
    if (!err) {
      return res.redirect('/thank-you.html');
    } else {
      return res.redirect('/payment-error.html');
    }
  })
});

app.listen(port);


text:
<!doctype html>

	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
	<title>CustomElements • TodoMVC</title>
	<link rel="stylesheet" href="assets/base.css">

	<link rel="stylesheet" href="css/app.css">

todos

			<input is="todo-item-input" id="new-todo" placeholder="What needs to be done?" autofocus>

			<input id="toggle-all" type="checkbox">
			Mark all as complete

						<input class="toggle" type="checkbox">
						Make a todo-item custom element
						<button class="destroy"></button>

					<input class="edit">

						<input class="toggle" type="checkbox" checked>
						Implement adding todos
						<button class="destroy"></button>

					<input class="edit">

						<input class="toggle" type="checkbox" checked>
						Add more todos
						<button class="destroy"></button>

					<input class="edit">

			1 item left

			<button id="clear-completed">Clear completed (1)</button>

Double-click to edit a todo

Template by Sindre Sorhus

Created by you

Part of TodoMVC


text:
for (var index = 0; index < array.length; index++) {
   console.log(index);
}


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading;

namespace Sanatana.Notifications.DAL.Queries
{
    public class FileJournalQueries
    {
        //fields
        protected FileInfo _fileInfo;
        protected ReaderWriterLockSlim _fileLocker;
        protected bool _directoryCreated;

        //init
        public FileJournalQueries(FileInfo fileInfo)
        {
            _fileInfo = fileInfo;
            _fileLocker = new ReaderWriterLockSlim();
        }

        //methods
        protected virtual FileInfo CreateDirectoryAndGetFile(bool createDirectory)
        {
            _fileInfo.Directory.Refresh();
            bool directoryCreated = _fileInfo.Directory.Exists;

            if (!directoryCreated && createDirectory)
            {
                _fileInfo.Directory.Create();
            }

            _fileInfo.Refresh();
            return _fileInfo;
        }

        public virtual void CreateLineList<T>(List<T> lines)
        {
            try
            {
                _fileLocker.EnterWriteLock();

                FileInfo fileInfo = CreateDirectoryAndGetFile(true);
                if (fileInfo.Exists)
                    fileInfo.Delete();

                using (FileStream fileStream = new FileStream(fileInfo.FullName
                    , FileMode.CreateNew, FileAccess.Write, FileShare.ReadWrite))
                using (StreamWriter streamWriter = new StreamWriter(fileStream))
                {
                    foreach (T line in lines)
                    {
                        streamWriter.WriteLine(line.ToString());
                    }
                }
            }
            finally
            {
                _fileLocker.ExitWriteLock();
            }
        }

        public virtual void AppendLineList<T>(List<T> lines)
        {
            try
            {
                _fileLocker.EnterWriteLock();

                FileInfo fileInfo = CreateDirectoryAndGetFile(true);

                using (FileStream fileStream = new FileStream(fileInfo.FullName
                    , FileMode.Append, FileAccess.Write, FileShare.ReadWrite))
                using (StreamWriter streamWriter = new StreamWriter(fileStream))
                {
                    foreach (T line in lines)
                    {
                        streamWriter.WriteLine(line.ToString());
                    }
                }

            }
            finally
            {
                _fileLocker.ExitWriteLock();
            }
        }

        public virtual List<string> ReadLineList()
        {
            List<string> lines = new List<string>();

            try
            {
                _fileLocker.EnterReadLock();

                FileInfo fileInfo = CreateDirectoryAndGetFile(false);
                if (!fileInfo.Exists || fileInfo.Length == 0)
                    return lines;

                using (FileStream fileStream = new FileStream(fileInfo.FullName
                    , FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                using (StreamReader streamReader = new StreamReader(fileStream))
                {
                    while (!streamReader.EndOfStream)
                    {
                        string line = streamReader.ReadLine();
                        if (string.IsNullOrEmpty(line))
                            continue;

                        lines.Add(line);
                    }
                }
            }
            finally
            {
                _fileLocker.ExitReadLock();
            }

            return lines;
        }
    }
}


text:
.item-summary {
    margin-bottom: 0.5rem;
    background-repeat: no-repeat;
    background-position: 0;
    padding-left: 32px;
}

.item-summary.octopus-script {
  background-image: url('img/step-script-template.png');
}

.item-summary.octopus-tentaclepackage {
  background-image: url('img/step-package-template.png');
}

.item-summary.octopus-email {
  background-image: url('img/step-email-template.png');
}

.item-summary.octopus-manual {
  background-image: url('img/step-manual-template.png');
}

.item-summary.octopus-azurecloudservice,
.item-summary.octopus-azurewebapp,
.item-summary.octopus-azurepowershell {
  background-image: url('img/step-azure-template.png');
}

.item-summary h4, .item-summary p {
    margin: 0;
}

.item-summary p {
    font-size: 0.6rem;
}


text:
package org.drools.core.util.debug;

import java.util.Stack;

import org.drools.common.NetworkNode;
import org.drools.core.util.ObjectHashSet;
import org.drools.reteoo.ObjectTypeNode;
import org.drools.reteoo.ObjectTypeNode.ObjectTypeNodeMemory;

public class ObjectTypeNodeVisitor extends AbstractNetworkNodeVisitor {

    public static final ObjectTypeNodeVisitor INSTANCE = new ObjectTypeNodeVisitor();

    protected ObjectTypeNodeVisitor() {
    }

    @Override
    protected void doVisit(NetworkNode node,
                           Stack<NetworkNode> nodeStack,
                           StatefulKnowledgeSessionInfo info) {
        ObjectTypeNode otn = (ObjectTypeNode) node;
        DefaultNodeInfo ni = (DefaultNodeInfo) info.getNodeInfo( node );
        ni.setMemoryEnabled( otn.isObjectMemoryEnabled() );

        if( otn.isObjectMemoryEnabled() ) {
            final ObjectHashSet memory = ((ObjectTypeNodeMemory) info.getSession().getNodeMemory( otn )).memory;
            ni.setFactMemorySize( memory.size() );
        }

    }

}


text:
<?php

namespace chegamos\entity;

use chegamos\util\Inflector;

class Place
{
    private $id = "";
    private $name = "";
    private $averageRating = 0;
    private $reviewCount = 0;
    private $category = null;
    private $address = null;
    private $point = null;
    private $mainUrl = "";
    private $iconUrl = "";
    private $otherUrl = "";
    private $smallPhotoUrl = "";
    private $mediumPhotoUrl = "";
    private $description = "";
    private $created = null;
    private $phone = null;
    private $placeInfo = null;
    private $reviews = null;
    private $photos = null;
    private $utilities;

    public function setId($id)
    {
        $this->id = $id;
    }

    public function getId()
    {
        return $this->id;
    }

    public function setName($name)
    {
        $this->name = Inflector::formatTitle($name);
    }

    public function getName()
    {
        return $this->name;
    }

    public function setCreated($created)
    {
        $this->created = $created;
    }

    public function getCreated()
    {
        return $this->created;
    }

    public function setPlaceInfo($placeInfo)
    {
        $this->placeInfo = $placeInfo;
    }

    public function getPlaceInfo()
    {
        return $this->placeInfo;
    }

    public function setPhone($phone)
    {
        $this->phone = $phone;
    }

    public function getPhone()
    {
        return $this->phone;
    }

    public function setDescription($description)
    {
        $this->description = $description;
    }

    public function getDescription()
    {
        return $this->description;
    }

    public function setAverageRating($averageRating)
    {
        $this->averageRating = $averageRating;
    }

    public function getAverageRating()
    {
        return $this->averageRating;
    }

    public function getAverageRatingString()
    {
        switch ($this->getAverageRating()) {
        case 1:
            return "Péssimo";
        case 2:
            return "Ruim";
        case 3:
            return "Regular";
        case 4:
            return "Bom";
        case 5:
            return "Excelente";
        default:
            return '';
            break;
        }
    }

    public function setReviewCount($reviewCount)
    {
        $this->reviewCount = $reviewCount;
    }

    public function getReviewCount()
    {
        return $this->reviewCount;
    }

    public function setCategory($category)
    {
        $this->category = $category;
    }

    public function getCategory()
    {
        return $this->category;
    }

    public function setAddress($address)
    {
        $this->address = $address;
    }

    public function getAddress()
    {
        return $this->address;
    }

    public function setPoint($point)
    {
        $this->point = $point;
    }

    public function getPoint()
    {
        return $this->point;
    }

    public function setMainUrl($mainUrl)
    {
        $this->mainUrl = $mainUrl;
    }

    public function getMainUrl()
    {
        return $this->mainUrl;
    }

    public function setOtherUrl($otherUrl)
    {
        $this->otherUrl = $otherUrl;
    }

    public function getOtherUrl()
    {
        return $this->otherUrl;
    }

    public function setIconUrl($iconUrl)
    {
        $this->iconUrl = $iconUrl;
    }

    public function getIconUrl()
    {
        return $this->iconUrl;
    }

    public function setReviews($reviews)
    {
        $this->reviews = $reviews;
    }

    public function getReviews()
    {
        return $this->reviews;
    }

    public function setPhotos($photos)
    {
        $this->photos = $photos;
    }

    public function getPhotos()
    {
        return $this->photos;
    }

    public function getShortPlaceUrl()
    {
        return ROOT_URL.'places/show/'.$this->getId();
    }

    public function getSmallPhotoUrl()
    {
        return $this->smallPhotoUrl;
    }

    public function setSmallPhotoUrl($smallPhotourl)
    {
        $this->smallPhotoUrl = $smallPhotourl;
    }

    public function getMediumPhotoUrl()
    {
        return $this->mediumPhotoUrl;
    }

    public function setMediumPhotoUrl($mediumPhotoUrl)
    {
        $this->mediumPhotoUrl = $mediumPhotoUrl;
    }

    public function setUtilities($utilities)
    {
        $this->utilities = $utilities;
    }

    public function getUtilities()
    {
        return $this->utilities;
    }

    public function getPlaceUrl()
    {
        $state = \strtolower($this->getAddress()->getCity()->getState());
        $state = \strtolower(Inflector::slug($state));
        $city = \strtolower($this->getAddress()->getCity()->getName());
        $city = \strtolower(Inflector::slug($city));
        $category = \strtolower(Inflector::slug($this->getCategory()));
        $name = \strtolower(Inflector::slug($this->getName()));
        $id = $this->getId();

        return ROOT_URL.$state.'/'.$city.'/'.
            $category.'/'.$name.'/'.$id.'.html';
    }

    public function getMapUrl()
    {
        if ($this->getPoint()->getLat() && $this->getPoint()->getLng()) {
            $mapUrl = "http://maplink.com.br/widget";

            $params = array();

            $params['v'] = '4.1';
            $params['lat'] = $this->getPoint()->getLat();
            $params['lng'] = $this->getPoint()->getLng();

            return $mapUrl.'?'.http_build_query($params);
        }

        return false;
    }

    public function getRouteUrl($location)
    {
        $routeUrl = "http://maps.google.com.br/m/directions";

        $params = array();

        $params['dirflg'] = 'd';

        $params['daddr'] = $this->address->getRouteAddress();

        if ($location->getAddress() instanceof Address) {
            $params['saddr'] = $location->getAddress()->getRouteAddress();
        }

        return $routeUrl.'?'.http_build_query($params);
    }
}


text: Repository whose only purpose is to test


text:
<?php

namespace Athletics\Make_Model\Twig\Extensions;

use Athletics\Make_Model\Config as Config;

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

/**
 * Twig Image Function
 *
 * To format requests for image sizes
 */
class ImageExtension extends \Twig_Extension {

	public function getName() {
		return 'image_extension';
	}

	public function getFunctions() {
		return array(
			new \Twig_SimpleFunction('image', array($this, 'image')),
		);
	}

	/**
	 * Format URL for Image sizes
	 *
	 * @param string $image
	 * @param array $size
	 * @return string $image
	 */
	public function image($image, $size = array()) {
		// no size, no need to add params
		if (empty($size)) {
			return $image;
		}

		// sanitize array keys
		if ( ! isset($size['width']) ) {
			$size['width'] = $size[0];
			unset($size[0]);
		}
		if ( count($size) === 2 && ! isset($size['height']) ) {
			$size['height'] = $size[1];
			unset($size[1]);
		}

		$datasource = Config::get('datasource');
		$datasource = ucfirst( strtolower($datasource) );

		switch ($datasource) {
			case 'Squarespace':
				$image = $this->_squarespace($image, $size);
				break;
		}

		return $image;
	}

	/**
	 * Squarespace
	 *
	 * @see http://developers.squarespace.com/using-the-imageloader/
	 * @param string $image
	 * @param array $size
	 * @return string $image
	 */
	private function _squarespace($image, $size) {
		if (count($size) === 2) {
			$width = $size['width'];
			$height = $size['height'];

			$image .= "?format={$width}x{$height}";
		}
		else {
			$image .= "?format={$size['width']}w";
		}

		return $image;
	}

}


text:
package user_test

import (
	"encoding/json"
	"net/http"
	"strings"
	"testing"

	"app/webapi/component"
	"app/webapi/internal/testrequest"
	"app/webapi/internal/testutil"
	"app/webapi/model"
	"app/webapi/store"

	"github.com/stretchr/testify/assert"
)

func TestDestroyAll(t *testing.T) {
	db, unique := testutil.LoadDatabase()
	core, _ := component.NewCoreMock(db)

	u := store.NewUser(core.DB, core.Q)
	_, err := u.Create("John", "Smith", "jsmith@example.com", "password")
	assert.Nil(t, err)

	w := testrequest.SendForm(t, core, "DELETE", "/v1/user", nil)

	r := new(model.OKResponse)
	err = json.Unmarshal(w.Body.Bytes(), &r.Body)
	assert.Nil(t, err)

	assert.Equal(t, http.StatusOK, w.Code)
	assert.Equal(t, "OK", r.Body.Status)
	assert.Equal(t, "users deleted", r.Body.Message)

	testutil.TeardownDatabase(unique)
}

func TestDestroyAllNoUsers(t *testing.T) {
	db, unique := testutil.LoadDatabase()
	core, _ := component.NewCoreMock(db)

	w := testrequest.SendForm(t, core, "DELETE", "/v1/user", nil)

	r := new(model.BadRequestResponse)
	err := json.Unmarshal(w.Body.Bytes(), &r.Body)
	assert.Nil(t, err)

	assert.Equal(t, http.StatusBadRequest, w.Code)
	assert.Equal(t, "Bad Request", r.Body.Status)
	assert.Equal(t, "no users to delete", r.Body.Message)

	testutil.TeardownDatabase(unique)
}

func TestDestroyValidation(t *testing.T) {
	for _, v := range []string{
		"DELETE /v1/user/1",
	} {
		db, unique := testutil.LoadDatabase()
		core, _ := component.NewCoreMock(db)

		arr := strings.Split(v, " ")

		w := testrequest.SendForm(t, core, arr[0], arr[1], nil)

		assert.Equal(t, http.StatusBadRequest, w.Code)

		testutil.TeardownDatabase(unique)
	}
}


text:
require 'rails_helper'

RSpec.describe Subscription, type: :model do

  describe "::ACCEPTED_CHARGE_OPTIONS" do
    it "defines a constant containing the accepted charge options" do
      expect(described_class.const_defined?(:ACCEPTED_CHARGE_OPTIONS)).to be_truthy
    end
  end

  describe "associations" do
    it{ is_expected.to belong_to :user }
    it{ is_expected.to belong_to :project }
    it{ is_expected.to belong_to :plan }
  end

  describe "validations" do
    let(:plan) { create(:plan, :with_credit_card) }
    let(:unpermitted_payment_subscription) { build(:subscription, :bank_billet_payment, plan: plan) }
    let(:permitted_payment_subscription) { build(:subscription, :credit_card_payment, plan: plan) }

    it { is_expected.to validate_presence_of(:status) }
    it { is_expected.to validate_presence_of(:charging_day) }
    it { is_expected.to validate_presence_of(:payment_method) }
    it { is_expected.to validate_presence_of(:plan_id) }
    it { is_expected.to validate_presence_of(:user_id) }
    it { is_expected.to validate_presence_of(:project_id) }

    context "when the locale is Portuguese" do
      before { I18n.locale = :pt }

      it { is_expected.to validate_presence_of(:donator_cpf).on(:create) }
    end

    context "when the locale is English" do
      before { I18n.locale = :en }

      it { is_expected.not_to validate_presence_of(:donator_cpf) }
    end

    it { is_expected.not_to allow_value(0).for(:charging_day) }
    it { is_expected.not_to allow_value(32).for(:charging_day) }

    describe "enumerators" do
      it "should define an enum for payment_method" do
        is_expected.to define_enum_for(:payment_method)
          .with([ :credit_card, :bank_billet ])
      end

      it "should define an enum for status" do
        is_expected.to define_enum_for(:status)
          .with([ :pending_payment, :paid, :unpaid, :canceled, :waiting_for_charging_day ])
      end
    end

    context "when the subscription is made with a plan's unpermitted payment type" do
      it "should be invalid" do
        expect(unpermitted_payment_subscription).to be_invalid
      end
    end

    context "when the payment_method is permitted by the plan" do
      it "should be valid" do
        expect(permitted_payment_subscription).to be_valid
      end
    end
  end

  describe ".accepted_charge_options" do
    let(:charge_options) do
      [
        Subscription.human_attribute_name('charge_options.indefinite'),
        Subscription.human_attribute_name('charge_options.for_three_months'),
        Subscription.human_attribute_name('charge_options.for_six_months'),
        Subscription.human_attribute_name('charge_options.for_a_year')
      ]
    end

    it "should return an array matching all the ACCEPTED_CHARGE_OPTIONS's constant keys" do
      expect(described_class.accepted_charge_options.keys).to match_array charge_options
    end
  end

  describe ".charging_day_reached" do
    let(:charging_date) { DateTime.current.change(day: 15) }
    let!(:subscriptions_scheduled_for_charging_date) do
      create_list(:subscription, 4, :waiting_for_charging_day, charging_day: 15)
    end

    before do
      create_list(:subscription, 5, :unpaid, charging_day: 15)
      create_list(:subscription, 3, :waiting_for_charging_day, charging_day: 13)
      create_list(:subscription, 3, :waiting_for_charging_day, charging_day: 18)
    end

    it "returns only waiting_for_charging_day subscriptions with the charging_day equals to the current day" do
      Timecop.freeze(charging_date) do
        expect(Subscription.charging_day_reached).to match_array subscriptions_scheduled_for_charging_date
      end
    end
  end

  describe "#available_for_canceling?" do
    let(:subscription) { build(:subscription, status) }

    context "status" do
      context "when :canceled" do
        let(:status) { :canceled }

        it { expect(subscription).to_not be_available_for_canceling }
      end

      [:paid, :unpaid, :pending_payment, :waiting_for_charging_day].each do |s|
        context "when :#{s}" do
          let(:status) { s }

          it { expect(subscription).to be_available_for_canceling }
        end
      end
    end
  end

  describe ".expired" do
    subject { Subscription.expired }

    context "when subject is paid" do
      context "and expires today" do
        let!(:subscription) { create(:subscription, :paid, expires_at: Date.current) }

        it { is_expected.to contain_exactly(subscription) }
      end

      context "and expired yesterday" do
        let!(:subscription) { create(:subscription, :paid, expires_at: Date.yesterday) }

        it { is_expected.to contain_exactly(subscription) }
      end

      context "and expires tomorrow" do
        before { create(:subscription, :paid, expires_at: Date.tomorrow) }

        it { is_expected.to be_empty }
      end

      context "and has no expires_at" do
        before { create(:subscription, :paid, expires_at: nil) }

        it { is_expected.to be_empty }
      end
    end

    context "when subject is not paid" do
      before do
        create(:subscription, :unpaid, expires_at: Date.current)
        create(:subscription, :waiting_for_charging_day, expires_at: Date.current)
        create(:subscription, :pending_payment, expires_at: Date.current)
        create(:subscription, :canceled, expires_at: Date.current)
      end

      it { is_expected.to be_empty }
    end
  end

  describe ".current_transaction" do
    let(:subscription) { create(:subscription) }

    subject { subscription.current_transaction }

    context "when the subscription has transactions" do
      let!(:transaction) { create(:transaction, subscription: subscription) }

      context "and there is a current transaction" do
        it "returns the current transaction" do
          current_transaction = create(:transaction, current: true, subscription: subscription)
          expect(subject).to eq current_transaction
        end
      end

      context "and there is no current transaction" do
        it { is_expected.to be_nil }
      end
    end

    context "when the subscription does not have transactions" do
      it { is_expected.to be_nil }
    end
  end

  describe ".charge_scheduled_for_today?" do
    let(:base_date) { DateTime.current.change(day: 15) }
    subject { subscription.charge_scheduled_for_today? }

    context "when the charging day is the same of the current day" do
      let(:subscription)  { build(:subscription, charging_day: base_date.day) }

      it "returns true" do
        Timecop.freeze(base_date) do
          expect(subject).to eq true
        end
      end
    end

    context "when the current day are different of the charging day" do
      let(:subscription)  { build(:subscription, charging_day: base_date.day + 1) }

      it { is_expected.to eq false }
    end
  end
end


text:
package com.discussion.portal.model.auth;

import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class UserAuthentication {

    @SerializedName("authorities")
    @Expose
    private List<Authority_> authorities = null;
    @SerializedName("details")
    @Expose
    private Details_ details;
    @SerializedName("authenticated")
    @Expose
    private Boolean authenticated;
    @SerializedName("principal")
    @Expose
    private String principal;
    @SerializedName("credentials")
    @Expose
    private String credentials;
    @SerializedName("name")
    @Expose
    private String name;

    public List<Authority_> getAuthorities() {
        return authorities;
    }

    public void setAuthorities(List<Authority_> authorities) {
        this.authorities = authorities;
    }

    public Details_ getDetails() {
        return details;
    }

    public void setDetails(Details_ details) {
        this.details = details;
    }

    public Boolean getAuthenticated() {
        return authenticated;
    }

    public void setAuthenticated(Boolean authenticated) {
        this.authenticated = authenticated;
    }

    public String getPrincipal() {
        return principal;
    }

    public void setPrincipal(String principal) {
        this.principal = principal;
    }

    public String getCredentials() {
        return credentials;
    }

    public void setCredentials(String credentials) {
        this.credentials = credentials;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}


text:
import ast
import re
from collections import OrderedDict, namedtuple
from typing import Any, Match

CallDescriptor = namedtuple('CallDescriptor', 'name args kwargs')
NON_PRINTABLE_PATTERN = re.compile('[\x00-\x1f]')

def safe_compile_text(txt: str, raises: bool = False) -> Any:
    """Generate actual objects from string representations. It internally uses
    python's ast (Abstract Syntax Trees), including support for safe 'calls',
    like in a repr of a datetime: `datetime.datetime(2017, 5, 20)`.
    Clearly uses this to convert params and results of the tasks, to be able to
    apply the advanced syntax coloring scheme seen on the Client.

    Other frameworks were not up to the task, as Clearly have some non-standard
    needs. I wanted a representation that could effectively be copied and pasted
    into a python REPL, without any changes and that would work! Which is a
    challenge to make it support arbitrary python objects...
    For example, on one hand Clearly have dicts which represent keyword arguments,
    and will show them just like a function or task would be called with, using the
    key=value notation. On the other hand, dicts in other roles would be rendered
    with the usual {key: value} notation!

    Also, it's worth saying that this is safe. I do not use "eval" command
    at all, which is potentially dangerous. This tool compiles the python
    objects received to an Abstract Syntax Tree, and recursively extracts
    the safe parts. Any calls or attribute lookups are returned as descriptors
    or strings, never being executed! And their parameters _will_ be analysed,
    and correctly syntax colored!

    Args:
        txt: the text
        raises: if True, raises an exception in case of error, ignores otherwise
    """

    def _convert(node):
        if isinstance(node, ast.Tuple):
            return tuple(map(_convert, node.elts))

        if isinstance(node, ast.List):
            return list(map(_convert, node.elts))

        if isinstance(node, ast.Set):
            return set(map(_convert, node.elts))

        if isinstance(node, ast.Dict):
            return OrderedDict((_convert(k), _convert(v))
                               for k, v in zip(node.keys, node.values))

        if isinstance(node, ast.Call):
            name = _convert(node.func)
            args = tuple(map(_convert, node.args))
            if name in ('tuple', 'list', 'set'):
                if len(node.args) > 1:
                    raise ValueError('{} takes at most 1 argument'.format(name))
                params = args[0] if node.args else ()
                return tuple(params) if name == 'tuple' else \
                    list(params) if name == 'list' else \
                    set(params)
            kwargs = OrderedDict((k.arg, _convert(k.value))
                                 for k in node.keywords)
            if name == 'dict':
                return kwargs
            return CallDescriptor(name,
                                  args if args else None,
                                  kwargs if kwargs else None)

        if isinstance(node, ast.Attribute):
            return '.'.join((node.value.id, node.attr))

        try:
            return ast.literal_eval(node)
        except ValueError:
            if isinstance(node, ast.Name):
                return node.id
            return 'unsupported: {}'.format(type(node))

    txt = NON_PRINTABLE_PATTERN.sub(_encode_to_hex, txt)
    try:
        txt = ast.parse(txt, mode='eval')
    except SyntaxError:
        if raises:
            raise
        return txt

    return _convert(txt.body)

def _encode_to_hex(match: Match) -> str:
    return r'\x{0:02x}'.format(ord(match.group()))


text:
<!--
Copyright (C) 2016-present Arctic Ice Studio <development@arcticicestudio.com>
Copyright (C) 2016-present Sven Greb <development@svengreb.de>

Project:    igloo
Repository: https://github.com/arcticicestudio/igloo
License:    MIT
-->
<keymap version="1" name="arctic-keymap-macos" parent="Mac OS X 10.5+">
  <action id="ChangesView.Move" />
  <action id="ChangesView.Revert" />
  <action id="CheckinProject" />
  <action id="ChooseDebugConfiguration" />
  <action id="ChooseRunConfiguration" />
  <action id="CodeGlance.toggle" />
  <action id="Console.TableResult.SelectRow" />
  <action id="Diff.FocusOppositePane" />
  <action id="Diff.FocusOppositePaneAndScroll" />
  <action id="Diff.NextChange">
    <keyboard-shortcut first-keystroke="shift meta close_bracket" />
  </action>
  <action id="Diff.PrevChange">
    <keyboard-shortcut first-keystroke="shift meta open_bracket" />
  </action>
  <action id="EditorDeleteToWordStart">
    <keyboard-shortcut first-keystroke="ctrl back_space" />
  </action>
  <action id="EditorNextWord">
    <keyboard-shortcut first-keystroke="ctrl right" />
  </action>
  <action id="EditorPreviousWord">
    <keyboard-shortcut first-keystroke="ctrl left" />
  </action>
  <action id="EditorSelectWord">
    <keyboard-shortcut first-keystroke="ctrl w" />
  </action>
  <action id="FindInPath">
    <keyboard-shortcut first-keystroke="shift meta f" />
    <keyboard-shortcut first-keystroke="shift ctrl f" />
  </action>
  <action id="GotoClass">
    <keyboard-shortcut first-keystroke="shift ctrl c" />
  </action>
  <action id="GotoFile">
    <keyboard-shortcut first-keystroke="shift ctrl g" />
  </action>
  <action id="GotoSymbol">
    <keyboard-shortcut first-keystroke="shift ctrl s" />
  </action>
  <action id="HideAllWindows">
    <keyboard-shortcut first-keystroke="ctrl alt d" />
  </action>
  <action id="Hotswap">
    <keyboard-shortcut first-keystroke="shift meta r" />
  </action>
  <action id="Jdbc.RunSqlScript" />
  <action id="MinimizeCurrentWindow" />
  <action id="NextTab">
    <keyboard-shortcut first-keystroke="ctrl tab" />
  </action>
  <action id="PreviousTab">
    <keyboard-shortcut first-keystroke="shift ctrl tab" />
  </action>
  <action id="QuickJavaDoc">
    <keyboard-shortcut first-keystroke="ctrl j" />
    <mouse-shortcut keystroke="control button2" />
    <keyboard-shortcut first-keystroke="ctrl q" />
  </action>
  <action id="RecentChangedFiles" />
  <action id="RecentFiles" />
  <action id="RenameElement">
    <keyboard-shortcut first-keystroke="ctrl alt r" />
  </action>
  <action id="ReplaceInPath">
    <keyboard-shortcut first-keystroke="shift ctrl r" />
  </action>
  <action id="RunClass" />
  <action id="RunDashboard.Run" />
  <action id="ShowBookmarks">
    <keyboard-shortcut first-keystroke="meta f3" />
    <keyboard-shortcut first-keystroke="shift meta m" />
  </action>
  <action id="ShowErrorDescription">
    <keyboard-shortcut first-keystroke="meta e" />
  </action>
  <action id="ShowIntentionActions">
    <keyboard-shortcut first-keystroke="shift space" />
  </action>
  <action id="SurroundWith">
    <keyboard-shortcut first-keystroke="ctrl alt s" />
  </action>
  <action id="Switcher" />
  <action id="TableResult.UnselectPreviousOccurrence" />
  <action id="ToggleBookmark">
    <keyboard-shortcut first-keystroke="meta m" />
  </action>
  <action id="UnselectPreviousOccurrence" />
  <action id="Vcs.MoveChangedLinesToChangelist" />
  <action id="Vcs.Push" />
  <action id="Vcs.QuickListPopupAction" />
  <action id="Vcs.RollbackChangedLines" />
  <action id="Vcs.ShowMessageHistory" />
  <action id="Vcs.UpdateProject" />
  <action id="VcsHistory.ShowAllAffected" />
</keymap>


text:
<!DOCTYPE html>

	<meta name="google-site-verification" content="lhtdM5EuGbCqa1e5q2FDrOTZQhAuOhi06JYWNTl8VVo" />
	<meta charset="UTF-8" />
	<meta name="viewport" content="width=device-width, user-scalable=no">
	<link rel="shortcut icon" href="https://www.stepaheadsolution.com/wp-content/uploads/2015/01/favicon.png" type="image/x-icon" />
	<title>ODL Login</title>

	<meta name="description" content="Step Ahead Solutions is a hybrid IT services provider delivering multiple services in cloud adoption, migration and computing."/>
	<link rel="canonical" href="https://www.stepaheadsolution.com/" />
	<meta property="og:locale" content="en_US" />
	<meta property="og:type" content="website" />
	<meta property="og:title" content="Hybrid IT Services - Step Ahead Solutions" />
	<meta property="og:description" content="Step Ahead Solutions is a hybrid IT services provider delivering multiple services in cloud adoption, migration and computing." />
	<meta property="og:url" content="https://www.stepaheadsolution.com/" />
	<meta property="og:site_name" content="Step Ahead Solution" />

	<link href='http://fonts.googleapis.com/css?family=Open+Sans:300,400' rel='stylesheet' type='text/css'>

	<link href="font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">

    <link href="css/bootstrap.min.css" rel="stylesheet">

    <link href="css/simple-sidebar.css" rel="stylesheet">

    <link href="css/login.css" rel="stylesheet">

	<link href="css/styleODL.css" rel="stylesheet">

		      <form class="form-signin" id="validate" autocomplete="on">

ODL Login

			        Email ID
			        <input type="email" id="inputEmail" class="form-control login-emailID" placeholder="Email ID" required autofocus>
			        Password
			        <input type="password" id="inputPassword" class="form-control login-password" placeholder="Password" required>

			            <input type="checkbox" value="remember-me"> Remember me

			        <button class="login-button" type="submit" onclick="location.href='ODLVault.html';">Sign in</button>

				        Register ·
				        Forgot password?

		      </form>

					© 2015 Step Ahead Solutions, Ins. All Rights Reserved

About us

Site Index

Contact Us

Safe Harbor & Privacy Policy

Core Values

Careers

Partners

Management

Press Room

Legal

Support

Terms of Use

Privacy

Copyright


text:
This talk revolves around profiling & optimization of Django applications. It aims at accreating performance by optimal usage of Django ORM, in-memory caching & handling resource intensive requests asynchronously using task queues such as Celery.

### Django Optimzations -- What to expect in this talk?

Many amateur developers who picks up Django write code which seems to work, but fails at scale.

Django has been made as a The web framework for perfectionists with deadlines, and perfection is often forgotten due to deadlines. In this talk, we'll discuss about common pitfalls to avoid while working on a Django based web application. The talk would revolve mostly around the following:

    - Profiling our web application to know exactly what queries are being executed on the database.
    - Making optimal use of Django ORM to avoid multiple queries to the database.
    - Usage of F objects, Q objects, prefetch_related, select_related et. all.
    Addressing n+1 queries problems to database with ORM.
    - Making use of Asynchronous requests to avoid creating a backlog for the request-response cycle. A little bit about task queues like Celery.
    - Caching: Different types of caches to use -- both django caching as well as something like in-memory Redis cache.

In the end we'll look at an overall architecture of entire Django web application including wsgi, nginx, caching and database layer. This would provide a starting point to write clean code and optimizing Django Applications to the audience

#### Find the [proposal here](https://cfp.pydelhi.org/pydelhi-conference-2017/proposals/optimizing-django-for-building-high-performance-systems~b68ne/)

This is made using [reveal.js](https://github.com/hakimel/reveal.js). I'm thankful to the creators of Reveal JS.


text:
"""
Test for the chocolatey module
"""

import os

import pytest

import salt.modules.chocolatey as chocolatey
import salt.utils
import salt.utils.platform
from tests.support.mock import MagicMock, patch

pytestmark = [
    pytest.mark.skipif(
        not salt.utils.platform.is_windows(), reason="Not a Windows system"
    )
]

@pytest.fixture(scope="module")
def choco_path():
    return "C:\\path\\to\\chocolatey.exe"

@pytest.fixture(scope="module")
def choco_path_pd():
    return os.path.join(
        os.environ.get("ProgramData"), "Chocolatey", "bin", "chocolatey.exe"
    )

@pytest.fixture(scope="module")
def choco_path_sd():
    return os.path.join(
        os.environ.get("SystemDrive"), "Chocolatey", "bin", "chocolatey.bat"
    )

@pytest.fixture(scope="module")
def mock_false():
    return MagicMock(return_value=False)

@pytest.fixture(scope="module")
def mock_true():
    return MagicMock(return_value=True)

@pytest.fixture()
def configure_loader_modules():
    return {chocolatey: {"__context__": {}, "__salt__": {}}}

def test__clear_context(choco_path):
    """
    Tests _clear_context function
    """
    context = {
        "chocolatey._yes": ["--yes"],
        "chocolatey._path": choco_path,
        "chocolatey._version": "0.9.9",
    }
    with patch.dict(chocolatey.__context__, context):
        chocolatey._clear_context()
        # Did it clear all chocolatey items from __context__P?
        assert chocolatey.__context__ == {}

def test__yes_context():
    """
    Tests _yes function when it exists in __context__
    """
    with patch.dict(chocolatey.__context__, {"chocolatey._yes": ["--yes"]}):
        result = chocolatey._yes()
        expected = ["--yes"]
        # Did it return correctly
        assert result == expected
        # Did it populate __context__
        assert chocolatey.__context__["chocolatey._yes"] == expected

def test__yes_version_greater():
    """
    Test _yes when Chocolatey version is greater than 0.9.9
    """
    mock_version = MagicMock(return_value="10.0.0")
    with patch("salt.modules.chocolatey.chocolatey_version", mock_version):
        result = chocolatey._yes()
        expected = ["--yes"]
        # Did it return correctly
        assert result == expected
        # Did it populate __context__
        assert chocolatey.__context__["chocolatey._yes"] == expected

def test__yes_version_less_than():
    """
    Test _yes when Chocolatey version is less than 0.9.9
    """
    mock_version = MagicMock(return_value="0.9.0")
    with patch("salt.modules.chocolatey.chocolatey_version", mock_version):
        result = chocolatey._yes()
        expected = []
        # Did it return correctly
        assert result == expected
        # Did it populate __context__
        assert chocolatey.__context__["chocolatey._yes"] == expected

def test__find_chocolatey_context(choco_path):
    """
    Test _find_chocolatey when it exists in __context__
    """
    with patch.dict(chocolatey.__context__, {"chocolatey._path": choco_path}):
        result = chocolatey._find_chocolatey()
        expected = choco_path
        assert result == expected

def test__find_chocolatey_which(choco_path):
    """
    Test _find_chocolatey when found with `cmd.which`
    """
    mock_which = MagicMock(return_value=choco_path)
    with patch.dict(chocolatey.__salt__, {"cmd.which": mock_which}):
        result = chocolatey._find_chocolatey()
        expected = choco_path
        # Does it return the correct path
        assert result == expected
        # Does it populate __context__
        assert chocolatey.__context__["chocolatey._path"] == expected

def test__find_chocolatey_programdata(mock_false, mock_true, choco_path_pd):
    """
    Test _find_chocolatey when found in ProgramData
    """
    with patch.dict(chocolatey.__salt__, {"cmd.which": mock_false}), patch(
        "os.path.isfile", mock_true
    ):
        result = chocolatey._find_chocolatey()
        expected = choco_path_pd
        # Does it return the correct path
        assert result == expected
        # Does it populate __context__
        assert chocolatey.__context__["chocolatey._path"] == expected

def test__find_chocolatey_systemdrive(mock_false, choco_path_sd):
    """
    Test _find_chocolatey when found on SystemDrive (older versions)
    """
    with patch.dict(chocolatey.__salt__, {"cmd.which": mock_false}), patch(
        "os.path.isfile", MagicMock(side_effect=[False, True])
    ):
        result = chocolatey._find_chocolatey()
        expected = choco_path_sd
        # Does it return the correct path
        assert result == expected
        # Does it populate __context__
        assert chocolatey.__context__["chocolatey._path"] == expected

def test_version_check_remote_false():
    """
    Test version when remote is False
    """
    list_return_value = {"ack": ["3.1.1"]}
    with patch.object(chocolatey, "list_", return_value=list_return_value):
        expected = {"ack": ["3.1.1"]}
        result = chocolatey.version("ack", check_remote=False)
        assert result == expected

def test_version_check_remote_true():
    """
    Test version when remote is True
    """
    list_side_effect = [
        {"ack": ["3.1.1"]},
        {"ack": ["3.1.1"], "Wolfpack": ["3.0.17"], "blackbird": ["1.0.79.3"]},
    ]
    with patch.object(chocolatey, "list_", side_effect=list_side_effect):
        expected = {"ack": {"available": ["3.1.1"], "installed": ["3.1.1"]}}
        result = chocolatey.version("ack", check_remote=True)
        assert result == expected

def test_version_check_remote_true_not_available():
    """
    Test version when remote is True but remote version is unavailable
    """
    list_side_effect = [
        {"ack": ["3.1.1"]},
        {"Wolfpack": ["3.0.17"], "blackbird": ["1.0.79.3"]},
    ]
    with patch.object(chocolatey, "list_", side_effect=list_side_effect):
        expected = {"ack": {"installed": ["3.1.1"]}}
        result = chocolatey.version("ack", check_remote=True)
        assert result == expected

def test_add_source(choco_path):
    """
    Test add_source when remote is False
    """
    cmd_run_all_mock = MagicMock(return_value={"retcode": 0, "stdout": "data"})
    cmd_run_which_mock = MagicMock(return_value=choco_path)
    with patch.dict(
        chocolatey.__salt__,
        {"cmd.which": cmd_run_which_mock, "cmd.run_all": cmd_run_all_mock},
    ):
        expected_call = [
            choco_path,
            "sources",
            "add",
            "--name",
            "source_name",
            "--source",
            "source_location",
        ]

        result = chocolatey.add_source("source_name", "source_location")
        cmd_run_all_mock.assert_called_with(expected_call, python_shell=False)

        expected_call = [
            choco_path,
            "sources",
            "add",
            "--name",
            "source_name",
            "--source",
            "source_location",
            "--priority",
            "priority",
        ]

        result = chocolatey.add_source(
            "source_name", "source_location", priority="priority"
        )
        cmd_run_all_mock.assert_called_with(expected_call, python_shell=False)


text:
"""
.. Copyright (c) 2014 Marshall Farrier
   license http://opensource.org/licenses/MIT

Data (:mod:`pynance.data`)
===============================================

.. currentmodule:: pynance.data

:mod:`pynance.data.combine`

:mod:`pynance.data.compare`

:mod:`pynance.data.feat`

:mod:`pynance.data.lab`

:mod:`pynance.data.prep`

:mod:`pynance.data.retrieve`
"""

from __future__ import absolute_import

__all__ = ["combine", "compare", "feat", "lab", "prep", "retrieve"]

# imported directly into data module
from . import combine
from .combine import *
from . import compare
from .compare import *
from . import prep
from .prep import *
from . import retrieve
from .retrieve import *

# imported as submodule
from . import feat
from . import lab


text:
require 'spec_helper'

describe "URL validation" do

  before(:all) do
    ActiveRecord::Schema.define(:version => 1) do

      create_table :users, :force => true do |t|
        t.column :homepage, :string
      end

    end
  end

  after(:all) do
    ActiveRecord::Base.connection.drop_table(:users)
  end

  context "with regular validator" do
    before do
      @user = User.new
    end

    it "should not allow nil as url" do
      @user.homepage = nil
      @user.should_not be_valid
    end

    it "should not allow blank as url" do
      @user.homepage = ""
      @user.should_not be_valid
    end

    it "should not allow an url without scheme" do
      @user.homepage = "www.example.com"
      @user.should_not be_valid
    end

    it "should allow an url with http" do
      @user.homepage = "http://localhost"
      @user.should be_valid
    end

    it "should allow an url with https" do
      @user.homepage = "https://localhost"
      @user.should be_valid
    end

    it "should not allow a url with an invalid scheme" do
      @user.homepage = "ftp://localhost"
      @user.should_not be_valid
    end

    it "should not allow a url with only a scheme" do
      @user.homepage = "http://"
      @user.should_not be_valid
    end

    it "should allow a url with an underscore" do
      @user.homepage = "http://foo_bar.com"
      @user.should be_valid
    end
  end

  context "with allow nil" do
    before do
      @user = UserWithNil.new
    end

    it "should allow nil as url" do
      @user.homepage = nil
      @user.should be_valid
    end

    it "should not allow blank as url" do
      @user.homepage = ""
      @user.should_not be_valid
    end

    it "should allow a valid url" do
      @user.homepage = "http://www.example.com"
      @user.should be_valid
    end

    it "should allow a url with an underscore" do
      @user.homepage = "http://foo_bar.com"
      @user.should be_valid
    end
  end

  context "with allow blank" do
    before do
      @user = UserWithBlank.new
    end

    it "should allow nil as url" do
      @user.homepage = nil
      @user.should be_valid
    end

    it "should allow blank as url" do
      @user.homepage = ""
      @user.should be_valid
    end

    it "should allow a valid url" do
      @user.homepage = "http://www.example.com"
      @user.should be_valid
    end

    it "should allow a url with an underscore" do
      @user.homepage = "http://foo_bar.com"
      @user.should be_valid
    end
  end

  context "with legacy syntax" do
    before do
      @user = UserWithLegacySyntax.new
    end

    it "should allow nil as url" do
      @user.homepage = nil
      @user.should be_valid
    end

    it "should allow blank as url" do
      @user.homepage = ""
      @user.should be_valid
    end

    it "should allow a valid url" do
      @user.homepage = "http://www.example.com"
      @user.should be_valid
    end

    it "should not allow invalid url" do
      @user.homepage = "random"
      @user.should_not be_valid
    end

    it "should allow a url with an underscore" do
      @user.homepage = "http://foo_bar.com"
      @user.should be_valid
    end
  end

  context "with ActiveRecord" do
    before do
      @user = UserWithAr.new
    end

    it "should not allow invalid url" do
      @user.homepage = "random"
      @user.should_not be_valid
    end
  end

  context "with ActiveRecord and legacy syntax" do
    before do
      @user = UserWithArLegacy.new
    end

    it "should not allow invalid url" do
      @user.homepage = "random"
      @user.should_not be_valid
    end
  end

  context "with regular validator and custom scheme" do
    before do
      @user = UserWithCustomScheme.new
    end

    it "should allow alternative URI schemes" do
      @user.homepage = "ftp://ftp.example.com"
      @user.should be_valid
    end
  end
end


text: <?php echo link_to(__('New Post', array(), 'messages'), 'aBlogAdmin/new', array(  'class' => 'a-btn big icon a-add',)) ?>


text:
Rails.application.routes.draw do
  devise_for :users

  root to: 'homes#show'

  require 'sidekiq/web'
  mount Sidekiq::Web => '/sidekiq'

  resources :test_jobs, only: [:create]
  resources :counters, only: [:destroy]
end


text:
[![Latest Version on Packagist][ico-version]][link-packagist]
[![Software License][ico-license]](LICENSE.md)
[![Build Status][ico-travis]][link-travis]
[![Total Downloads][ico-downloads]][link-downloads]

**Note:** Replace ```shawn sandy``` ```shawnsandy``` ```shawnsandy.com``` ```shawnsandy04@gmail.com``` ```shawnsandy``` ```simple_kit``` ```Simple desctriptiption``` with their correct values in [README.md](README.md), [CHANGELOG.md](CHANGELOG.md), [CONTRIBUTING.md](CONTRIBUTING.md), [LICENSE.md](LICENSE.md) and [composer.json](composer.json) files, then delete this line.

This is where your description should go. Try and limit it to a paragraph or two, and maybe throw in a mention of what
PSRs you support to avoid any confusion with users and contributors.

## Install

Via Composer

``` bash
$ composer require shawnsandy/simple_kit
```

## Usage

``` php
$skeleton = new League\Skeleton();
echo $skeleton->echoPhrase('Hello, League!');
```

## Change log

Please see [CHANGELOG](CHANGELOG.md) for more information what has changed recently.

## Testing

``` bash
$ composer test
```

## Contributing

Please see [CONTRIBUTING](CONTRIBUTING.md) and [CONDUCT](CONDUCT.md) for details.

## Security

If you discover any security related issues, please email shawnsandy04@gmail.com instead of using the issue tracker.

## Credits

- [shawn sandy][link-author]
- [All Contributors][link-contributors]

## License

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

[ico-version]: https://img.shields.io/packagist/v/shawnsandy/laravel-simple-pack.svg?style=flat-square
[ico-license]: https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square
[ico-travis]: https://img.shields.io/travis/LaravelToolKit/laravel-simple-pack/master.svg?style=flat-square
[ico-downloads]: https://img.shields.io/packagist/dt/shawnsandy/laravel-simple-pack.svg?style=flat-square

[link-packagist]: https://packagist.org/packages/shawnsandy/laravel-simple-pack
[link-travis]: https://travis-ci.org/LaravelToolKit/laravel-simple-pack
[link-downloads]: https://packagist.org/packages/shawnsandy/laravel-simple-pack
[link-author]: https://github.com/shawnsandy
[link-contributors]: ../../contributors


text:
#import <Foundation/Foundation.h>

@class PBMWebView;
@class PBMViewExposure;

NS_ASSUME_NONNULL_BEGIN

@protocol PBMExposureChangeDelegate <NSObject>

- (void)webView:(PBMWebView *)webView exposureChange:(PBMViewExposure *)viewExposure;
- (BOOL)shouldCheckExposure;

@end
NS_ASSUME_NONNULL_END


text:
<?php
/**
 * Created by PhpStorm.
 * User: hert
 * Date: 03.03.14
 * Time: 17:45
 */

namespace Tixi\ApiBundle\Interfaces\Management;

use Tixi\CoreDomain\DriverCategory;

/**
 * Class DriverCategoryAssembler
 * @package Tixi\ApiBundle\Interfaces
 */
class DriverCategoryAssembler {

    /**
     * @param DriverCategoryRegisterDTO $driverCategoryDTO
     * @return DriverCategory
     */
    public function registerDTOtoNewDriverCategory(DriverCategoryRegisterDTO $driverCategoryDTO) {
        $driverCategory = DriverCategory::registerDriverCategory(
            $driverCategoryDTO->name, $driverCategoryDTO->memo);
        return $driverCategory;
    }

    /**
     * @param DriverCategoryRegisterDTO $driverCategoryDTO
     * @param DriverCategory $driverCategory
     * @return DriverCategory
     */
    public function registerDTOtoDriverCategory(DriverCategoryRegisterDTO $driverCategoryDTO, DriverCategory $driverCategory) {
        $driverCategory->updateDriverCategoryData(
            $driverCategoryDTO->name, $driverCategoryDTO->memo);
        return $driverCategory;
    }

    /**
     * @param DriverCategory $driverCategory
     * @return DriverCategoryRegisterDTO
     */
    public function driverCategoryToDriverCategoryRegisterDTO(DriverCategory $driverCategory) {
        $driverCategoryDTO = new DriverCategoryRegisterDTO();
        $driverCategoryDTO->id = $driverCategory->getId();
        $driverCategoryDTO->name = $driverCategory->getName();
        $driverCategoryDTO->memo = $driverCategory->getMemo();
        return $driverCategoryDTO;
    }

    /**
     * @param $driverCategorys
     * @return array
     */
    public function driverCategorysToDriverCategoryListDTOs($driverCategorys) {
        $dtoArray = array();
        foreach ($driverCategorys as $driverCategory) {
            $dtoArray[] = $this->driverCategorysToDriverCategoryListDTO($driverCategory);
        }
        return $dtoArray;
    }

    /**
     * @param DriverCategory $driverCategory
     * @return DriverCategoryListDTO
     */
    public function driverCategorysToDriverCategoryListDTO(DriverCategory $driverCategory) {
        $driverCategoryEmbeddedListDTO = new DriverCategoryListDTO();
        $driverCategoryEmbeddedListDTO->id = $driverCategory->getId();
        $driverCategoryEmbeddedListDTO->name = $driverCategory->getName();
        return $driverCategoryEmbeddedListDTO;
    }

}


text:
template <typename ...Tp>
class AnimatedGroup
{
public:
    template <size_t I>
    using AnimatedElement = typename std::tuple_element<I, AnimatedTuple<Tp...>>::type::ValueType;

    AnimatedGroup(Tp... properties):
        m_properties(Animated<Tp>(properties)...)
    {}

    void tick(int32_t deltaTime)
    {
        iterateTick<0, Tp...>(m_properties, deltaTime);
    }

    void stop()
    {
        iterateStop<0, Tp...>(m_properties);
    }

    template <size_t I>
    void animate(AnimationPtr<AnimatedElement<I>> &&animation)
    {
        std::get<I>(m_properties).animate(std::move(animation));
    }

    template <size_t I>
    AnimatedElement<I> value() const
    {
        return std::get<I>(m_properties).value();
    }

private:
    AnimatedTuple<Tp...> m_properties;
};

#endif  // CORE_ANIMATEDGROUP_HPP_


text:
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var path = require('path');

module.exports = {
    devtool: 'source-map',
    entry: [
        './src/client.js'
    ],
    output: {
        path: path.join(__dirname, 'dist'),
        publicPath: '/',
        filename: 'client.[hash].js'
    },
    module: {
        loaders: [
            {
                test: /\.jsx?$/,
                loader: 'babel-loader',
                exclude: /node_modules/
            },
            {
                test: /\.css$/,
                loader: 'style-loader!css-loader!postcss-loader'
            },
            {
                test: /\.(jpe?g|png|gif)$/i,
                loaders: [
                    'file?hash=sha512&digest=hex&name=assets/images/[hash:base58:8].[ext]',
                    'image-webpack?bypassOnDebug&optimizationLevel=7&interlaced=false'
                ]
            },
            {
                test: /\.(woff|woff2)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
                loader: 'url-loader?limit=10000&mimetype=application/font-woff&name=assets/fonts/[name].[ext]'
            },
            {
                test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
                loader: 'file-loader?name=assets/fonts/[name].[ext]'
            }
        ]
    },
    postcss: function () {
        return [
            require('autoprefixer')(
                {
                    browsers: ['last 2 versions']
                }
            ),
            require('postcss-nested'),
            require('postcss-simple-vars'),
        ];
    },
    resolve: {
        modulesDirectories: ['node_modules', 'bower_components'],
        extensions: ['', '.js', '.jsx']
    },
    plugins: [
        new webpack.optimize.OccurenceOrderPlugin(),
        new webpack.NoErrorsPlugin(),
        new HtmlWebpackPlugin({
            title: 'Pekkis Goes To Movies',
            template: 'web/index.prod.html',
            favicon: 'web/favicon.ico',
            inject: 'body',
        }),
        new webpack.optimize.UglifyJsPlugin({
            'mangle': false,
            'compress': {
                /* eslint-disable camelcase */
                dead_code: true,  // discard unreachable code
                unsafe: false, // some unsafe optimizations (see below)
                unused: false, // drop unused variables/functions
                hoist_vars: false, // hoist variable declarations
                side_effects: false, // drop side-effect-free statements
                global_defs: {} // glob
                /* eslint-enable camelcase */
            }
        }),
        new webpack.NoErrorsPlugin(),
        new webpack.DefinePlugin({
            __DEVELOPMENT__: process.env.NODE_ENV === 'development',
            __DEVTOOLS__: false
        }),

    ]
};


text:
class User < ActiveRecord::Base

  has_secure_password

  has_many :trips
  has_many :future_trips

  validates :username, :email, presence: true
  validates :username, :email, uniqueness: true

end


text:
package com.rapid7.component.messaging.relay.amqp;

import java.io.IOException;
import java.util.Collection;

import com.rapid7.component.messaging.relay.encoding.MessageRelayEncoding.RelayControlMessage.EndpointType;

/**
 * A ControlMessageHandler concrete instance that intercepts encoded RelayControlMessage instances
 * and uses them to configure forwarding of queues and exchanges for a specific message retriever.
 * Any other messages (not of type RelayControlMessage) are forwarded to the supplied downstream
 * MessageHandler instance.
 */
public class ControlMessageProcessor extends ControlMessageHandler
{

   private BusMessageRetriever m_controlRetriever;

   /**
    * Create a ControlMessageHandler instance.
    * @param controlRetriever The BusMessageRetriever to configure.
    * handlers in a chain. Otherwise, filter out the message after it has been processed.
    */
   public ControlMessageProcessor(BusMessageRetriever controlRetriever)
   {
      super(false);
      m_controlRetriever = controlRetriever;
   }

   @Override
   protected void handleQueuePublishRequest(String queueName, boolean fullAck){
      try {
	m_controlRetriever.addTargetQueue(queueName,true,fullAck);
    } catch (IOException e) {
	System.err.println("Error while publishing relay target queue '" + queueName + "': " + e.getMessage());
    }
   }

   @Override
   protected void handleQueueUnpublishRequest(String queueName) {
      try {
	m_controlRetriever.removeTargetQueue(queueName,true);
    } catch (IOException e) {
	System.err.println("Error while removing relay target queue '" + queueName + "': " + e.getMessage());
    }
   }

   @Override
   protected void handleExchangePublishRequest(String exchangeName, EndpointType type,
         Collection<String> bindings, boolean fullAck) {
      try {
	m_controlRetriever.addTargetExchange(exchangeName,type, bindings, fullAck);
    } catch (IOException e) {
	System.err.println("Error while publishing relay target exchange '" + exchangeName + "': "
		+ e.getMessage());
    }
   }

   @Override
   protected void handleExchangeUnpublishRequest(String exchangeName,
         Collection<String> bindings) {
      try {
	m_controlRetriever.removeTargetExchange(exchangeName, bindings, true);
    } catch (IOException e) {
	System.err.println("Error while removing relay target exchange '" + exchangeName + "': "
		+ e.getMessage());
    }
   }

   @Override
   protected void handleUnpublishAllRequest() {
      try {
	m_controlRetriever.removeAllTargets(true);
    } catch (IOException e) {
	System.err.println("Error while removing all relay target endpoints.");
    }
   }

}


text:
module Sinatra
  module Soap
    class Wsdl

      @@actions = {}

      def self.actions
        @@actions
      end

      def self.register(name, *args, &block)
        @@actions[name] = {}
        args = args.pop || {}
        args.each do |key, value|
          @@actions[name][key] = value || {}
        end
        @@actions[name][:block] = block if block_given?
      end

      def self.generate
      end

      attr_accessor :action, :block, :arguments

      def initialize(action)
        data = all[action]
        raise Soap::Error, "Undefined Soap Action" if data.nil?
        @action = action
        @block = data[:block]
        @arguments = data.select {|k,v| k != :block}
      end

      def all
        @@actions
      end

    end
  end
end