text:
package com.dci.intellij.dbn.debugger.breakpoint;

import com.dci.intellij.dbn.common.util.DocumentUtil;
import com.dci.intellij.dbn.debugger.evaluation.DBProgramDebuggerEditorsProvider;
import com.dci.intellij.dbn.editor.DBContentType;
import com.dci.intellij.dbn.language.common.psi.BasePsiElement;
import com.dci.intellij.dbn.language.common.psi.PsiUtil;
import com.dci.intellij.dbn.language.psql.PSQLFileType;
import com.dci.intellij.dbn.vfs.SourceCodeFile;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.xdebugger.XDebuggerBundle;
import com.intellij.xdebugger.XSourcePosition;
import com.intellij.xdebugger.breakpoints.XLineBreakpoint;
import com.intellij.xdebugger.breakpoints.XLineBreakpointType;
import com.intellij.xdebugger.evaluation.XDebuggerEditorsProvider;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

public class DBProgramBreakpointType extends XLineBreakpointType<DBProgramBreakpointProperties> {
    public DBProgramBreakpointType() {
        super("db-program", "DB-Program Breakpoint");
    }

    @Override
    public boolean canPutAt(@NotNull VirtualFile file, int line, @NotNull Project project) {
        if (file.getFileType().equals(PSQLFileType.INSTANCE)) {
            if (file instanceof SourceCodeFile) {
                SourceCodeFile sourceCodeFile = (SourceCodeFile) file;
                DBContentType contentType = sourceCodeFile.getContentType();
                if (contentType == DBContentType.CODE || contentType == DBContentType.CODE_BODY) {
                    Document document = DocumentUtil.getDocument(file);
                    int lineOffset = document.getLineStartOffset(line);
                    PsiFile psiFile = PsiUtil.getPsiFile(project, file);
                    PsiElement element = psiFile.findElementAt(lineOffset);
                    while (element != null && !(element instanceof BasePsiElement)) {
                        element = element.getNextSibling();
                    }
                    if (element != null) {
                        BasePsiElement basePsiElement = (BasePsiElement) element;
                        int elementLine = document.getLineNumber(basePsiElement.getTextOffset());
                        return elementLine == line;
                    }

                    /*if (element != null) {
                        BasePsiElement basePsiElement = (BasePsiElement) element;
                        BasePsiElement executableCodePsiElement = basePsiElement.lookupPsiElementByAttribute(ElementTypeAttribute.EXECUTABLE_CODE);
                        if (executableCodePsiElement != null){
                            int executableLine = document.getLineNumber(executableCodePsiElement.getTextOffset());
                            return executableLine == line;
                        }
                    }*/
                }
            }
        }
        return false;
    }

    @Override
    public DBProgramBreakpointProperties createBreakpointProperties(@NotNull VirtualFile file, int line) {
        return new DBProgramBreakpointProperties(file, line);
    }

    @Override
    public XDebuggerEditorsProvider getEditorsProvider() {
        return DBProgramDebuggerEditorsProvider.INSTANCE;
    }

    @Nullable
    @Override
    public XDebuggerEditorsProvider getEditorsProvider(@NotNull XLineBreakpoint<DBProgramBreakpointProperties> breakpoint, @NotNull Project project) {
        return DBProgramDebuggerEditorsProvider.INSTANCE;
    }

    @Override
    public String getDisplayText(XLineBreakpoint breakpoint) {
        XSourcePosition sourcePosition = breakpoint.getSourcePosition();
        if (sourcePosition != null ){
        VirtualFile file = sourcePosition.getFile();
        return XDebuggerBundle.message("xbreakpoint.default.display.text",
                breakpoint.getLine() + 1,
                file.getPresentableUrl());
        }
        return "unknown";
    }
}


