text:
:mod:`tabs.campaign`
====================

.. module:: tabs.campaign
   :synopsis:

This module provides the contents of the tab representing the campaign
information in client's graphical interface.

Classes
-------

.. autoclass:: king_phisher.client.tabs.campaign.CampaignViewCredentialsTab
   :show-inheritance:
   :members:

.. autoclass:: king_phisher.client.tabs.campaign.CampaignViewDashboardTab
   :show-inheritance:
   :members:

.. autoclass:: king_phisher.client.tabs.campaign.CampaignViewDeaddropTab
   :show-inheritance:
   :members:

.. autoclass:: king_phisher.client.tabs.campaign.CampaignViewGenericTab
   :show-inheritance:
   :members:

.. autoclass:: king_phisher.client.tabs.campaign.CampaignViewGenericTableTab
   :show-inheritance:
   :members:

.. autoclass:: king_phisher.client.tabs.campaign.CampaignViewMessagesTab
   :show-inheritance:
   :members:

.. autoclass:: king_phisher.client.tabs.campaign.CampaignViewTab
   :show-inheritance:
   :members:
   :special-members: __init__

.. autoclass:: king_phisher.client.tabs.campaign.CampaignViewVisitsTab
   :show-inheritance:
   :members:

redpajama_set_name: RedPajamaGithub


text:
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- vim:set ts=4 sw=4 sts=4 noet: */
#ifndef FLINT_CT_H_
#define FLINT_CT_H_

#include "flint/bc.h"
#include "runtime/execution-unit.h"
#include "runtime/flow.h"

#include <memory>
#include <vector>

namespace flint {

class CalculationDependency;
class Layout;

namespace ct {

typedef std::vector<std::unique_ptr<ReductionUnit> > ReductionUnitVector;

typedef std::vector<std::unique_ptr<CalculationDependency> > CalculationDependencyVector;

enum class Availability {
	kNone = 0,
	kLiteral = 1,
	kConstant = 2
};

class DataFlowAnalyzer {
public:
	DataFlowAnalyzer(const DataFlowAnalyzer &) = delete;
	DataFlowAnalyzer &operator=(const DataFlowAnalyzer &) = delete;

	DataFlowAnalyzer(const Layout *layout, int layer_size, Bytecode *bytecode);

	/*
	 * Returns true if there is no code at all, false otherwise.
	 */
	bool IsEmpty() const;

	void CalculateCodeOffset();

	/*
	 * This function drops some elements of shv_, bhv_, and cv_ not associated
	 * with any existing sector, thus should be called first.
	 */
	bool SolveLocation();

	int GetMaxNoir();

	int GetMaxNumberOfData();

	bool SolveDependencies(const FlowInboundMap *inbound,
						   Availability availability = Availability::kConstant,
						   size_t *color = nullptr);

	void ScheduleEvents(const FlowInboundMap &inbound);

private:
	void CollectCalculationDependencies(CalculationDependencyVector *cdv);

	void CollectReductionUnits(const FlowInboundMap *inbound,
							   ReductionUnitVector *ruv);

protected:
	int GetNol() const;
	ShVector &GetShv();
	BhVector &GetBhv();
	CVector &GetCv();

	const Layout *layout_;
	size_t layer_size_;
	Bytecode *bytecode_;

	std::vector<ExecutionUnit> euv_;

	std::unique_ptr<int[]> code_offset_;
};

}
}

#endif


text:
#ifndef BERRYQTSHOWPERSPECTIVEDIALOG_H
#define BERRYQTSHOWPERSPECTIVEDIALOG_H

#include <QDialog>

class QModelIndex;

namespace Ui {
class QtShowPerspectiveDialog;
}

namespace berry {

struct IPerspectiveRegistry;

class QtShowPerspectiveDialog : public QDialog
{
  Q_OBJECT

public:
  explicit QtShowPerspectiveDialog(IPerspectiveRegistry* perspReg, QWidget *parent = nullptr);
  ~QtShowPerspectiveDialog();

  QString GetSelection() const;

private:

  Q_SLOT void setDescription(const QModelIndex& index);

  Ui::QtShowPerspectiveDialog *ui;
};

}

#endif // BERRYQTSHOWPERSPECTIVEDIALOG_H


text:
autocommit off;
drop table if exists tz_test;

create table tz_test(id int, a char(40), b varchar(40), c string, d enum('a', 'b', 'c'), e enum('12:00:01 PM 01/02/2019', '12:00:01 PM 01/02/2019 +08:00', '12:00:01 PM 01/02/2019 +09:00', '12:00:01 PM 01/02/2019 Asia/Tokyo'));
insert into tz_test values(1, 'aaa', 'bbb', 'ccc', 3, 2);
insert into tz_test values(2, '2020-12-1 20:00:00', '2020-12-1 20:00:00', '2020-12-1 20:00:00', 3, 1);
insert into tz_test values(3, '2020-12-1 20:00:00 +9:00', '2020-12-1 20:00:00 +9:00', '2020-12-1 20:00:00 +9:00', 2, 3);
insert into tz_test values(4, '2020-12-1 20:00:00 Asia/Tokyo', '2020-12-1 20:00:00 Asia/Tokyo', '2020-12-1 20:00:00 Asia/Tokyo', 1, 4);
insert into tz_test values(5, '2020-12-1 20:00:00.789 Asia/Tokyo', '2020-12-1 20:00:00.789 Asia/Tokyo', '2020-12-1 20:00:00.789 Asia/Tokyo', 1, 4);
commit;

set system parameters 'alter_table_change_type_strict=no';
set timezone 'Europe/Malta';
-- 1:00 EU

--test: cast character string columns to TIMESTAMP types
alter table tz_test modify a timestamp;
alter table tz_test modify b timestamp;
alter table tz_test modify c timestamp;
alter table tz_test modify d timestamp;
alter table tz_test modify e timestamp;
show full columns in tz_test;
select * from tz_test order by 1;
rollback;

--test: cast character string columns to TIMESTAMPLTZ types
alter table tz_test modify a timestamp with local time zone;
alter table tz_test modify b timestamp with local time zone;
alter table tz_test modify c timestamp with local time zone;
alter table tz_test modify d timestamp with local time zone;
alter table tz_test modify e timestamp with local time zone;
show full columns in tz_test;
select * from tz_test order by 1;
rollback;

--test: cast character string columns to TIMESTAMPTZ types
alter table tz_test modify a timestamp with time zone;
alter table tz_test modify b timestamp with time zone;
alter table tz_test modify c timestamp with time zone;
alter table tz_test modify d timestamp with time zone;
alter table tz_test modify e timestamp with time zone;
show full columns in tz_test;
select * from tz_test order by 1;

drop table tz_test;
commit;

set timezone 'Asia/Seoul';

autocommit on;


text:
package logs

import "time"

//go:generate go run github.com/maxbrunsfeld/counterfeiter/v6 . Loggable
type Loggable interface {
	ToLog(loc *time.Location) string
	ToSimpleLog() string
	GetSourceName() string
}

//go:generate go run github.com/maxbrunsfeld/counterfeiter/v6 . Repository

type Repository interface {
	RecentLogsFor(appGUID string) ([]Loggable, error)
	TailLogsFor(appGUID string, onConnect func(), logChan chan<- Loggable, errChan chan<- error)
	Close()
}

const defaultBufferTime time.Duration = 25 * time.Millisecond

func max(a, b int) int {
	if a > b {
		return a
	}
	return b
}


text:
finalstate
==========

A configuration managment app written in python/flask and zeromq


