text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.Collections;
using System.Data;
using Approve.EntityBase;
using Approve.Common;
using System.Data.SqlClient;
using Approve.RuleCenter;
using ProjectData;

public partial class JZDW_AppMain_FileUp : System.Web.UI.Page
{
    RCenter rq = new RCenter();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            btnSave.Attributes["onclick"] = "return check();";
            ShowFileType();
        }
    }
    private void ShowFileType()
    {
        ProjectDB db = new ProjectDB();

        string FPrjFileId = Request.QueryString["FPrjFileId"];
        lType.Text = db.getSysFileName(FPrjFileId);

        if (string.IsNullOrEmpty(lType.Text))
        {
            lType.Text = "附件";
        }

    }
    //保存
    private void saveInfo()
    {
        string FAppId = EConvert.ToString(Session["FAppId"]);
        if (!string.IsNullOrEmpty(Request.QueryString["FAppId"]))
        {
            FAppId = Request.QueryString["FAppId"];
        }

        pageTool tool = new pageTool(this.Page);

        if (string.IsNullOrEmpty(t_FUrl.Value))
        {
            tool.showMessage("请选择文件");
            return;
        }
        if (string.IsNullOrEmpty(t_FName.Text))
        {
            tool.showMessage("请填写附件名称");
            t_FName.Focus();
            return;
        }

        SaveOptionEnum so = SaveOptionEnum.Insert;
        SortedList sl = new SortedList();
        if (ViewState["FID"] != null)
        {
            so = SaveOptionEnum.Update;
            sl.Add("FID", ViewState["FID"]);
        }
        else
        {
            sl.Add("FID", Guid.NewGuid());
            sl.Add("FCreateTime", DateTime.Now);
            sl.Add("FIsdeleted", 0);
        }
        sl.Add("FPrjFileId", Request.QueryString["FPrjFileId"]);
        sl.Add("FAppId", FAppId);//业务ID
        sl.Add("FFileName", t_FName.Text);//文件名
        sl.Add("FFilePath", t_FUrl.Value);//文件地址
        sl.Add("FSize", t_FFileSize.Value);//文件大小
        sl.Add("FFileType", t_FFileType.Value);//文件类型
        sl.Add("FUserId", Request.QueryString["FUserId"]);//上传人(如果有的话。)
        if (rq.SaveEBase("CF_AppPrj_FileOther", sl, "FID", so))
        {
            ViewState["FID"] = sl["FID"].ToString();
            tool.showMessageAndRunFunction("保存成功", "window.returnValue=1;");
        }
        else
        {
            tool.showMessage("保存失败,请重试");
        }
    }

    //保存按钮
    protected void btnSave_Click(object sender, EventArgs e)
    {
        saveInfo();
    }

    //选择文件后返回刷新
    protected void btnQuery_Click(object sender, EventArgs e)
    {
        //附件url
        string str = t_FUrl.Value;
        //文件大小单位
        string n = "Byte";
        //文件大小
        float s = EConvert.ToInt(t_FFileSize.Value);
        if (s > 1024) { s = s / 1024; n = "KB"; }
        if (s > 1024) { s = s / 1024; n = "MB"; }
        //附件类型
        t_FFileType.Value = str.Split('.').ToList().Last();
        //附件文件名
        string m = str.Split('/').ToList().Last();
        name.Text = m + "(大小:" + s.ToString("0.0") + n + ")";
        if (string.IsNullOrEmpty(t_FName.Text))
        {
            t_FName.Text = m.Replace("." + m.Split('.').ToList().Last(), "");
        }
    }

    //添加下一个
    protected void btnNext_Click(object sender, EventArgs e)
    {
        ViewState["FID"] = null;
        t_FName.Text = "";//文件名
        t_FUrl.Value = "";//文件地址
        t_FFileSize.Value = "";//文件大小
        t_FFileType.Value = "";//文件类型
        name.Text = "";
    }
}


text:
var debug = require('debug')('nodemon');
var path = require('path');
var monitor = require('./monitor');
var cli = require('./cli');
var version = require('./version');
var util = require('util');
var utils = require('./utils');
var bus = utils.bus;
var help = require('./help');
var config = require('./config');
var spawn = require('./spawn');
var eventHandlers = {};

// this is fairly dirty, but theoretically sound since it's part of the
// stable module API
config.required = utils.isRequired;

function nodemon(settings) {
  nodemon.reset();

  // allow the cli string as the argument to nodemon, and allow for
  // `node nodemon -V app.js` or just `-V app.js`
  if (typeof settings === 'string') {
    settings = settings.trim();
    if (settings.indexOf('node') !== 0) {
      if (settings.indexOf('nodemon') !== 0) {
        settings = 'nodemon ' + settings;
      }
      settings = 'node ' + settings;
    }
    settings = cli.parse(settings);
  }

  // set the debug flag as early as possible to get all the detailed logging
  if (settings.verbose) {
    utils.debug = true;
  }

  if (settings.help) {
    console.log(help(settings.help));
    if (!config.required) {
      process.exit(0);
    }
  }

  if (settings.version) {
    version().then(function (v) {
      console.log(v);
      if (!config.required) {
        process.exit(0);
      }
    });
    return;
  }

  // nodemon tools like grunt-nodemon. This affects where
  // the script is being run from, and will affect where
  // nodemon looks for the nodemon.json files
  if (settings.cwd) {
    // this is protection to make sure we haven't dont the chdir already...
    // say like in cli/parse.js (which is where we do this once already!)
    if (process.cwd() !== path.resolve(config.system.cwd, settings.cwd)) {
      process.chdir(settings.cwd);
    }
  }

  config.load(settings, function (config) {
    if (!config.options.dump && !config.options.execOptions.script &&
      config.options.execOptions.exec === 'node') {
      if (!config.required) {
        console.log(help('usage'));
        process.exit();
      }
      return;
    }

    // before we print anything, update the colour setting on logging
    utils.colours = config.options.colours;

    // always echo out the current version
    utils.log.info(version.pinned);

    if (config.options.cwd) {
      utils.log.detail('process root: ' + process.cwd());
    }

    config.loaded.forEach(function (filename) {
      utils.log.detail('reading config ' + filename);
    });

    // echo out notices about running state
    if (config.options.stdin && config.options.restartable) {
      // allow nodemon to restart when the use types 'rs\n'
      process.stdin.resume();
      process.stdin.setEncoding('utf8');
      process.stdin.on('data', function (data) {
        data = (data + '').trim().toLowerCase();

        // if the keys entered match the restartable value, then restart!
        if (data === config.options.restartable) {
          bus.emit('restart');
        }
      });
    } else if (config.options.stdin) {
      // if 'restartable' is disabled (via a nodemon.json)
      // then it's possible we're being used with a REPL
      // so let's make sure we don't eat the key presses
      // but also, since we're wrapping, watch out for
      // special keys, like ctrl+c x 2 or '.exit' or ctrl+d
      var ctrlC = false;
      var buffer = '';

      process.stdin.on('data', function (data) {
        buffer += data;
        data = data.toString();
        var chr = data.charCodeAt(0);
        if (chr === 3) {
          if (ctrlC) {
            process.exit();
          }
          ctrlC = true;
        } else if (buffer === '.exit' || chr === 4) {
          process.exit();
        } else if (ctrlC || chr === 10) {
          ctrlC = false;
          buffer = '';
        }
      });
      process.stdin.setRawMode(true);
    }

    if (config.options.restartable) {
      utils.log.info('to restart at any time, enter `' +
        config.options.restartable + '`');
    }

    var none = function (v) {
      return v;
    };

    utils.log.detail('ignoring: ' + config.options.monitor.map(function (rule) {
      return rule.slice(0, 1) === '!' ? rule.slice(1) : false;
    }).filter(none).join(' '));

    utils.log.info('watching: ' + config.options.monitor.map(function (rule) {
      return rule.slice(0, 1) !== '!' ? rule : false;
    }).filter(none).join(' '));

    utils.log.detail('watching extensions: ' + config.options.execOptions.ext);

    if (config.options.dump) {
      utils.log._log('log', '--------------');
      utils.log._log('log', 'node: ' + process.version);
      utils.log._log('log', 'nodemon: ' + version.pinned);
      utils.log._log('log', 'command: ' + process.argv.join(' '));
      utils.log._log('log', 'cwd: ' + process.cwd());
      utils.log._log('log', ['OS:', process.platform, process.arch].join(' '));
      utils.log._log('log', '--------------');
      utils.log._log('log', util.inspect(config, { depth: null }));
      utils.log._log('log', '--------------');
      if (!config.required) {
        process.exit();
      }

    } else {
      config.run = true;

      if (config.options.stdout === false) {
        nodemon.on('start', function () {
          nodemon.stdout = bus.stdout;
          nodemon.stderr = bus.stderr;

          bus.emit('readable');
        });
      }

      if (config.options.events && Object.keys(config.options.events).length) {
        Object.keys(config.options.events).forEach(function (key) {
          utils.log.detail('bind ' + key + ' -> `' +
            config.options.events[key] + '`');
          nodemon.on(key, function () {
            if (config.options && config.options.events) {
              spawn(config.options.events[key], config,
                [].slice.apply(arguments));
            }
          });
        });
      }

      monitor.run(config.options);
    }
  });

  return nodemon;
}

nodemon.restart = function () {
  utils.log.status('restarting child process');
  bus.emit('restart');
  return nodemon;
};

nodemon.addListener = nodemon.on = function (event, handler) {
  if (!eventHandlers[event]) { eventHandlers[event] = []; }
  eventHandlers[event].push(handler);
  bus.on(event, handler);
  return nodemon;
};

nodemon.once = function (event, handler) {
  if (!eventHandlers[event]) { eventHandlers[event] = []; }
  eventHandlers[event].push(handler);
  bus.once(event, function () {
    debug('bus.once(%s)', event);
    eventHandlers[event].splice(eventHandlers[event].indexOf(handler), 1);
    handler.apply(this, arguments);
  });
  return nodemon;
};

nodemon.emit = function () {
  bus.emit.apply(bus, [].slice.call(arguments));
  return nodemon;
};

nodemon.removeAllListeners = function (event) {
  // unbind only the `nodemon.on` event handlers
  Object.keys(eventHandlers).filter(function (e) {
    return event ? e === event : true;
  }).forEach(function (event) {
    eventHandlers[event].forEach(function (handler) {
      bus.removeListener(event, handler);
      eventHandlers[event].splice(eventHandlers[event].indexOf(handler), 1);
    });
  });

  return nodemon;
};

nodemon.reset = function (done) {
  bus.emit('reset', done);
};

bus.on('reset', function (done) {
  debug('reset');
  nodemon.removeAllListeners();
  monitor.run.kill(true, function () {
    utils.reset();
    config.reset();
    config.run = false;
    if (done) {
      done();
    }
  });
});

// expose the full config
nodemon.config = config;

module.exports = nodemon;

redpajama_set_name: RedPajamaGithub


text:
@interface EmotionalShareBtnViewTests : XCTestCase

@property (strong, nonatomic) EmotionalShareBtnView *shareBtnView;

@end

@implementation EmotionalShareBtnViewTests

- (void)setUp {
    [super setUp];
    _shareBtnView = [[EmotionalShareBtnView alloc]initWithFrame:CGRectMake(0, 0, 210, 10)];
    typeof(self) bSelf = self;
    [_shareBtnView setCallback:^{
        [[NSNotificationCenter defaultCenter] postNotificationName:kNotification_ShareClick object:bSelf userInfo:nil];
    }];
}

- (void)tearDown {
    [super tearDown];
}

- (void)testShareButtonClick {
    [self expectationForNotification:kNotification_ShareClick
                              object:self
                             handler:^BOOL(NSNotification *notification) {
                                 if ([notification.name isEqualToString:kNotification_ShareClick]) {
                                     return YES;
                                 }
                                 return NO;
                             }];
    [_shareBtnView touchesEnded:nil withEvent:nil];
    [self waitForExpectationsWithTimeout:2 handler:^(NSError *error) {

    }];
}

@end


text:
package org.zaproxy.addon.spider;