text: ( 0">, {{author}})

redpajama_set_name: RedPajamaGithub


text:
import React from 'react';
import PropTypes from 'prop-types';
import Link from 'next/link';
import * as types from '../prop-types';

const AlbumTile = ({ linkProps, src, title, width, height }) => {
  const ratio = height / width;
  return (

        <Link {...linkProps}>
          <a style={{ paddingTop: `${(ratio * 100).toFixed(6)}%` }}>

        </Link>

{title}

  );
};

AlbumTile.propTypes = {
  linkProps: types.linkProps.isRequired,
  src: PropTypes.string.isRequired,
  title: PropTypes.string.isRequired,
  width: PropTypes.number.isRequired,
  height: PropTypes.number.isRequired,
};

export default AlbumTile;


text:
using System.Linq;
using CroquetAustralia.Domain.Features.TournamentEntry.Events;

namespace CroquetAustralia.QueueProcessor.Email.EmailGenerators
{
    public class ACEightsEOIEmailGenerator : BaseEmailGenerator
    {
        /* todo: remove hard coding of email addresses */
        private static readonly EmailAddress ACSC = new EmailAddress("acquinn@bigpond.com", "Croquet Australia - Chair AC Selection");

        private static readonly EmailAddress[] BCC =
        {
            new EmailAddress("admin@croquet-australia.com.au", "Croquet Australia"),
            ACSC
        };

        public ACEightsEOIEmailGenerator(EmailMessageSettings emailMessageSettings)
            : base(emailMessageSettings, ACSC, GetBCC(emailMessageSettings))
        {
        }

        protected override string GetTemplateName(EntrySubmitted entrySubmitted)
        {
            return "ACEightsEOI";
        }

        private static EmailAddress[] GetBCC(EmailMessageSettings emailMessageSettings)
        {
            return emailMessageSettings.Bcc.Any() ? BCC : new EmailAddress[] {};
        }
    }
}


text:
#ifndef JSPLAY_MOUSE_H
#define JSPLAY_MOUSE_H

#include "v8.h"
#include <map>
#include <script/script-object-wrap.h>

enum class MouseButton {
    Left,
    Right,
    Middle,
};

class Window;

class Mouse : public ScriptObjectWrap<Mouse> {

public:
    Mouse(v8::Isolate *isolate, Window* window);

    bool IsButtonDown(MouseButton button);
    bool IsButtonPress(MouseButton button);
    static void New(const v8::FunctionCallbackInfo<v8::Value>& args);
    void UpdateState();

    double x() const {
        return x_;
    }

    double y() const {
        return y_;
    }

protected:
    virtual void Initialize() override;

private:
    static void GetX(v8::Local<v8::String> name,
                     const v8::PropertyCallbackInfo<v8::Value> &args);
    static void GetY(v8::Local<v8::String> name,
                     const v8::PropertyCallbackInfo<v8::Value> &args);
    static void IsButtonDown(const v8::FunctionCallbackInfo<v8::Value>& args);
    static void IsButtonPress(const v8::FunctionCallbackInfo<v8::Value>& args);
    static void UpdateState(const v8::FunctionCallbackInfo<v8::Value>& args);

    double x_;
    double y_;
    std::map<int, int> oldState_;
    std::map<int, int> newState_;
    Window* window_;
};

#endif // JSPLAY_MOUSE_H


text:
/**
 * If Greater-Than Helper. Renders the block none of the first
 * argument is greater than the second.
 *
 * {{#if-lt a 5}} content {{/if-lt}}
 */
module.exports = function ifGt (a, b) {
    var options = arguments[arguments.length - 1];
    if (a > b) { return options.fn(this); }
    else { return options.inverse(this); }
};


text:
<?php

class MAB_ActionBox extends MAB_Base{
	private $_is_configured = false;
	private $_id = null;
	private $_type = null;
	private $_meta = array();
	private $_html_UniqueId = '_mab_html_unique_id';

	protected $track = true; // enable or disable tracking
	protected $_template_obj = null;

	/**
	 * Get Action Box
	 *
	 * @filters get_action_box-$type
	 * @uses apply_filters( "get_action_box-$type" );
	 *
	 * @return HTML the actual action box in HTML code
	 */
	function getActionBox( $id = null, $loadAssets = true ){

		if( is_null( $id ) || '' === $id ){
			//expect $id to already have been passed when the object was instantiated
			if( !$this->isConfigured() ) return '';
		} else {
			if( !$this->init( $id ) ) return '';
		}

		$box = $this->getTemplate();

		if( $loadAssets ){ //TODO: load assets only if $box is not empty?
			$this->loadAssets();
		}

		return $box;
	}

	/**
	 * Returns an action box object
	 *
	 * @param $id ID of the action box to get
	 * @return MAB_ActionBox|null null if action box does not exist.
	 */
	public static function get($id){
		$mab = new MAB_ActionBox($id);

		if(!$mab->isConfigured())
			return null;
		else
			return $mab;
	}

	function getTemplateObj(){
		return $this->_template_obj;
	}

	function getTemplate(){
		return $this->_template_obj->getTemplate();
	}

	function loadAssets(){
		if( !$this->isConfigured() ) return;
		return $this->_template_obj->loadAssets();
	}

	/**
	 * Get HTML Unique ID for each action box
	 */
	function getHtmlId(){
		//this to have unique ID attribute of the main containing div in case there is more
		//than 1 of the same action box. Cache key is composed of $_htmlUniqueId prefix and
		//ID of the action box.
		$actionBoxId = $this->getId();

		$htmlUniqueId = wp_cache_get( $this->_html_UniqueId . $actionBoxId );
		if( false === $htmlUniqueId ){
			//this is the first
			$htmlUniqueId = 1;
			wp_cache_set( $this->_html_UniqueId . $actionBoxId, $htmlUniqueId );
		} else {
			//another box is already displayed
			$htmlUniqueId++;
			wp_cache_replace( $this->_html_UniqueId . $actionBoxId, $htmlUniqueId );
		}

		return $actionBoxId.$htmlUniqueId;
	}

	/**
	 * @return TRUE if the action box was configured, FALSE otherwise
	 */
	function init( $id = null ){
		$MabBase = MAB();
		//stop early if $id is empty
		if( $id === '' || is_null( $id ) ) return false;

		//make sure action box exists
		$actionbox = get_post( $id );

		if( empty( $actionbox ) ){
			return false;
		}

		// make sure the $actionbox post object is not trashed
		if($actionbox->post_status == 'trash'){
			return false;
		}

		//make sure action box type is registered
		$type = $MabBase->get_mab_meta( $id, 'type' );
		if( !$MabBase->get_registered_action_box_type( $type ) ){
			//error_log($type . ' not registered');
			return false;
		}
		$this->_type = $type;

		$this->_id = $id;
		$this->_meta = $MabBase->get_mab_meta( $id );

		//set $_is_configured to TRUE indicating that this action box
		//is configured correctly
		$this->_is_configured = true;

		$this->_template_obj = new MAB_Template( $this );

		// set html data
		$this->setHtmlData('mabid', $id);
		$this->setHtmlData('trackid', $id);
		$this->setHtmlData('type', $this->getActionBoxType());

		// set tracking/analytics
		$this->track(true);

		return true;
	}

	function getStyleKey(){
		if( !$this->isConfigured() || empty( $this->_meta['style'] ) ) return '';

		return $this->_meta['style'];
	}

	function getActionBoxType(){
		return $this->_type;
	}

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

	function getMeta(){
		return $this->_meta;
	}

	/**
	 * See MAB_Template::addClass() method for description
	 */
	function addClass($class){
		if(!$this->isConfigured()) return false;

		return $this->getTemplateObj()->addClass($class);
	}

	/**
	 * @see  MAB_Template::removeClass
	 */
	function removeClass($class){
		if(!$this->isConfigured()) return false;

		return $this->getTemplateObj()->removeClass($class);
	}

	/**
	 * See MAB_Template::setHtmlData() method for description
	 */
	function setHtmlData($name, $value){
		if(!$this->isConfigured()) return false;

		return $this->getTemplateObj()->setHtmlData($name, $value);
	}

	/**
	 * See MAB_Template::getHtmlData() method for description
	 */
	function getHtmlData($name = ''){
		if(!$this->isConfigured()) return false;

		return $this->getTemplateObj()->getHtmlData($name);
	}

	function htmlData(){
		if(!$this->isConfigured()) return false;
		return $this->getTemplateObj()->htmlData();
	}

	/**
	 * See MAB_Template::setInlineStyle() method for description
	 */
	function setInlineStyle($name, $value){
		if(!$this->isConfigured()) return false;

		return $this->getTemplateObj()->setInlineStyle($name, $value);
	}

	/**
	 * See MAB_Template::getInlineStyle() method for description
	 */
	function getInlineStyle($name = ''){
		if(!$this->isConfigured()) return false;

		return $this->getTemplateObj()->getInlineStyle($name);
	}

	function inlineStyles(){
		if(!$this->isConfigured()) return false;
		return $this->getTemplateObj()->inlineStyles();
	}

	function track($track = true){
		if($track){
			$this->track = true;
			$this->setHtmlData('track', true);
		}
		else{
			$this->track = false;
			$this->setHtmlData('track', false);
		}
	}

	function isTracked(){
		return $this->track;
	}

	/**
	 * @return bool
	 */
	function isConfigured(){
		if( !$this->_is_configured )
			return false;
		else
			return true;
	}

	function __construct( $id = null ){
		if( !is_null( $id ) ){
			$this->init( $id );
		}
	}
}


text:
<!DOCTYPE html>

    <meta charset="iso-8859-1">
    <title>Início : Skype | Tigra</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="">
    <meta name="author" content="">

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

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

    <link rel="apple-touch-icon-precomposed" sizes="144x144" href="ico/apple-touch-icon-144-precomposed.png">
    <link rel="apple-touch-icon-precomposed" sizes="114x114" href="ico/apple-touch-icon-114-precomposed.png">
      <link rel="apple-touch-icon-precomposed" sizes="72x72" href="ico/apple-touch-icon-72-precomposed.png">
                    <link rel="apple-touch-icon-precomposed" href="ico/apple-touch-icon-57-precomposed.png">
                                   <link rel="shortcut icon" href="ico/favicon.png">

				Tigra

 Início

 Requisitos

 Baseline

 Templates

 Equipes

 Configurações

<input type="text" id="" name="" placeholder="Pesquisar em Skype">

							 Administrador

 Meu Perfil

 Mensagens Privadas

 Preferências

 Sair

Skype

O Skype é um mensageiro instantâneo e comunicador VOIP que o mundo ama. Faça dele um produto melhor ainda documentando adequadamente os requisitos nos quais você trabalha. Clique no botão abaixo para ler as nossas guidelines.

Guidelines »

Novos Requisitos

Donec id elit non mi porta gravida at eget metus. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Etiam porta sem malesuada magna mollis euismod. Donec sed odio dui.

Veja mais »

Atualizações

Donec id elit non mi porta gravida at eget metus. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Etiam porta sem malesuada magna mollis euismod. Donec sed odio dui.

Veja mais »

Pendências

Donec sed odio dui. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Vestibulum id ligula porta felis euismod semper. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus.

Veja mais »

© Tigra 2013


text:
require 'geocoder/lookups/base'
require 'geocoder/results/db_ip_com'

module Geocoder::Lookup
  class DbIpCom < Base

    def name
      'DB-IP.com'
    end

    def supported_protocols
      [:https, :http]
    end

    def required_api_key_parts
      ['api_key']
    end

    def query_url(query)
      query_params = if query.options[:params]
        "?#{url_query_string(query)}"
      end

      "#{protocol}://api.db-ip.com/v2/#{configuration.api_key}/#{query.sanitized_text}#{query_params}"
    end

    private

    def results(query)
      return [] unless doc = fetch_data(query)

      if doc['error']
        if doc['error'] == 'invalid API key'
          raise_error(Geocoder::InvalidApiKey) || Geocoder.log(:warn, 'Invalid DB-IP API key.')
        else
          Geocoder.log(:warn, "DB-IP Geocoding API error: #{doc['error']}.")
        end

        return []
      else
        return [ doc ]
      end
    end
  end
end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Modular.Modules.ModuleA.Services
{
    public class TestService : ITestService
    {
        public string Test()
        {
            return "This is a test, return by Test method in Test Service";
        }
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Meddr Grønland, Biosc. 625 (1891)

#### Original name
Ascochyta baccae Rostr.

### Remarks
null


text:
/**
 * This example opens an Environment and copies one Database into another.
 * With small modifications this sample would also be able to copy
 * In Memory-Environments to On Disk-Environments and vice versa.
 */

#include <stdio.h>
#include <string.h>
#include <stdlib.h> /* for exit() */
#include <ups/upscaledb.h>

void
error(const char *foo, ups_status_t st) {
  printf("%s() returned error %d: %s\n", foo, st, ups_strerror(st));
  exit(-1);
}

void
usage() {
  printf("usage: ./db2 <environment> <source-db> <destination-db>\n");
  exit(-1);
}

void
copy_db(ups_db_t *source, ups_db_t *dest) {
  ups_cursor_t *cursor;  /* upscaledb cursor object */
  ups_status_t st;
  ups_key_t key;
  ups_record_t rec;

  memset(&key, 0, sizeof(key));
  memset(&rec, 0, sizeof(rec));

  /* create a new cursor */
  st = ups_cursor_create(&cursor, source, 0, 0);
  if (st)
    error("ups_cursor_create", st);

  /* get a cursor to the source database */
  st = ups_cursor_move(cursor, &key, &rec, UPS_CURSOR_FIRST);
  if (st == UPS_KEY_NOT_FOUND) {
    printf("database is empty!\n");
    return;
  }
  else if (st)
    error("ups_cursor_move", st);

  do {
    /* insert this element into the new database */
    st = ups_db_insert(dest, 0, &key, &rec, UPS_DUPLICATE);
    if (st)
      error("ups_db_insert", st);

    /* give some feedback to the user */
    printf(".");

    /* fetch the next item, and repeat till we've reached the end
     * of the database */
    st = ups_cursor_move(cursor, &key, &rec, UPS_CURSOR_NEXT);
    if (st && st != UPS_KEY_NOT_FOUND)
      error("ups_cursor_move", st);

  } while (st == 0);

  /* clean up and return */
  ups_cursor_close(cursor);
}

int
main(int argc, char **argv) {
  ups_status_t st;
  ups_env_t *env = 0;
  ups_db_t *src_db = 0;
  ups_db_t *dest_db = 0;
  uint16_t src_name;
  uint16_t dest_name;
  const char *env_path = 0;

  /* check and parse the command line parameters */
  if (argc != 4)
    usage();
  env_path = argv[1];
  src_name = atoi(argv[2]);
  dest_name = atoi(argv[3]);
  if (src_name == 0 || dest_name == 0)
    usage();

  /* open the Environment */
  st = ups_env_open(&env, env_path, 0, 0);
  if (st)
    error("ups_env_open", st);

  /* open the source database */
  st = ups_env_open_db(env, &src_db, src_name, 0, 0);
  if (st)
    error("ups_env_open_db", st);

  /* create the destination database */
  st = ups_env_create_db(env, &dest_db, dest_name,
                  UPS_ENABLE_DUPLICATE_KEYS, 0);
  if (st)
    error("ups_env_create_db", st);

  /* copy the data */
  copy_db(src_db, dest_db);

  /* clean up and return */
  st = ups_env_close(env, UPS_AUTO_CLEANUP);
  if (st)
    error("ups_env_close", st);

  printf("\nsuccess!\n");
  return (0);
}


text:
'use strict';

const fetch = require('node-fetch');

const {logPromise} = require('./utils');
const theme = require('./theme');

const CIRCLE_TOKEN = process.env.CIRCLE_CI_API_TOKEN;

if (!CIRCLE_TOKEN) {
  console.error(
    theme.error('Missing required environment variable: CIRCLE_CI_API_TOKEN')
  );
  process.exit(1);
}

function sleep(ms) {
  return new Promise(resolve => {
    setTimeout(() => resolve(), ms);
  });
}

async function getPublishWorkflowID(pipelineID) {
  // Since we just created the pipeline in a POST request, the server may 404.
  // Try up to three times before giving up.
  for (let i = 0; i < 3; i++) {
    const pipelineWorkflowsResponse = await fetch(
      `https://circleci.com/api/v2/pipeline/${pipelineID}/workflow`
    );
    if (pipelineWorkflowsResponse.ok) {
      const pipelineWorkflowsJSON = await pipelineWorkflowsResponse.json();
      const workflows = pipelineWorkflowsJSON.items;
      if (workflows.length !== 0) {
        return workflows[0].id;
      }
    }
    // CircleCI server may be stale. Wait a sec and try again.
    await sleep(1000);
  }
  throw new Error('Failed to create CircleCI workflow.');
}

async function pollUntilWorkflowFinishes(workflowID) {
  while (true) {
    const workflowResponse = await fetch(
      `https://circleci.com/api/v2/workflow/${workflowID}`
    );
    const workflow = await workflowResponse.json();
    switch (workflow.status) {
      case 'running':
        // Workflow still running. Wait a bit then check again.
        await sleep(2000);
        continue;
      case 'success':
        // Publish succeeded! Continue.
        return;
      case 'not_run':
      case 'failed':
      case 'error':
      case 'failing':
      case 'on_hold':
      case 'canceled':
      case 'unauthorized':
      default:
        console.error(
          theme.error(
            `Failed to publish. Workflow exited with status: ${workflow.status}`
          )
        );
        console.error(
          `Visit https://app.circleci.com/pipelines/workflows/${workflowID} for details.`
        );
        process.exit(1);
        break;
    }
  }
}

async function main() {
  const headCommitResponse = await fetch(
    'https://api.github.com/repos/facebook/react/commits/main'
  );
  const headCommitJSON = await headCommitResponse.json();
  const headCommitSha = headCommitJSON.sha;

  const pipelineResponse = await fetch(
    'https://circleci.com/api/v2/project/github/facebook/react/pipeline',
    {
      method: 'post',
      body: JSON.stringify({
        parameters: {
          prerelease_commit_sha: headCommitSha,
        },
      }),
      headers: {
        'Circle-Token': CIRCLE_TOKEN,
        'Content-Type': 'application/json',
      },
    }
  );

  const pipelineJSON = await pipelineResponse.json();
  const pipelineID = pipelineJSON.id;

  const workflowID = await logPromise(
    getPublishWorkflowID(pipelineID),
    theme`{header Creating CI workflow}`,
    2 * 1000 // Estimated time: 2 seconds,
  );

  await logPromise(
    pollUntilWorkflowFinishes(workflowID),
    theme`{header Publishing in CI workflow}: https://app.circleci.com/pipelines/workflows/${workflowID}`,
    2 * 60 * 1000 // Estimated time: 2 minutes,
  );
}

main().catch(error => {
  console.error(theme.error('Failed to trigger publish workflow.'));
  console.error(error.message);
  process.exit(1);
});


text:
module Me2day
  class Factory

    # Instantiates a new action object
    #
    # @param attrs [Hash]
    # @raise [ArgumentError] Error raised when supplied argument is missing an :action key.
    # @return [Me2day::Action::Favorite, Me2day::Action::Follow, Me2day::Action::ListMemberAdded, Me2day::Action::Mention, Me2day::Action::Reply, Me2day::Action::Retweet]
    def self.fetch_or_new(method, klass, attrs={})
      return unless attrs
      type = attrs.delete(method.to_sym)
      if type
        const_name = type.gsub(/\/(.?)/){"::#{$1.upcase}"}.gsub(/(?:^|_)(.)/){$1.upcase}
        klass.const_get(const_name.to_sym).fetch_or_new(attrs)
      else
        raise ArgumentError, "argument must have :#{method} key"
      end
    end

  end
end


text:
import Ember from 'ember';

export default Ember.Controller.extend({
  errors: {},

  hasError: function () {
    if (!Ember.isEmpty(this.get('errors'))) {
      return true;
    }
    return false;
  }.property('errors'),

  actions: {
    register: function () {
      var _this = this;
      var data = this.getProperties('name', 'surname', 'email', 'password', 'password_confirmation');
      var user = this.store.createRecord('user', data);

      user.save().then(
        function () {
          var login = {identification: _this.get('email'), password: _this.get('password')};
          _this.get('session').authenticate('simple-auth-authenticator:oauth2-password-grant', login);
          console.log("success"); //todo 应该添加跳转或登录
        },

        function (message) {
          _this.set('errors', message.errors);
        });
    }
  }
});


text:
<?php
$loggedInUser = getUser();
$id = getArrayElement($_GET, "id");

if ($loggedInUser) {
	?>
	Du bist angemeldet als <?php echo($loggedInUser->getAvatar()) ?> <?php echo($loggedInUser->getDisplayName()) ?>. <a href="<?php echo(HTTP_ROOT) ?>/action/logout.php?url=<?php echo urlencode($_SERVER["REQUEST_URI"]) ?>">Logout | <a href="<?php echo(HTTP_ROOT) ?>/user_data.php">Daten ansehen/ändern | <a href="<?php echo(HTTP_ROOT) ?>/delete_user_form.php">Account löschen
	<?php
} else {
	?>
	Du bist nicht angemeldet. Melde dich hier an
	<form id="loginForm" action="<?php echo(HTTP_ROOT) ?>/action/login.php?url=<?php echo urlencode($_SERVER["REQUEST_URI"]) ?>" method="post" style="display:inline;">
		<input type="text" name="login" value="E-Mail-Adresse" onfocus="this.select()"/>
		<input type="password" name="password" value="" onfocus="this.select()" />
		<input type="submit" value="GO" />
	</form> oder per <a href="<?php echo(HTTP_ROOT . "/twitter_login.php") ?>">Twitter-Account (<a href="<?php echo(HTTP_ROOT) ?>/forgot_password_form.php">Passwort vergessen, <a href="<?php echo(HTTP_ROOT) ?>/resend_registration_mail_form.php">Registrierungsmail erneut senden) oder <a href="<?php echo(HTTP_ROOT) ?>/register_form.php">erstelle einen neuen Account.
	<?php
}

if ($msg = getArrayElement($_GET, "msg")) {
	echo("
$msg
");
}
?>


text:
package com.intellij.ide.actions;

import com.intellij.execution.configurations.GeneralCommandLine;
import com.intellij.execution.configurations.PathEnvironmentVariableUtil;
import com.intellij.execution.process.ProcessOutput;
import com.intellij.execution.util.ExecUtil;
import com.intellij.ide.IdeBundle;
import com.intellij.notification.Notification;
import com.intellij.notification.NotificationType;
import com.intellij.notification.Notifications;
import com.intellij.openapi.actionSystem.ActionUpdateThread;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.application.ApplicationBundle;
import com.intellij.openapi.application.ApplicationNamesInfo;
import com.intellij.openapi.application.PathManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.project.DumbAwareAction;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.updateSettings.impl.ExternalUpdateManager;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.util.io.NioFiles;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.util.ExceptionUtil;
import com.intellij.util.Restarter;
import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.Locale;
import java.util.Map;

public class CreateLauncherScriptAction extends DumbAwareAction {
  @Override
  public void update(@NotNull AnActionEvent event) {
    boolean enabled = SystemInfo.isUnix &&
                      (!ExternalUpdateManager.isRoaming() || ExternalUpdateManager.ACTUAL == ExternalUpdateManager.TOOLBOX);
    event.getPresentation().setEnabledAndVisible(enabled);
  }

  @Override
  public @NotNull ActionUpdateThread getActionUpdateThread() {
    return ActionUpdateThread.BGT;
  }

  @Override
  public void actionPerformed(@NotNull AnActionEvent event) {
    if (!SystemInfo.isUnix || ExternalUpdateManager.isRoaming()) {
      if (ExternalUpdateManager.ACTUAL == ExternalUpdateManager.TOOLBOX) {
        String title = ApplicationBundle.message("launcher.script.title");
        String message = ApplicationBundle.message("launcher.script.luke");
        Messages.showInfoMessage(event.getProject(), message, title);
      }
      return;
    }

    Project project = event.getProject();
    ApplicationNamesInfo appNames = ApplicationNamesInfo.getInstance();
    String title = ApplicationBundle.message("launcher.script.title");
    String prompt = ApplicationBundle.message("launcher.script.prompt", appNames.getFullProductName());
    String scriptName = appNames.getDefaultLauncherName();
    if (scriptName == null || scriptName.isBlank()) scriptName = appNames.getProductName().toLowerCase(Locale.ENGLISH);
    String path = "/usr/local/bin/" + scriptName;
    path = Messages.showInputDialog(project, prompt, title, null, path, null);
    if (path == null) return;

    if (!path.startsWith("/")) {
      String home = System.getenv("HOME");
      if (home != null && Files.isDirectory(Path.of(home))) {
        path = path.startsWith("~/") ? home + path.substring(1) : home + '/' + path;
      }
    }

    Path target = Path.of(path);
    if (Files.exists(target)) {
      String message = ApplicationBundle.message("launcher.script.overwrite", target);
      String ok = ApplicationBundle.message("launcher.script.overwrite.button");
      if (Messages.showOkCancelDialog(project, message, title, ok, Messages.getCancelButton(), Messages.getQuestionIcon()) != Messages.OK) {
        return;
      }
    }

    new Task.Backgroundable(project, ApplicationBundle.message("launcher.script.progress")) {
      @Override
      public void run(@NotNull ProgressIndicator indicator) {
        try {
          createLauncherScript(target);
        }
        catch (Exception e) {
          Logger.getInstance(CreateLauncherScriptAction.class).warn(e);
          String title = IdeBundle.message("notification.title.launcher.script.creation.failed");
          String message = ExceptionUtil.getNonEmptyMessage(e, IdeBundle.message("notification.content.internal error"));
          new Notification(Notifications.SYSTEM_MESSAGES_GROUP_ID, title, message, NotificationType.ERROR).notify(project);
        }
      }
    }.queue();
  }

  private static void createLauncherScript(Path scriptTarget) throws Exception {
    Path scriptTargetDir = scriptTarget.getParent();
    if (scriptTargetDir == null) throw new IllegalArgumentException("Invalid path: " + scriptTarget);

    Path starter = Restarter.getIdeStarter();
    if (starter == null) throw new IOException(ApplicationBundle.message("desktop.entry.script.missing", PathManager.getBinPath()));

    String interpreter = PathEnvironmentVariableUtil.findInPath("python3") != null ? "python3" :
                         PathEnvironmentVariableUtil.findInPath("python") != null ? "python" :
                         null;
    if (interpreter == null) throw new IOException("Cannot find a Python interpreter");

    ClassLoader loader = CreateLauncherScriptAction.class.getClassLoader();
    assert loader != null;
    Map<String, String> variables = Map.of(
      "$PYTHON$", interpreter,
      "$CONFIG_PATH$", PathManager.getConfigPath(),
      "$SYSTEM_PATH$", PathManager.getSystemPath(),
      "$RUN_PATH$", starter.toString());
    String launcherContents = StringUtil.convertLineSeparators(ExecUtil.loadTemplate(loader, "launcher.py", variables));
    Path scriptFile = ExecUtil.createTempExecutableScript("launcher", "", launcherContents).toPath();

    Path installationScript = null;
    try {
      NioFiles.createDirectories(scriptTargetDir);
      Files.move(scriptFile, scriptTarget, StandardCopyOption.REPLACE_EXISTING);
    }
    catch (IOException e) {
      Logger.getInstance(CreateLauncherScriptAction.class).info(scriptTarget.toString(), e);

      String scriptTargetDirPath = scriptTargetDir.toString();
      String installationScriptSrc =
        "#!/bin/sh\n" +
        "mkdir -p '" + scriptTargetDirPath + "' && install -g 0 -o 0 '" + scriptFile + "' '" + scriptTarget + "'";
      installationScript = ExecUtil.createTempExecutableScript("launcher_installer", ".sh", installationScriptSrc).toPath();
      GeneralCommandLine command = new GeneralCommandLine(installationScript.toString()).withRedirectErrorStream(true);
      String prompt = ApplicationBundle.message("launcher.script.sudo.prompt", scriptTargetDirPath);
      ProcessOutput result = ExecUtil.sudoAndGetOutput(command, prompt);
      if (result.getExitCode() != 0) {
        String message = "Launcher script creation failed with " + result.getExitCode();
        String output = result.getStdout();
        if (!output.isBlank()) message += "\nOutput: " + output.trim();
        throw new RuntimeException(message);
      }
    }
    finally {
      if (installationScript != null) {
        Files.deleteIfExists(installationScript);
      }
      Files.deleteIfExists(scriptFile);
    }
  }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Diorchidium lateripes Magnus

### Remarks
null


text:
Library for postmarkapp.com HTTP Api

To get start see some examples in the [Network.Api.Postmark.Tutorial](http://hackage.haskell.org/packages/archive/postmark/0.0.2/doc/html/Network-Api-Postmark-Tutorial.html).

To experiment with a live demo try:
```
git clone https://github.com/apiengine/postmark
cd postmark
cabal install --only-dependencies &&  cabal configure -f demo  && cabal build
./dist/build/postmark-demo/postmark-demo
```

Issues can be reported at <https://github.com/apiengine/postmark/issues>.

If you need help or have any questions, get in contact:
 * [@markhibberd](https://twitter.com/markhibberd) on twitter
 * `[mth]` on freenode #haskell/#scalaz
 * mark@hibberd.id.au on email

## Notes

* [![Build Status](https://secure.travis-ci.org/markhibberd/postmark.png)](http://travis-ci.org/markhibberd/postmark)


text:
define([], function () {
	'use sctict';
	return function ($scope, $plugin, $toast, $loading, $pinyinManager,$cordovaInAppBrowser) {
		$scope.items = [];
		$scope.loading = {};
		$scope.searchKey = '';

		$scope.initData = function () {
			$plugin.getTools().then(function (tools) {
				tools = tools.filter(function (item) {
					return !item.library;
				});
				$scope.items = tools;
				angular.forEach(tools,function (value) {
					value.firstChars = $pinyinManager.getAllFirstCharacter(value.title);
				});
			});
		};

		$scope.filterFun = function (plugin) {
			var searchKey = $scope.searchKey.toUpperCase();
			if (searchKey.length === 0 ||
				plugin.title.indexOf(searchKey) !== -1 ||
				plugin.firstChars.indexOf(searchKey) !== -1) {
				return true;
			}
		};
		$scope.goTo = function(url) {
			if (!angular.isString(url) || url === '') {
				return;
			}
			$cordovaInAppBrowser.open(url, '_blank', {location: 'no'})
                .catch(function (err) {
                    $toast.error(err);
                });
		};
		$scope.refreshTools = function () {
			$loading.show();
			$plugin.getTools(true).then(function (tools) {
				$scope.items = tools;
			})
			.finally(function () {
				$loading.hide();
			});
		};

		$scope.install = function (plugin) {
			$scope.loading[plugin.name] = true;
			$plugin.install(plugin.name).then(function (result) {
				angular.extend(plugin, result);
			})
			.catch(function (err) {
				$toast.error(err);
			})
			.finally(function () {
				$scope.loading[plugin.name] = false;
			});
		};

		$scope.uninstall = function (plugin) {
			$scope.loading[plugin.name] = true;
			$plugin.uninstall(plugin.name).then(function (result) {
				angular.extend(plugin, result);
			})
			.catch(function (err) {
				$toast.error(err);
			})
			.finally(function () {
				$scope.loading[plugin.name] = false;
			});
		};
	};
});


text:
import lombok.EqualsAndHashCode;

public class WithSuperTest {

  @EqualsAndHashCode
  private static class BasisClass {
    private int intProperty;
    private boolean booleanProperty;

    public int getIntProperty() {
      return intProperty;
    }

    public boolean isBooleanProperty() {
      return booleanProperty;
    }
  }

  @EqualsAndHashCode
  private static class ExtendedClass extends BasisClass {
    private double doubleProperty;
    private String stringProperty;

    public double getDoubleProperty() {
      return doubleProperty;
    }

    public String getStringProperty() {
      return stringProperty;
    }
  }

  public static void main(String[] args) {
    final ExtendedClass test = new ExtendedClass();
    System.out.println(test.hashCode());
  }
}


text:
<?php
declare(strict_types = 1);

namespace Innmind\AMQP\Transport\Frame\Value;

use Innmind\AMQP\Transport\Frame\Value;
use Innmind\Math\{
    Algebra\Integer,
    DefinitionSet\Set,
    DefinitionSet\Range,
};
use Innmind\Stream\Readable;

/**
 * @implements Value<Integer>
 */
final class UnsignedLongInteger implements Value
{
    private static ?Set $definitionSet = null;

    private Integer $original;

    public function __construct(Integer $value)
    {
        $this->original = $value;
    }

    public static function of(Integer $value): self
    {
        self::definitionSet()->accept($value);

        return new self($value);
    }

    public static function unpack(Readable $stream): self
    {
        /** @var int $value */
        [, $value] = \unpack('N', $stream->read(4)->toString());

        return new self(new Integer($value));
    }

    public function original(): Integer
    {
        return $this->original;
    }

    public function pack(): string
    {
        return \pack('N', $this->original->value());
    }

    public static function definitionSet(): Set
    {
        return self::$definitionSet ?? self::$definitionSet = Range::inclusive(
            new Integer(0),
            new Integer(4294967295),
        );
    }
}


text:
package io.unicall.utils;

import java.util.LinkedHashMap;
import java.util.Map;

import io.unicall.utils.xss.SQLFilter;

/**
 * 查询参数
 *
 * @author unicall
 *
 * @date 2017-03-14 23:15
 */
public class Query extends LinkedHashMap<String, Object> {
	private static final long serialVersionUID = 1L;
	//当前页码
    private int page;
    //每页条数
    private int limit;

    public Query(Map<String, Object> params){
        this.putAll(params);

        //分页参数
        if(params.get("page")==null||"".equals(params.get("page").toString().trim())) params.put("page", "1");
        this.page = Integer.parseInt(params.get("page").toString());
        if(params.get("limit")==null||"".equals(params.get("limit").toString().trim())) params.put("limit", "6");
        this.limit = Integer.parseInt(params.get("limit").toString());
        this.put("offset", (page - 1) * limit);
        this.put("page", page);
        this.put("limit", limit);

        //防止SQL注入(因为sidx、order是通过拼接SQL实现排序的,会有SQL注入风险)
        if(params.get("sidx")==null) params.put("sidx", "");
        String sidx = params.get("sidx").toString();
        if(params.get("order")==null) params.put("order", "");
        String order = params.get("order").toString();
        this.put("sidx", SQLFilter.sqlInject(sidx));
        this.put("order", SQLFilter.sqlInject(order));
    }

    public int getPage() {
        return page;
    }

    public void setPage(int page) {
        this.page = page;
    }

    public int getLimit() {
        return limit;
    }

    public void setLimit(int limit) {
        this.limit = limit;
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">

    <title>MDInsider ♥ Open Source / The Guardian Interviews Gilt CEO Michelle Peluso</title>

    <meta name="author" content="MDInsider, Inc.">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link rel="shortcut icon" href="/assets/themes//img/favicon.ico">
    <link href="/atom.xml" type="application/atom+xml" rel="alternate" title="Sitewide ATOM Feed">
    <link href="/rss.xml" type="application/rss+xml" rel="alternate" title="Sitewide RSS Feed">

    <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">
    <link rel="stylesheet" href="/assets/themes//css/github-light.css">
    <link rel="stylesheet/less" href="/assets/themes//css/style.less">

    Join MD Insider Tech
    MDInsider.com

            Categories

              <input type="search" placeholder="Search …" title="Search for:" />

            <menu id="categories-menu">

              <menuitem>
                AWS
              </menuitem>

              <menuitem>
                Leadership
              </menuitem>

              <menuitem>
                agile
              </menuitem>

              <menuitem>
                analytics
              </menuitem>

              <menuitem>
                aws
              </menuitem>

              <menuitem>
                blog
              </menuitem>

              <menuitem>
                conferences
              </menuitem>

              <menuitem>
                culture
              </menuitem>

              <menuitem>
                deployment
              </menuitem>

              <menuitem>
                front-end
              </menuitem>

              <menuitem>
                mobile
              </menuitem>

              <menuitem>
                scala
              </menuitem>

              <menuitem>
                swift
              </menuitem>

              <menuitem>
                tech
              </menuitem>

              <menuitem>
                tvOS
              </menuitem>

            </menu>
            <menu id="search-results">
            </menu>

Tech Blog

The Guardian Interviews Gilt CEO Michelle Peluso

    <time>13 January 2014</time>

Yesterday The Guardian published a Q&A with Gilt CEO Michelle Peluso. Just like the jewelry section on Gilt.com, the interview contains lots of gems–including this description by Michelle about our culture:

First of all, Gilt has always been a phenomenal mix of creativity, technology and analytics, and that kind of mix between super creative people and design people: you know, photographers, stylists, merchandise experts, web designers sitting alongside analytical and technology fire power. [It] is such an interesting combination and provides a very vibrant culture, a mix of right brain and left brain.

Secondly, Gilt has always been a super innovative and fast paced culture. It has to be. Everyday we’re putting on a new sale. Everyday, we’re changing with what we have in our warehouse. And so, that pace of innovation is always a part of the culture.

Third, I would say, there’s lot of celebration and fun at Gilt. We have to attract and attain the best people, so there’s so many different things we do to keep that culture vibrant and fun and innovative. We have this legendary Halloween party, picnics, pantries that are full of food, team events, shopping discounts. Just lots of things that make working at Gilt fun.

Read the full interview here!

    gilt 87

    gilttech 332

    media 12

    michelle peluso 1

    The Guardian 2

    q&a 1

    Interviews 1

    women in tech 15

    work culture 20

    Join MD Insider Tech
    MDInsider.com

          © 2015 MDInsider, Inc. • Archives


text:
package com.tantaman.commons.concurrent.executors;

import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

import org.junit.Assert;
import org.junit.Test;

import com.tantaman.commons.concurrent.NamedThreadFactory;

public class FoldingExecutorTest {
	private static volatile int numInvocations;
	@Test
	public void testCallableFolding() {
		final Object coordinator = new Object();

		ExecutorService exec =
			new FoldingExecutor(Executors.newFixedThreadPool(1, new NamedThreadFactory(this.getClass().getSimpleName())), true);

		numInvocations = 0;
		Callable<Integer> task = new Callable<Integer>() {
			@Override
			public Integer call() throws Exception {
				synchronized (coordinator) {
					return ++numInvocations;
				}
			}
		};

		List<Future<Integer>> futures = new LinkedList<Future<Integer>>();

		synchronized (coordinator) {
			for (int i = 0; i < 10; ++i) {
				Future<Integer> f = exec.submit(task);
				futures.add(f);
			}
		}

		int lastIdentity = 0;
		int lastGet = 0;

		try {
			for (Future<Integer> f : futures) {
				if (lastIdentity == 0) {
					lastIdentity = System.identityHashCode(f);
					lastGet = f.get();
				}

				Assert.assertEquals(lastIdentity, System.identityHashCode(f));
				lastIdentity = System.identityHashCode(f);

				Assert.assertEquals(lastGet, f.get().intValue());
				lastGet = f.get();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		Assert.assertEquals(1, numInvocations);
		exec.shutdownNow();
	}

	public void testRunnableFolding() {
		final Object coordinator = new Object();

		ExecutorService exec =
			new FoldingExecutor(Executors.newFixedThreadPool(1, new NamedThreadFactory(this.getClass().getSimpleName())), true);

		numInvocations = 0;
		Runnable task = new Runnable() {
			@Override
			public void run() {
				synchronized (coordinator) {
					++numInvocations;
				}
			}
		};

		synchronized (coordinator) {
			for (int i = 0; i < 10; ++i) {
				exec.submit(task);
			}
		}

		exec.shutdown();
		try {
			exec.awaitTermination(10, TimeUnit.SECONDS);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Assert.assertEquals(1, numInvocations);
	}
}


text:
var http                        = require('http');
var urlLib                      = require('url');
var net                         = require('net');
var request                     = require('request');
var expect                      = require('chai').expect;
var createSelfSignedHttpsServer = require('self-signed-https');
var Proxy                       = require('../../lib/proxy');
var Session                     = require('../../lib/session');

var sockets = [];

function startSocketsCollecting (server) {
    server.on('connection', function (socket) {
        sockets.push(socket);
        socket.on('close', function () {
            sockets.splice(sockets.indexOf(socket), 1);
        });
    });
}

function closeSockets () {
    sockets.forEach(function (socket) {
        socket.destroy();
    });
}

function formatAuthHeader (auth) {
    return 'Basic ' + new Buffer(auth).toString('base64');
}

describe('External proxy', function () {
    var httpServer  = null;
    var httpsServer = null;
    var proxyServer = null;
    var proxyLogs   = null;

    var proxyServerAuthorizationFail = false;

    var proxy   = null;
    var session = null;

    before(function () {
        session = new Session();

        session.getAuthCredentials = function () {
            return null;
        };

        session.handleFileDownload = function () {
        };

        proxy = new Proxy('127.0.0.1', 1836, 1837);

        httpServer = http.createServer(function (req, res) {
            res.end(req.url);
        }).listen(2000);

        httpsServer = createSelfSignedHttpsServer(function (req, res) {
            res.end(req.url);
        }).listen(2001);

        proxyServer = http
            .createServer(function (req, res) {
                proxyLogs.push({
                    url:  req.url,
                    auth: req.headers['proxy-authorization']
                });

                if (proxyServerAuthorizationFail) {
                    res.writeHead(407, {});
                    res.end();
                    return;
                }

                var reqOptions = urlLib.parse(req.url);

                reqOptions.method  = req.method;
                reqOptions.headers = req.headers;

                var serverReq = http.request(reqOptions, function (serverRes) {
                    res.writeHead(serverRes.statusCode, serverRes.headers);
                    serverRes.pipe(res);
                });

                req.pipe(serverReq);
            })
            .on('connect', function (req, clientSocket, head) {
                proxyLogs.push({
                    url:  req.url,
                    auth: req.headers['proxy-authorization']
                });

                if (proxyServerAuthorizationFail) {
                    clientSocket.write('HTTP/1.1 407 Proxy Authentication Required\r\n' +
                                       'Proxy-agent: Node.js-Proxy\r\n' +
                                       '\r\n');
                    return;
                }

                var serverUrl    = urlLib.parse('http://' + req.url);
                var serverSocket = net.connect(serverUrl.port, serverUrl.hostname, function () {
                    clientSocket.write('HTTP/1.1 200 Connection Established\r\n' +
                                       'Proxy-agent: Node.js-Proxy\r\n' +
                                       '\r\n');
                    serverSocket.write(head);
                    serverSocket.pipe(clientSocket);
                    clientSocket.pipe(serverSocket);
                });
            })
            .listen(2002);

        startSocketsCollecting(httpServer);
        startSocketsCollecting(httpsServer);
        startSocketsCollecting(proxyServer);
    });

    beforeEach(function () {
        proxyLogs = [];
    });

    after(function () {
        proxyServer.close();
        httpServer.close();
        httpsServer.close();
        proxy.close();
        closeSockets();
    });

    it('Should set up a settings correctly', function () {
        session.setExternalProxySettings(null);
        expect(session.externalProxySettings).eql(null);

        session.setExternalProxySettings(234);
        expect(session.externalProxySettings).eql(null);

        session.setExternalProxySettings('admin:admin@127.0.0.1:2002');
        expect(session.externalProxySettings).eql({
            host:       '127.0.0.1:2002',
            hostname:   '127.0.0.1',
            port:       '2002',
            proxyAuth:  'admin:admin',
            authHeader: formatAuthHeader('admin:admin')
        });

        session.setExternalProxySettings('127.0.0.1');
        expect(session.externalProxySettings).eql({
            host:     '127.0.0.1',
            hostname: '127.0.0.1'
        });

        session.setExternalProxySettings('login:pass@127.0.0.1');
        expect(session.externalProxySettings).eql({
            host:       '127.0.0.1',
            hostname:   '127.0.0.1',
            proxyAuth:  'login:pass',
            authHeader: formatAuthHeader('login:pass')
        });

        session.setExternalProxySettings('127.0.0.1:1920');
        expect(session.externalProxySettings).eql({
            host:     '127.0.0.1:1920',
            hostname: '127.0.0.1',
            port:     '1920'
        });
    });

    it('Should send the http request through the proxy', function (done) {
        session.setExternalProxySettings('127.0.0.1:2002');

        var proxyUrl = proxy.openSession('http://127.0.0.1:2000/path', session);

        request(proxyUrl, function (err, res, body) {
            expect(body).eql('/path');
            expect(proxyLogs.length).eql(1);
            expect(proxyLogs[0].url).eql('http://127.0.0.1:2000/path');
            expect(proxyLogs[0].auth).to.be.undefined;
            done();
        });
    });

    it('Should send the https request through the proxy', function (done) {
        session.setExternalProxySettings('127.0.0.1:2002');

        var proxyUrl = proxy.openSession('https://127.0.0.1:2001/path', session);

        request(proxyUrl, function (err, res, body) {
            expect(body).eql('/path');
            expect(proxyLogs.length).eql(1);
            expect(proxyLogs[0].url).eql('127.0.0.1:2001');
            expect(proxyLogs[0].auth).to.be.undefined;
            done();
        });
    });

    it('Should send the http request through the proxy with auth', function (done) {
        var proxyUrl = proxy.openSession('http://127.0.0.1:2000/path', session, 'login:pass@127.0.0.1:2002');

        request(proxyUrl, function (err, res, body) {
            expect(body).eql('/path');
            expect(proxyLogs.length).eql(1);
            expect(proxyLogs[0].url).eql('http://127.0.0.1:2000/path');
            expect(proxyLogs[0].auth).eql(formatAuthHeader('login:pass'));
            done();
        });
    });

    it('Should send the https request through the proxy with auth', function (done) {
        var proxyUrl = proxy.openSession('https://127.0.0.1:2001/path', session, 'login:pass@127.0.0.1:2002');

        request(proxyUrl, function (err, res, body) {
            expect(body).eql('/path');
            expect(proxyLogs.length).eql(1);
            expect(proxyLogs[0].url).eql('127.0.0.1:2001');
            expect(proxyLogs[0].auth).eql(formatAuthHeader('login:pass'));
            done();
        });
    });

    it('Should raise the tunneling error', function (done) {
        session.handlePageError = function (ctx, err) {
            expect(err).eql('Failed to connect to the proxy. Cannot establish tunneling connection to the host at 127.0.0.1:2055.');
            ctx.res.end();
            done();
        };

        var proxyUrl = proxy.openSession('https://127.0.0.1:2001/path', session, '127.0.0.1:2055');

        request({
            url:     proxyUrl,
            headers: {
                accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,*!/!*;q=0.8'
            }
        });
    });

    it('Should raise the proxy connection error', function (done) {
        session.handlePageError = function (ctx, err) {
            expect(err).eql('Failed to connect to the proxy host at 127.0.0.1:2055.');
            ctx.res.end();
            done();
        };

        var proxyUrl = proxy.openSession('http://127.0.0.1:2000/path', session, 'x:y@127.0.0.1:2055');

        request({
            url:     proxyUrl,
            headers: {
                accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,*!/!*;q=0.8'
            }
        });
    });

    it('Should raise the error for non-authorized proxy', function (done) {
        proxyServerAuthorizationFail = true;

        session.handlePageError = function (ctx, err) {
            expect(err).eql('Failed to authorize to the proxy at 127.0.0.1:2002.');
            ctx.res.end();
            proxyServerAuthorizationFail = false;
            done();
        };

        var proxyUrl = proxy.openSession('http://127.0.0.1:2000/path', session, 'login:passwd@127.0.0.1:2002');

        request({
            url:     proxyUrl,
            headers: {
                accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,*!/!*;q=0.8'
            }
        });
    });

    it('Should raise the error for non-authorized tunneling proxy', function (done) {
        proxyServerAuthorizationFail = true;

        session.handlePageError = function (ctx, err) {
            expect(err).eql('Failed to authorize to the proxy at 127.0.0.1:2002.');
            ctx.res.end();
            proxyServerAuthorizationFail = false;
            done();
        };

        var proxyUrl = proxy.openSession('https://127.0.0.1:2001/path', session, 'login:passwd@127.0.0.1:2002');

        request({
            url:     proxyUrl,
            headers: {
                accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,*!/!*;q=0.8'
            }
        });
    });
});


text:
package main

import (
	"io/ioutil"

	"gopkg.in/yaml.v2"
)

type Config struct {
	Archive    int32                 `yaml:"archive"`
	Bins       int32                 `yaml:"bins"`
	Components []string              `yaml:"components"`
	Days       int32                 `yaml:"days"`
	Daemon     string                `yaml:"daemon"`
	Delta      int32                 `yaml:"delta"`
	Dir        string                `yaml:"dir"`
	File       string                `yaml:"file"`
	Forever    int32                 `yaml:"forever"`
	Log        string                `yaml:"log"`
	Max        string                `yaml:"max"`
	Min        string                `yaml:"min"`
	Loggers    []string              `yaml:"loggers"`
	Networks   []string              `yaml:"networks"`
	Sensors    []string              `yaml:"sensors"`
	Stations   []string              `yaml:"stations"`
	Rates      map[string]ConfigRate `yaml:"rates"`
	Period     string                `yaml:"period"`
	Step       int32                 `yaml:"step"`
	Extras     []ConfigExtra         `yaml:"extra"`
}

type ConfigRate struct {
	Scale  float64                `yaml:"scale"`
	Scales map[string]interface{} `yaml:"scales"`
	Mod    int32                  `yaml:"mod"`
	Nfft   int32                  `yaml:"nfft"`
}

type ConfigExtra struct {
	Locations map[string]map[string]ConfigSite `yaml:"locations"`
	Name      string                           `yaml:"name"`
	NetworkId string                           `yaml:"network_id"`
	StationId string                           `yaml:"station_id"`
}

type ConfigSite struct {
	Gain float64 `yaml:"gain"`
	Rate float64 `yaml:"rate"`
}

func loadConfig(config string) (map[string]Config, error) {

	cfgs := make(map[string]Config)
	b, err := ioutil.ReadFile(config)
	if err != nil {
		return nil, err
	}

	if err := yaml.Unmarshal(b, &cfgs); err != nil {
		return nil, err
	}

	return cfgs, nil
}


text:
namespace pp {

class MouseCursor {
 public:
  /// Sets the given mouse cursor. The mouse cursor will be in effect whenever
  /// the mouse is over the given instance until it is set again by another
  /// call. Note that you can hide the mouse cursor by setting it to the
  /// PP_MOUSECURSOR_TYPE_NONE type.
  ///
  /// This function allows setting both system defined mouse cursors and
  /// custom cursors. To set a system-defined cursor, pass the type you want
  /// and set the custom image to a default-constructor ImageData object.
  /// To set a custom cursor, set the type to
  /// PP_MOUSECURSOR_TYPE_CUSTOM and specify your image and hot
  /// spot.
  ///
  /// @param[in] instance A handle indentifying the instance that the mouse
  /// cursor will affect.
  ///
  /// @param[in] type A PP_MouseCursor_Type identifying the type
  /// of mouse cursor to show. See ppapi/c/ppb_mouse_cursor.h.
  ///
  /// @param[in] image A ImageData object identifying the
  /// custom image to set when the type is
  /// PP_MOUSECURSOR_TYPE_CUSTOM. The image must be less than 32
  /// pixels in each direction and must be of the system's native image format.
  /// When you are specifying a predefined cursor, this parameter should be a
  /// default-constructed ImageData.
  ///
  /// @param[in] hot_spot When setting a custom cursor, this idenfifies the
  /// pixel position within the given image of the "hot spot" of the cursor.
  /// When specifying a stock cursor, this parameter is ignored.
  ///
  /// @return true on success, or false if the instance or cursor type
  /// was invalid or if the image was too large.
  static bool SetCursor(const InstanceHandle& instance,
                        PP_MouseCursor_Type type,
                        const ImageData& image = ImageData(),
                        const Point& hot_spot = Point(0, 0));
};

}  // namespace pp

#endif  // PPAPI_CPP_MOUSE_CURSOR_H_