text:
[![Docker Hub](https://img.shields.io/badge/docker-ready-blue.svg)](https://registry.hub.docker.com/u/lukasmartinelli/chronograf/) [![Docker Pulls](https://img.shields.io/docker/pulls/lukasmartinelli/chronograf.svg)](https://registry.hub.docker.com/u/lukasmartinelli/chronograf/)

Docker Image for [InfluxDB Chronograf](https://influxdb.com/chronograf/index.html).

![Chronograf Screenshot](https://influxdb.com/img/blog/chronograf.gif)

## Run

```
docker run -t lukasmartinelli/chronograf
```

## Configuration

| Environment Variable    | Description
|-------------------------|------------------------------------------------------
| `INFLUXDB_PROTO`        | InfluxDB logging protocol (default `http`)
| `INFLUXDB_HOST`         | InfluxDB host (default `localhost`)
| `INFLUXDB_PORT`         | InfluxDB port (default `8086`)

## Tags

- 0.1.0
- latest


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

import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;

/**
 * Avail Blanking
 *
 * @see AWS API
 *      Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class AvailBlanking implements Serializable, Cloneable, StructuredPojo {

    /** Blanking image to be used. Leave empty for solid black. Only bmp and png images are supported. */
    private InputLocation availBlankingImage;
    /** When set to enabled, causes video, audio and captions to be blanked when insertion metadata is added. */
    private String state;

    /**
     * Blanking image to be used. Leave empty for solid black. Only bmp and png images are supported.
     *
     * @param availBlankingImage
     *        Blanking image to be used. Leave empty for solid black. Only bmp and png images are supported.
     */

    public void setAvailBlankingImage(InputLocation availBlankingImage) {
        this.availBlankingImage = availBlankingImage;
    }

    /**
     * Blanking image to be used. Leave empty for solid black. Only bmp and png images are supported.
     *
     * @return Blanking image to be used. Leave empty for solid black. Only bmp and png images are supported.
     */

    public InputLocation getAvailBlankingImage() {
        return this.availBlankingImage;
    }

    /**
     * Blanking image to be used. Leave empty for solid black. Only bmp and png images are supported.
     *
     * @param availBlankingImage
     *        Blanking image to be used. Leave empty for solid black. Only bmp and png images are supported.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public AvailBlanking withAvailBlankingImage(InputLocation availBlankingImage) {
        setAvailBlankingImage(availBlankingImage);
        return this;
    }

    /**
     * When set to enabled, causes video, audio and captions to be blanked when insertion metadata is added.
     *
     * @param state
     *        When set to enabled, causes video, audio and captions to be blanked when insertion metadata is added.
     * @see AvailBlankingState
     */

    public void setState(String state) {
        this.state = state;
    }

    /**
     * When set to enabled, causes video, audio and captions to be blanked when insertion metadata is added.
     *
     * @return When set to enabled, causes video, audio and captions to be blanked when insertion metadata is added.
     * @see AvailBlankingState
     */

    public String getState() {
        return this.state;
    }

    /**
     * When set to enabled, causes video, audio and captions to be blanked when insertion metadata is added.
     *
     * @param state
     *        When set to enabled, causes video, audio and captions to be blanked when insertion metadata is added.
     * @return Returns a reference to this object so that method calls can be chained together.
     * @see AvailBlankingState
     */

    public AvailBlanking withState(String state) {
        setState(state);
        return this;
    }

    /**
     * When set to enabled, causes video, audio and captions to be blanked when insertion metadata is added.
     *
     * @param state
     *        When set to enabled, causes video, audio and captions to be blanked when insertion metadata is added.
     * @return Returns a reference to this object so that method calls can be chained together.
     * @see AvailBlankingState
     */

    public AvailBlanking withState(AvailBlankingState state) {
        this.state = state.toString();
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getAvailBlankingImage() != null)
            sb.append("AvailBlankingImage: ").append(getAvailBlankingImage()).append(",");
        if (getState() != null)
            sb.append("State: ").append(getState());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof AvailBlanking == false)
            return false;
        AvailBlanking other = (AvailBlanking) obj;
        if (other.getAvailBlankingImage() == null ^ this.getAvailBlankingImage() == null)
            return false;
        if (other.getAvailBlankingImage() != null && other.getAvailBlankingImage().equals(this.getAvailBlankingImage()) == false)
            return false;
        if (other.getState() == null ^ this.getState() == null)
            return false;
        if (other.getState() != null && other.getState().equals(this.getState()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getAvailBlankingImage() == null) ? 0 : getAvailBlankingImage().hashCode());
        hashCode = prime * hashCode + ((getState() == null) ? 0 : getState().hashCode());
        return hashCode;
    }

    @Override
    public AvailBlanking clone() {
        try {
            return (AvailBlanking) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
        }
    }

    @com.amazonaws.annotation.SdkInternalApi
    @Override
    public void marshall(ProtocolMarshaller protocolMarshaller) {
        com.amazonaws.services.medialive.model.transform.AvailBlankingMarshaller.getInstance().marshall(this, protocolMarshaller);
    }
}


text:
package org.elasticsearch.client.ml.inference.preprocessing;

import org.elasticsearch.client.ml.inference.NamedXContentObject;

/**
 * Describes a pre-processor for a defined machine learning model
 */
public interface PreProcessor extends NamedXContentObject {

    /**
     * @return The name of the pre-processor
     */
    String getName();
}


text:
'use strict'

const t = require('tap')
const test = t.test
const Fastify = require('../..')
const supportedMethods = ['DELETE', 'GET', 'HEAD', 'PATCH', 'POST', 'PUT', 'OPTIONS']

test('fastify.all should add all the methods to the same url', t => {
  t.plan(supportedMethods.length * 2)

  const fastify = Fastify()

  fastify.all('/', (req, reply) => {
    reply.send({ method: req.raw.method })
  })

  supportedMethods.forEach(injectRequest)

  function injectRequest (method) {
    const options = {
      url: '/',
      method: method
    }

    if (method === 'POST' || method === 'PUT' || method === 'PATCH') {
      options.payload = { hello: 'world' }
    }

    fastify.inject(options, (err, res) => {
      t.error(err)
      var payload = JSON.parse(res.payload)
      t.deepEqual(payload, { method: method })
    })
  }
})


text:
investigation!
=============


text:
content-editable
============

Custom element making children editable and triggers save event on blur, built with [Polymer](https://www.polymer-project.org/).

See the [component page](http://mikaelharsjo.github.io/content-editable/components/content-editable/) for more information.

## Example
```html
<content-editable>
  <h1>I am an editable heading</h1>
</content-editable>
```

## Contributing

Try out the component via demo.html file via a local web server. There are several ways to do this but one easy method is to run a simple web server that ships with Python, using the commands:

```sh
python -m SimpleHTTPServer
```

Or other method using NodeJS:

```sh
npm install -g http-server
http-server ./ -p 8000
```

This starts a web server on port 8000, so you can try the element by navigating a browser to `localhost:8000/test/index.html`.

### web-component-tester

The tests are also compatible with [web-component-tester](https://github.com/Polymer/web-component-tester). You can run them on multiple local browsers via:

```sh
npm install -g web-component-tester
wct
```


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

import csv
import sqlite3
import tempfile

import six
import attr
import pytest
import shutil

from rnacentral_pipeline.databases.data import Reference
from rnacentral_pipeline.databases.data import IdReference
from rnacentral_pipeline.databases.data import KnownServices
import rnacentral_pipeline.databases.helpers.publications as pub

@pytest.mark.parametrize(
    "raw_id,namespace,external_id",
    [
        (26184978, KnownServices.pmid, "26184978"),
        ("pmid:26184978", KnownServices.pmid, "26184978"),
        ("PMID:26184978", KnownServices.pmid, "26184978"),
        ("doi:10.1038/srep12276", KnownServices.doi, "10.1038/srep12276"),
        ("DOI:10.1038/srep12276", KnownServices.doi, "10.1038/srep12276"),
        ("PMCID:PMC5785218", KnownServices.pmcid, "PMC5785218"),
        ("PMC5785218", KnownServices.pmcid, "PMC5785218"),
        ("pmcid:pmc5785218", KnownServices.pmcid, "PMC5785218"),
        ("pmc5785218", KnownServices.pmcid, "PMC5785218"),
    ],
)
def test_reference_builds_a_id_ref(raw_id, namespace, external_id):
    assert pub.reference(raw_id) == IdReference(
        namespace=namespace,
        external_id=external_id,
    )


text:
package http_test

import (
	"log"
	"net/http"

	gomhttp "github.com/rakyll/gom/http"
)

func Example_gorillaMux() {
	mux := http.NewServeMux()
	mux.HandleFunc("/debug/_gom", gomhttp.Handler())
	log.Println(http.ListenAndServe("localhost:6060", nil))
}


text:
TF.js deployment of tensorflow/ssd_mobilenet_v2/1.

<!-- asset-path: legacy -->
<!-- parent-model: tensorflow/ssd_mobilenet_v2/1 -->

## Origin

This model is based on [tensorflow/ssd_mobilenet_v2/1](https://tfhub.dev/tensorflow/ssd_mobilenet_v2/1).

This model is published on NPM as `@tensorflow-models/coco-ssd`.

See the [NPM documentation](https://www.npmjs.com/package/@tensorflow-models/coco-ssd)
for how to load and use the model in JavaScript.


text:
<?php

/**
 * Customizations for the mobile theme.
 */
class MobileThemeHooks implements Gdn_IPlugin {

    /**
     * No setup required.
     */
    public function setup() {
    }

    /**
     * Remove plugins that are not mobile friendly!
     */
    public function gdn_dispatcher_afterAnalyzeRequest_handler($Sender) {
        // Remove plugins so they don't mess up layout or functionality.
        $inPublicDashboard = ($Sender->application() == 'dashboard' && in_array($Sender->controller(), array('Activity', 'Profile', 'Search')));
        if (in_array($Sender->application(), array('vanilla', 'conversations')) || $inPublicDashboard) {
            Gdn::pluginManager()->removeMobileUnfriendlyPlugins();
        }
        saveToConfig('Garden.Format.EmbedSize', '240x135', false);
    }

    /**
     * Add mobile meta info. Add script to hide iPhone browser bar on pageload.
     */
    public function base_render_before($Sender) {
        if (isMobile() && is_object($Sender->Head)) {
            $Sender->Head->addTag('meta', array('name' => 'viewport', 'content' => "width=device-width,minimum-scale=1.0,maximum-scale=1.0"));
            $Sender->Head->addString('
<script type="text/javascript">
   // If not looking for a specific comment, hide the address bar in iphone
   var hash = window.location.href.split("#")[1];
   if (typeof(hash) == "undefined") {
      setTimeout(function () {
        window.scrollTo(0, 1);
      }, 1000);
   }
</script>');
        }
    }

    /**
     * Add button, remove options, increase click area on discussions list.
     */
    public function categoriesController_render_before($Sender) {
        $Sender->ShowOptions = false;
        saveToConfig('Vanilla.AdminCheckboxes.Use', false, false);
        $this->addButton($Sender, 'Discussion');
        $this->discussionsClickable($Sender);
    }

    /**
     * Add button, remove options, increase click area on discussions list.
     */
    public function discussionsController_render_before($Sender) {
        $Sender->ShowOptions = false;
        saveToConfig('Vanilla.AdminCheckboxes.Use', false, false);
        $this->addButton($Sender, 'Discussion');
        $this->discussionsClickable($Sender);
    }

    /**
     * Add New Discussion button.
     */
    public function discussionController_render_before($Sender) {
        $this->addButton($Sender, 'Discussion');
    }

    /**
     * Add New Discussion button.
     */
    public function draftsController_render_before($Sender) {
        $this->addButton($Sender, 'Discussion');
    }

    /**
     * Add New Conversation button.
     */
    public function messagesController_render_before($Sender) {
        $this->addButton($Sender, 'Conversation');
    }

    /**
     * Add New Discussion button.
     */
    public function postController_render_before($Sender) {
        $this->addButton($Sender, 'Discussion');
    }

    /**
     * Add a button to the navbar.
     */
    private function addButton($Sender, $ButtonType) {
        if (is_object($Sender->Menu)) {
            if ($ButtonType == 'Discussion') {
                $Sender->Menu->addLink(
                    'NewDiscussion',
                    img('themes/mobile/design/images/new.png', array('alt' => t('New Discussion'))),
                    '/post/discussion'.(array_key_exists('CategoryID', $Sender->Data) ? '/'.$Sender->Data['CategoryID'] : ''),
                    array('Garden.SignIn.Allow'),
                    array('class' => 'NewDiscussion')
                );
            } elseif ($ButtonType == 'Conversation')
                $Sender->Menu->addLink(
                    'NewConversation',
                    img('themes/mobile/design/images/new.png', array('alt' => t('New Conversation'))),
                    '/messages/add',
                    '',
                    array('class' => 'NewConversation')
                );
        }
    }

    /**
     * Increases clickable area on a discussions list.
     */
    private function discussionsClickable($Sender) {
        // Make sure that discussion clicks (anywhere in a discussion row) take the user to the discussion.
        if (property_exists($Sender, 'Head') && is_object($Sender->Head)) {
            $Sender->Head->addString('
<script type="text/javascript">
   jQuery(document).ready(function($) {
      $("ul.DataList li.Item").click(function() {
         var href = $(this).find(".Title a").attr("href");
         if (typeof href != "undefined")
            document.location = href;
      });
   });
</script>');
        }
    }

    /**
     * Add the user photo before the user Info on the profile page.
     */
    public function profileController_beforeUserInfo_handler($Sender) {
        $UserPhoto = new UserPhotoModule();
        echo $UserPhoto->toString();
    }
}


text:
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from builtins import *

def create_serialized_candidate_view(session, C, verbose=False):
    """Creates a view in the database for a Candidate sub-class C defined over
    Span contexts, which are direct children of a single sentence.

    Creates VIEW with schema:
        candidate.id, candidate.split, span0.*, ..., spanK.*, sentence.*

    NOTE: This limited functionality should be expanded for arbitrary context
    trees. Also this should be made more dialect-independent.
    """
    selects, froms, joins = [], [], []
    for i, arg in enumerate(C.__argnames__):
        # Select the context CID
        selects.append("{0}.{1}_cid".format(C.__tablename__, arg))
        # Then all of its span columns
        selects.append("span{0}.*".format(i))
        froms.append("span AS span{0}".format(i))
        joins.append("{0}.{1}_id = span{2}.id".format(C.__tablename__, arg, i))

    sql = """
    CREATE VIEW IF NOT EXISTS {0}_serialized AS
        SELECT
            candidate.id,
            candidate.split,
            {1},
            sentence.*
        FROM
            candidate,
            {0},
            {2},
            sentence
        WHERE
            candidate.id = {0}.id
            AND sentence.id = span0.sentence_id
            AND {3}
    """.format(
        C.__tablename__,
        ", ".join(selects),
        ", ".join(froms),
        " AND ".join(joins)
    )
    if verbose:
        print("Creating view...")
        print(sql)
    session.execute(sql)


text:
// gamescreen.js
// Copyright (c) 2014 AKIYAMA Kouhei
// This software is released under the MIT License.

(function(global){
    if(!global.misohena){global.misohena = {};}
    var mypkg = global.misohena;

    var SCREEN_NORMAL = GameScreen.SCREEN_NORMAL = 0;
    var SCREEN_MAXIMIZED = GameScreen.SCREEN_MAXIMIZED = 1;
    var SCREEN_FULLSCREEN = GameScreen.SCREEN_FULLSCREEN = 2;

    var CONTROL_HEIGHT = 30;

    function px(v)
    {
        return v + "px";
    }

    mypkg.GameScreen = GameScreen;
    function GameScreen(originalWidth, originalHeight)
    {
        var lastScreenState = SCREEN_NORMAL; // 最後に検出したフルスクリーン状態。
        var maximizeInWindow = false; // 非フルスクリーン時にウィンドウ内最大化するならtrue。
        var contentAreaKeepRatio = true; //contentAreaの縦横比をoriginalWidth,originalHeightの比率に固定するならtrue。contentAreaKeepSizeがtrueならfalseでもtrueとして扱う。
        var contentAreaKeepSize = true; //contentAreaのwidth,heightをoriginalWidth,originalHeightに固定するならtrue。screenAreaとの大きさの違いはcontentArea.style.transformで調整する。

        // Create HTMLElements
        var screenArea = document.createElement("div");
        screenArea.style.background = "#000000";
        screenArea.style.overflow = "hidden";
        screenArea.className = "gamescreen-screenarea";

        var contentArea = document.createElement("div");
        contentArea.className = "gamescreen-contentarea";
        screenArea.appendChild(contentArea);

        var controlBarObj = new ControlBar("gamescreen-controlbar");
        screenArea.appendChild(controlBarObj.getElement());

        // Backup initial styles
        ///@todo 変更したときにバックアップして、不要になったら戻す。
        var oldBodyStyleOverflow = document.body.style.overflow;
        var oldScreenAreaStylePosition = screenArea.style.position;
        var oldViewportMetaElementContent;

        // Observe window size
        window.addEventListener("resize", onResize, false);
        window.addEventListener("orientationchange", onResize, false);
        screenArea.addEventListener("resize", onResize, false); //Chromeにおいて、翻訳バーや開発者用バーが消えるときにwindowのresizeイベントが発生しないので、screenAreaのresizeで代用する。
        // リサイズイベントが発生せずにフルスクリーンになることもあるので注意。
        // 全画面化前後でウィンドウのサイズが変わらない場合。
        document.addEventListener("fullscreenchange", onResize, false);
        document.addEventListener("mozfullscreenchange", onResize, false);
        document.addEventListener("webkitfullscreenchange", onResize, false);
        document.addEventListener("msfullscreenchange", onResize, false);

        // Update style
        onResize();

        // public methods
        this.getElement = function() { return screenArea;};
        this.getElementContentArea = function() { return contentArea;};
        this.getElementControlBar = function() { return controlBarObj.getElement();};
        this.getControlBar = function() { return controlBarObj;};

        // private methods
        function setStyleNormal()
        {
            document.body.style.overflow = oldBodyStyleOverflow;

            screenArea.style.display = "inline-block";
            screenArea.style.position = oldScreenAreaStylePosition;
            screenArea.style.left = "auto";
            screenArea.style.top = "auto";
            screenArea.style.width = "auto";
            screenArea.style.height = "auto";
            screenArea.style.zIndex = "auto";

            contentArea.style.position = "relative";
            contentArea.style.left = "0";
            contentArea.style.top = "0";
            contentArea.style.width = originalWidth + "px";
            contentArea.style.height = originalHeight + "px";
            contentArea.style.webkitTransformOrigin =
            contentArea.style.transformOrigin = "left top";
            contentArea.style.webkitTransform =
            contentArea.style.transform = "";

            controlBarObj.getElement().style.position = "static";
            controlBarObj.getElement().style.left = "0";
            controlBarObj.getElement().style.top = "0";
            controlBarObj.getElement().style.width = "auto";
        }
        function setStyleMaximized()
        {
            document.body.style.overflow = "hidden"; //hide body scrollbar

            var clientWidth = document.documentElement.clientWidth;
            var clientHeight = document.documentElement.clientHeight;

            screenArea.style.display = "block";
            screenArea.style.position = "fixed";
            screenArea.style.left = "0";
            screenArea.style.top = "0";
            screenArea.style.width = clientWidth + "px";
            screenArea.style.height = clientHeight + "px";
            screenArea.style.zIndex = "999999";

            fitContentAreaToScreenArea(clientWidth, clientHeight);
        }
        function setStyleFullscreen()
        {
            document.body.style.overflow = "hidden"; //hide body scrollbar

            screenArea.style.display = "block"; //inline-blockだとChromeでは100%で大きくならない。
            screenArea.style.position = oldScreenAreaStylePosition;
            screenArea.style.left = "auto";
            screenArea.style.top = "auto";
            screenArea.style.width = "100%";
            screenArea.style.height = "100%";
            screenArea.style.zIndex = "auto";

            var clientWidth = screenArea.clientWidth;
            var clientHeight = screenArea.clientHeight;

            fitContentAreaToScreenArea(clientWidth, clientHeight);
        }
        function fitContentAreaToScreenArea(screenWidth, screenHeight)
        {
            if(contentAreaKeepRatio || contentAreaKeepSize){

                var fitToHeight = screenWidth * originalHeight >= screenHeight * originalWidth;
                var contentAreaWidth = fitToHeight
                    ? originalWidth * screenHeight / originalHeight
                    : screenWidth;
                var contentAreaHeight = fitToHeight
                    ? screenHeight
                    : originalHeight * screenWidth / originalWidth;
                var controlBarHeight = controlBarObj.getElement().clientHeight;

                contentArea.style.position = "absolute";
                contentArea.style.left = (screenWidth - contentAreaWidth)/2 + "px";
                contentArea.style.top = (screenHeight - contentAreaHeight)/2 + "px";

                if(contentAreaKeepSize){
                    contentArea.style.width = originalWidth + "px";
                    contentArea.style.height = originalHeight + "px";
                    contentArea.style.webkitTransformOrigin =
                    contentArea.style.transformOrigin = "left top";
                    contentArea.style.webkitTransform =
                    contentArea.style.transform = "scale(" + (contentAreaWidth / originalWidth) + "," + (contentAreaHeight / originalHeight) + ")";
                }
                else{
                    contentArea.style.width = contentAreaWidth + "px";
                    contentArea.style.height = contentAreaHeight + "px";
                    contentArea.style.webkitTransformOrigin =
                    contentArea.style.transformOrigin = "left top";
                    contentArea.style.webkitTransform =
                    contentArea.style.transform = "";
                }
            }
            else{
                contentArea.style.width = screenWidth + "px";
                contentArea.style.height = screenHeight + "px";
            }

            controlBarObj.getElement().style.position = "absolute";
            controlBarObj.getElement().style.left = "0px";
            controlBarObj.getElement().style.top = (screenHeight - controlBarHeight) + "px";
            controlBarObj.getElement().style.width = screenWidth + "px";
        }

        function onResize()
        {
            updateViewportMetaElement();

            if(getFullscreenMode()){
                setStyleFullscreen();
                setLastScreenState(SCREEN_FULLSCREEN);
            }
            else{
                if(maximizeInWindow){
                    setStyleMaximized();
                    setLastScreenState(SCREEN_MAXIMIZED);
                }
                else{
                    setStyleNormal();
                    setLastScreenState(SCREEN_NORMAL);
                }
            }
        }

        // Maximize methods
        this.setMaximizeInWindow = setMaximizeInWindow;
        function setMaximizeInWindow(b)
        {
            maximizeInWindow = b;
            onResize();
        }

        // Fullscreen state methods

        this.setFullscreenMode = setFullscreenMode;
        function setFullscreenMode(b)
        {
            if(getFullscreenMode() == b){
                return;
            }
            if(screenArea){
                if(b){
                    if(screenArea.requestFullscreen) {
                        screenArea.requestFullscreen();
                    }
                    else if(screenArea.mozRequestFullScreen) {
                        screenArea.mozRequestFullScreen();
                    }
                    else if(screenArea.webkitRequestFullscreen) {
                        screenArea.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT);
                    }
                    else if(screenArea.msRequestFullscreen) {
                        screenArea.msRequestFullscreen();
                    }

                }
                else{
                    if(document.exitFullscreen) {
                        document.exitFullscreen();
                    }
                    else if(document.cancelFullScreen) {
                        document.cancelFullScreen();
                    }
                    else if(document.mozCancelFullScreen) {
                        document.mozCancelFullScreen();
                    }
                    else if(document.webkitCancelFullScreen) {
                        document.webkitCancelFullScreen();
                    }
                    else if(document.msExitFullscreen) {
                        document.msExitFullscreen();
                    }
                }
            }
        }

        this.getFullscreenMode = getFullscreenMode;
        function getFullscreenMode()
        {
            return document.fullscreenElement
                || document.mozFullScreenElement
                || document.webkitFullscreenElement
                || document.msFullscreenElement;
        }

        this.isFullscreenAvailable = isFullscreenAvailable;
        function isFullscreenAvailable()
        {
            return document.fullscreenEnabled
                || document.mozFullScreenEnabled
                || document.webkitFullscreenEnabled
                || document.msFullscreenEnabled;
        }

        // Screen state tracking methods

        function setLastScreenState(state)
        {
            if(state != lastScreenState){
                lastScreenState = state;

                // ボタン状態を更新する。
                if(screenModeControl){
                    screenModeControl.updateState();
                }
                // バーを自動的に隠すかどうかを設定する。
                if(controlBarObj){
                    controlBarObj.setAutoHideMode(state != SCREEN_NORMAL);
                }
            }
        }
        this.getLastScreenState = getLastScreenState;
        function getLastScreenState()
        {
            return lastScreenState;
        }

        // Viewport methods (surpress

        function getViewportMetaElement()
        {
            var metaArray = document.getElementsByTagName("meta");
            for(var index = 0; index < metaArray.length; ++index){
                var elem = metaArray[index];
                if(elem.getAttribute("name") == "viewport"){
                    return elem;
                }
            }
            return null;
        }
        /**
         * name=viewportと指定してあるmeta要素を返します。無ければ作ります。
         */
        function aquireViewportMetaElement()
        {
            var currMeta = getViewportMetaElement();
            if(currMeta){
                return currMeta;
            }
            var newMeta = document.createElement("meta");
            newMeta.setAttribute("name", "viewport");
            document.getElementsByTagName("head")[0].appendChild(newMeta);
            return newMeta;
        }

        function getOriginalHeightWithControl()
        {
            return originalHeight + (getFullscreenMode() ? 0 : controlBarObj.getElement().clientHeight);
        }

        /**
         * viewportメタ要素を更新します。
         */
        function updateViewportMetaElement()
        {
            // backup old content=
            var meta = aquireViewportMetaElement();
            if(oldViewportMetaElementContent === undefined){
                oldViewportMetaElementContent = meta.getAttribute("content") || "";
            }

            if(!getFullscreenMode() && !maximizeInWindow){
                meta.setAttribute("content", oldViewportMetaElementContent);
            }
            else{
                //disable user scaling
                meta.setAttribute("content", "initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no");
            }
        }

        // ScreenModeControl
        var screenModeControl = new ScreenModeControl(this);
    }
    GameScreen.wrap = wrapScreen;
    function wrapScreen(content, originalWidth, originalHeight){
        var screen = new GameScreen(originalWidth, originalHeight);
        screen.getElementContentArea().appendChild(content);
        return screen;
    }

    //
    // ControlBar Button
    //
    function createButton()
    {
        var BUTTON_OPACITY_NORMAL = "0.6";
        var BUTTON_OPACITY_HOVER = "1.0";
        var BUTTON_HEIGHT = CONTROL_HEIGHT;

        var div = document.createElement("div");
        div.style.position = "relative";
        div.style.height = px(BUTTON_HEIGHT);
        div.style.lineHeight = px(BUTTON_HEIGHT);
        div.style.display = "table-cell";
        div.style.textAlign = "center";
        div.style.verticalAlign = "middle";
        div.style.marginLeft = "4px";
        div.style.opacity = BUTTON_OPACITY_NORMAL;
        div.style.fontSize = px(BUTTON_HEIGHT * 0.5);
        div.style.cursor = "default";
        div.style.userSelect =
            div.style.msUserSelect =
            div.style.MozUserSelect =
            div.style.webkitUserSelect = "none";

        div.addEventListener("mouseenter", function(e){ div.style.opacity = BUTTON_OPACITY_HOVER;});
        div.addEventListener("mouseleave", function(e){ div.style.opacity = BUTTON_OPACITY_NORMAL;});

        div.setDisabled = function(b){
            div.style.display = b ? "none" : "";
            return div;
        };
        div.setIcon = function(url, urlW, urlH, iconX, iconY, iconW, iconH){
            div.style.width = px(iconW);
            div.style.height = px(iconH);
            div.style.background = "url(" + url + ") no-repeat " + px(iconX) + " " + px(iconY);
            div.style.backgroundSize = px(urlW) + " " + px(urlH);
            return div;
        };
        div.setOnClick = function(onClick){
            div.addEventListener("click", onClick);
            return div;
        };
        var textNode = null;
        div.setText = function(text){
            var newTextNode = text ? document.createTextNode(text) : null;
            if(newTextNode){
                div.insertBefore(newTextNode, textNode);
            }
            if(textNode){
                div.removeChild(textNode);
            }
            textNode = newTextNode;
            return div;
        };

        return div;
    }

    //
    // ControlBar
    //
    mypkg.GameScreen.ControlBar = ControlBar;
    function ControlBar(className)
    {
        var bar = document.createElement("div");
        bar.className = className;
        bar.style.height = px(CONTROL_HEIGHT);
        bar.style.background = "rgba(20,20,20,0.7)";
        bar.style.color = "#ffffff";

        this.getElement = function(){return bar;};

        this.add = add;
        function add(ctrl, leftOrRight)
        {
            ctrl.style.cssFloat = leftOrRight || "left";
            bar.appendChild(ctrl);
            return ctrl;
        }
        this.addButton = addButton;
        function addButton(leftOrRight)
        {
            return add(createButton(), leftOrRight);
        }

        // Auto Hide Mode

        var autoHideMode = false;
        var timer = null;
        var opacity = 1.0;
        var opacityVel = 0;
        var TIMER_PERIOD = 20;
        var OPACITY_VEL_HIDE = -0.01;
        function onTime()
        {
            opacity += opacityVel;

            if((opacityVel < 0 && opacity <= 0) ||
               (opacityVel > 0 && opacity >= 1.00) ||
               (opacityVel == 0)){
                cancelBarAnimation();
            }
            bar.style.opacity = Math.min(1, Math.max(0, opacity));
        }
        function cancelBarAnimation()
        {
            if(timer !== null){
                clearInterval(timer);
                timer = null;
            }
        }
        function hideBar(opacityFrom)
        {
            cancelBarAnimation();
            opacity = 1.0 - OPACITY_VEL_HIDE * 1000 / TIMER_PERIOD;
            opacityVel = OPACITY_VEL_HIDE;
            timer = setInterval(onTime, TIMER_PERIOD);
        }
        function showBar()
        {
            cancelBarAnimation();
            bar.style.opacity = 1.0;
        }
        function initAutoHideMode()
        {
            bar.addEventListener("mousemove", function(e){
                if(autoHideMode){
                    showBar();
                }
            }, false);
            bar.addEventListener("mouseleave", function(e){
                if(autoHideMode){
                    hideBar();
                }
            }, false);
            //bar.addEventListener("touchend", function(e){
            //    if(autoHideMode){
            //        hideBar();
            //    }
            //}, false); ///@todo
        }
        this.setAutoHideMode = setAutoHideMode;
        function setAutoHideMode(b)
        {
            autoHideMode = b;
            if(b){
                hideBar();
            }
            else{
                showBar();
            }
        }
        initAutoHideMode();
    }

    //
    // Screen Mode Buttons
    //
    mypkg.GameScreen.ScreenModeControl = ScreenModeControl;
    function ScreenModeControl(gameScreen)
    {
        var ICON_URL = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHgAAAAeCAMAAADQFyqnAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAAZQTFRF////////VXz1bAAAAAJ0Uk5T/wDltzBKAAAAzUlEQVR42uSX0Q7CMAhFD///00aTRSHQQm3FaB/Hximw3d4hTYuvBi/ujvuKLpNKsL2oFzCjjR8Ex8k5Cn50XS89EfzodYMbJR70BXaCZIthXGrUsHBX6dRzcG0OJbDtfuKTQD/8nFEZHFUsU7DJVQRXBWcXWJrA0gSWfwbTBKYJzAr4DQExwkxC5qmdCGMwCTBDsNbenW81c/DCCZlyMxpsznGj+Thx7RRiI+B3MjJ7M7OTs0M5s1eSnpwNWwDvMbwnwJ8x9L/173QTYAD91gyN3Y8dkgAAAABJRU5ErkJggg==";
        var ICON_WIDTH = 30; //oroginal 30px
        var ICON_HEIGHT = 30; //original 30px
        var ICON_X_SCREEN_NORMAL = -ICON_WIDTH*0;
        var ICON_X_SCREEN_MAX_DOWN = -ICON_WIDTH*1;
        var ICON_X_SCREEN_MAX_UP = -ICON_WIDTH*2;
        var ICON_X_SCREEN_FULL = -ICON_WIDTH*3;
        var ICON_Y_NORMAL = -ICON_HEIGHT*0;
        var ICON_URL_WIDTH = ICON_WIDTH*4;
        var ICON_URL_HEIGHT = ICON_HEIGHT*1;

        var controlBar = gameScreen.getControlBar();

        function addBtn(iconX, maximized, fullscreen)
        {
            function changeMode(e)
            {
                if(gameScreen){
                    if(typeof(maximized) == "boolean"){
                        gameScreen.setMaximizeInWindow(maximized);
                    }
                    if(typeof(fullscreen) == "boolean"){
                        gameScreen.setFullscreenMode(fullscreen);
                    }
                }
            }
            return controlBar.addButton("right").
                setOnClick(changeMode).
                setIcon(ICON_URL, ICON_URL_WIDTH, ICON_URL_HEIGHT,
                        iconX, ICON_Y_NORMAL, ICON_WIDTH, ICON_HEIGHT);
        }

        var screenFullButton = addBtn(ICON_X_SCREEN_FULL, null, true);
        var screenMaxDownButton = addBtn(ICON_X_SCREEN_MAX_DOWN, true, false);
        var screenMaxUpButton = addBtn(ICON_X_SCREEN_MAX_UP, true, false);
        var screenNormalButton = addBtn(ICON_X_SCREEN_NORMAL, false, false);
        updateState();

        this.updateState = updateState;
        function updateState()
        {
            var state = gameScreen != null ? gameScreen.getLastScreenState() : -1;
            if(screenNormalButton != null){
                screenNormalButton.setDisabled(state == GameScreen.SCREEN_NORMAL);
            }
            if(screenMaxDownButton != null){
                screenMaxDownButton.setDisabled(state != GameScreen.SCREEN_FULLSCREEN);
            }
            if(screenMaxUpButton != null){
                screenMaxUpButton.setDisabled(state != GameScreen.SCREEN_NORMAL);
            }
            if(screenFullButton != null){
                screenFullButton.setDisabled(
                    state == GameScreen.SCREEN_FULLSCREEN ||
                    !(gameScreen && gameScreen.isFullscreenAvailable()));
            }
        }
    }
})(this);


text:
import socket
import time
import re
#import logging

#logging.basicConfig(level=logging.DEBUG, format="%(asctime)s - %(name)s - %(levelname)s\t Thread-%(thread)d - %(message)s", filename='/tmp/gmond.log', filemode='w')
#logging.debug('starting up')

def metric_handler(name):

    match = re.search(r"redis-llen_(\d+)_(\w+)",name)
    if not match:
         return 1
    database = match.group(1)
    list = match.group(2)

    if (database not in metric_handler.databases) or (list not in metric_handler.lists):
        return 0

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((metric_handler.host, metric_handler.port))
    s.send("SELECT %s\r\n" % database)
    info = s.recv(4096)
    s.send("LLEN %s\r\n" % list)
    info = s.recv(4096)

    metric_handler.info = {}
    if ":" != info[0]:
        return 0

    try:
          n, v = info.split(":")
          metric_handler.info[name] = int(v)
    except Exception, e:
        logging.debug("caught exception %s" % e)
        pass

    s.close()

    #logging.debug("returning metric_handl: %s %s %s" % (metric_handler.info.get(name, 0), metric_handler.info, metric_handler))
    return metric_handler.info.get(name, 0)

def metric_init(params={}):
    metric_handler.host = params.get("host", "127.0.0.1")
    metric_handler.port = int(params.get("port", 6379))

    databases = params.get("databases", "0");
    metric_handler.databases = []
    if databases.__len__() > 0:
        metric_handler.databases = map(str.strip, databases.split(','))

    lists = params.get("lists", "");
    metric_handler.lists = []
    if lists.__len__() > 0:
        metric_handler.lists = map(str.strip, lists.split(','))

    metrics = {
        "redis-llen": {"units": "items"},
    }
    metric_handler.descriptors = {}

    for database in metric_handler.databases:
        for list in metric_handler.lists:
            for base_name, updates in metrics.iteritems():
                name = "%s_%s_%s" % (base_name, database, list)
                descriptor = {
                    "name": name,
                    "call_back": metric_handler,
                    "time_max": 90,
                    "value_type": "int",
                    "units": "",
                    "slope": "both",
                    "format": "%d",
                    "description": "http://redis.io/commands/llen",
                    "groups": "redis_list_size_%s" % database,
                }
                descriptor.update(updates)
                metric_handler.descriptors[name] = descriptor
    return metric_handler.descriptors.values()

def metric_cleanup():
    pass

#This code is for debugging
if __name__ == '__main__':
    params = {'databases': '0,1, 2', 'lists': 'listA, listB,listC'}
    metric_init(params)
    for d in metric_handler.descriptors.values():
        v = d['call_back'](d['name'])
        print 'value for %s is %u' % (d['name'], v)


text:
@interface IDEDistributionConsoleLogger : DVTConsoleLogger
{
    int _exclusiveLogLevel;
}

@property(readonly) int exclusiveLogLevel; // @synthesize exclusiveLogLevel=_exclusiveLogLevel;
- (void)logMessage:(id)arg1 forAspect:(id)arg2 logLevel:(int)arg3;
- (id)initWithExclusiveLogLevel:(int)arg1;

@end


text:
using ElectronicObserver.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ElectronicObserver.Observer.kcsapi.api_req_air_corps
{
	public class change_name : APIBase
	{

		public override bool IsRequestSupported => true;

		public override void OnRequestReceived(Dictionary<string, string> data)
		{

			var corps = KCDatabase.Instance.BaseAirCorps;
			int aircorpsID = BaseAirCorpsData.GetID(data);

			if (corps.ContainsKey(aircorpsID))
			{
				corps[aircorpsID].LoadFromRequest(APIName, data);
			}

			base.OnRequestReceived(data);
		}

		public override string APIName => "api_req_air_corps/change_name";
	}

}


text:
package org.waveprotocol.wave.client.widget.button;

import com.google.gwt.event.dom.client.HasMouseOutHandlers;
import com.google.gwt.event.dom.client.HasMouseOverHandlers;
import com.google.gwt.event.dom.client.MouseOutEvent;
import com.google.gwt.event.dom.client.MouseOutHandler;
import com.google.gwt.event.dom.client.MouseOverEvent;
import com.google.gwt.event.dom.client.MouseOverHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Widget;

import org.waveprotocol.wave.client.widget.button.ToggleButton.ToggleButtonListener;

/**
 * Convenience widget that combines the abstract notion of a
 * {@link ToggleButtonController} with some physical widget so that we don't
 * have to return both in a pair from the ButtonFactory.
 *
 */
public class ToggleButtonWidget extends Composite implements ToggleButtonController,
    HasMouseOverHandlers, HasMouseOutHandlers {
  /**
   * The controller for the wrapped widget.
   */
  private final ToggleButtonController controller;

  /**
   * @param controller Controls a button represented by w.
   * @param w The physical representation of a button.
   */
  public ToggleButtonWidget(ToggleButtonController controller, Widget w) {
    initWidget(w);
    this.controller = controller;
  }

  /** {@inheritDoc} */
  public void setOn(boolean isOn) {
    controller.setOn(isOn);
  }

  /** {@inheritDoc} */
  public void setToggleListener(ToggleButtonListener listener) {
    controller.setToggleListener(listener);
  }

  @Override
  public void setDisabled(boolean isDisabled) {
    controller.setDisabled(isDisabled);
  }

  /** {@inheritDoc} */
  public HandlerRegistration addMouseOutHandler(MouseOutHandler handler) {
    return addDomHandler(handler, MouseOutEvent.getType());
  }

  /** {@inheritDoc} */
  public HandlerRegistration addMouseOverHandler(MouseOverHandler handler) {
    return addDomHandler(handler, MouseOverEvent.getType());
  }
}


text:
var myname = 'html.document.js_statement';

var zvar = require('../../../js/module/gen/statements/var');
var objects = require('../../../js/module/gen/statements/objects');
var zfunction = require('../../../js/module/gen/statements/function');
var zclass = require('../../../js/module/gen/statements/class');
var ifswitch = require('../../../js/module/gen/statements/if-switch');
var statements = require('../../../js/module/gen/statements/statements');
var expressions = require('../../../js/module/gen/statements/expressions');
var call = require('../../../js/module/gen/statements/call');
var loops = require('../../../js/module/gen/statements/loops');
var exceptions = require('../../../js/module/gen/statements/exceptions');
var html = require('../../../js/module/gen/statements/html');
var debug = require('../../../js/module/gen/statements/debug');

var md = module.exports = {};
md.stm = {};

zvar.load(md);
objects.load(md);
zfunction.load(md);
zclass.load(md);
ifswitch.load(md);
statements.load(md);
expressions.load(md);
call.load(md);
loops.load(md);
exceptions.load(md);
html.load(md);
debug.load(md);

md.genItem = function(model, ctx) {
    var stm = md.stm[model.wzElement];
    if (stm) {
        stm(model, ctx);
    }
    else {
        throw ctx.error(myname + '. Unknown statement tag/element: ' + model.wzTag + '/' + model.wzElement, model);
    }
};

md.genItems = function(items, ctx, options) {
    var opt = options || {},
        from = opt.from || 0,
        indent = typeof opt.indent === 'undefined' ? true : opt.indent;
    if (indent) {
        ctx.indent();
    }
    var i, i_len=items.length, item;
    for (i=0; i<i_len; i++) {
        item = items[i];
        md.genItem(item, ctx);
    }
    if (indent) {
        ctx.deindent();
    }
};

md.stm.codeline = function(model, ctx) {
    ctx.w(model.wzName);
    md.genItems(model.items, ctx);
};


text:
from datetime import datetime # time manipulation functions
from datetime import date
from datetime import time
import locale # support of local locale (oh really ?), and internationalization
import pytz

""" Permet l'extraction des dates au format voulu, et dans la timezone de Paris """
class GestionDatetime:

	""" Initialise la timezone et le format """
	def __init__(self):
		self.paris = pytz.timezone('Europe/Paris')
		self.format = "%Y%m%dT%H%M%SZ"

	""" Formate proprement la date passé en paramètre """
	def getDatetime(self, my_date):
		date = my_date.to_ical()
		dtutcdate = pytz.utc.localize(datetime.strptime(date.decode(), self.format))
		dtdate = dtutcdate.astimezone(self.paris)

		return dtdate


text:
CREATE TABLE inbound (
	ip_dst VARCHAR NOT NULL,
	packets UNSIGNED INTEGER DEFAULT 0,
	bytes UNSIGNED BIG INTEGER DEFAULT 0,
	stamp_inserted INTEGER NOT NULL,
	stamp_updated INTEGER,
	CONSTRAINT inbound_pk PRIMARY KEY (ip_dst, stamp_inserted)
);

CREATE TABLE outbound (
	ip_src VARCHAR NOT NULL,
	packets UNSIGNED INTEGER DEFAULT 0,
	bytes UNSIGNED BIG INTEGER DEFAULT 0,
	stamp_inserted INTEGER NOT NULL,
	stamp_updated INTEGER,
	CONSTRAINT outbound_pk PRIMARY KEY (ip_src, stamp_inserted)
);


text:
import MarkdownIt = require("markdown-it");
import Token = require("markdown-it/lib/token");

import MarkdownItContainer = require("markdown-it-container");

const md = new MarkdownIt();

md.use(MarkdownItContainer, 'spoiler', {
    validate: (params: any) => params.trim().match(/^spoiler\s+(.*)$/),
    render: (tokens: Token[], index: number) => {
        const match = tokens[index].info.trim().match(/^spoiler\s+(.*)$/);
        const onClick =
            "this.parentNode.classList.toggle('_expanded');" +
            "event.preventDefault();";

        if (tokens[index].nesting === 1) {
            return (
                // tslint:disable-next-line prefer-template
                '
\n' +
                '
\n' +
                md.utils.escapeHtml(match && match[1] || '') + '\n' +
                '
\n' +
                '
\n'
            );
        } else {
            return '

\n';
        }
    }
});

const src = `:::spoiler This Is Spoiler Title
Here is spoiler content.
:::`;

md.render(src);


text:
export PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/sbin:/usr/local/bin
clear
printf "
#######################################################################
#       OneinStack for CentOS/RadHat 6+ Debian 7+ and Ubuntu 12+      #
#              Reset Database root password for OneinStack            #
#       For more information please visit https://oneinstack.com      #
#######################################################################
"
oneinstack_dir=$(dirname "`readlink -f $0`")
pushd ${oneinstack_dir} > /dev/null
. ./options.conf
. ./include/color.sh
. ./include/check_dir.sh

Input_db_root_password() {
  [ ! -d "${db_install_dir}" ] && { echo "${CFAILURE}Database is not installed on your system! ${CEND}"; exit 1; }
  while :; do echo
    read -p "Please input the root password of database: " New_dbrootpwd
    [ -n "`echo $New_dbrootpwd | grep '[+|&]'`" ] && { echo "${CWARNING}input error,not contain a plus sign (+) and &${CEND}"; continue; }
    (( ${#New_dbrootpwd} >= 5 )) && break || echo "${CWARNING}database root password least 5 characters! ${CEND}"
  done
}

Reset_db_root_password() {
  ${db_install_dir}/bin/mysqladmin -uroot -p"$dbrootpwd" password "$New_dbrootpwd" -h localhost > /dev/null 2>&1
  status_Localhost=`echo $?`
  ${db_install_dir}/bin/mysqladmin -uroot -p"$dbrootpwd" password "$New_dbrootpwd" -h 127.0.0.1 > /dev/null 2>&1
  status_127=`echo $?`
  if [ $status_Localhost == '0' -a $status_127 == '0' ]; then
    sed -i "s+^dbrootpwd.*+dbrootpwd='$New_dbrootpwd'+" ./options.conf
    echo
    echo "Password reset succesfully! "
    echo "The new password: ${CMSG}${New_dbrootpwd}${CEND}"
    echo
  else
    echo "${CFAILURE}Reset Database root password failed! ${CEND}"
  fi
}

if [ "$1" == 'quiet' ]; then
  New_dbrootpwd="`< /dev/urandom tr -dc A-Za-z0-9 | head -c8`"
  sleep 2 && [ ! -e /tmp/mysql.sock ] && /etc/init.d/mysqld start
  Reset_db_root_password
  [ $? -eq 0 ] && sed -i '/reset_db_root_password/d' /etc/rc.d/rc.local
else
  Input_db_root_password
  Reset_db_root_password
fi
popd > /dev/null


text:
// @file sock.cpp

#include "mongo/pch.h"

#include "mongo/util/net/sock.h"

#if !defined(_WIN32)
# include <sys/socket.h>
# include <sys/types.h>
# include <sys/socket.h>
# include <sys/un.h>
# include <netinet/in.h>
# include <netinet/tcp.h>
# include <arpa/inet.h>
# include <errno.h>
# include <netdb.h>
# if defined(__openbsd__)
#  include <sys/uio.h>
# endif
#endif

#ifdef MONGO_SSL
#include "mongo/util/net/ssl_manager.h"
#endif

#include "mongo/util/background.h"
#include "mongo/util/concurrency/value.h"
#include "mongo/util/fail_point_service.h"
#include "mongo/util/mongoutils/str.h"
#include "mongo/db/cmdline.h"

namespace mongo {
    MONGO_FP_DECLARE(throwSockExcep);

    static bool ipv6 = false;
    void enableIPv6(bool state) { ipv6 = state; }
    bool IPv6Enabled() { return ipv6; }

    void setSockTimeouts(int sock, double secs) {
        struct timeval tv;
        tv.tv_sec = (int)secs;
        tv.tv_usec = (int)((long long)(secs*1000*1000) % (1000*1000));
        bool report = logLevel > 3; // solaris doesn't provide these
        DEV report = true;
#if defined(_WIN32)
        tv.tv_sec *= 1000; // Windows timeout is a DWORD, in milliseconds.
        int status = setsockopt( sock, SOL_SOCKET, SO_RCVTIMEO, (char *) &tv.tv_sec, sizeof(DWORD) ) == 0;
        if( report && (status == SOCKET_ERROR) ) log() << "unable to set SO_RCVTIMEO" << endl;
        status = setsockopt( sock, SOL_SOCKET, SO_SNDTIMEO, (char *) &tv.tv_sec, sizeof(DWORD) ) == 0;
        DEV if( report && (status == SOCKET_ERROR) ) log() << "unable to set SO_SNDTIMEO" << endl;
#else
        bool ok = setsockopt( sock, SOL_SOCKET, SO_RCVTIMEO, (char *) &tv, sizeof(tv) ) == 0;
        if( report && !ok ) log() << "unable to set SO_RCVTIMEO" << endl;
        ok = setsockopt( sock, SOL_SOCKET, SO_SNDTIMEO, (char *) &tv, sizeof(tv) ) == 0;
        DEV if( report && !ok ) log() << "unable to set SO_SNDTIMEO" << endl;
#endif
    }

#if defined(_WIN32)
    void disableNagle(int sock) {
        int x = 1;
        if ( setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, (char *) &x, sizeof(x)) )
            error() << "disableNagle failed: " << errnoWithDescription() << endl;
        if ( setsockopt(sock, SOL_SOCKET, SO_KEEPALIVE, (char *) &x, sizeof(x)) )
            error() << "SO_KEEPALIVE failed: " << errnoWithDescription() << endl;
    }
#else

    void disableNagle(int sock) {
        int x = 1;

#ifdef SOL_TCP
        int level = SOL_TCP;
#else
        int level = SOL_SOCKET;
#endif

        if ( setsockopt(sock, level, TCP_NODELAY, (char *) &x, sizeof(x)) )
            error() << "disableNagle failed: " << errnoWithDescription() << endl;

#ifdef SO_KEEPALIVE
        if ( setsockopt(sock, SOL_SOCKET, SO_KEEPALIVE, (char *) &x, sizeof(x)) )
            error() << "SO_KEEPALIVE failed: " << errnoWithDescription() << endl;

#  ifdef __linux__
        socklen_t len = sizeof(x);
        if ( getsockopt(sock, level, TCP_KEEPIDLE, (char *) &x, &len) )
            error() << "can't get TCP_KEEPIDLE: " << errnoWithDescription() << endl;

        if (x > 300) {
            x = 300;
            if ( setsockopt(sock, level, TCP_KEEPIDLE, (char *) &x, sizeof(x)) ) {
                error() << "can't set TCP_KEEPIDLE: " << errnoWithDescription() << endl;
            }
        }

        len = sizeof(x); // just in case it changed
        if ( getsockopt(sock, level, TCP_KEEPINTVL, (char *) &x, &len) )
            error() << "can't get TCP_KEEPINTVL: " << errnoWithDescription() << endl;

        if (x > 300) {
            x = 300;
            if ( setsockopt(sock, level, TCP_KEEPINTVL, (char *) &x, sizeof(x)) ) {
                error() << "can't set TCP_KEEPINTVL: " << errnoWithDescription() << endl;
            }
        }
#  endif
#endif

    }

#endif

    string getAddrInfoStrError(int code) {
#if !defined(_WIN32)
        return gai_strerror(code);
#else
        /* gai_strerrorA is not threadsafe on windows. don't use it. */
        return errnoWithDescription(code);
#endif
    }

    // --- SockAddr

    SockAddr::SockAddr(int sourcePort) {
        memset(as<sockaddr_in>().sin_zero, 0, sizeof(as<sockaddr_in>().sin_zero));
        as<sockaddr_in>().sin_family = AF_INET;
        as<sockaddr_in>().sin_port = htons(sourcePort);
        as<sockaddr_in>().sin_addr.s_addr = htonl(INADDR_ANY);
        addressSize = sizeof(sockaddr_in);
    }

    SockAddr::SockAddr(const char * _iporhost , int port) {
        string target = _iporhost;
        if( target == "localhost" ) {
            target = "127.0.0.1";
        }

        if( mongoutils::str::contains(target, '/') ) {
#ifdef _WIN32
            uassert(13080, "no unix socket support on windows", false);
#endif
            uassert(13079, "path to unix socket too long",
                    target.size() < sizeof(as<sockaddr_un>().sun_path));
            as<sockaddr_un>().sun_family = AF_UNIX;
            strcpy(as<sockaddr_un>().sun_path, target.c_str());
            addressSize = sizeof(sockaddr_un);
        }
        else {
            addrinfo* addrs = NULL;
            addrinfo hints;
            memset(&hints, 0, sizeof(addrinfo));
            hints.ai_socktype = SOCK_STREAM;
            //hints.ai_flags = AI_ADDRCONFIG; // This is often recommended but don't do it.
                                              // SERVER-1579
            hints.ai_flags |= AI_NUMERICHOST; // first pass tries w/o DNS lookup
            hints.ai_family = (IPv6Enabled() ? AF_UNSPEC : AF_INET);

            StringBuilder ss;
            ss << port;
            int ret = getaddrinfo(target.c_str(), ss.str().c_str(), &hints, &addrs);

            // old C compilers on IPv6-capable hosts return EAI_NODATA error
#ifdef EAI_NODATA
            int nodata = (ret == EAI_NODATA);
#else
            int nodata = false;
#endif
            if ( (ret == EAI_NONAME || nodata) ) {
                // iporhost isn't an IP address, allow DNS lookup
                hints.ai_flags &= ~AI_NUMERICHOST;
                ret = getaddrinfo(target.c_str(), ss.str().c_str(), &hints, &addrs);
            }

            if (ret) {
                // we were unsuccessful
                if( target != "0.0.0.0" ) { // don't log if this as it is a
                                            // CRT construction and log() may not work yet.
                    log() << "getaddrinfo(\"" << target << "\") failed: " <<
                        gai_strerror(ret) << endl;
                }
                *this = SockAddr(port);
            }
            else {
                //TODO: handle other addresses in linked list;
                fassert(16501, addrs->ai_addrlen <= sizeof(sa));
                memcpy(&sa, addrs->ai_addr, addrs->ai_addrlen);
                addressSize = addrs->ai_addrlen;
                freeaddrinfo(addrs);
            }
        }
    }

    bool SockAddr::isLocalHost() const {
        switch (getType()) {
        case AF_INET: return getAddr() == "127.0.0.1";
        case AF_INET6: return getAddr() == "::1";
        case AF_UNIX: return true;
        default: return false;
        }
        fassert(16502, false);
        return false;
    }

    string SockAddr::toString(bool includePort) const {
        string out = getAddr();
        if (includePort && getType() != AF_UNIX && getType() != AF_UNSPEC)
            out += mongoutils::str::stream() << ':' << getPort();
        return out;
    }

    sa_family_t SockAddr::getType() const {
        return sa.ss_family;
    }

    unsigned SockAddr::getPort() const {
        switch (getType()) {
        case AF_INET:  return ntohs(as<sockaddr_in>().sin_port);
        case AF_INET6: return ntohs(as<sockaddr_in6>().sin6_port);
        case AF_UNIX: return 0;
        case AF_UNSPEC: return 0;
        default: massert(SOCK_FAMILY_UNKNOWN_ERROR, "unsupported address family", false); return 0;
        }
    }

    std::string SockAddr::getAddr() const {
        switch (getType()) {
        case AF_INET:
        case AF_INET6: {
            const int buflen=128;
            char buffer[buflen];
            int ret = getnameinfo(raw(), addressSize, buffer, buflen, NULL, 0, NI_NUMERICHOST);
            massert(13082, mongoutils::str::stream() << "getnameinfo error "
                    << getAddrInfoStrError(ret), ret == 0);
            return buffer;
        }

        case AF_UNIX:
            return (addressSize > 2 ? as<sockaddr_un>().sun_path : "anonymous unix socket");
        case AF_UNSPEC:
            return "(NONE)";
        default:
            massert(SOCK_FAMILY_UNKNOWN_ERROR, "unsupported address family", false); return "";
        }
    }

    bool SockAddr::operator==(const SockAddr& r) const {
        if (getType() != r.getType())
            return false;

        if (getPort() != r.getPort())
            return false;

        switch (getType()) {
        case AF_INET:
            return as<sockaddr_in>().sin_addr.s_addr == r.as<sockaddr_in>().sin_addr.s_addr;
        case AF_INET6:
            return memcmp(as<sockaddr_in6>().sin6_addr.s6_addr,
                          r.as<sockaddr_in6>().sin6_addr.s6_addr,
                          sizeof(in6_addr)) == 0;
        case AF_UNIX:
            return strcmp(as<sockaddr_un>().sun_path, r.as<sockaddr_un>().sun_path) == 0;
        case AF_UNSPEC:
            return true; // assume all unspecified addresses are the same
        default:
            massert(SOCK_FAMILY_UNKNOWN_ERROR, "unsupported address family", false);
        }
        return false;
    }

    bool SockAddr::operator!=(const SockAddr& r) const {
        return !(*this == r);
    }

    bool SockAddr::operator<(const SockAddr& r) const {
        if (getType() < r.getType())
            return true;
        else if (getType() > r.getType())
            return false;

        if (getPort() < r.getPort())
            return true;
        else if (getPort() > r.getPort())
            return false;

        switch (getType()) {
        case AF_INET:
            return as<sockaddr_in>().sin_addr.s_addr < r.as<sockaddr_in>().sin_addr.s_addr;
        case AF_INET6:
            return memcmp(as<sockaddr_in6>().sin6_addr.s6_addr,
                          r.as<sockaddr_in6>().sin6_addr.s6_addr,
                          sizeof(in6_addr)) < 0;
        case AF_UNIX:
            return strcmp(as<sockaddr_un>().sun_path, r.as<sockaddr_un>().sun_path) < 0;
        case AF_UNSPEC:
            return false;
        default:
            massert(SOCK_FAMILY_UNKNOWN_ERROR, "unsupported address family", false);
        }
        return false;
    }

    SockAddr unknownAddress( "0.0.0.0", 0 );

    string makeUnixSockPath(int port) {
        return mongoutils::str::stream() << cmdLine.socket << "/mongodb-" << port << ".sock";
    }

    // If an ip address is passed in, just return that.  If a hostname is passed
    // in, look up its ip and return that.  Returns "" on failure.
    string hostbyname(const char *hostname) {
        string addr =  SockAddr(hostname, 0).getAddr();
        if (addr == "0.0.0.0")
            return "";
        else
            return addr;
    }

    //  --- my --

    DiagStr& _hostNameCached = *(new DiagStr); // this is also written to from commands/cloud.cpp

    string getHostName() {
        char buf[256];
        int ec = gethostname(buf, 127);
        if ( ec || *buf == 0 ) {
            log() << "can't get this server's hostname " << errnoWithDescription() << endl;
            return "";
        }
        return buf;
    }

    /** we store our host name once */
    string getHostNameCached() {
        string temp = _hostNameCached.get();
        if (_hostNameCached.empty()) {
            temp = getHostName();
            _hostNameCached = temp;
        }
        return temp;
    }

    string prettyHostName() {
        StringBuilder s;
        s << getHostNameCached();
        if( cmdLine.port != CmdLine::DefaultDBPort )
            s << ':' << mongo::cmdLine.port;
        return s.str();
    }

    // --------- SocketException ----------

#ifdef MSG_NOSIGNAL
    const int portSendFlags = MSG_NOSIGNAL;
    const int portRecvFlags = MSG_NOSIGNAL;
#else
    const int portSendFlags = 0;
    const int portRecvFlags = 0;
#endif

    string SocketException::toString() const {
        stringstream ss;
        ss << _ei.code << " socket exception [" << _type << "] ";

        if ( _server.size() )
            ss << "server [" << _server << "] ";

        if ( _extra.size() )
            ss << _extra;

        return ss.str();
    }

    // ------------ Socket -----------------

    Socket::Socket(int fd , const SockAddr& remote) :
        _fd(fd), _remote(remote), _timeout(0) {
        _logLevel = 0;
        _init();
    }

    Socket::Socket( double timeout, int ll ) {
        _logLevel = ll;
        _fd = -1;
        _timeout = timeout;
        _init();
    }

    Socket::~Socket() {
        close();
#ifdef MONGO_SSL
        if ( _ssl ) {
            SSL_shutdown( _ssl );
            SSL_free( _ssl );
            _ssl = 0;
        }
#endif
    }

    void Socket::_init() {
        _bytesOut = 0;
        _bytesIn = 0;
#ifdef MONGO_SSL
        _ssl = 0;
        _sslAccepted = 0;
#endif
    }

    void Socket::close() {
        if ( _fd >= 0 ) {
            closesocket( _fd );
            _fd = -1;
        }
    }

#ifdef MONGO_SSL
    void Socket::secure(SSLManager* mgr) {
        fassert(16503, mgr);
        fassert(16504, !_ssl);
        fassert(16505, _fd >= 0);
        _ssl = mgr->connect(_fd);
        mgr->validatePeerCertificate(_ssl);
    }

    void Socket::secureAccepted( SSLManager * ssl ) {
        _sslAccepted = ssl;
    }
#endif

    void Socket::doSSLHandshake() {
#ifdef MONGO_SSL
        if (!_sslAccepted) return;

        fassert(16506, _fd);
        _ssl = _sslAccepted->accept(_fd);
        _sslAccepted->validatePeerCertificate(_ssl);
        _sslAccepted = 0;

#endif
    }

    class ConnectBG : public BackgroundJob {
    public:
        ConnectBG(int sock, SockAddr remote) : _sock(sock), _remote(remote) { }

        void run() { _res = ::connect(_sock, _remote.raw(), _remote.addressSize); }
        string name() const { return "ConnectBG"; }
        int inError() const { return _res; }

    private:
        int _sock;
        int _res;
        SockAddr _remote;
    };

    bool Socket::connect(SockAddr& remote) {
        _remote = remote;

        _fd = socket(remote.getType(), SOCK_STREAM, 0);
        if ( _fd == INVALID_SOCKET ) {
            LOG(_logLevel) << "ERROR: connect invalid socket " << errnoWithDescription() << endl;
            return false;
        }

        if ( _timeout > 0 ) {
            setTimeout( _timeout );
        }

        ConnectBG bg(_fd, remote);
        bg.go();
        if ( bg.wait(5000) ) {
            if ( bg.inError() ) {
                close();
                return false;
            }
        }
        else {
            // time out the connect
            close();
            bg.wait(); // so bg stays in scope until bg thread terminates
            return false;
        }

        if (remote.getType() != AF_UNIX)
            disableNagle(_fd);

#ifdef SO_NOSIGPIPE
        // ignore SIGPIPE signals on osx, to avoid process exit
        const int one = 1;
        setsockopt( _fd , SOL_SOCKET, SO_NOSIGPIPE, &one, sizeof(int));
#endif

        _fdCreationMicroSec = curTimeMicros64();
        return true;
    }

    int Socket::_send( const char * data , int len ) {
#ifdef MONGO_SSL
        if ( _ssl ) {
            return SSL_write( _ssl , data , len );
        }
#endif
        return ::send( _fd , data , len , portSendFlags );
    }

    // sends all data or throws an exception
    void Socket::send( const char * data , int len, const char *context ) {
        while( len > 0 ) {
            int ret = -1;
            if (MONGO_FAIL_POINT(throwSockExcep)) {
#if defined(_WIN32)
                WSASetLastError(WSAENETUNREACH);
#else
                errno = ENETUNREACH;
#endif
            }
            else {
                ret = _send(data, len);
            }

            if (ret == -1)
                _handleSendError(ret, context);

            _bytesOut += ret;

            fassert(16507, ret <= len);
            len -= ret;
            data += ret;

        }
    }

    void Socket::_send( const vector< pair< char *, int > > &data, const char *context ) {
        for (vector< pair<char *, int> >::const_iterator i = data.begin();
             i != data.end();
             ++i) {
            char * data = i->first;
            int len = i->second;
            send( data, len, context );
        }
    }

    /** sends all data or throws an exception
     * @param context descriptive for logging
     */
    void Socket::send( const vector< pair< char *, int > > &data, const char *context ) {

#ifdef MONGO_SSL
        if ( _ssl ) {
            _send( data , context );
            return;
        }
#endif

#if defined(_WIN32)
        // TODO use scatter/gather api
        _send( data , context );
#else
        vector<struct iovec> d( data.size() );
        int i = 0;
        for (vector< pair<char *, int> >::const_iterator j = data.begin();
             j != data.end();
             ++j) {
            if ( j->second > 0 ) {
                d[ i ].iov_base = j->first;
                d[ i ].iov_len = j->second;
                ++i;
                _bytesOut += j->second;
            }
        }
        struct msghdr meta;
        memset( &meta, 0, sizeof( meta ) );
        meta.msg_iov = &d[ 0 ];
        meta.msg_iovlen = d.size();

        while( meta.msg_iovlen > 0 ) {
            int ret = -1;
            if (MONGO_FAIL_POINT(throwSockExcep)) {
#if defined(_WIN32)
                WSASetLastError(WSAENETUNREACH);
#else
                errno = ENETUNREACH;
#endif
            }
            else {
                ret = ::sendmsg(_fd, &meta, portSendFlags);
            }

            if (ret == -1) {
                if ( errno != EAGAIN || _timeout == 0 ) {
                    LOG(_logLevel) << "Socket " << context <<
                        " send() " << errnoWithDescription() << ' ' << remoteString() << endl;
                    throw SocketException( SocketException::SEND_ERROR , remoteString() );
                }
                else {
                    LOG(_logLevel) << "Socket " << context <<
                        " send() remote timeout " << remoteString() << endl;
                    throw SocketException( SocketException::SEND_TIMEOUT , remoteString() );
                }
            }
            else {
                struct iovec *& i = meta.msg_iov;
                while( ret > 0 ) {
                    if ( i->iov_len > unsigned( ret ) ) {
                        i->iov_len -= ret;
                        i->iov_base = (char*)(i->iov_base) + ret;
                        ret = 0;
                    }
                    else {
                        ret -= i->iov_len;
                        ++i;
                        --(meta.msg_iovlen);
                    }
                }
            }
        }
#endif
    }

    void Socket::recv( char * buf , int len ) {
        int retries = 0;
        while( len > 0 ) {
            int ret = -1;
            if (MONGO_FAIL_POINT(throwSockExcep)) {
#if defined(_WIN32)
                WSASetLastError(WSAENETUNREACH);
#else
                errno = ENETUNREACH;
#endif
            }
            else {
                ret = unsafe_recv(buf, len);
            }
            if (ret <= 0) {
                _handleRecvError(ret, len, &retries);
                continue;
            }

            if ( len <= 4 && ret != len )
                LOG(_logLevel) << "Socket recv() got " << ret <<
                    " bytes wanted len=" << len << endl;
            fassert(16508, ret <= len);
            len -= ret;
            buf += ret;
        }
    }

    int Socket::unsafe_recv( char *buf, int max ) {
        int x = _recv( buf , max );
        _bytesIn += x;
        return x;
    }

    int Socket::_recv( char *buf, int max ) {
#ifdef MONGO_SSL
        if ( _ssl ){
            return SSL_read( _ssl , buf , max );
        }
#endif
        return ::recv( _fd , buf , max , portRecvFlags );
    }

    void Socket::_handleSendError(int ret, const char* context) {
#ifdef MONGO_SSL
        if (_ssl) {
            LOG(_logLevel) << "SSL Error ret: " << ret << " err: " << SSL_get_error(_ssl , ret)
                           << " " << ERR_error_string(ERR_get_error(), NULL)
                           << endl;
            throw SocketException(SocketException::SEND_ERROR , remoteString());
        }
#endif

#if defined(_WIN32)
        const int mongo_errno = WSAGetLastError();
        if ( mongo_errno == WSAETIMEDOUT && _timeout != 0 ) {
#else
        const int mongo_errno = errno;
        if ( ( mongo_errno == EAGAIN || mongo_errno == EWOULDBLOCK ) && _timeout != 0 ) {
#endif
            LOG(_logLevel) << "Socket " << context <<
                " send() timed out " << remoteString() << endl;
            throw SocketException(SocketException::SEND_TIMEOUT , remoteString());
        }
        else {
            LOG(_logLevel) << "Socket " << context << " send() "
                           << errnoWithDescription(mongo_errno) << ' ' << remoteString() << endl;
            throw SocketException(SocketException::SEND_ERROR , remoteString());
        }
    }

    void Socket::_handleRecvError(int ret, int len, int* retries) {
        if (ret == 0) {
            LOG(3) << "Socket recv() conn closed? " << remoteString() << endl;
            throw SocketException(SocketException::CLOSED , remoteString());
        }

        // ret < 0
#ifdef MONGO_SSL
        if (_ssl) {
            LOG(_logLevel) << "SSL Error ret: " << ret << " err: " << SSL_get_error(_ssl , ret)
                           << " " << ERR_error_string(ERR_get_error(), NULL)
                           << endl;
            throw SocketException(SocketException::RECV_ERROR, remoteString());
        }
#endif

#if defined(_WIN32)
        int e = WSAGetLastError();
#else
        int e = errno;
# if defined(EINTR)
        if (e == EINTR) {
            LOG(_logLevel) << "EINTR retry " << ++*retries << endl;
            return;
        }
# endif
#endif

#if defined(_WIN32)
        // Windows
        if ((e == EAGAIN || e == WSAETIMEDOUT) && _timeout > 0) {
#else
        if (e == EAGAIN && _timeout > 0) {
#endif
            // this is a timeout
            LOG(_logLevel) << "Socket recv() timeout  " << remoteString() <<endl;
            throw SocketException(SocketException::RECV_TIMEOUT, remoteString());
        }

        LOG(_logLevel) << "Socket recv() " <<
            errnoWithDescription(e) << " " << remoteString() <<endl;
        throw SocketException(SocketException::RECV_ERROR , remoteString());
    }

    void Socket::setTimeout( double secs ) {
        setSockTimeouts( _fd, secs );
    }

#if defined(_WIN32)
    struct WinsockInit {
        WinsockInit() {
            WSADATA d;
            if ( WSAStartup(MAKEWORD(2,2), &d) != 0 ) {
                out() << "ERROR: wsastartup failed " << errnoWithDescription() << endl;
                problem() << "ERROR: wsastartup failed " << errnoWithDescription() << endl;
                _exit(EXIT_NTSERVICE_ERROR);
            }
        }
    } winsock_init;
#endif

} // namespace mongo