import java.io.IOException;
import java.net.ConnectException;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;
import java.util.List;
import javax.net.ssl.SSLException;
import org.apache.commons.httpclient.URI;
import org.apache.commons.httpclient.URIException;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.parosproxy.paros.Constant;
import org.parosproxy.paros.control.Control;
import org.parosproxy.paros.db.DatabaseException;
import org.parosproxy.paros.extension.history.ExtensionHistory;
import org.parosproxy.paros.model.HistoryReference;
import org.parosproxy.paros.network.HttpHeader;
import org.parosproxy.paros.network.HttpHeaderField;
import org.parosproxy.paros.network.HttpMalformedHeaderException;
import org.parosproxy.paros.network.HttpMessage;
import org.parosproxy.paros.network.HttpRequestHeader;
import org.parosproxy.paros.network.HttpResponseHeader;
import org.zaproxy.addon.spider.filters.ParseFilter;
import org.zaproxy.addon.spider.filters.ParseFilter.FilterResult;
import org.zaproxy.addon.spider.parser.ParseContext;
import org.zaproxy.addon.spider.parser.SpiderParser;
import org.zaproxy.addon.spider.parser.SpiderResourceFound;

/** The SpiderTask representing a spidering task performed during the Spidering process. */
public class SpiderTask implements Runnable {

    /** The parent spider. */
    private Spider parent;

    /**
     * The history reference to the database record where the request message has been partially
     * filled in.
     *
     *
Might be {@code null} if failed to create or persist the message, if the task was already
     * executed or if a clean up was performed.
     *
     * @see #cleanup()
     * @see #deleteHistoryReference()
     * @see #prepareHttpMessage()
     */
    private HistoryReference reference;

    /** The spider resource found. */
    private SpiderResourceFound resourceFound;

    private ExtensionHistory extHistory;

    /** The Constant log. */
    private static final Logger log = LogManager.getLogger(SpiderTask.class);

    /**
     * Instantiates a new spider task using the target URI. The purpose of this task is to crawl the
     * given uri, using the provided method and supplied request headers, find any other uris in the
     * fetched resource and create other tasks.
     *
     *
The body of the request message is also provided in the {@literal requestBody} parameter
     * and will be used when fetching the resource from the specified uri.
     *
     * @param parent the spider controlling the crawling process
     * @param resourceFound the spider resource found
     * @param uri the uri that this task should process
     */
    public SpiderTask(Spider parent, SpiderResourceFound resourceFound, URI uri) {
        super();
        this.parent = parent;
        this.resourceFound = resourceFound;

        log.debug("New task submitted for uri: {}", uri);

        // Create a new HttpMessage that will be used for the request and persist it in the database
        // using HistoryReference
        try {
            HttpRequestHeader requestHeader =
                    new HttpRequestHeader(
                            resourceFound.getMethod(), uri, resourceFound.getHttpVersion());
            // Intentionally adding supplied request headers before the referer header
            // to prioritize "send referer header" option
            for (HttpHeaderField header : resourceFound.getHeaders()) {
                requestHeader.addHeader(header.getName(), header.getValue());
            }
            if (resourceFound.getMessage() != null
                    && parent.getSpiderParam().isSendRefererHeader()) {
                requestHeader.setHeader(
                        HttpRequestHeader.REFERER,
                        resourceFound.getMessage().getRequestHeader().getURI().toString());
            }
            HttpMessage msg = new HttpMessage(requestHeader);
            if (!resourceFound.getBody().isEmpty()) {
                msg.getRequestHeader().setContentLength(resourceFound.getBody().length());
                msg.setRequestBody(resourceFound.getBody());
            }
            this.reference =
                    new HistoryReference(
                            parent.getModel().getSession(), HistoryReference.TYPE_SPIDER_TASK, msg);
        } catch (HttpMalformedHeaderException e) {
            log.error("Error while building HttpMessage for uri: {}", uri, e);
        } catch (DatabaseException e) {
            log.error("Error while persisting HttpMessage for uri: {}", uri, e);
        }
    }

    @Override
    public void run() {
        try {
            if (reference == null) {
                log.warn("Null URI. Skipping crawling task: {}", this);
                return;
            }

            log.debug(
                    "Spider Task Started. Processing uri at depth {} using already constructed message: {}",
                    resourceFound.getDepth(),
                    reference.getURI());

            runImpl();
        } finally {
            parent.postTaskExecution();
            log.debug("Spider Task finished.");
        }
    }

    private void runImpl() {
        // Check if the should stop
        if (parent.isStopped()) {
            log.debug("Spider process is stopped. Skipping crawling task...");
            deleteHistoryReference();
            return;
        }

        // Check if the crawling process is paused and do any "before execution" processing
        parent.preTaskExecution();

        // Fetch the resource
        HttpMessage msg;
        try {
            msg = prepareHttpMessage();
        } catch (Exception e) {
            log.error("Failed to prepare HTTP message: ", e);
            return;
        }

        try {
            fetchResource(msg);
        } catch (Exception e) {
            setErrorResponse(msg, e);
            parent.notifyListenersSpiderTaskResult(
                    new SpiderTaskResult(msg, getSkippedMessage("ioerror")));
            return;
        }

        // Check if the should stop
        if (parent.isStopped()) {
            parent.notifyListenersSpiderTaskResult(
                    new SpiderTaskResult(msg, getSkippedMessage("stopped")));
            log.debug("Spider process is stopped. Skipping crawling task...");
            return;
        }
        // Check if the crawling process is paused
        parent.checkPauseAndWait();

        // Check the parse filters to see if the resource should be skipped from parsing
        FilterResult filterResult = FilterResult.NOT_FILTERED;
        boolean wanted = false;
        for (ParseFilter filter : parent.getController().getParseFilters()) {
            filterResult = filter.filtered(msg);
            if (filterResult.isFiltered()) {
                break;
            } else if (filterResult == FilterResult.WANTED) wanted = true;
        }
        if (!wanted && !filterResult.isFiltered()) {
            filterResult = parent.getController().getDefaultParseFilter().filtered(msg);
        }
        if (filterResult.isFiltered()) {
            log.debug(
                    "Resource [{}] fetched, but will not be parsed due to a ParseFilter rule: {}",
                    msg.getRequestHeader().getURI(),
                    filterResult.getReason());

            parent.notifyListenersSpiderTaskResult(
                    new SpiderTaskResult(msg, filterResult.getReason()));
            return;
        }

        // Check if the should stop
        if (parent.isStopped()) {
            parent.notifyListenersSpiderTaskResult(
                    new SpiderTaskResult(msg, getSkippedMessage("stopped")));
            log.debug("Spider process is stopped. Skipping crawling task...");
            return;
        }
        // Check if the crawling process is paused
        parent.checkPauseAndWait();

        int maxDepth = parent.getSpiderParam().getMaxDepth();
        if (maxDepth == SpiderParam.UNLIMITED_DEPTH || resourceFound.getDepth() < maxDepth) {
            parent.notifyListenersSpiderTaskResult(new SpiderTaskResult(msg));
            processResource(parent, resourceFound.getDepth(), msg);
        } else {
            parent.notifyListenersSpiderTaskResult(
                    new SpiderTaskResult(msg, getSkippedMessage("maxdepth")));
        }
    }

    private String getSkippedMessage(String key) {
        return parent.getExtensionSpider()
                .getMessages()
                .getString("spider.task.message.skipped." + key);
    }

    /**
     * Prepares the HTTP message to be sent to the target server.
     *
     *
The HTTP message is read from the database and set up with common headers (e.g.
     * User-Agent) and properties (e.g. user).
     *
     * @return the HTTP message
     * @throws HttpMalformedHeaderException if an error occurred while parsing the HTTP message read
     *     from the database
     * @throws DatabaseException if an error occurred while reading the HTTP message from the
     *     database
     */
    private HttpMessage prepareHttpMessage()
            throws HttpMalformedHeaderException, DatabaseException {
        // Build fetch the request message from the database
        HttpMessage msg;
        try {
            msg = reference.getHttpMessage();
            // HistoryReference is about to be deleted, so no point keeping referencing it.
            msg.setHistoryRef(null);
        } finally {
            deleteHistoryReference();
        }

        msg.getRequestHeader().setHeader(HttpHeader.IF_MODIFIED_SINCE, null);
        msg.getRequestHeader().setHeader(HttpHeader.IF_NONE_MATCH, null);

        // Check if there is a custom user agent
        if (parent.getSpiderParam().getUserAgent() != null) {
            msg.getRequestHeader()
                    .setHeader(HttpHeader.USER_AGENT, parent.getSpiderParam().getUserAgent());
        }

        // Check if there's a need to send the message from the point of view of a User
        if (parent.getScanUser() != null) {
            msg.setRequestingUser(parent.getScanUser());
        }
        return msg;
    }

    /**
     * Deletes the history reference, should be called when no longer needed.
     *
     *
The call to this method has no effect if the history reference no longer exists (i.e.
     * {@code null}).
     *
     * @see #reference
     */
    private void deleteHistoryReference() {
        if (reference == null) {
            return;
        }

        if (getExtensionHistory() != null) {
            getExtensionHistory().delete(reference);
            reference = null;
        }
    }

    private void setErrorResponse(HttpMessage msg, Exception cause) {
        StringBuilder strBuilder = new StringBuilder(250);
        if (cause instanceof SSLException) {
            strBuilder.append(Constant.messages.getString("network.ssl.error.connect"));
            strBuilder.append(msg.getRequestHeader().getURI().toString()).append('\n');
            strBuilder
                    .append(Constant.messages.getString("network.ssl.error.exception"))
                    .append(cause.getMessage())
                    .append('\n');
            strBuilder
                    .append(Constant.messages.getString("network.ssl.error.exception.rootcause"))
                    .append(ExceptionUtils.getRootCauseMessage(cause))
                    .append('\n');
            strBuilder.append(
                    Constant.messages.getString(
                            "network.ssl.error.help",
                            Constant.messages.getString("network.ssl.error.help.url")));

            strBuilder.append("\n\nStack Trace:\n");
            for (String stackTraceFrame : ExceptionUtils.getRootCauseStackTrace(cause)) {
                strBuilder.append(stackTraceFrame).append('\n');
            }
        } else {
            strBuilder
                    .append(cause.getClass().getName())
                    .append(": ")
                    .append(cause.getLocalizedMessage())
                    .append("\n\nStack Trace:\n");
            for (String stackTraceFrame : ExceptionUtils.getRootCauseStackTrace(cause)) {
                strBuilder.append(stackTraceFrame).append('\n');
            }
        }

        String message = strBuilder.toString();

        HttpResponseHeader responseHeader;
        try {
            responseHeader = new HttpResponseHeader("HTTP/1.1 400 ZAP IO Error");
            responseHeader.setHeader(HttpHeader.CONTENT_TYPE, "text/plain; charset=UTF-8");
            responseHeader.setHeader(
                    HttpHeader.CONTENT_LENGTH,
                    Integer.toString(message.getBytes(StandardCharsets.UTF_8).length));
            msg.setResponseHeader(responseHeader);
            msg.setResponseBody(message);
        } catch (HttpMalformedHeaderException e) {
            log.error("Failed to create error response:", e);
        }
    }

    /**
     * Process a resource, searching for links (uris) to other resources.
     *
     * @param message the HTTP Message
     */
    static void processResource(Spider parent, int depth, HttpMessage message) {
        List<SpiderParser> parsers = parent.getController().getParsers();

        // Get the full path of the file
        String path = null;
        try {
            path = message.getRequestHeader().getURI().getPath();
        } catch (URIException e) {
        } finally {
            // Handle null paths.
            if (path == null) path = "";
        }

        ParseContext ctx =
                new ParseContext(
                        parent.getSpiderParam(),
                        parent.getExtensionSpider().getValueGenerator(),
                        message,
                        path,
                        depth);
        boolean alreadyConsumed = false;
        for (SpiderParser parser : parsers) {
            if (parser.canParseResource(ctx, alreadyConsumed)) {
                log.debug("Parser {} can parse resource '{}'", parser, path);
                if (parser.parseResource(ctx)) {
                    alreadyConsumed = true;
                }
            } else {
                log.debug("Parser {} cannot parse resource '{}'", parser, path);
            }
        }
    }

    private ExtensionHistory getExtensionHistory() {
        if (this.extHistory == null) {
            this.extHistory =
                    Control.getSingleton()
                            .getExtensionLoader()
                            .getExtension(ExtensionHistory.class);
        }
        return this.extHistory;
    }

    /**
     * Fetches a resource.
     *
     * @param msg the HTTP message that will be sent to the server
     * @throws IOException Signals that an I/O exception has occurred.
     */
    private void fetchResource(HttpMessage msg) throws IOException {
        if (parent.getHttpSender() == null) {
            return;
        }

        try {
            parent.getHttpSender().sendAndReceive(msg);
        } catch (ConnectException e) {
            log.debug("Failed to connect to: {}", msg.getRequestHeader().getURI(), e);
            throw e;
        } catch (SocketTimeoutException e) {
            log.debug("Socket timeout: {}", msg.getRequestHeader().getURI(), e);
            throw e;
        } catch (SocketException e) {
            log.debug("Socket exception: {}", msg.getRequestHeader().getURI(), e);
            throw e;
        } catch (UnknownHostException e) {
            log.debug("Unknown host: {}", msg.getRequestHeader().getURI(), e);
            throw e;
        } catch (Exception e) {
            log.error(
                    "An error occurred while fetching the resource [{}]: {}",
                    msg.getRequestHeader().getURI(),
                    e.getMessage(),
                    e);
            throw e;
        }
    }

    /**
     * Cleans up the resources used by the task.
     *
     *
Should be called if the task was not executed.
     */
    void cleanup() {
        deleteHistoryReference();
    }
}


text:
using NUnit.Framework;

namespace IronVelocity.Tests.TemplateExecution
{
    [TestFixture(StaticTypingMode.AsProvided)]
    [TestFixture(StaticTypingMode.PromoteContextToGlobals)]
    public class PrecedenceTests : TemplateExeuctionBase
    {
        public PrecedenceTests(StaticTypingMode mode) : base(mode)
        {
        }

        [TestCase("true || true && false", true, TestName = "when_ExecutingAnExpression_AndHasHigherPrecedenceThanOr")]
        [TestCase("false && true || true ", true, TestName = "when_ExecutingAnExpression_AndHasHigherPrecedenceThanOr")]
        [TestCase("false && false == false", false, TestName = "when_ExecutingAnExpression_EqualityHasHigherPrecedenceThanAnd")]
        [TestCase("false == true > false", false, TestName = "when_ExecutingAnExpression_RelationalHasHigherPrecedenceThanEquality")]
        [TestCase("1 > 2 + 3", false, TestName = "when_ExecutingAnExpression_AdditiveHasHigherPrecedenceThanRelational")]
        [TestCase("1 + 2 * 5", 11, TestName = "when_ExecutingAnExpression_MultiplicativeHasHigherPrecedenceThanAdditive")]

        //The following are the same expressions as above, but using parentheses to ensure the first operator is performed first
        //These should all give different results to above
        [TestCase("(true || true) && false", false, TestName = "when_ExecutingAnExpression_ParenthesiedExpressionHasHigherPrecedence1")]
        [TestCase("(false && false) == false", true, TestName = "when_ExecutingAnExpression_ParenthesiedExpressionHasHigherPrecedence2")]
        [TestCase("(false == true) > false", null, TestName = "when_ExecutingAnExpression_ParenthesiedExpressionHasHigherPrecedence3")]
        [TestCase("(1 > 2) + 3", null, TestName = "when_ExecutingAnExpression_ParenthesiedExpressionHasHigherPrecedence4")]
        [TestCase("(1 + 2) * 5", 15, TestName = "when_ExecutingAnExpression_ParenthesiedExpressionHasHigherPrecedence5")]
        public void Test(string input, object expected)
        {
            var result = EvaluateExpression(input);
            Assert.That(result, Is.EqualTo(expected));
        }

    }
}


text:
'use strict';

angular.module('patrons').controller('PatronsController', ['$scope', '$stateParams', '$location', 'Authentication', 'Patrons',
	function($scope, $stateParams, $location, Authentication, Patrons) {
		$scope.authentication = Authentication;

		$scope.create = function() {
			var patron = new Patrons({
				title: this.title,
				content: this.content
			});
			patron.$save(function(response) {
				$location.path('patrons/' + response._id);
			}, function(errorResponse) {
				$scope.error = errorResponse.data.message;
			});

			this.title = '';
			this.content = '';
		};

		$scope.remove = function(patron) {
			if (patron) {
				patron.$remove();

				for (var i in $scope.patrons) {
					if ($scope.patrons[i] === patron) {
						$scope.patrons.splice(i, 1);
					}
				}
			} else {
				$scope.patron.$remove(function() {
					$location.path('patrons');
				});
			}
		};

		$scope.update = function() {
			var patron = $scope.patron;

			patron.$update(function() {
				$location.path('patrons/' + patron._id);
			}, function(errorResponse) {
				$scope.error = errorResponse.data.message;
			});
		};

		$scope.find = function() {
			$scope.patrons = Patrons.query();
		};

		$scope.findOne = function() {
			$scope.patron = Patrons.get({
				patronId: $stateParams.patronId
			});
		};
	}
]);


text:
using Xamarin.Forms;
using Plugin.Connectivity;

namespace NetStatus {
	public partial class App : Application {
		public App()
		{
			InitializeComponent();

			setNetworkStatus();
		}

		protected override void OnStart()
		{
			CrossConnectivity.Current.ConnectivityChanged += (sender, e) => {
				setNetworkStatus();
			};
		}

		protected override void OnSleep()
		{
			// Handle when your app sleeps
		}

		protected override void OnResume()
		{
			// Handle when your app resumes
		}

		void setNetworkStatus()
		{
			if (CrossConnectivity.Current != null && CrossConnectivity.Current.IsConnected) {
				MainPage = new NetworkViewPage();
			} else {
				MainPage = new NoNetworkPage();
			}

		}
	}
}


text:
<?php

// $Id$

require_once('../../../../boot.inc.php');
boot('my_site_adm');

require_once($WSC->get_site_inc_dir().'modules/tangra_cms/pages/vpage/vpage_template_del_wp.class.php');

session_start();

global $_MODULES_REGISTER;
$user_auth_config = $_MODULES_REGISTER->get_module_config('admin_user_auth');

$page = new VPage_Template_Del_WP('vpage_template_del', $user_auth_config);
$SITE->run($page, new Web_Context);


text:
require "minitest/autorun"
require "irs527"
require "date"
require "csv"
require "pry"
class TestFormList < MiniTest::Test
  def setup
    @form_list = Irs527::Utility.generate_index("test/sample.txt", "test/sample.csv")
    @csv = CSV.read("test/sample.csv", "r")
    @query = @form_list.query("371401847")
  end

  def test_name_of_org_matches_index
    assert @form_list["454919869"][:name] == @csv[0][1]
  end

  def test_form_list_loads_correctly
    assert_instance_of Irs527::FormList, Irs527::FormList.load("test/sample.csv", "test/sample.txt")
  end

  def test_proc_objects_return_form_8871_objects_when_called
    forms = @form_list["454919869"][:forms][:form_8871].map { |form| form.call }
    assert forms.all? { |form| form.is_a?(Irs527::Form8871) }
  end

  def test_proc_objects_return_form_8872_objects_when_called
    forms = @form_list["371401847"][:forms][:form_8872].map { |form| form.call }
    assert forms.all? { |form| form.is_a?(Irs527::Form8872) }
  end

  def test_query_object_gets_created
    assert_instance_of Irs527::Query, @query
  end

  def test_names_returns_hash_of_orgs_and_eins
    assert @form_list.names[0] == { ein: "454919869", name: "BOB SQUERI FOR DISTRICT 7 SUPERVISOR 2012" }
    assert @form_list.names[1] == { ein: "593417598", name: "Florida Chamber of Commerce CCE" }
  end
end


text:
#include <aws/codecommit/model/BatchAssociateApprovalRuleTemplateWithRepositoriesError.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::Utils::Json;
using namespace Aws::Utils;

namespace Aws
{
namespace CodeCommit
{
namespace Model
{

BatchAssociateApprovalRuleTemplateWithRepositoriesError::BatchAssociateApprovalRuleTemplateWithRepositoriesError() :
    m_repositoryNameHasBeenSet(false),
    m_errorCodeHasBeenSet(false),
    m_errorMessageHasBeenSet(false)
{
}

BatchAssociateApprovalRuleTemplateWithRepositoriesError::BatchAssociateApprovalRuleTemplateWithRepositoriesError(JsonView jsonValue) :
    m_repositoryNameHasBeenSet(false),
    m_errorCodeHasBeenSet(false),
    m_errorMessageHasBeenSet(false)
{
  *this = jsonValue;
}

BatchAssociateApprovalRuleTemplateWithRepositoriesError& BatchAssociateApprovalRuleTemplateWithRepositoriesError::operator =(JsonView jsonValue)
{
  if(jsonValue.ValueExists("repositoryName"))
  {
    m_repositoryName = jsonValue.GetString("repositoryName");

    m_repositoryNameHasBeenSet = true;
  }

  if(jsonValue.ValueExists("errorCode"))
  {
    m_errorCode = jsonValue.GetString("errorCode");

    m_errorCodeHasBeenSet = true;
  }

  if(jsonValue.ValueExists("errorMessage"))
  {
    m_errorMessage = jsonValue.GetString("errorMessage");

    m_errorMessageHasBeenSet = true;
  }

  return *this;
}

JsonValue BatchAssociateApprovalRuleTemplateWithRepositoriesError::Jsonize() const
{
  JsonValue payload;

  if(m_repositoryNameHasBeenSet)
  {
   payload.WithString("repositoryName", m_repositoryName);

  }

  if(m_errorCodeHasBeenSet)
  {
   payload.WithString("errorCode", m_errorCode);

  }

  if(m_errorMessageHasBeenSet)
  {
   payload.WithString("errorMessage", m_errorMessage);

  }

  return payload;
}

} // namespace Model
} // namespace CodeCommit
} // namespace Aws


text:
namespace glimac {

SDLWindowManager::SDLWindowManager(uint32_t width, uint32_t height, const char* title) {
    if(0 != SDL_Init(SDL_INIT_VIDEO)) {
        std::cerr << SDL_GetError() << std::endl;
        return;
    }
    if(!SDL_SetVideoMode(width, height, 32, SDL_OPENGL)) {
        std::cerr << SDL_GetError() << std::endl;
        return;
    }
    SDL_WM_SetCaption(title, nullptr);
}

SDLWindowManager::~SDLWindowManager() {
    SDL_Quit();
}

bool SDLWindowManager::pollEvent(SDL_Event& e) {
    return SDL_PollEvent(&e);
}

bool SDLWindowManager::isKeyPressed(SDLKey key) const {
    return SDL_GetKeyState(nullptr)[key];
}

// button can SDL_BUTTON_LEFT, SDL_BUTTON_RIGHT and SDL_BUTTON_MIDDLE
bool SDLWindowManager::isMouseButtonPressed(uint32_t button) const {
    return SDL_GetMouseState(nullptr, nullptr) & SDL_BUTTON(button);
}

glm::ivec2 SDLWindowManager::getMousePosition() const {
    glm::ivec2 mousePos;
    SDL_GetMouseState(&mousePos.x, &mousePos.y);
    return mousePos;
}

void SDLWindowManager::swapBuffers() {
    SDL_GL_SwapBuffers();
}

float SDLWindowManager::getTime() const {
    return 0.001f * SDL_GetTicks();
}

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;

namespace BehaviorLibrary.Components.Decorators
{
    public class Inverter : BehaviorComponent
    {

        private BehaviorComponent _Behavior;

        /// <summary>
        /// inverts the given behavior
        /// -Returns Success on Failure or Error
        /// -Returns Failure on Success
        /// -Returns Running on Running
        /// </summary>
        /// <param name="behavior"></param>
        public Inverter(BehaviorComponent behavior)
        {
            _Behavior = behavior;
        }

        /// <summary>
        /// performs the given behavior
        /// </summary>
        /// <returns>the behaviors return code</returns>
        public override BehaviorReturnCode Behave()
        {
            try
            {
                switch (_Behavior.Behave())
                {
                    case BehaviorReturnCode.Failure:
                        ReturnCode = BehaviorReturnCode.Success;
                        return ReturnCode;
                    case BehaviorReturnCode.Success:
                        ReturnCode = BehaviorReturnCode.Failure;
                        return ReturnCode;
                    case BehaviorReturnCode.Running:
                        ReturnCode = BehaviorReturnCode.Running;
                        return ReturnCode;
                }
            }
            catch (Exception e)
            {
				if (Debug.isDebugBuild) {
					Debug.Log(e.ToString());
				}
                ReturnCode = BehaviorReturnCode.Success;
                return ReturnCode;
            }

            ReturnCode = BehaviorReturnCode.Success;
            return ReturnCode;

        }

    }
}


text:
<!DOCTYPE html>

This is articles

This is articles with GitHub Pages.


text:
package com.hellokoding.auth.service;

import java.util.List;

import com.hellokoding.auth.model.Customer;

public interface CustomerService {
	void save(Customer brand);

	public List<Customer> getAllCustomer();
	public List<Customer> findByMobile(String name);

	public Customer findCustomerById(Long id);

}


text:
<?php

namespace Kdyby\Translation\Dumper;

use Nette\Neon\Neon;
use Symfony\Component\Translation\MessageCatalogue;

/**
 * Generates Neon files from a message catalogue.
 */
class NeonFileDumper extends \Symfony\Component\Translation\Dumper\FileDumper
{

	use \Kdyby\StrictObjects\Scream;

	/**
	 * {@inheritDoc}
	 */
	public function formatCatalogue(MessageCatalogue $messages, $domain, array $options = [])
	{
		return Neon::encode($messages->all($domain), Neon::BLOCK);
	}

	/**
	 * {@inheritDoc}
	 */
	protected function format(MessageCatalogue $messages, $domain)
	{
		return Neon::encode($messages->all($domain), Neon::BLOCK);
	}

	/**
	 * {@inheritDoc}
	 */
	protected function getExtension()
	{
		return 'neon';
	}

}


text:
package testutils

import (
	"flag"
	"io/ioutil"
	"testing"

	"github.com/GoogleCloudPlatform/k8s-config-connector/pkg/test"

	"github.com/google/go-cmp/cmp"
)

var update = flag.Bool("update", false, "update .golden files")

func VerifyContentsMatch(t *testing.T, actualBytes []byte, expectedFilePath string) {
	if *update {
		ioutil.WriteFile(expectedFilePath, actualBytes, 0644)
	}
	expectedBytes, err := ioutil.ReadFile(expectedFilePath)
	if err != nil {
		t.Fatalf("error reading file '%v': %v", expectedFilePath, err)
	}
	expectedBytes = []byte(test.TrimLicenseHeaderFromYaml(string(expectedBytes)))
	diff := cmp.Diff(actualBytes, expectedBytes)
	if diff != "" {
		t.Logf("actual value:\n%v", string(actualBytes))
		t.Logf("expected value:\n%v", string(expectedBytes))
		t.Logf("actual value does not match expected value in '%v'", expectedFilePath)
		t.Fatalf("diff: %v", diff)
	}
}


text: A web apge to display my work in different mediums. Video, photo, audio, web.


text:
from openstackx.api import base
from openstackx import compute # fixme import from jacobian

class Flavor(compute.Flavor):
    def __repr__(self):
        return "<Flavor: %s>" % self.name

    def delete(self, purge=False):
        self.manager.delete(self.id, purge)

#    @property
#    def memory_mb(self):
#        return self._info['memory_mb']

class FlavorManager(compute.FlavorManager):
    resource_class = Flavor

    def create(self, name, memory_mb, vcpus, local_gb, flavorid,
               swap=0, rxtx_quota=0, rxtx_cap=0):

        body = {}
        body['flavor'] = {}
        body['flavor']['name'] = name
        body['flavor']['memory_mb'] = memory_mb
        body['flavor']['vcpus'] = vcpus
        body['flavor']['local_gb'] = local_gb
        body['flavor']['flavorid'] = flavorid
        body['flavor']['swap'] = swap
        body['flavor']['rxtx_quota'] = rxtx_quota
        body['flavor']['rxtx_cap'] = rxtx_cap

        return self._create('/admin/flavors', body, "flavor")

    def delete(self, id, purge=False):
        self._delete("/admin/flavors/%s?purge=%s" % (id, purge))

    def list(self):
        """
        Get a list of all flavors.

        :rtype: list of :class:`Flavor`.
        """
        return self._list("/admin/flavors", "flavors")


text:
package org.apache.ambari.server.serveraction.upgrades;

import static org.easymock.EasyMock.anyLong;
import static org.easymock.EasyMock.anyObject;
import static org.easymock.EasyMock.anyString;
import static org.easymock.EasyMock.createNiceMock;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.replay;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import javax.persistence.EntityManager;

import org.apache.ambari.server.H2DatabaseCleaner;
import org.apache.ambari.server.Role;
import org.apache.ambari.server.RoleCommand;
import org.apache.ambari.server.actionmanager.ExecutionCommandWrapper;
import org.apache.ambari.server.actionmanager.ExecutionCommandWrapperFactory;
import org.apache.ambari.server.actionmanager.HostRoleCommand;
import org.apache.ambari.server.actionmanager.HostRoleStatus;
import org.apache.ambari.server.actionmanager.ServiceComponentHostEventWrapper;
import org.apache.ambari.server.agent.CommandReport;
import org.apache.ambari.server.agent.ExecutionCommand;
import org.apache.ambari.server.metadata.ActionMetadata;
import org.apache.ambari.server.orm.GuiceJpaInitializer;
import org.apache.ambari.server.orm.InMemoryDefaultTestModule;
import org.apache.ambari.server.orm.dao.ExecutionCommandDAO;
import org.apache.ambari.server.orm.dao.HostDAO;
import org.apache.ambari.server.orm.dao.HostRoleCommandDAO;
import org.apache.ambari.server.orm.dao.UpgradeDAO;
import org.apache.ambari.server.orm.entities.HostEntity;
import org.apache.ambari.server.orm.entities.HostRoleCommandEntity;
import org.apache.ambari.server.orm.entities.UpgradeGroupEntity;
import org.apache.ambari.server.orm.entities.UpgradeItemEntity;
import org.apache.ambari.server.serveraction.AbstractServerAction;
import org.apache.ambari.server.state.Cluster;
import org.apache.ambari.server.state.Clusters;
import org.apache.ambari.server.state.ServiceComponentHostEvent;
import org.apache.ambari.server.state.StackId;
import org.apache.ambari.server.state.svccomphost.ServiceComponentHostOpInProgressEvent;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.persist.UnitOfWork;
import com.google.inject.util.Modules;

public class AutoSkipFailedSummaryActionTest {

  private Injector m_injector;

  private static final StackId HDP_STACK = new StackId("HDP-2.2.0");

  @Inject
  private ExecutionCommandDAO executionCommandDAO;

  @Inject
  private HostDAO hostDAO;

  @Inject
  private ExecutionCommandWrapperFactory ecwFactory;

  // Mocked out values
  private UpgradeDAO upgradeDAOMock;
  private HostRoleCommandDAO hostRoleCommandDAOMock;
  private Clusters clustersMock;
  private Cluster clusterMock;

  @Before
  public void setup() throws Exception {
    // Create instances of mocks
    upgradeDAOMock = createNiceMock(UpgradeDAO.class);
    hostRoleCommandDAOMock = createNiceMock(HostRoleCommandDAO.class);
    clustersMock = createNiceMock(Clusters.class);
    clusterMock = createNiceMock(Cluster.class);

    expect(clustersMock.getCluster(anyString())).andReturn(clusterMock).anyTimes();
    replay(clustersMock);

    expect(clusterMock.getDesiredStackVersion()).andReturn(HDP_STACK).anyTimes();
    replay(clusterMock);

    // Initialize injector
    InMemoryDefaultTestModule module = new InMemoryDefaultTestModule();
    m_injector = Guice.createInjector(Modules.override(module).with(new MockModule()));
    m_injector.getInstance(GuiceJpaInitializer.class);
    m_injector.injectMembers(this);
    m_injector.getInstance(UnitOfWork.class).begin();

    // Normally initialized in runtime when loading stack
    m_injector.getInstance(ActionMetadata.class).addServiceCheckAction("ZOOKEEPER");
  }

  @After
  public void teardown() throws Exception {
    m_injector.getInstance(UnitOfWork.class).end();
    H2DatabaseCleaner.clearDatabase(m_injector.getProvider(EntityManager.class).get());
  }

  /**
   * Tests successful workflow
   */
  @Test
  public void testAutoSkipFailedSummaryAction__green() throws Exception {
    AutoSkipFailedSummaryAction action = new AutoSkipFailedSummaryAction();
    m_injector.injectMembers(action);

    ServiceComponentHostEvent event = createNiceMock(ServiceComponentHostEvent.class);

    // Set mock for parent's getHostRoleCommand()
    HostRoleCommand hostRoleCommand = new HostRoleCommand("host1", Role.AMBARI_SERVER_ACTION,
        event, RoleCommand.EXECUTE, hostDAO, executionCommandDAO, ecwFactory);
    hostRoleCommand.setRequestId(1l);
    hostRoleCommand.setStageId(1l);

    ExecutionCommand executionCommand = new ExecutionCommand();
    executionCommand.setClusterName("cc");
    executionCommand.setRoleCommand(RoleCommand.EXECUTE);
    executionCommand.setRole("AMBARI_SERVER_ACTION");
    executionCommand.setServiceName("");
    executionCommand.setTaskId(1l);
    ExecutionCommandWrapper wrapper = new ExecutionCommandWrapper(executionCommand);
    hostRoleCommand.setExecutionCommandWrapper(wrapper);

    Field f = AbstractServerAction.class.getDeclaredField("hostRoleCommand");
    f.setAccessible(true);
    f.set(action, hostRoleCommand);

    final UpgradeItemEntity upgradeItem1 = new UpgradeItemEntity();
    upgradeItem1.setStageId(5l);
    final UpgradeItemEntity upgradeItem2 = new UpgradeItemEntity();
    upgradeItem2.setStageId(6l);

    UpgradeGroupEntity upgradeGroupEntity = new UpgradeGroupEntity();
    upgradeGroupEntity.setId(11l);
    // List of upgrade items in group
    List<UpgradeItemEntity> groupUpgradeItems = new ArrayList<UpgradeItemEntity>(){{
      add(upgradeItem1);
      add(upgradeItem2);
    }};
    upgradeGroupEntity.setItems(groupUpgradeItems);

    UpgradeItemEntity upgradeItemEntity = new UpgradeItemEntity();
    upgradeItemEntity.setGroupEntity(upgradeGroupEntity);

    expect(upgradeDAOMock.findUpgradeItemByRequestAndStage(anyLong(), anyLong())).andReturn(upgradeItemEntity).anyTimes();
    expect(upgradeDAOMock.findUpgradeGroup(anyLong())).andReturn(upgradeGroupEntity).anyTimes();
    replay(upgradeDAOMock);

    List<HostRoleCommandEntity> skippedTasks = new ArrayList<HostRoleCommandEntity>() {{
      // It's empty - no skipped tasks
    }};
    expect(hostRoleCommandDAOMock.findByStatusBetweenStages(anyLong(),
      anyObject(HostRoleStatus.class), anyLong(), anyLong())).andReturn(skippedTasks).anyTimes();
    replay(hostRoleCommandDAOMock);

    ConcurrentMap<String, Object> requestSharedDataContext = new ConcurrentHashMap<String, Object>();
    CommandReport result = action.execute(requestSharedDataContext);

    assertNotNull(result.getStructuredOut());
    assertEquals(0, result.getExitCode());
    assertEquals(HostRoleStatus.COMPLETED.toString(), result.getStatus());
    assertEquals("There were no skipped failures", result.getStdOut());
    assertEquals("{}", result.getStructuredOut());
    assertEquals("", result.getStdErr());
  }

  /**
   * Tests workflow with few skipped tasks
   */
  @Test
  public void testAutoSkipFailedSummaryAction__red() throws Exception {
    AutoSkipFailedSummaryAction action = new AutoSkipFailedSummaryAction();
    m_injector.injectMembers(action);

    ServiceComponentHostEvent event = createNiceMock(ServiceComponentHostEvent.class);

    // Set mock for parent's getHostRoleCommand()
    final HostRoleCommand hostRoleCommand = new HostRoleCommand("host1", Role.AMBARI_SERVER_ACTION,
        event, RoleCommand.EXECUTE, hostDAO, executionCommandDAO, ecwFactory);
    hostRoleCommand.setRequestId(1l);
    hostRoleCommand.setStageId(1l);

    ExecutionCommand executionCommand = new ExecutionCommand();
    executionCommand.setClusterName("cc");
    executionCommand.setRoleCommand(RoleCommand.EXECUTE);
    executionCommand.setRole("AMBARI_SERVER_ACTION");
    executionCommand.setServiceName("");
    executionCommand.setTaskId(1l);
    ExecutionCommandWrapper wrapper = new ExecutionCommandWrapper(executionCommand);
    hostRoleCommand.setExecutionCommandWrapper(wrapper);

    Field f = AbstractServerAction.class.getDeclaredField("hostRoleCommand");
    f.setAccessible(true);
    f.set(action, hostRoleCommand);

    final UpgradeItemEntity upgradeItem1 = new UpgradeItemEntity();
    upgradeItem1.setStageId(5l);
    final UpgradeItemEntity upgradeItem2 = new UpgradeItemEntity();
    upgradeItem2.setStageId(6l);

    UpgradeGroupEntity upgradeGroupEntity = new UpgradeGroupEntity();
    upgradeGroupEntity.setId(11l);
    // List of upgrade items in group
    List<UpgradeItemEntity> groupUpgradeItems = new ArrayList<UpgradeItemEntity>(){{
      add(upgradeItem1);
      add(upgradeItem2);
    }};
    upgradeGroupEntity.setItems(groupUpgradeItems);

    UpgradeItemEntity upgradeItemEntity = new UpgradeItemEntity();
    upgradeItemEntity.setGroupEntity(upgradeGroupEntity);

    expect(upgradeDAOMock.findUpgradeItemByRequestAndStage(anyLong(), anyLong())).andReturn(upgradeItemEntity).anyTimes();
    expect(upgradeDAOMock.findUpgradeGroup(anyLong())).andReturn(upgradeGroupEntity).anyTimes();
    replay(upgradeDAOMock);

    List<HostRoleCommandEntity> skippedTasks = new ArrayList<HostRoleCommandEntity>() {{
      add(createSkippedTask("DATANODE", "DATANODE", "host1.vm",
        "RESTART HDFS/DATANODE", RoleCommand.CUSTOM_COMMAND,
        "RESTART"
        ));
      add(createSkippedTask("DATANODE", "DATANODE", "host2.vm",
        "RESTART HDFS/DATANODE", RoleCommand.CUSTOM_COMMAND,
        "RESTART"));
      add(createSkippedTask("ZOOKEEPER_QUORUM_SERVICE_CHECK", "ZOOKEEPER_CLIENT", "host2.vm",
        "SERVICE_CHECK ZOOKEEPER", RoleCommand.SERVICE_CHECK, null));
    }};
    expect(hostRoleCommandDAOMock.findByStatusBetweenStages(anyLong(),
      anyObject(HostRoleStatus.class), anyLong(), anyLong())).andReturn(skippedTasks).anyTimes();
    replay(hostRoleCommandDAOMock);

    ConcurrentMap<String, Object> requestSharedDataContext = new ConcurrentHashMap<String, Object>();
    CommandReport result = action.execute(requestSharedDataContext);

    assertNotNull(result.getStructuredOut());
    assertEquals(0, result.getExitCode());
    assertEquals(HostRoleStatus.HOLDING.toString(), result.getStatus());
    assertEquals("There were 3 skipped failure(s) that must be addressed " +
      "before you can proceed. Please resolve each failure before continuing with the upgrade.",
      result.getStdOut());
    assertEquals("{\"failures\":" +
        "{\"service_check\":[\"ZOOKEEPER\"]," +
        "\"host_component\":{" +
        "\"host1.vm\":[{\"component\":\"DATANODE\",\"service\":\"HDFS\"}]," +
        "\"host2.vm\":[{\"component\":\"DATANODE\",\"service\":\"HDFS\"}]}}," +
        "\"skipped\":[\"service_check\",\"host_component\"]}",
      result.getStructuredOut());
    assertEquals("The following steps failed but were automatically skipped:\n" +
      "DATANODE on host1.vm: RESTART HDFS/DATANODE\n" +
      "DATANODE on host2.vm: RESTART HDFS/DATANODE\n" +
      "ZOOKEEPER_CLIENT on host2.vm: SERVICE_CHECK ZOOKEEPER\n", result.getStdErr());
  }

  /**
   * Tests workflow with failed service check
   */
  @Test
  public void testAutoSkipFailedSummaryAction__red__service_checks_only() throws Exception {
    AutoSkipFailedSummaryAction action = new AutoSkipFailedSummaryAction();
    m_injector.injectMembers(action);

    ServiceComponentHostEvent event = createNiceMock(ServiceComponentHostEvent.class);

    // Set mock for parent's getHostRoleCommand()
    final HostRoleCommand hostRoleCommand = new HostRoleCommand("host1", Role.AMBARI_SERVER_ACTION,
        event, RoleCommand.EXECUTE, hostDAO, executionCommandDAO, ecwFactory);
    hostRoleCommand.setRequestId(1l);
    hostRoleCommand.setStageId(1l);

    ExecutionCommand executionCommand = new ExecutionCommand();
    executionCommand.setClusterName("cc");
    executionCommand.setRoleCommand(RoleCommand.EXECUTE);
    executionCommand.setRole("AMBARI_SERVER_ACTION");
    executionCommand.setServiceName("");
    executionCommand.setTaskId(1l);
    ExecutionCommandWrapper wrapper = new ExecutionCommandWrapper(executionCommand);
    hostRoleCommand.setExecutionCommandWrapper(wrapper);

    Field f = AbstractServerAction.class.getDeclaredField("hostRoleCommand");
    f.setAccessible(true);
    f.set(action, hostRoleCommand);

    final UpgradeItemEntity upgradeItem1 = new UpgradeItemEntity();
    upgradeItem1.setStageId(5l);
    final UpgradeItemEntity upgradeItem2 = new UpgradeItemEntity();
    upgradeItem2.setStageId(6l);

    UpgradeGroupEntity upgradeGroupEntity = new UpgradeGroupEntity();
    upgradeGroupEntity.setId(11l);
    // List of upgrade items in group
    List<UpgradeItemEntity> groupUpgradeItems = new ArrayList<UpgradeItemEntity>(){{
      add(upgradeItem1);
      add(upgradeItem2);
    }};
    upgradeGroupEntity.setItems(groupUpgradeItems);

    UpgradeItemEntity upgradeItemEntity = new UpgradeItemEntity();
    upgradeItemEntity.setGroupEntity(upgradeGroupEntity);

    expect(upgradeDAOMock.findUpgradeItemByRequestAndStage(anyLong(), anyLong())).andReturn(upgradeItemEntity).anyTimes();
    expect(upgradeDAOMock.findUpgradeGroup(anyLong())).andReturn(upgradeGroupEntity).anyTimes();
    replay(upgradeDAOMock);

    List<HostRoleCommandEntity> skippedTasks = new ArrayList<HostRoleCommandEntity>() {{
      add(createSkippedTask("ZOOKEEPER_QUORUM_SERVICE_CHECK", "ZOOKEEPER_CLIENT", "host2.vm",
        "SERVICE_CHECK ZOOKEEPER", RoleCommand.SERVICE_CHECK, null));
    }};
    expect(hostRoleCommandDAOMock.findByStatusBetweenStages(anyLong(),
      anyObject(HostRoleStatus.class), anyLong(), anyLong())).andReturn(skippedTasks).anyTimes();
    replay(hostRoleCommandDAOMock);

    ConcurrentMap<String, Object> requestSharedDataContext = new ConcurrentHashMap<String, Object>();
    CommandReport result = action.execute(requestSharedDataContext);

    assertNotNull(result.getStructuredOut());
    assertEquals(0, result.getExitCode());
    assertEquals(HostRoleStatus.HOLDING.toString(), result.getStatus());
    assertEquals("There were 1 skipped failure(s) that must be addressed " +
        "before you can proceed. Please resolve each failure before continuing with the upgrade.",
      result.getStdOut());
    assertEquals("{\"failures\":{\"service_check\":[\"ZOOKEEPER\"]},\"skipped\":[\"service_check\"]}",
      result.getStructuredOut());
    assertEquals("The following steps failed but were automatically skipped:\n" +
      "ZOOKEEPER_CLIENT on host2.vm: SERVICE_CHECK ZOOKEEPER\n", result.getStdErr());
  }

  /**
   * Tests workflow with failed host component tasks only
   */
  @Test
  public void testAutoSkipFailedSummaryAction__red__host_components_only() throws Exception {
    AutoSkipFailedSummaryAction action = new AutoSkipFailedSummaryAction();
    m_injector.injectMembers(action);

    ServiceComponentHostEvent event = createNiceMock(ServiceComponentHostEvent.class);

    // Set mock for parent's getHostRoleCommand()
    final HostRoleCommand hostRoleCommand = new HostRoleCommand("host1", Role.AMBARI_SERVER_ACTION,
        event, RoleCommand.EXECUTE, hostDAO, executionCommandDAO, ecwFactory);
    hostRoleCommand.setRequestId(1l);
    hostRoleCommand.setStageId(1l);

    ExecutionCommand executionCommand = new ExecutionCommand();
    executionCommand.setClusterName("cc");
    executionCommand.setRoleCommand(RoleCommand.EXECUTE);
    executionCommand.setRole("AMBARI_SERVER_ACTION");
    executionCommand.setServiceName("");
    executionCommand.setTaskId(1l);
    ExecutionCommandWrapper wrapper = new ExecutionCommandWrapper(executionCommand);
    hostRoleCommand.setExecutionCommandWrapper(wrapper);

    Field f = AbstractServerAction.class.getDeclaredField("hostRoleCommand");
    f.setAccessible(true);
    f.set(action, hostRoleCommand);

    final UpgradeItemEntity upgradeItem1 = new UpgradeItemEntity();
    upgradeItem1.setStageId(5l);
    final UpgradeItemEntity upgradeItem2 = new UpgradeItemEntity();
    upgradeItem2.setStageId(6l);

    UpgradeGroupEntity upgradeGroupEntity = new UpgradeGroupEntity();
    upgradeGroupEntity.setId(11l);
    // List of upgrade items in group
    List<UpgradeItemEntity> groupUpgradeItems = new ArrayList<UpgradeItemEntity>(){{
      add(upgradeItem1);
      add(upgradeItem2);
    }};
    upgradeGroupEntity.setItems(groupUpgradeItems);

    UpgradeItemEntity upgradeItemEntity = new UpgradeItemEntity();
    upgradeItemEntity.setGroupEntity(upgradeGroupEntity);

    expect(upgradeDAOMock.findUpgradeItemByRequestAndStage(anyLong(), anyLong())).andReturn(upgradeItemEntity).anyTimes();
    expect(upgradeDAOMock.findUpgradeGroup(anyLong())).andReturn(upgradeGroupEntity).anyTimes();
    replay(upgradeDAOMock);

    List<HostRoleCommandEntity> skippedTasks = new ArrayList<HostRoleCommandEntity>() {{
      add(createSkippedTask("DATANODE", "DATANODE", "host1.vm",
        "RESTART HDFS/DATANODE", RoleCommand.CUSTOM_COMMAND,
        "RESTART"
      ));
      add(createSkippedTask("DATANODE", "DATANODE", "host2.vm",
        "RESTART HDFS/DATANODE", RoleCommand.CUSTOM_COMMAND,
        "RESTART"));
    }};
    expect(hostRoleCommandDAOMock.findByStatusBetweenStages(anyLong(),
      anyObject(HostRoleStatus.class), anyLong(), anyLong())).andReturn(skippedTasks).anyTimes();
    replay(hostRoleCommandDAOMock);

    ConcurrentMap<String, Object> requestSharedDataContext = new ConcurrentHashMap<String, Object>();
    CommandReport result = action.execute(requestSharedDataContext);

    assertNotNull(result.getStructuredOut());
    assertEquals(0, result.getExitCode());
    assertEquals(HostRoleStatus.HOLDING.toString(), result.getStatus());
    assertEquals("There were 2 skipped failure(s) that must be addressed " +
        "before you can proceed. Please resolve each failure before continuing with the upgrade.",
      result.getStdOut());
    assertEquals("{\"failures\":" +
        "{\"host_component\":" +
        "{\"host1.vm\":[{\"component\":\"DATANODE\",\"service\":\"HDFS\"}]," +
        "\"host2.vm\":[{\"component\":\"DATANODE\",\"service\":\"HDFS\"}]}}," +
        "\"skipped\":[\"host_component\"]}",
      result.getStructuredOut());
    assertEquals("The following steps failed but were automatically skipped:\n" +
      "DATANODE on host1.vm: RESTART HDFS/DATANODE\n" +
      "DATANODE on host2.vm: RESTART HDFS/DATANODE\n", result.getStdErr());
  }

  private HostRoleCommandEntity createSkippedTask(String role, String componentName,
                                                  String hostname, String commandDetail,
                                                  RoleCommand roleCommand, String customCommandName) {
    HostRoleCommandEntity result = new HostRoleCommandEntity();

    ServiceComponentHostEvent event = new ServiceComponentHostOpInProgressEvent(componentName, hostname, 77l);
    ServiceComponentHostEventWrapper eventWrapper = new ServiceComponentHostEventWrapper(event);
    result.setEvent(eventWrapper.getEventJson());

    HostEntity hostEntity = new HostEntity();
    hostEntity.setHostName(hostname);
    result.setHostEntity(hostEntity);

    result.setTaskId(7l);
    result.setExitcode(1);
    result.setOutputLog("/output.log");
    result.setErrorLog("/error.log");
    result.setStdOut("Some stdout".getBytes());
    result.setStdError("Some stderr".getBytes());
    result.setCommandDetail(commandDetail);
    result.setRole(Role.valueOf(role));
    result.setRoleCommand(roleCommand);
    result.setCustomCommandName(customCommandName);
    result.setStatus(HostRoleStatus.SKIPPED_FAILED);

    return result;
  }

  public class MockModule extends AbstractModule {
    @Override
    protected void configure() {
      bind(UpgradeDAO.class).toInstance(upgradeDAOMock);
      bind(HostRoleCommandDAO.class).toInstance(hostRoleCommandDAOMock);
      bind(Clusters.class).toInstance(clustersMock);
    }
  }

}


text:
<?php
/**
 * for crawling
 *
 */
namespace Crawler;
class Crawl
{
	private static $__proxy_list = array();
	private static $__current_proxy_num = 0;
	private static $__last_proxy_get_date = 0;

	// return headers
	protected static $_return_headers = array();

	// request_type page or image or json
	protected static $_request_type = 'page';

	// request_method get or post
	protected static $_request_method = 'get';

	// request headers
	protected static $_request_headers = array();

	// request body
	protected static $_request_body = array();

	// リトライ機構
	const RETRY_MAX_CNT = 7;
	private static $__retry_cnt = 0;

	// Refreshダミー機構
	const REFRESH_MAX_CNT = 10;
	private static $__refresh_cnt = 0;

	/**
	 * Init, config loading.
	 */
	public static function _init()
	{
		\Config::load('crawler', true);
	}

	/**
	 * access and return parsed html object
	 *
	 * @param string $uri
	 *        bool   $use_proxy
	 *        bool   $refresh
	 *        bool   $retry
	 * @return mixed simple_html_dom
	 *               string
	 */
	public static function curl($uri, $use_proxy = false, $refresh = false, $retry = false)
	{
		if( ! $retry)
		{
			self::$__retry_cnt = 0;
			self::$__refresh_cnt = 0;
		}
		$curl = \Request::forge($uri, 'curl')
		        ->set_method(static::$_request_method)
		        ->set_option(CURLOPT_TIMEOUT, 10)
		        ->set_option(CURLOPT_USERAGENT, \Config::get('crawler.dummy_agent'));
		foreach(static::$_request_headers as $header => $content)
		{
			$curl->set_header($header, $content);
		}
		if(static::$_request_type === 'image')
		{
			$curl->set_option(CURLOPT_RETURNTRANSFER, 1);
		}
		if( ! empty(static::$_request_body))
		{
			$curl->set_params(static::$_request_body);
		}
		if($use_proxy)
		{
			$proxy_list = static::_get_proxy();
			if( ! empty($proxy_list))
			{
				self::$__current_proxy_num = rand(0, (count($proxy_list) - 1));
				$proxy = $proxy_list[self::$__current_proxy_num];
				$curl->set_option(CURLOPT_PROXY, $proxy);
			}
			// for loop use if not refresh
			if( empty($proxy_list))
			{
				// for loop use
				usleep(\Config::get('crawler.usleep_time'));
			}
			elseif( ! $refresh)
			{
				usleep(\Config::get('crawler.usleep_time_with_proxy'));
			}
		}
		elseif( ! $refresh)
		{
			// for loop use
			usleep(\Config::get('crawler.usleep_time'));
		}

		try
		{
			$curl->execute();
			static::$_return_headers = $curl->response_info();
			$result = $curl->response()->body;
			if(static::$_request_type === 'page')
			{
				$result = \str_get_html($result);
				if( ! empty($result->find('title', 0)) and preg_match('/アクセスが?制限/', $result->find('title', 0)->plaintext))
				{
					// access restrict occured. retry use other proxy
					throw new \RequestException($curl->response()->body, 401);
				}
				if( is_object($result->find('meta[http-equiv=Refresh]', 0)))
				{
					if(self::$__refresh_cnt > self::REFRESH_MAX_CNT)
					{
						throw new \Exception('Refresh loop...');
					}
					self::$__refresh_cnt++;
					return self::curl($uri, $use_proxy, true);
				}
			}
			if(static::$_request_type === 'json')
			{
				$result = \Format::forge($result, 'json')->to_array();
			}
			// retry, refresh reset
			self::$__retry_cnt = 0;
			self::$__refresh_cnt = 0;
		}
		catch(\RequestException $e)
		{
			// 404, または画像収集の場合はRequestStatusException側へ
			if($e->getCode() == 404 or static::$_request_type === 'image')
			{
				throw new \RequestStatusException($e->getMessage(), $e->getCode());
			}
			self::$__retry_cnt++;
			if(self::$__retry_cnt <= self::RETRY_MAX_CNT)
			{
				\Log::warning(__METHOD__.': retry execute. now cnt='.self::$__retry_cnt);
				// おそらくタイムアウトになったであろうproxyは時間短縮のため再利用しない
				if($use_proxy and ! empty($use_porxy))
				{
					unset(self::$__proxy_list[self::$__current_proxy_num]);
					// array key reset
					self::$__proxy_list = array_values(self::$__proxy_list);
				}
				return self::curl($uri, $use_proxy, false, true);
			}
			// retry回数が一定以上に達したら終了
			throw new \RequestException($e->getMessage(), $e->getCode());
		}
		return $result;
	}

	/**
	 * 適切なクロールデータトリム
	 *
	 */
	protected static function _trim($str)
	{
		return trim(html_entity_decode(preg_replace('/[\s(\r?\n)]+/', ' ', str_replace(' ', ' ', $str))));
	}

	/**
	 * proxyリストの取得
	 *
	 * @return array
	 */
	protected static function _get_proxy()
	{
		// 一定時間が過ぎるかもしくは候補プロキシがN値以下の場合にリストを再取得する
		if(
			strtotime('-10 hours') < self::$__last_proxy_get_date and
			count(self::$__proxy_list) >= 3 // 3つ以下しか使いまわせなくなったらリストを更新
		)
		{
			return self::$__proxy_list;
		}
		$list = array();
		// 野良プロキシの取得
		if( ! empty(\Config::get('crawler.get_proxy.app_key')))
		{
			$url = 'http://www.getproxy.jp/proxyapi?ApiKey='.\Config::get('crawler.get_proxy.app_key').'&area=JP&sort=requesttime&orderby=asc';
			$curl = \Request::forge($url, 'curl')
			        ->set_method('get')
			        ->set_option(CURLOPT_TIMEOUT, 60)
			        ->execute();
			$xml = \Format::forge($curl->response()->body, 'xml')->to_array();
			if( ! isset($xml['errorinfo']) and count($xml) > 1)
			{
				foreach($xml['item'] as $proxy)
				{
					$list[] = $proxy['ip'];
				}
			}
		}
		// merge custom proxies
		$list = array_merge($list, \Config::get('crawler.custom_proxies'));
		self::$__proxy_list = $list;
		self::$__last_proxy_get_date = strtotime('now');
		if(empty($list))
		{
			\Log::info(__METHOD__.': can\'t get any proxies');
		}
		return $list;
	}

	/**
	 * 最後に利用したプロキシ取得
	 *
	 */
	protected static function _get_last_use_proxy()
	{
		if(empty(self::$__proxy_list))
		{
			return null;
		}
		return self::$__proxy_list[self::$__current_proxy_num];
	}
}


text:
import * as when from 'when';

export function unwrapPromise<T>(promise: when.Promise<T>): Promise<T> {
  return new Promise<T>((resolve, reject) => {
    promise.then(resolve).catch(reject);
  });
}


text:
package channel

import "context"

// SendWithContext either sends val to ch and returns nil
// or, if ctx.Done() receives, returns ctx.Err()
func SendWithContext[T any](
	ctx context.Context,
	ch chan<- T,
	val T,
) error {
	select {
	case <-ctx.Done():
		return ctx.Err()
	case ch <- val:
		return nil
	}
}


text:
This application consumes s3 credentials supplied via the [dingo-s3](http://www.dingotiles.com/dingo-s3/) service broker.

## Run the app
```
cf create-service dingo-s3 essential s3-example-bucket
cf push --no-start
cf bind-service spring-s3-upload-example s3-example-bucket
cf set-env spring-s3-upload-example S3_SERVICE_NAME s3-example-bucket
cf start spring-s3-upload-example
```


text:
package ec2

import (
	"context"
	awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware"
	"github.com/aws/aws-sdk-go-v2/aws/signer/v4"
	"github.com/aws/smithy-go/middleware"
	smithyhttp "github.com/aws/smithy-go/transport/http"
)

// Downloads the contents of the Client VPN endpoint configuration file for the
// specified Client VPN endpoint. The Client VPN endpoint configuration file
// includes the Client VPN endpoint and certificate information clients need to
// establish a connection with the Client VPN endpoint.
func (c *Client) ExportClientVpnClientConfiguration(ctx context.Context, params *ExportClientVpnClientConfigurationInput, optFns ...func(*Options)) (*ExportClientVpnClientConfigurationOutput, error) {
	if params == nil {
		params = &ExportClientVpnClientConfigurationInput{}
	}

	result, metadata, err := c.invokeOperation(ctx, "ExportClientVpnClientConfiguration", params, optFns, c.addOperationExportClientVpnClientConfigurationMiddlewares)
	if err != nil {
		return nil, err
	}

	out := result.(*ExportClientVpnClientConfigurationOutput)
	out.ResultMetadata = metadata
	return out, nil
}

type ExportClientVpnClientConfigurationInput struct {

	// The ID of the Client VPN endpoint.
	//
	// This member is required.
	ClientVpnEndpointId *string

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

	noSmithyDocumentSerde
}

type ExportClientVpnClientConfigurationOutput struct {

	// The contents of the Client VPN endpoint configuration file.
	ClientConfiguration *string

	// Metadata pertaining to the operation's result.
	ResultMetadata middleware.Metadata

	noSmithyDocumentSerde
}

func (c *Client) addOperationExportClientVpnClientConfigurationMiddlewares(stack *middleware.Stack, options Options) (err error) {
	err = stack.Serialize.Add(&awsEc2query_serializeOpExportClientVpnClientConfiguration{}, middleware.After)
	if err != nil {
		return err
	}
	err = stack.Deserialize.Add(&awsEc2query_deserializeOpExportClientVpnClientConfiguration{}, middleware.After)
	if err != nil {
		return err
	}
	if err = addSetLoggerMiddleware(stack, options); err != nil {
		return err
	}
	if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil {
		return err
	}
	if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil {
		return err
	}
	if err = addResolveEndpointMiddleware(stack, options); err != nil {
		return err
	}
	if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil {
		return err
	}
	if err = addRetryMiddlewares(stack, options); err != nil {
		return err
	}
	if err = addHTTPSignerV4Middleware(stack, options); err != nil {
		return err
	}
	if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil {
		return err
	}
	if err = awsmiddleware.AddRecordResponseTiming(stack); err != nil {
		return err
	}
	if err = addClientUserAgent(stack); err != nil {
		return err
	}
	if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil {
		return err
	}
	if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil {
		return err
	}
	if err = addOpExportClientVpnClientConfigurationValidationMiddleware(stack); err != nil {
		return err
	}
	if err = stack.Initialize.Add(newServiceMetadataMiddleware_opExportClientVpnClientConfiguration(options.Region), middleware.Before); err != nil {
		return err
	}
	if err = addRequestIDRetrieverMiddleware(stack); err != nil {
		return err
	}
	if err = addResponseErrorMiddleware(stack); err != nil {
		return err
	}
	if err = addRequestResponseLogging(stack, options); err != nil {
		return err
	}
	return nil
}

func newServiceMetadataMiddleware_opExportClientVpnClientConfiguration(region string) *awsmiddleware.RegisterServiceMetadata {
	return &awsmiddleware.RegisterServiceMetadata{
		Region:        region,
		ServiceID:     ServiceID,
		SigningName:   "ec2",
		OperationName: "ExportClientVpnClientConfiguration",
	}
}


text:
@interface SR_RegisterViewController : UIViewController

@end


text:
import urllib, urllib2, time, re
from operator import attrgetter
from inputs import SitesFile
from utilities import Parser

class SiteFacade(object):
    def __init__(self):
        self._sites = []

    def runSiteAutomation(self,webretrievedelay,targetlist,source,postbydefault):
        #SingleResultsSite(String URL, Int Delay, String TargetType, String ReportStringForResults, String Target, String SiteFriendlyName,
                          #String RegEx, String FullUrlToSubmitToSite,String ImportantAttributeForSiteToReport,Dict Parameters,
                          #Dict Headers)

        if SitesFile.fileExists():
            sitetree = SitesFile.getXMLTree()
            for siteelement in sitetree.iter(tag="site"):
                if source == "allsources" or source == siteelement.get("name"):
                    for targ in targetlist:
                        sitetypematch=False
                        targettype = self.identifyTargetType(targ)
                        for st in siteelement.find("sitetype").findall("entry"):
                            if st.text==targettype:
                                sitetypematch=True
                        if sitetypematch:
                            site = Site.buildSiteFromXML(siteelement,webretrievedelay,targettype,targ)
                            if (site.Params != None or site.Headers != None) and site.APIKey != None:
                                self._sites.append(PostTransactionAPIKeySite(site))
                            elif site.Params != None or site.Headers != None:
                                self._sites.append(PostTransactionPositiveCapableSite(site,postbydefault))
                            elif isinstance(site.RegEx,basestring):
                                self._sites.append(SingleResultsSite(site))
                            else:
                                self._sites.append(MultiResultsSite(site))

    @property
    def Sites(self):
        if self._sites is None or len(self._sites) == 0:
            return None
        return self._sites

    # Identify if the target is an IP, URL, or HASH
    def identifyTargetType(self,target):
        ipAddress = re.compile('\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}', re.IGNORECASE)
        ipFind = re.findall(ipAddress,target)
        if ipFind is not None and len(ipFind) > 0:
            return "ip"

        md5 = re.compile('[a-fA-F0-9]{32}', re.IGNORECASE)
        md5Find = re.findall(md5,target)
        if md5Find is not None and len(md5Find) > 0:
            return "md5"

        return "hostname"

class Site(object):
    def __init__(self,domainurl,webretrievedelay,targettype,reportstringforresult,target,friendlyname,regex,fullurl,importantproperty,params,headers,apikey):
        self._sourceurl = domainurl
        self._webretrievedelay=webretrievedelay
        self._targetType = targettype
        self._reportstringforresult = reportstringforresult
        self._errormessage = "[-] Cannot scrape"
        self._usermessage = "[*] Checking"
        self._target = target
        self._friendlyName = friendlyname
        self._regex = regex
        self._fullURL = ""
        self.FullURL = fullurl # call the helper method to clean %TARGET% from fullurl string
        self._importantProperty = importantproperty
        self._params = None
        if params is not None:
            self.Params = params # call the helper method to clean %TARGET% from params string

        if headers is None:
            self._headers = None
        else:
            self._headers = headers
        if apikey is None:
            self._apikey = None
        else:
            self._apikey = apikey
        self._results = []
        self._messagetopost = ""

    @classmethod
    def buildSiteFromXML(self,siteelement,webretrievedelay,targettype,target):
        domainurl = siteelement.find("domainurl").text
        reportstringforresult = Site.buildStringOrListfromXML(siteelement,"reportstringforresult")
        sitefriendlyname = Site.buildStringOrListfromXML(siteelement,"sitefriendlyname")
        regex = Site.buildStringOrListfromXML(siteelement,"regex")
        fullurl = siteelement.find("fullurl").text
        importantproperty = Site.buildStringOrListfromXML(siteelement,"importantproperty")
        params = Site.buildDictionaryFromXML(siteelement,"params")
        headers = Site.buildDictionaryFromXML(siteelement,"headers")
        apikey = Site.buildStringOrListfromXML(siteelement,"apikey")
        return Site(domainurl,webretrievedelay,targettype,reportstringforresult,target,sitefriendlyname,regex,fullurl,importantproperty,params,headers,apikey)

    @classmethod
    def buildStringOrListfromXML(self,siteelement,elementstring):
        variablename = ""
        if len(siteelement.find(elementstring).findall("entry"))==0:
            return None

        if len(siteelement.find(elementstring).findall("entry"))>1:
            variablename = []
            for entry in siteelement.find(elementstring).findall("entry"):
                variablename.append(entry.text)
        else:
            variablename = ""
            variablename = siteelement.find(elementstring).find("entry").text
        return variablename

    @classmethod
    def buildDictionaryFromXML(self,siteelement,elementstring):
        variablename = ""
        if len(siteelement.find(elementstring).findall("entry"))>0:
            variablename = {}
            for entry in siteelement.find(elementstring).findall("entry"):
                variablename[entry.get("key")] =  entry.text
        else:
            return None
        return variablename

    @property
    def WebRetrieveDelay(self):
        return self._webretrievedelay

    @property
    def TargetType(self):
        return self._targetType

    @property
    def ReportStringForResult(self):
        return self._reportstringforresult

    @property
    def FriendlyName(self):
        return self._friendlyName

    @property
    def RegEx(self):
        return self._regex

    @property
    def URL(self):
        return self._sourceurl

    @property
    def MessageToPost(self):
        return self._messagetopost

    @property
    def ErrorMessage(self):
        return self._errormessage

    @property
    def UserMessage(self):
        return self._usermessage

    @property
    def FullURL(self):
        return self._fullURL

    @FullURL.setter
    def FullURL(self,fullurl):
        if len(fullurl) > 0:
            fullurlreplaced = fullurl.replace("%TARGET%",self._target)
            self._fullURL = fullurlreplaced
        else:
            self._fullURL = ""

    @property
    def ImportantPropertyString(self):
        return self._importantProperty

    @property
    def Params(self):
        if self._params is None:
            return None
        if len(self._params) == 0:
            return None
        return self._params

    @Params.setter
    def Params(self,params):
        if len(params) > 0:
            for key in params:
                if params[key] == "%TARGET%":
                    params[key] = self._target
            self._params = params
        else:
            self._params = None

    @property
    def Headers(self):
        if self._headers is None:
            return None
        if len(self._headers) == 0:
            return None
        return self._headers

    @property
    def APIKey(self):
        if self._apikey is None:
            return None
        if len(self._apikey) == 0:
            return None
        return self._apikey

    @property
    def Target(self):
        return self._target

    @property
    def Results(self):
        if self._results is None or len(self._results) == 0:
            return None
        return self._results

    def addResults(self,results):
        #if no return from site, seed the results with an empty list
        if results is None or len(results) == 0:
            self._results = None
        else:
            self._results = results

    def postMessage(self,message):
        self._messagetopost = message
        print self.MessageToPost

    def getImportantProperty(self,index):
        if isinstance(self._importantProperty,basestring):
            siteimpprop = getattr(self,"get"+self._importantProperty,Site.getResults)
        else:
            siteimpprop = getattr(self,"get"+self._importantProperty[index],Site.getResults)
        return siteimpprop()

    def getTarget(self):
        return self.Target

    def getResults(self):
        return self.Results

    def getFullURL(self):
        return self.FullURL

# Function to pull content from a website
    def getWebScrape(self):
        delay = self.WebRetrieveDelay
        proxy = urllib2.ProxyHandler()
        opener = urllib2.build_opener(proxy)
        try:
            response = opener.open(self.FullURL)
            content = response.read()
            contentString = str(content)
            time.sleep(delay)
            return contentString
        except:
            self.postMessage('[-] Cannot connect to ' + self.FullURL)

class SingleResultsSite(Site):
    def __init__(self,site):
        self._site = site
        super(SingleResultsSite,self).__init__(self._site.URL,self._site.WebRetrieveDelay,self._site.TargetType,\
                                               self._site.ReportStringForResult,self._site.Target,self._site.FriendlyName,self._site.RegEx,\
                                               self._site.FullURL,self._site.ImportantPropertyString,self._site.Params,self._site.Headers,self._site.APIKey)
        self.postMessage(self.UserMessage + " " + self.FullURL)
        websitecontent = self.getContentList()
        if websitecontent is not None:
            self.addResults(websitecontent)

    def getContentList(self):
        try:
            content = self.getWebScrape()
            repattern = re.compile(self.RegEx, re.IGNORECASE)
            foundlist = re.findall(repattern,content)
            return foundlist
        except:
            self.postMessage(self.ErrorMessage + " " + self.FullURL)
            return None

class MultiResultsSite(Site):
    def __init__(self,site):
        self._site = site
        super(MultiResultsSite,self).__init__(self._site.URL,self._site.WebRetrieveDelay,self._site.TargetType,\
                                              self._site.ReportStringForResult,self._site.Target,self._site.FriendlyName,self._site.RegEx,\
                                              self._site.FullURL,self._site.ImportantPropertyString,self._site.Params,self._site.Headers,self._site.APIKey)
        self._results = [[] for x in xrange(len(self._site.RegEx))]
        self.postMessage(self.UserMessage + " " + self.FullURL)
        for index in range(len(self.RegEx)):
            websitecontent = self.getContentList(index)
            if websitecontent is not None:
                self.addResults(websitecontent,index)

    def addResults(self,results,index):
        #if no return from site, seed the results with an empty list
        if results is None or len(results) == 0:
            self._results[index] = None
        else:
            self._results[index] = results

    def getContentList(self,index):
        try:
            content = self.getWebScrape()
            repattern = re.compile(self.RegEx[index], re.IGNORECASE)
            foundlist = re.findall(repattern,content)
            return foundlist
        except:
            self.postMessage(self.ErrorMessage + " " + self.FullURL)
            return None

class PostTransactionPositiveCapableSite(Site):
    def __init__(self,site,postbydefault):
        self._site = site
        self._postByDefault = postbydefault
        #first entry of regexlist is the check - if we find something here (positive), there is no list of regexs and thus
        #we cannot run the post
        if isinstance(self._site.RegEx,basestring):
            return
        else:
            regextofindforpost = self._site.RegEx[0]
            newregexlist = self._site.RegEx[1:]
            super(PostTransactionPositiveCapableSite,self).__init__(self._site.URL,self._site.WebRetrieveDelay,self._site.TargetType,\
                                                  self._site.ReportStringForResult,self._site.Target,\
                                                  self._site.FriendlyName,newregexlist,self._site.FullURL,\
                                                  self._site.ImportantPropertyString,self._site.Params,self._site.Headers,self._site.APIKey)
            self.postMessage(self.UserMessage + " " + self.FullURL)
            content = self.getContent()
            if content != None:
                if self.postIsNecessary(regextofindforpost,content) and self.Params is not None and self.Headers is not None:
                    print '[-] This target requires a submission. Submitting now, this may take a moment.'
                    content = self.submitPost(self.Params,self.Headers)
                else:
                    pass
                if content != None:
                    if not isinstance(self.FriendlyName,basestring):#this is a multi instance
                        self._results = [[] for x in xrange(len(self.RegEx))]
                        for index in range(len(self.RegEx)):
                            self.addMultiResults(self.getContentList(content,index),index)
                    else:#this is a single instance
                        self.addResults(self.getContentList(content))

    def addMultiResults(self,results,index):
        #if no return from site, seed the results with an empty list
        if results is None or len(results) == 0:
            self._results[index] = None
        else:
            self._results[index] = results

    def getContentList(self,content,index=-1):
        try:
            if index==-1:#this is a return for a single instance site
                repattern = re.compile(self.RegEx, re.IGNORECASE)
                foundlist = re.findall(repattern,content)
                return foundlist
            else:#this is the return for a multisite
                repattern = re.compile(self.RegEx[index], re.IGNORECASE)
                foundlist = re.findall(repattern,content)
                return foundlist
        except:
            self.postMessage(self.ErrorMessage + " " + self.FullURL)
            return None

    def getContent(self):
        try:
            content = self.getWebScrape()
            return content
        except:
            self.postMessage(self.ErrorMessage + " " + self.FullURL)
            return None

    def postIsNecessary(self,regex,content):
        #check if the user set to post or not on the cmd line
        if not self._postByDefault:
            return False
        else:
            repattern = re.compile(regex, re.IGNORECASE)
            found = re.findall(repattern,content)
            if found:
                return True
            else:
                return False
        #here to catch any fall through
        return False

    def submitPost(self,raw_params,headers):
        try:
            url = (self.URL)
            params = urllib.urlencode(raw_params)
            request = urllib2.Request(url,params,headers)
            page = urllib2.urlopen(request)
            page = page.read()
            content = str(page)
            return content
        except:
            self.postMessage(self.ErrorMessage + " " + self.FullURL)
            return None

class PostTransactionAPIKeySite(Site):
    def __init__(self,site):
        self._site = site
        super(PostTransactionAPIKeySite,self).__init__(self._site.URL,self._site.WebRetrieveDelay,self._site.TargetType,\
                                              self._site.ReportStringForResult,self._site.Target,\
                                              self._site.FriendlyName,self._site.RegEx,self._site.FullURL,\
                                              self._site.ImportantPropertyString,self._site.Params,self._site.Headers,self._site.APIKey)
        self.postMessage(self.UserMessage + " " + self.FullURL)
        content = self.submitPost(self.Params,self.Headers)
        if content != None:
            if not isinstance(self.FriendlyName,basestring):#this is a multi instance
                self._results = [[] for x in xrange(len(self.RegEx))]
                for index in range(len(self.RegEx)):
                    self.addMultiResults(self.getContentList(content,index),index)
            else:#this is a single instance
                self.addResults(self.getContentList(content))

    def addMultiResults(self,results,index):
        #if no return from site, seed the results with an empty list
        if results is None or len(results) == 0:
            self._results[index] = None
        else:
            self._results[index] = results

    def getContentList(self,content,index=-1):
        try:
            if index==-1:#this is a return for a single instance site
                repattern = re.compile(self.RegEx, re.IGNORECASE)
                foundlist = re.findall(repattern,content)
                return foundlist
            else:#this is the return for a multisite
                repattern = re.compile(self.RegEx[index], re.IGNORECASE)
                foundlist = re.findall(repattern,content)
                return foundlist
        except:
            self.postMessage(self.ErrorMessage + " " + self.FullURL)
            return None

    def submitPost(self,raw_params,headers):
        try:
            url = (self.FullURL)
            params = urllib.urlencode(raw_params)
            request = urllib2.Request(url,params,headers)
            page = urllib2.urlopen(request)
            page = page.read()
            content = str(page)
            return content
        except:
            self.postMessage(self.ErrorMessage + " " + self.FullURL)
            return None


text:
package com.google.gerrit.httpd.rpc.account;

import com.google.gerrit.common.data.GroupDetail;
import com.google.gerrit.common.errors.NameAlreadyUsedException;
import com.google.gerrit.common.errors.NoSuchGroupException;
import com.google.gerrit.httpd.rpc.Handler;
import com.google.gerrit.reviewdb.AccountGroup;
import com.google.gerrit.reviewdb.AccountGroupName;
import com.google.gerrit.reviewdb.ReviewDb;
import com.google.gerrit.server.IdentifiedUser;
import com.google.gerrit.server.account.GroupCache;
import com.google.gerrit.server.account.GroupControl;
import com.google.gerrit.server.git.RenameGroupOp;
import com.google.gwtorm.client.OrmDuplicateKeyException;
import com.google.gwtorm.client.OrmException;
import com.google.inject.Inject;
import com.google.inject.assistedinject.Assisted;

import java.util.Collections;
import java.util.Date;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;

class RenameGroup extends Handler<GroupDetail> {
  interface Factory {
    RenameGroup create(AccountGroup.Id id, String newName);
  }

  private final ReviewDb db;
  private final GroupCache groupCache;
  private final GroupControl.Factory groupControlFactory;
  private final GroupDetailFactory.Factory groupDetailFactory;
  private final RenameGroupOp.Factory renameGroupOpFactory;
  private final IdentifiedUser currentUser;

  private final AccountGroup.Id groupId;
  private final String newName;

  @Inject
  RenameGroup(final ReviewDb db, final GroupCache groupCache,
      final GroupControl.Factory groupControlFactory,
      final GroupDetailFactory.Factory groupDetailFactory,
      final RenameGroupOp.Factory renameGroupOpFactory,
      final IdentifiedUser currentUser,
      @Assisted final AccountGroup.Id groupId, @Assisted final String newName) {
    this.db = db;
    this.groupCache = groupCache;
    this.groupControlFactory = groupControlFactory;
    this.groupDetailFactory = groupDetailFactory;
    this.renameGroupOpFactory = renameGroupOpFactory;
    this.currentUser = currentUser;
    this.groupId = groupId;
    this.newName = newName;
  }

  @Override
  public GroupDetail call() throws OrmException, NameAlreadyUsedException,
      NoSuchGroupException {
    final GroupControl ctl = groupControlFactory.validateFor(groupId);
    final AccountGroup group = db.accountGroups().get(groupId);
    if (group == null || !ctl.isOwner()) {
      throw new NoSuchGroupException(groupId);
    }

    final AccountGroup.NameKey old = group.getNameKey();
    final AccountGroup.NameKey key = new AccountGroup.NameKey(newName);

    try {
      final AccountGroupName id = new AccountGroupName(key, groupId);
      db.accountGroupNames().insert(Collections.singleton(id));
    } catch (OrmDuplicateKeyException dupeErr) {
      // If we are using this identity, don't report the exception.
      //
      AccountGroupName other = db.accountGroupNames().get(key);
      if (other != null && other.getId().equals(groupId)) {
        return groupDetailFactory.create(groupId).call();
      }

      // Otherwise, someone else has this identity.
      //
      throw new NameAlreadyUsedException();
    }

    group.setNameKey(key);
    db.accountGroups().update(Collections.singleton(group));

    AccountGroupName priorName = db.accountGroupNames().get(old);
    if (priorName != null) {
      db.accountGroupNames().delete(Collections.singleton(priorName));
    }

    groupCache.evict(group);
    groupCache.evictAfterRename(old);
    renameGroupOpFactory.create( //
        currentUser.newCommitterIdent(new Date(), TimeZone.getDefault()), //
        group.getGroupUUID(), //
        old.get(), newName).start(0, TimeUnit.MILLISECONDS);

    return groupDetailFactory.create(groupId).call();
  }
}


text:
<link rel="stylesheet" type="text/css" media="screen" href="../dist/w2ui.css" />

    <input placeholder="before" style="margin-bottom: 5px;"/>

    <input placeholder="after" style="margin-top: 5px;"/>


text:
<list model="document" colors='{"expiry_date,#f00":[["expired","=",true]]}'>
    <search>
        <field name="categ_id"/>
        <field name="description"/>
        <field name="date"/>
        <field name="expiry_date"/>
    </search>
    <field name="file" target="_blank"/>
    <field name="categ_id"/>
    <field name="description"/>
    <field name="related_id"/>
    <field name="date"/>
    <field name="expiry_date"/>
    <field name="expired" invisible="1"/>
</list>


text:
{-# LANGUAGE DeriveFunctor #-}
module Distribution.Solver.Modular.Package
  ( I(..)
  , Loc(..)
  , PackageId
  , PackageIdentifier(..)
  , PackageName(..)
  , PI(..)
  , PN
  , QPV
  , instI
  , makeIndependent
  , primaryPP
  , showI
  , showPI
  , unPN
  ) where

import Data.List as L

import Distribution.Package -- from Cabal

import Distribution.Solver.Modular.Version
import Distribution.Solver.Types.PackagePath

-- | A package name.
type PN = PackageName

-- | Unpacking a package name.
unPN :: PN -> String
unPN (PackageName pn) = pn

-- | Package version. A package name plus a version number.
type PV = PackageId

-- | Qualified package version.
type QPV = Qualified PV

-- | Package id. Currently just a black-box string.
type PId = UnitId

-- | Location. Info about whether a package is installed or not, and where
-- exactly it is located. For installed packages, uniquely identifies the
-- package instance via its 'PId'.
--
-- TODO: More information is needed about the repo.
data Loc = Inst PId | InRepo
  deriving (Eq, Ord, Show)

-- | Instance. A version number and a location.
data I = I Ver Loc
  deriving (Eq, Ord, Show)

-- | String representation of an instance.
showI :: I -> String
showI (I v InRepo)   = showVer v
showI (I v (Inst uid)) = showVer v ++ "/installed" ++ shortId uid
  where
    -- A hack to extract the beginning of the package ABI hash
    shortId (SimpleUnitId (ComponentId i))
            = snip (splitAt 4) (++ "...")
            . snip ((\ (x, y) -> (reverse x, y)) . break (=='-') . reverse) ('-':)
            $ i
    snip p f xs = case p xs of
                    (ys, zs) -> (if L.null zs then id else f) ys

-- | Package instance. A package name and an instance.
data PI qpn = PI qpn I
  deriving (Eq, Ord, Show, Functor)

-- | String representation of a package instance.
showPI :: PI QPN -> String
showPI (PI qpn i) = showQPN qpn ++ "-" ++ showI i

instI :: I -> Bool
instI (I _ (Inst _)) = True
instI _              = False

-- | Is the package in the primary group of packages.  This is used to
-- determine (1) if we should try to establish stanza preferences
-- for this goal, and (2) whether or not a user specified @--constraint@
-- should apply to this dependency (grep 'primaryPP' to see the
-- use sites).  In particular this does not include packages pulled in
-- as setup deps.
--
primaryPP :: PackagePath -> Bool
primaryPP (PackagePath _ns q) = go q
  where
    go Unqualified = True
    go (Base  _)   = True
    go (Setup _)   = False
    go (Exe _ _)   = False

-- | Create artificial parents for each of the package names, making
-- them all independent.
makeIndependent :: [PN] -> [QPN]
makeIndependent ps = [ Q pp pn | (pn, i) <- zip ps [0::Int ..]
                               , let pp = PackagePath (Independent i) Unqualified
                     ]