text:
package function.external.mpc;

import function.external.base.DataManager;
import global.Data;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import utils.DBManager;
import utils.ErrorManager;

/**
 *
 * @author nick
 */
public class MPCManager {
    static final String table = "mpc.variant";

    private static PreparedStatement preparedStatement4Variant;

    public static void init() {
        if(MPCCommand.isInclude) {
            String sql = "SELECT MPC FROM " + table + " WHERE chr=? AND pos=? AND alt=?";
            preparedStatement4Variant = DBManager.initPreparedStatement(sql);
        }
    }

    public static String getHeader() {
        return "MPC";
    }

    public static String getVersion() {
        return "MPC: " + DataManager.getVersion(table) + "\n";
    }

    public static float getScore(String chr, int pos, String ref, String alt) {
        if (ref.length() > 1
                || alt.length() > 1) { // indels
            return Data.FLOAT_NA;
        }

        if (chr.equalsIgnoreCase("MT")) { // not support MT regions
            return Data.FLOAT_NA;
        }

        float mpc = Data.FLOAT_NA;

        try {
            preparedStatement4Variant.setString(1, chr);
            preparedStatement4Variant.setInt(2, pos);
            preparedStatement4Variant.setString(3, alt);
            ResultSet rs = preparedStatement4Variant.executeQuery();
            if (rs.next()) {
                mpc = rs.getFloat("MPC");

            }

            rs.close();
        } catch (SQLException ex) {
            ErrorManager.send(ex);
        }

        return mpc;
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Status (Public javadocs 2016.10.0 API)</title>
<meta name="date" content="2016-10-03">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

WildFly Swarm API, 2016.10.0

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.wildfly.swarm.monitor

Interface Status

All Known Implementing Classes:

CompositeHealthStatus, HealthStatus

public interface Status

Since:

23/03/16

Author:

Heiko Braun

Nested Class Summary

Nested Classes

Modifier and Type
Interface and Description

static class
Status.State

Method Summary

All Methods Instance Methods Abstract Methods

Modifier and Type
Method and Description

Optional<String>
getMessage()

Status.State
getState()

Method Detail

getState

Status.State getState()

getMessage

Optional<String> getMessage()

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

WildFly Swarm API, 2016.10.0

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

Copyright © 2016 JBoss by Red Hat. All rights reserved.

redpajama_set_name: RedPajamaGithub


text:
import tornado.httpserver
import tornado.websocket
import tornado.ioloop
import tornado.web
import Tank_Controller

class WSHandler(tornado.websocket.WebSocketHandler):
    def check_origin(self, origin):
      return True

    def open(self):
      print 'new connection'
      self.write_message("Hello World")
      self.tank = Tank_Controller.TankController()

    def on_message(self, message):
      print 'message received %s' % message
      self.tank.got_message(message);
      self.write_message(message);

    def on_close(self):
      print 'connection closed'

application = tornado.web.Application([
    (r'/ws', WSHandler),
])

if __name__ == "__main__":
    http_server = tornado.httpserver.HTTPServer(application)
    http_server.listen(8888)
    tornado.ioloop.IOLoop.instance().start()


text:
package org.wildfly.swarm.management;

import java.security.Security;
import java.util.Properties;

import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.PathElement;
import org.jboss.as.controller.client.ModelControllerClient;
import org.jboss.as.controller.client.helpers.Operations;
import org.jboss.dmr.ModelNode;
import org.jboss.dmr.ModelType;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.wildfly.security.WildFlyElytronProvider;
import org.wildfly.swarm.Swarm;
import org.wildfly.swarm.arquillian.CreateSwarm;
import org.wildfly.swarm.spi.api.JARArchive;

import static org.fest.assertions.Assertions.assertThat;

/**
 * @author Bob McWhirter
 */
@RunWith(Arquillian.class)
public class ArqSecuredManagementInterfaceWithPrecomputedPropertiesTest {

    @Deployment(testable = false)
    public static Archive createDeployment() {
        JARArchive deployment = ShrinkWrap.create(JARArchive.class, "myapp.jar");
        deployment.add(EmptyAsset.INSTANCE, "nothing");
        return deployment;
    }

    @CreateSwarm
    public static Swarm newContainer() throws Exception {
        return new Swarm()
                .fraction(
                        ManagementFraction.createDefaultFraction()
                                .httpInterfaceManagementInterface((iface) -> {
                                    iface.securityRealm("ManagementRealm");
                                })
                                .securityRealm("ManagementRealm", (realm) -> {
                                    realm.inMemoryAuthentication((authn) -> {
                                        authn.add(new Properties() {{
                                            put("bob", "9b511b00aa7f2265621e38d2cf665f2f");
                                        }});
                                    });
                                    realm.inMemoryAuthorization();
                                })
                );
    }

    @Test
    @RunAsClient
    public void testClient() throws Exception {

        Security.addProvider(new WildFlyElytronProvider());

        ModelControllerClient client = ModelControllerClient.Factory.create(
                "localhost", 9990, new AuthCallbackHandler("ManagementRealm", "bob", "tacos!")
        );

        ModelNode response = client.execute(Operations.createOperation("whoami"));

        assertThat(response.get("outcome").asString()).isEqualTo("success");

        ModelNode result = response.get("result");

        assertThat(result).isNotNull();
        assertThat(result.isDefined()).isTrue();

        ModelNode identity = result.get("identity");

        assertThat(identity).isNotNull();
        assertThat(identity.isDefined()).isTrue();

        assertThat(identity.get("username").asString()).isEqualTo("bob");

        // ===

        response = client.execute(Operations.createOperation("read-resource", PathAddress.pathAddress(PathElement.pathElement("deployment", "*")).toModelNode()));

        assertThat(response.get("outcome").asString()).isEqualTo("success");

        result = response.get("result");

        assertThat(result).isNotNull();
        assertThat(result.isDefined()).isTrue();
        assertThat(result.getType()).isEqualTo(ModelType.LIST);
        assertThat(result.asList()).hasSize(1);

        ModelNode myapp = result.get(0);

        assertThat(myapp).isNotNull();
        assertThat(myapp.isDefined()).isTrue();

        ModelNode myappResult = myapp.get("result");

        assertThat(myappResult).isNotNull();
        assertThat(myappResult.isDefined()).isTrue();

        assertThat(myappResult.get("name").asString()).isEqualTo("myapp.jar");

    }

}


text:
package org.apache.camel.component.salesforce;

import java.net.URI;
import java.util.concurrent.TimeUnit;

import org.apache.camel.component.salesforce.internal.SalesforceSession;
import org.apache.camel.component.salesforce.internal.client.SalesforceHttpRequest;
import org.apache.camel.component.salesforce.internal.client.SalesforceSecurityHandler;
import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.client.HttpClientTransport;
import org.eclipse.jetty.client.HttpConversation;
import org.eclipse.jetty.client.HttpRequest;
import org.eclipse.jetty.client.api.Request;
import org.eclipse.jetty.util.ssl.SslContextFactory;

/**
 * Custom Salesforce HTTP Client that creates {@link SalesforceHttpRequest} requests.
 */
public class SalesforceHttpClient extends HttpClient {

    // default total request timeout in msecs
    static final long DEFAULT_TIMEOUT = 60000;

    private static final int DEFAULT_MAX_RETRIES = 3;
    private static final int DEFAULT_MAX_CONTENT_LENGTH = 4 * 1024 * 1024;

    private SalesforceSession session;
    private int maxRetries = DEFAULT_MAX_RETRIES;
    private int maxContentLength = DEFAULT_MAX_CONTENT_LENGTH;
    private long timeout = DEFAULT_TIMEOUT;

    public SalesforceHttpClient() {
    }

    public SalesforceHttpClient(SslContextFactory sslContextFactory) {
        super(sslContextFactory);
    }

    public SalesforceHttpClient(HttpClientTransport transport, SslContextFactory sslContextFactory) {
        super(transport, sslContextFactory);
    }

    @Override
    public HttpRequest newHttpRequest(HttpConversation conversation, URI uri) {
        final SalesforceHttpRequest request = new SalesforceHttpRequest(this, conversation, uri);
        request.timeout(timeout, TimeUnit.MILLISECONDS);
        return request;
    }

    @Override
    public Request copyRequest(HttpRequest oldRequest, URI newURI) {
        return super.copyRequest(oldRequest, newURI);
    }

    @Override
    protected void doStart() throws Exception {
        if (getSession() == null) {
            throw new IllegalStateException("Missing SalesforceSession in property session!");
        }
        getProtocolHandlers().add(new SalesforceSecurityHandler(this));
        super.doStart();
    }

    public SalesforceSession getSession() {
        return session;
    }

    public void setSession(SalesforceSession session) {
        this.session = session;
    }

    public int getMaxRetries() {
        return maxRetries;
    }

    public void setMaxRetries(int maxRetries) {
        this.maxRetries = maxRetries;
    }

    public int getMaxContentLength() {
        return maxContentLength;
    }

    public void setMaxContentLength(int maxContentLength) {
        this.maxContentLength = maxContentLength;
    }

    public long getTimeout() {
        return timeout;
    }

    public void setTimeout(long timeout) {
        this.timeout = timeout;
    }
}


text:
jQuery clueTip Plugin
---------------------

License
========

Dual licensed under the MIT and GPL licenses:

* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html

Copyright Karl Swedberg

Requirements
============

* jQuery v1.3+

Description
===========
Displays a highly customizable tooltip when the user interacts with the matched element. As of clueTip version 1.1, this plugin is [ThemeRoller Ready][1].

### Important clueTip 1.2 Change  ###

Version 1.2 of the clueTip plugin changes the HTML structure of the tooltip. It uses classes instead of IDs for the elements within the clueTip. This allows multiple tooltips to be visible at the same time (one per call to the .cluetip() method) if the `multiple` option is set to `true`.

The plugin may not work as expected if you update jquery.cluetip.js to version 1.2+ and you don't also update the jquery.cluetip.css stylesheet.

If you have a lot invested in the old clueTip's structure with the IDs, you can get it back by:

1. adding the jquery.compat.cluetip.js file immediately after jquery.cluetip.js, AND
2. replacing jquery.cluetip.css with jquery.compat.cluetip.css.

### Options ###

The clueTip plugin allows for (too?) many options. For a complete list, check out the [plugin's home page][2]

### Content via ajax ###

By default, the clueTip plugin loads a page indicated by the "rel" attribute via ajax and displays its contents. However, *the attribute to be used for both the body and the heading of the clueTip is user-configurable*.
If a "title" attribute is specified, its value is used as the clueTip's heading.

### Content from HTML element ###

Optionally, the clueTip's body can display content from an element on the same page.

Just indicate the element's id (e.g. "#some-id") in the rel attribute.

### Content from title attribute ####

Optionally, the clueTip's body can display content from the title attribute, when a delimiter is indicated.

* The string before the first instance of the delimiter is set as the clueTip's heading.
* All subsequent strings are wrapped in separate DIVs and placed in the clueTip's body.

Examples
========

This is the most basic clueTip. It displays a 275px-wide clueTip on mouseover of the element with an ID of "tip." On mouseout of the element, the clueTip is hidden.

    $('#tip).cluetip();

The following displays a clueTip on mouseover of all `<a>` elements with class="clue". The hovered element gets a class of "highlight" added to it (so that it can be styled appropriately. This may be useful for non-anchor elements in older browsers such as IE6.). The clueTip is "sticky," which means that it will not be hidden until the user either clicks on its "close" text/graphic or displays another clueTip. The "close" text/graphic is set to display at the bottom of the clueTip (default is top) and display an image rather than the default "Close" text. Moreover, the body of the clueTip is truncated to the first 60 characters, which are followed by an ellipsis (...). Finally, the clueTip retrieves the content with a `POST` request rather than the default `GET`.

    $('a.clue').cluetip({
      hoverClass: 'highlight',
      sticky: true,
      closePosition: 'bottom',
      closeText: '<img src="cross.png" alt="close" />',
      truncate: 60,
      ajaxSettings: {
        type: 'POST'
      }
    });

You can programmatically hide (close) a clueTip by triggering the "hideCluetip" custom event. On a touch-enabled device, for example, you could hide any visible clueTips when the user touches anywhere in the body except on a link or on the clueTip itself:

    $('body').bind('touchstart', function(event) {
     event = event.originalEvent;
     var tgt = event.touches[0] && event.touches[0].target,
         $tgt = $(tgt);

     if (tgt.nodeName !== 'A' && !$tgt.closest('div.cluetip').length ) {
       $(document).trigger('hideCluetip');
     }
    });

More examples can be found at [http://plugins.learningjquery.com/cluetip/demo/](http://plugins.learningjquery.com/cluetip/demo/)

Credits
=======

* Originally inspired by Cody Lindley's jTip (http://www.codylindley.com)
* Huge thanks to Jonathan Chaffer, Glen Lipka, Shelane Enos, Hector Santos, Torben Schreiter, Dan G. Switzer, Jörn Zaefferer, and the many others who helped report and fix bugs and suggest features.

[1]: http://jqueryui.com/themeroller/
[2]: http://plugins.learningjquery.com/cluetip/


text:
package model;

public final class PlayerContext {
    private final Trooper trooper;
    private final World world;

    public PlayerContext(Trooper trooper, World world) {
        this.trooper = trooper;
        this.world = world;
    }

    public Trooper getTrooper() {
        return trooper;
    }

    public World getWorld() {
        return world;
    }
}


text:
var addon = require('../native');

module.exports = addon.fib;


text:
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class Settings
    Inherits System.Windows.Forms.Form

    'Form overrides dispose to clean up the component list.
    <System.Diagnostics.DebuggerNonUserCode()> _
    Protected Overrides Sub Dispose(ByVal disposing As Boolean)
        Try
            If disposing AndAlso components IsNot Nothing Then
                components.Dispose()
            End If
        Finally
            MyBase.Dispose(disposing)
        End Try
    End Sub

    'Required by the Windows Form Designer
    Private components As System.ComponentModel.IContainer

    'NOTE: The following procedure is required by the Windows Form Designer
    'It can be modified using the Windows Form Designer.
    'Do not modify it using the code editor.
    <System.Diagnostics.DebuggerStepThrough()> _
    Private Sub InitializeComponent()
        Dim resources As System.ComponentModel.ComponentResourceManager = New System.ComponentModel.ComponentResourceManager(GetType(Settings))
        Me.SettingsOKButton = New System.Windows.Forms.Button()
        Me.SettingsCancelButton = New System.Windows.Forms.Button()
        Me.ConnectionSettingsGroup = New System.Windows.Forms.GroupBox()
        Me.TCPPortTextBox = New System.Windows.Forms.TextBox()
        Me.TCPIPAddressTextBox = New System.Windows.Forms.TextBox()
        Me.TCPConnectionRadio = New System.Windows.Forms.RadioButton()
        Me.SerialConnectionRadio = New System.Windows.Forms.RadioButton()
        Me.SerialBaudCombo = New System.Windows.Forms.ComboBox()
        Me.TCPIPAddressLabel = New System.Windows.Forms.Label()
        Me.SerialPortCombo = New System.Windows.Forms.ComboBox()
        Me.TCPPortLabel = New System.Windows.Forms.Label()
        Me.SerialPortLabel = New System.Windows.Forms.Label()
        Me.SerialBaudLabel = New System.Windows.Forms.Label()
        Me.TTSSettingsGroupBox = New System.Windows.Forms.GroupBox()
        Me.FliteExecutableTextBox = New System.Windows.Forms.TextBox()
        Me.FliteExecutableLabel = New System.Windows.Forms.Label()
        Me.ConnectionSettingsGroup.SuspendLayout()
        Me.TTSSettingsGroupBox.SuspendLayout()
        Me.SuspendLayout()
        '
        'SettingsOKButton
        '
        Me.SettingsOKButton.Anchor = System.Windows.Forms.AnchorStyles.None
        Me.SettingsOKButton.Location = New System.Drawing.Point(133, 263)
        Me.SettingsOKButton.Name = "SettingsOKButton"
        Me.SettingsOKButton.Size = New System.Drawing.Size(67, 23)
        Me.SettingsOKButton.TabIndex = 0
        Me.SettingsOKButton.Text = "OK"
        '
        'SettingsCancelButton
        '
        Me.SettingsCancelButton.Anchor = System.Windows.Forms.AnchorStyles.None
        Me.SettingsCancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel
        Me.SettingsCancelButton.Location = New System.Drawing.Point(206, 263)
        Me.SettingsCancelButton.Name = "SettingsCancelButton"
        Me.SettingsCancelButton.Size = New System.Drawing.Size(67, 23)
        Me.SettingsCancelButton.TabIndex = 1
        Me.SettingsCancelButton.Text = "Cancel"
        '
        'ConnectionSettingsGroup
        '
        Me.ConnectionSettingsGroup.Controls.Add(Me.TCPPortTextBox)
        Me.ConnectionSettingsGroup.Controls.Add(Me.TCPIPAddressTextBox)
        Me.ConnectionSettingsGroup.Controls.Add(Me.TCPConnectionRadio)
        Me.ConnectionSettingsGroup.Controls.Add(Me.SerialConnectionRadio)
        Me.ConnectionSettingsGroup.Controls.Add(Me.SerialBaudCombo)
        Me.ConnectionSettingsGroup.Controls.Add(Me.TCPIPAddressLabel)
        Me.ConnectionSettingsGroup.Controls.Add(Me.SerialPortCombo)
        Me.ConnectionSettingsGroup.Controls.Add(Me.TCPPortLabel)
        Me.ConnectionSettingsGroup.Controls.Add(Me.SerialPortLabel)
        Me.ConnectionSettingsGroup.Controls.Add(Me.SerialBaudLabel)
        Me.ConnectionSettingsGroup.Location = New System.Drawing.Point(6, 6)
        Me.ConnectionSettingsGroup.Name = "ConnectionSettingsGroup"
        Me.ConnectionSettingsGroup.Size = New System.Drawing.Size(274, 200)
        Me.ConnectionSettingsGroup.TabIndex = 1
        Me.ConnectionSettingsGroup.TabStop = False
        Me.ConnectionSettingsGroup.Text = "Connection"
        '
        'TCPPortTextBox
        '
        Me.TCPPortTextBox.Location = New System.Drawing.Point(52, 172)
        Me.TCPPortTextBox.Name = "TCPPortTextBox"
        Me.TCPPortTextBox.Size = New System.Drawing.Size(117, 20)
        Me.TCPPortTextBox.TabIndex = 5
        '
        'TCPIPAddressTextBox
        '
        Me.TCPIPAddressTextBox.Location = New System.Drawing.Point(82, 140)
        Me.TCPIPAddressTextBox.Name = "TCPIPAddressTextBox"
        Me.TCPIPAddressTextBox.Size = New System.Drawing.Size(87, 20)
        Me.TCPIPAddressTextBox.TabIndex = 3
        '
        'TCPConnectionRadio
        '
        Me.TCPConnectionRadio.AutoSize = True
        Me.TCPConnectionRadio.Location = New System.Drawing.Point(6, 115)
        Me.TCPConnectionRadio.Name = "TCPConnectionRadio"
        Me.TCPConnectionRadio.Size = New System.Drawing.Size(46, 17)
        Me.TCPConnectionRadio.TabIndex = 2
        Me.TCPConnectionRadio.Text = "TCP"
        Me.TCPConnectionRadio.UseVisualStyleBackColor = True
        '
        'SerialConnectionRadio
        '
        Me.SerialConnectionRadio.AutoSize = True
        Me.SerialConnectionRadio.Checked = True
        Me.SerialConnectionRadio.Location = New System.Drawing.Point(6, 20)
        Me.SerialConnectionRadio.Name = "SerialConnectionRadio"
        Me.SerialConnectionRadio.Size = New System.Drawing.Size(51, 17)
        Me.SerialConnectionRadio.TabIndex = 2
        Me.SerialConnectionRadio.TabStop = True
        Me.SerialConnectionRadio.Text = "Serial"
        Me.SerialConnectionRadio.UseVisualStyleBackColor = True
        '
        'SerialBaudCombo
        '
        Me.SerialBaudCombo.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList
        Me.SerialBaudCombo.FormattingEnabled = True
        Me.SerialBaudCombo.Items.AddRange(New Object() {"115200", "57600", "38400", "19200", "9600", "4800", "2400", "1200", "300", "110"})
        Me.SerialBaudCombo.Location = New System.Drawing.Point(82, 74)
        Me.SerialBaudCombo.Name = "SerialBaudCombo"
        Me.SerialBaudCombo.Size = New System.Drawing.Size(70, 21)
        Me.SerialBaudCombo.TabIndex = 1
        '
        'TCPIPAddressLabel
        '
        Me.TCPIPAddressLabel.AutoSize = True
        Me.TCPIPAddressLabel.Location = New System.Drawing.Point(22, 143)
        Me.TCPIPAddressLabel.Name = "TCPIPAddressLabel"
        Me.TCPIPAddressLabel.Size = New System.Drawing.Size(61, 13)
        Me.TCPIPAddressLabel.TabIndex = 0
        Me.TCPIPAddressLabel.Text = "IP Address:"
        '
        'SerialPortCombo
        '
        Me.SerialPortCombo.Cursor = System.Windows.Forms.Cursors.Arrow
        Me.SerialPortCombo.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList
        Me.SerialPortCombo.FormattingEnabled = True
        Me.SerialPortCombo.Location = New System.Drawing.Point(79, 42)
        Me.SerialPortCombo.Name = "SerialPortCombo"
        Me.SerialPortCombo.Size = New System.Drawing.Size(73, 21)
        Me.SerialPortCombo.Sorted = True
        Me.SerialPortCombo.TabIndex = 1
        '
        'TCPPortLabel
        '
        Me.TCPPortLabel.AutoSize = True
        Me.TCPPortLabel.Location = New System.Drawing.Point(22, 175)
        Me.TCPPortLabel.Name = "TCPPortLabel"
        Me.TCPPortLabel.Size = New System.Drawing.Size(29, 13)
        Me.TCPPortLabel.TabIndex = 0
        Me.TCPPortLabel.Text = "Port:"
        '
        'SerialPortLabel
        '
        Me.SerialPortLabel.AutoSize = True
        Me.SerialPortLabel.Location = New System.Drawing.Point(22, 45)
        Me.SerialPortLabel.Name = "SerialPortLabel"
        Me.SerialPortLabel.Size = New System.Drawing.Size(58, 13)
        Me.SerialPortLabel.TabIndex = 0
        Me.SerialPortLabel.Text = "Serial Port:"
        '
        'SerialBaudLabel
        '
        Me.SerialBaudLabel.AutoSize = True
        Me.SerialBaudLabel.Location = New System.Drawing.Point(20, 77)
        Me.SerialBaudLabel.Name = "SerialBaudLabel"
        Me.SerialBaudLabel.Size = New System.Drawing.Size(61, 13)
        Me.SerialBaudLabel.TabIndex = 0
        Me.SerialBaudLabel.Text = "Baud Rate:"
        '
        'TTSSettingsGroupBox
        '
        Me.TTSSettingsGroupBox.Controls.Add(Me.FliteExecutableTextBox)
        Me.TTSSettingsGroupBox.Controls.Add(Me.FliteExecutableLabel)
        Me.TTSSettingsGroupBox.Location = New System.Drawing.Point(6, 212)
        Me.TTSSettingsGroupBox.Name = "TTSSettingsGroupBox"
        Me.TTSSettingsGroupBox.Size = New System.Drawing.Size(274, 45)
        Me.TTSSettingsGroupBox.TabIndex = 2
        Me.TTSSettingsGroupBox.TabStop = False
        Me.TTSSettingsGroupBox.Text = "Text to Speech"
        '
        'FliteExecutableTextBox
        '
        Me.FliteExecutableTextBox.Cursor = System.Windows.Forms.Cursors.IBeam
        Me.FliteExecutableTextBox.Location = New System.Drawing.Point(90, 17)
        Me.FliteExecutableTextBox.Name = "FliteExecutableTextBox"
        Me.FliteExecutableTextBox.Size = New System.Drawing.Size(177, 20)
        Me.FliteExecutableTextBox.TabIndex = 4
        '
        'FliteExecutableLabel
        '
        Me.FliteExecutableLabel.AutoSize = True
        Me.FliteExecutableLabel.Location = New System.Drawing.Point(6, 20)
        Me.FliteExecutableLabel.Name = "FliteExecutableLabel"
        Me.FliteExecutableLabel.Size = New System.Drawing.Size(85, 13)
        Me.FliteExecutableLabel.TabIndex = 0
        Me.FliteExecutableLabel.Text = "Flite Executable:"
        '
        'Settings
        '
        Me.AcceptButton = Me.SettingsOKButton
        Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
        Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
        Me.CancelButton = Me.SettingsCancelButton
        Me.ClientSize = New System.Drawing.Size(285, 298)
        Me.Controls.Add(Me.TTSSettingsGroupBox)
        Me.Controls.Add(Me.SettingsCancelButton)
        Me.Controls.Add(Me.SettingsOKButton)
        Me.Controls.Add(Me.ConnectionSettingsGroup)
        Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog
        Me.Icon = CType(resources.GetObject("$this.Icon"), System.Drawing.Icon)
        Me.MaximizeBox = False
        Me.MinimizeBox = False
        Me.Name = "Settings"
        Me.ShowInTaskbar = False
        Me.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent
        Me.Text = "Settings"
        Me.ConnectionSettingsGroup.ResumeLayout(False)
        Me.ConnectionSettingsGroup.PerformLayout()
        Me.TTSSettingsGroupBox.ResumeLayout(False)
        Me.TTSSettingsGroupBox.PerformLayout()
        Me.ResumeLayout(False)

    End Sub
    Friend WithEvents SettingsOKButton As System.Windows.Forms.Button
    Friend WithEvents ConnectionSettingsGroup As System.Windows.Forms.GroupBox
    Friend WithEvents TCPPortTextBox As System.Windows.Forms.TextBox
    Friend WithEvents TCPIPAddressTextBox As System.Windows.Forms.TextBox
    Friend WithEvents TCPConnectionRadio As System.Windows.Forms.RadioButton
    Friend WithEvents SerialConnectionRadio As System.Windows.Forms.RadioButton
    Friend WithEvents SerialBaudCombo As System.Windows.Forms.ComboBox
    Friend WithEvents TCPIPAddressLabel As System.Windows.Forms.Label
    Friend WithEvents SerialPortCombo As System.Windows.Forms.ComboBox
    Friend WithEvents TCPPortLabel As System.Windows.Forms.Label
    Friend WithEvents SerialPortLabel As System.Windows.Forms.Label
    Friend WithEvents SerialBaudLabel As System.Windows.Forms.Label
    Friend WithEvents SettingsCancelButton As System.Windows.Forms.Button
    Friend WithEvents TTSSettingsGroupBox As System.Windows.Forms.GroupBox
    Friend WithEvents FliteExecutableTextBox As System.Windows.Forms.TextBox
    Friend WithEvents FliteExecutableLabel As System.Windows.Forms.Label

End Class


text:
require 'spec_helper'
require 'support/available_languages_helper'

describe ThatLanguage, "ko (korean)" do
  include AvailableLanguagesHelper

  use_language_code "ko"
  use_language :"Korean"

  # WhatLanguageTest
  assert_that_language_with "이 어떤 언어인가?"
end


text:
OpenLMI Journald Scripts documentation
==========================================

Contents:

.. toctree::
   :maxdepth: 2

   cmdline
   python

Indices and tables
==================

* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`


text:
package filestore

import (
	"context"
	"fmt"
	"io"
	"os"
	"path/filepath"

	"github.com/ipfs/go-ipfs/blocks/blockstore"
	pb "github.com/ipfs/go-ipfs/filestore/pb"
	dshelp "github.com/ipfs/go-ipfs/thirdparty/ds-help"
	posinfo "github.com/ipfs/go-ipfs/thirdparty/posinfo"
	"gx/ipfs/QmYsEQydGrsxNZfAiskvQ76N2xE9hDQtSAkRSynwMiUK3c/go-block-format"

	proto "gx/ipfs/QmT6n4mspWYEya864BhCUJEgyxiRfmiSY9ruQwTUNpRKaM/protobuf/proto"
	ds "gx/ipfs/QmdHG8MAuARdGHxx4rPQASLcvhz24fzjSQq7AJRAQEorq5/go-datastore"
	dsns "gx/ipfs/QmdHG8MAuARdGHxx4rPQASLcvhz24fzjSQq7AJRAQEorq5/go-datastore/namespace"
	dsq "gx/ipfs/QmdHG8MAuARdGHxx4rPQASLcvhz24fzjSQq7AJRAQEorq5/go-datastore/query"
	cid "gx/ipfs/QmeSrf6pzut73u6zLQkRFQ3ygt3k6XFT2kjdYP8Tnkwwyg/go-cid"
)

// FilestorePrefix identifies the key prefix for FileManager blocks.
var FilestorePrefix = ds.NewKey("filestore")

// FileManager is a blockstore implementation which stores special
// blocks FilestoreNode type. These nodes only contain a reference
// to the actual location of the block data in the filesystem
// (a path and an offset).
type FileManager struct {
	ds   ds.Batching
	root string
}

// CorruptReferenceError implements the error interface.
// It is used to indicate that the block contents pointed
// by the referencing blocks cannot be retrieved (i.e. the
// file is not found, or the data changed as it was being read).
type CorruptReferenceError struct {
	Code Status
	Err  error
}

// Error() returns the error message in the CorruptReferenceError
// as a string.
func (c CorruptReferenceError) Error() string {
	return c.Err.Error()
}

// NewFileManager initializes a new file manager with the given
// datastore and root. All FilestoreNodes paths are relative to the
// root path given here, which is prepended for any operations.
func NewFileManager(ds ds.Batching, root string) *FileManager {
	return &FileManager{dsns.Wrap(ds, FilestorePrefix), root}
}

// AllKeysChan returns a channel from which to read the keys stored in
// the FileManager. If the given context is cancelled the channel will be
// closed.
func (f *FileManager) AllKeysChan(ctx context.Context) (<-chan *cid.Cid, error) {
	q := dsq.Query{KeysOnly: true}

	res, err := f.ds.Query(q)
	if err != nil {
		return nil, err
	}

	out := make(chan *cid.Cid, dsq.KeysOnlyBufSize)
	go func() {
		defer close(out)
		for {
			v, ok := res.NextSync()
			if !ok {
				return
			}

			k := ds.RawKey(v.Key)
			c, err := dshelp.DsKeyToCid(k)
			if err != nil {
				log.Error("decoding cid from filestore: %s", err)
				continue
			}

			select {
			case out <- c:
			case <-ctx.Done():
				return
			}
		}
	}()

	return out, nil
}

// DeleteBlock deletes the reference-block from the underlying
// datastore. It does not touch the referenced data.
func (f *FileManager) DeleteBlock(c *cid.Cid) error {
	err := f.ds.Delete(dshelp.CidToDsKey(c))
	if err == ds.ErrNotFound {
		return blockstore.ErrNotFound
	}
	return err
}

// Get reads a block from the datastore. Reading a block
// is done in two steps: the first step retrieves the reference
// block from the datastore. The second step uses the stored
// path and offsets to read the raw block data directly from disk.
func (f *FileManager) Get(c *cid.Cid) (blocks.Block, error) {
	dobj, err := f.getDataObj(c)
	if err != nil {
		return nil, err
	}

	out, err := f.readDataObj(c, dobj)
	if err != nil {
		return nil, err
	}

	return blocks.NewBlockWithCid(out, c)
}

func (f *FileManager) getDataObj(c *cid.Cid) (*pb.DataObj, error) {
	o, err := f.ds.Get(dshelp.CidToDsKey(c))
	switch err {
	case ds.ErrNotFound:
		return nil, blockstore.ErrNotFound
	default:
		return nil, err
	case nil:
		//
	}

	return unmarshalDataObj(o)
}

func unmarshalDataObj(o interface{}) (*pb.DataObj, error) {
	data, ok := o.([]byte)
	if !ok {
		return nil, fmt.Errorf("stored filestore dataobj was not a []byte")
	}

	var dobj pb.DataObj
	if err := proto.Unmarshal(data, &dobj); err != nil {
		return nil, err
	}

	return &dobj, nil
}

// reads and verifies the block
func (f *FileManager) readDataObj(c *cid.Cid, d *pb.DataObj) ([]byte, error) {
	p := filepath.FromSlash(d.GetFilePath())
	abspath := filepath.Join(f.root, p)

	fi, err := os.Open(abspath)
	if os.IsNotExist(err) {
		return nil, &CorruptReferenceError{StatusFileNotFound, err}
	} else if err != nil {
		return nil, &CorruptReferenceError{StatusFileError, err}
	}
	defer fi.Close()

	_, err = fi.Seek(int64(d.GetOffset()), io.SeekStart)
	if err != nil {
		return nil, &CorruptReferenceError{StatusFileError, err}
	}

	outbuf := make([]byte, d.GetSize_())
	_, err = io.ReadFull(fi, outbuf)
	if err == io.EOF || err == io.ErrUnexpectedEOF {
		return nil, &CorruptReferenceError{StatusFileChanged, err}
	} else if err != nil {
		return nil, &CorruptReferenceError{StatusFileError, err}
	}

	outcid, err := c.Prefix().Sum(outbuf)
	if err != nil {
		return nil, err
	}

	if !c.Equals(outcid) {
		return nil, &CorruptReferenceError{StatusFileChanged,
			fmt.Errorf("data in file did not match. %s offset %d", d.GetFilePath(), d.GetOffset())}
	}

	return outbuf, nil
}

// Has returns if the FileManager is storing a block reference. It does not
// validate the data, nor checks if the reference is valid.
func (f *FileManager) Has(c *cid.Cid) (bool, error) {
	// NOTE: interesting thing to consider. Has doesnt validate the data.
	// So the data on disk could be invalid, and we could think we have it.
	dsk := dshelp.CidToDsKey(c)
	return f.ds.Has(dsk)
}

type putter interface {
	Put(ds.Key, interface{}) error
}

// Put adds a new reference block to the FileManager. It does not check
// that the reference is valid.
func (f *FileManager) Put(b *posinfo.FilestoreNode) error {
	return f.putTo(b, f.ds)
}

func (f *FileManager) putTo(b *posinfo.FilestoreNode, to putter) error {
	var dobj pb.DataObj

	if !filepath.HasPrefix(b.PosInfo.FullPath, f.root) {
		return fmt.Errorf("cannot add filestore references outside ipfs root (%s)", f.root)
	}

	p, err := filepath.Rel(f.root, b.PosInfo.FullPath)
	if err != nil {
		return err
	}

	dobj.FilePath = proto.String(filepath.ToSlash(p))
	dobj.Offset = proto.Uint64(b.PosInfo.Offset)
	dobj.Size_ = proto.Uint64(uint64(len(b.RawData())))

	data, err := proto.Marshal(&dobj)
	if err != nil {
		return err
	}

	return to.Put(dshelp.CidToDsKey(b.Cid()), data)
}

// PutMany is like Put() but takes a slice of blocks instead,
// allowing it to create a batch transaction.
func (f *FileManager) PutMany(bs []*posinfo.FilestoreNode) error {
	batch, err := f.ds.Batch()
	if err != nil {
		return err
	}

	for _, b := range bs {
		if err := f.putTo(b, batch); err != nil {
			return err
		}
	}

	return batch.Commit()
}


text:
package org.jboss.weld.vertx.serviceproxy;

import org.jboss.weld.vertx.WeldVerticle;

import io.vertx.core.Future;
import io.vertx.serviceproxy.ProxyHelper;

/**
 *
 * @author Martin Kouba
 */
public class EchoServiceVerticle extends WeldVerticle {

    @Override
    public void start(Future<Void> startFuture) throws Exception {
        super.start(startFuture);
        ProxyHelper.registerService(EchoService.class, vertx, new EchoServiceImpl(), "echo-service-address");
    }

}


text:
'use strict';

/*!
 * ignore
 */

module.exports = applyHooks;

/*!
 * Register hooks for this model
 *
 * @param {Model} model
 * @param {Schema} schema
 */

function applyHooks(model, schema, options) {
  options = options || {};

  const kareemOptions = {
    useErrorHandlers: true,
    numCallbackParams: 1,
    nullResultByDefault: true,
    contextParameter: true
  };
  const objToDecorate = options.decorateDoc ? model : model.prototype;

  model.$appliedHooks = true;
  for (let i = 0; i < schema.childSchemas.length; ++i) {
    const childModel = schema.childSchemas[i].model;
    if (childModel.$appliedHooks) {
      continue;
    }
    applyHooks(childModel, schema.childSchemas[i].schema, options);
    if (childModel.discriminators != null) {
      let keys = Object.keys(childModel.discriminators);
      for (let j = 0; j < keys.length; ++j) {
        applyHooks(childModel.discriminators[keys[j]],
          childModel.discriminators[keys[j]].schema, options);
      }
    }
  }

  objToDecorate.$__save = schema.s.hooks.
    createWrapper('save', objToDecorate.$__save, null, kareemOptions);
  objToDecorate.$__validate = schema.s.hooks.
    createWrapper('validate', objToDecorate.$__validate, null, kareemOptions);
  objToDecorate.$__remove = schema.s.hooks.
    createWrapper('remove', objToDecorate.$__remove, null, kareemOptions);
  objToDecorate.$__init = schema.s.hooks.
    createWrapperSync('init', objToDecorate.$__init, null, kareemOptions);
}


text:
using content::UserMetricsAction;

PanelHost::PanelHost(Panel* panel, Profile* profile)
    : panel_(panel),
      profile_(profile),
      extension_function_dispatcher_(profile, this),
      weak_factory_(this) {
}

PanelHost::~PanelHost() {
}

void PanelHost::Init(const GURL& url) {
  if (url.is_empty())
    return;

  web_contents_.reset(content::WebContents::Create(
      profile_, content::SiteInstance::CreateForURL(profile_, url),
      MSG_ROUTING_NONE, NULL, NULL));
  chrome::SetViewType(web_contents_.get(), chrome::VIEW_TYPE_PANEL);
  web_contents_->SetDelegate(this);
  content::WebContentsObserver::Observe(web_contents_.get());

  favicon_tab_helper_.reset(new FaviconTabHelper(web_contents_.get()));

  web_contents_->GetController().LoadURL(
      url, content::Referrer(), content::PAGE_TRANSITION_LINK, std::string());
}

void PanelHost::DestroyWebContents() {
  web_contents_.reset();
  favicon_tab_helper_.reset();
}

SkBitmap PanelHost::GetPageIcon() const {
  return favicon_tab_helper_.get() ?
      favicon_tab_helper_->GetFavicon() : SkBitmap();
}

void PanelHost::NavigationStateChanged(const content::WebContents* source,
                                       unsigned changed_flags) {
  // Only need to update the title if the title changed while not loading,
  // because the title is also updated when loading state changes.
  if ((changed_flags & content::INVALIDATE_TYPE_TAB) ||
      ((changed_flags & content::INVALIDATE_TYPE_TITLE) &&
       !source->IsLoading()))
    panel_->UpdateTitleBar();
}

void PanelHost::ActivateContents(content::WebContents* contents) {
  panel_->Activate();
}

void PanelHost::DeactivateContents(content::WebContents* contents) {
  panel_->Deactivate();
}

void PanelHost::LoadingStateChanged(content::WebContents* source) {
  bool is_loading = source->IsLoading();
  panel_->LoadingStateChanged(is_loading);
}

void PanelHost::CloseContents(content::WebContents* source) {
  panel_->Close();
}

void PanelHost::MoveContents(content::WebContents* source,
                             const gfx::Rect& pos) {
  panel_->SetBounds(pos);
}

bool PanelHost::IsPopupOrPanel(const content::WebContents* source) const {
  return true;
}

void PanelHost::ContentsZoomChange(bool zoom_in) {
  Zoom(zoom_in ? content::PAGE_ZOOM_IN : content::PAGE_ZOOM_OUT);
}

bool PanelHost::IsApplication() const {
  return true;
}

bool PanelHost::HandleContextMenu(const content::ContextMenuParams& params) {
  return true;  // Disallow context menu.
}

void PanelHost::HandleKeyboardEvent(
    const content::NativeWebKeyboardEvent& event) {
  return panel_->HandleKeyboardEvent(event);
}

void PanelHost::WebContentsFocused(content::WebContents* contents) {
  panel_->WebContentsFocused(contents);
}

void PanelHost::ResizeDueToAutoResize(content::WebContents* web_contents,
                                      const gfx::Size& new_size) {
  panel_->OnContentsAutoResized(new_size);
}

void PanelHost::RenderViewGone(base::TerminationStatus status) {
  CloseContents(web_contents_.get());
}

void PanelHost::WebContentsDestroyed(content::WebContents* web_contents) {
  // Close the panel after we return to the message loop (not immediately,
  // otherwise, it may destroy this object before the stack has a chance
  // to cleanly unwind.)
  MessageLoop::current()->PostTask(
      FROM_HERE,
      base::Bind(&PanelHost::ClosePanel, weak_factory_.GetWeakPtr()));
}

void PanelHost::ClosePanel() {
  panel_->Close();
}

bool PanelHost::OnMessageReceived(const IPC::Message& message) {
  bool handled = true;
  IPC_BEGIN_MESSAGE_MAP(PanelHost, message)
    IPC_MESSAGE_HANDLER(ExtensionHostMsg_Request, OnRequest)
    IPC_MESSAGE_UNHANDLED(handled = false)
  IPC_END_MESSAGE_MAP()
  return handled;
}

void PanelHost::OnRequest(const ExtensionHostMsg_Request_Params& params) {
  if (!web_contents_.get())
    return;

  extension_function_dispatcher_.Dispatch(params,
                                          web_contents_->GetRenderViewHost());
}

extensions::WindowController* PanelHost::GetExtensionWindowController() const {
  return panel_->extension_window_controller();
}

content::WebContents* PanelHost::GetAssociatedWebContents() const {
  return web_contents_.get();
}

void PanelHost::Reload() {
  content::RecordAction(UserMetricsAction("Reload"));
  web_contents_->GetController().Reload(true);
}

void PanelHost::ReloadIgnoringCache() {
  content::RecordAction(UserMetricsAction("ReloadIgnoringCache"));
  web_contents_->GetController().ReloadIgnoringCache(true);
}

void PanelHost::StopLoading() {
  content::RecordAction(UserMetricsAction("Stop"));
  web_contents_->Stop();
}

void PanelHost::Zoom(content::PageZoom zoom) {
  chrome_page_zoom::Zoom(web_contents_.get(), zoom);
}


text:
using BizUnit.Core.TestBuilder;
using System;

namespace BizUnit.TestSteps.File
{
    public class CopyStep : TestStepBase
    {

        private string _sourcePath;
        private string _destinationPath;

        /// <summary>
        /// Gets or sets the source path.
        /// </summary>
        /// <value>The source path.</value>
        public string SourcePath
        {
            get { return _sourcePath; }
            set { _sourcePath = value; }
        }

        /// <summary>
        /// Gets or sets the destination path.
        /// </summary>
        /// <value>The destination path.</value>
        public string DestinationPath
        {
            get { return _destinationPath; }
            set { _destinationPath = value; }
        }

        /// <summary>
        /// ITestStep.Execute() implementation
        /// </summary>
        /// <param name='context'>The context for the test, this holds state that is passed beteen tests</param>
        public override void Execute(Context context)
        {
            context.LogInfo("Copying '{0}' to '{1}'", _sourcePath, _destinationPath);
            System.IO.File.Copy(_sourcePath, _destinationPath);

            context.LogInfo("FileCopyStep has been copied file from: \"{0}\" to \"{1}\"", _sourcePath, _destinationPath);
        }

        public override void Validate(Context context)
        {
            if (string.IsNullOrEmpty(_destinationPath))
            {
                throw new ArgumentNullException("DestinationPath is either null or of zero length");
            }
            _destinationPath = context.SubstituteWildCards(_destinationPath);

            if (string.IsNullOrEmpty(_sourcePath))
            {
                throw new ArgumentNullException("SourcePath is either null or of zero length");
            }
            _sourcePath = context.SubstituteWildCards(_sourcePath);
        }
    }
}


text:
package se.culvertsoft.mgen.javapack.util;

import java.util.ArrayList;
import java.util.List;

import se.culvertsoft.mgen.api.model.Field;
import se.culvertsoft.mgen.javapack.classes.MGenBase;
import se.culvertsoft.mgen.javapack.exceptions.MissingRequiredFieldsException;
import se.culvertsoft.mgen.javapack.exceptions.UnexpectedTypeException;
import se.culvertsoft.mgen.javapack.metadata.FieldSetDepth;

/**
 * Class holding utility methods used by MGen's built in readers and writers.
 * Used for validating objects and throwing exceptions with useful error
 * messages. Only intended to be used internally by the MGen built-in
 * serializers.
 */
public class BuiltInSerializerUtils {

	/**
	 * Throws an UnexpectedTypeException with a useful error message.
	 *
	 * @param extraInfo
	 *            Extra text to append to the error message
	 *
	 * @param expTag
	 *            The type tag expected
	 *
	 * @param readTag
	 *            The type tag actually read
	 */
	public static void throwUnexpectTag(
			final String extraInfo,
			final byte expTag,
			final byte readTag) {
		throw new UnexpectedTypeException("Unexpected type tag. Expected " + expTag + " but got "
				+ readTag + ". " + extraInfo);
	}

	/**
	 * Throws an UnexpectedTypeException with a useful error message.
	 *
	 * @param extraInfo
	 *            Extra text to append to the error message
	 *
	 * @param expTypeName
	 *            The expected type name
	 *
	 * @param typeName
	 *            The type name of the object actually read back
	 */
	public static void throwUnexpectType(
			final String extraInfo,
			final String expTypeName,
			final String typeName) {
		throw new UnexpectedTypeException("Unexpected type received. Expected " + expTypeName
				+ " but got " + typeName + ". " + extraInfo);
	}

	/**
	 * Throws a MissingRequiredFieldsException with a useful error message.
	 *
	 * @param missingFields
	 *            The required fields that are missing
	 *
	 * @param object
	 *            The objects they are missing on
	 */
	public static
			void
			throwMissingReqFields(final List<Field> missingFields, final MGenBase object) {
		throw new MissingRequiredFieldsException("Missing required fields [" + missingFields
				+ "] on object '" + object + "'");
	}

	/**
	 * Checks that the MGen object provided has no missing required fields, and
	 * if it does, throws a MissingRequiredFieldsException.
	 *
	 * @param object
	 *            The MGen object to test
	 *
	 * @param depth
	 *            If to test the object DEEP or SHALLOW
	 */
	public static void ensureNoMissingReqFields(final MGenBase object, final FieldSetDepth depth) {

		if (object != null && !object._validate(depth)) {

			final ArrayList<Field> missingReqFields = new ArrayList<Field>();

			for (final Field f : object._fields()) {
				if (f.isRequired() && !object._isFieldSet(f, depth)) {
					missingReqFields.add(f);
				}
			}

			throw new MissingRequiredFieldsException("Missing required fields [" + missingReqFields
					+ "] on object '" + object + "'");
		}
	}

	/**
	 * Checks that the MGen object provided has no missing required fields, and
	 * if it does, throws a MissingRequiredFieldsException. The test is
	 * performed SHALLOW.
	 *
	 * @param object
	 *            The MGen object to test
	 */
	public static void ensureNoMissingReqFields(final MGenBase object) {
		ensureNoMissingReqFields(object, FieldSetDepth.SHALLOW);
	}

}


text:
import UserInfo from './UserInfo';

class Member {
  constructor(props) {
    this.userInfo = new UserInfo(props.userInfo);
    this.lastConsumedMessageIndex = props.lastConsumedMessageIndex;
    this.lastConsumptionTimestamp = this.lastConsumptionTimestamp ? new Date(this.lastConsumptionTimestamp) : null;
  }
}

export default Member;


text:
from ...core import database as db
from ..enums import (
    ReturnType, SpatialFunctionGroup, SpatialType)
from ..template import AbstractSpatialFunction

class Segmentize(AbstractSpatialFunction):
    """
    ST_Segmentize
    """

    def __init__(self, max_segment_length=0):
        self._max_segment_length = max_segment_length

    @property
    def max_segment_length(self):
        return self._max_segment_length

    @max_segment_length.setter
    def max_segment_length(self, value):
        self._max_segment_length = value

    @classmethod
    def function_name(cls):
        return "ST_Segmentize"

    @classmethod
    def alias_name(cls):
        return None

    @classmethod
    def function_group(cls):
        return SpatialFunctionGroup.EDITORS

    @classmethod
    def function_help(cls):
        return "https://postgis.net/docs/ST_Segmentize.html"

    @classmethod
    def start_postgis_version(cls):
        return "1.2.2"

    @classmethod
    def spatial_type_support(cls):
        return [
            SpatialType.GEOMETRY,
            SpatialType.GEOGRAPHY,
        ]

    @classmethod
    def return_type(cls):
        return ReturnType.GEOMETRY

    def execute_query(self, wkt):
        output = db.execute("""
            SELECT ST_AsText(ST_Segmentize(ST_GeomFromText(%s), %s));
        """, (wkt, self.max_segment_length, ))
        return output

    def sample_query_as_text(self, wkt):
        return """
            SELECT ST_AsText(ST_Segmentize(ST_GeomFromText('{0}'), {1}))
        """.format(wkt, self.max_segment_length)


text:
package javax.portlet.tck.beans;

import java.io.Serializable;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import javax.portlet.EventRequest;
import javax.portlet.EventResponse;
import javax.portlet.MutableRenderParameters;
import javax.portlet.PortletMode;
import javax.portlet.PortletModeException;
import javax.portlet.PortletResponse;
import javax.portlet.WindowState;
import javax.portlet.WindowStateException;
import javax.servlet.http.Cookie;
import javax.xml.namespace.QName;

import org.w3c.dom.DOMException;
import org.w3c.dom.Element;

/**
 * This class tests a wrapper class by simulating the class to be wrapped.The test code verifies that the arguments
 * passed to the wrapping method are correctly passed to the wrapped class. Simulated return data is passed back to the
 * caller.
 *
 * @author nick
 */

public class EventResponseWrapperChecker extends WrapperChecker implements EventResponse {

   PortletResponse resp;
   Element         element;

   public EventResponseWrapperChecker(PortletResponse portletResp) {
      resp = portletResp;
      element = resp.createElement("p");
   }

   @Override
   public void setWindowState(WindowState windowState) throws WindowStateException {
      String meth = "setWindowState";
      Object[] args = { windowState };
      checkArgs(meth, args);
      return;

   }

   @Override
   public void setRenderParameters(Map<String, String[]> parameters) {
      String meth = "setRenderParameters";
      Object[] args = { parameters };
      checkArgs(meth, args);
      return;

   }

   @Override
   public void setRenderParameter(String key, String... values) {
      String meth = "setRenderParameter";
      Object[] args = { key, values };
      checkArgs(meth, args);
      return;

   }

   @Override
   public Map<String, String[]> getRenderParameterMap() {
      String meth = "getRenderParameterMap";
      Object[] args = {};
      Map<String, String[]> parms = new HashMap<String, String[]>();
      parms.put("parm1", new String[] { "val1", "val2" });
      parms.put("parm2", new String[] { "val1", "val2" });
      Map<String, String[]> ret = parms;
      retVal = ret;
      checkArgs(meth, args);
      return ret;
   }

   @Override
   public PortletMode getPortletMode() {
      String meth = "getPortletMode";
      Object[] args = {};
      PortletMode ret = PortletMode.EDIT;
      retVal = ret;
      checkArgs(meth, args);
      return ret;
   }

   @Override
   public WindowState getWindowState() {
      String meth = "getWindowState";
      Object[] args = {};
      WindowState ret = WindowState.NORMAL;
      retVal = ret;
      checkArgs(meth, args);
      return ret;
   }

   @Override
   public void removePublicRenderParameter(String name) {
      String meth = "removePublicRenderParameter";
      Object[] args = { name };
      checkArgs(meth, args);
      return;

   }

   @Override
   public void setEvent(QName arg0, Serializable arg1) {
      String meth = "setEvent";
      Object[] args = { arg0, arg1 };
      checkArgs(meth, args);
      return;

   }

   @Override
   public void setPortletMode(PortletMode portletMode) throws PortletModeException {
      String meth = "setPortletMode";
      Object[] args = { portletMode };
      checkArgs(meth, args);
      return;

   }

   @Override
   public void setRenderParameter(String key, String value) {
      String meth = "setRenderParameter";
      Object[] args = { key, value };
      checkArgs(meth, args);
      return;

   }

   @Override
   public void setEvent(String name, Serializable value) {
      String meth = "setEvent";
      Object[] args = { name, value };
      checkArgs(meth, args);
      return;

   }

   @Override
   public void addProperty(String key, String value) {
      String meth = "addProperty";
      Object[] args = { key, value };
      checkArgs(meth, args);
      return;

   }

   @Override
   public void setProperty(String key, String value) {
      String meth = "setProperty";
      Object[] args = { key, value };
      checkArgs(meth, args);
      return;

   }

   @Override
   public String encodeURL(String path) {
      String meth = "encodeURL";
      Object[] args = { path };
      String ret = "value";
      retVal = ret;
      checkArgs(meth, args);
      return ret;
   }

   @Override
   public String getNamespace() {
      String meth = "getNamespace";
      Object[] args = {};
      String ret = "value";
      retVal = ret;
      checkArgs(meth, args);
      return ret;
   }

   @Override
   public void addProperty(Cookie cookie) {
      String meth = "addProperty";
      Object[] args = { cookie };
      checkArgs(meth, args);
      return;

   }

   @Override
   public void addProperty(String key, Element element) {
      String meth = "addProperty";
      Object[] args = { key, element };
      checkArgs(meth, args);
      return;

   }

   @Override
   public Element createElement(String tagName) throws DOMException {
      String meth = "createElement";
      Object[] args = { tagName };
      Element ret = element;
      retVal = ret;
      checkArgs(meth, args);
      return ret;
   }

   @Override
   public void setRenderParameters(EventRequest request) {
      String meth = "setRenderParameters";
      Object[] args = { request };
      checkArgs(meth, args);
      return;

   }

   @Override
   public String getProperty(String arg0) {
      return null;
   }

   @Override
   public Collection<String> getPropertyNames() {
      return null;
   }

   @Override
   public Collection<String> getPropertyValues(String arg0) {
      return null;
   }

   @Override
   public MutableRenderParameters getRenderParameters() {
      return null;
   }

}


text:
<?php

declare(strict_types=1);

namespace Cmfcmf\Module\MediaModule\Entity\Watermark;

use Cmfcmf\Module\MediaModule\Font\FontCollection;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;
use Gedmo\Uploadable\Uploadable;
use Imagine\Image\Box;
use Imagine\Image\ImagineInterface;

/**
 * @ORM\Entity
 * @Gedmo\Uploadable(pathMethod="getPathToUploadTo", filenameGenerator="SHA1", appendNumber=true,
 *     allowedTypes="image/png,image/jpeg,image/gif")
 *
 * NOTE: If you change the allowed mime types here, make sure to also change them in
 * {@link ImageWatermarkType}.
 */
class ImageWatermarkEntity extends AbstractWatermarkEntity implements Uploadable
{
    /**
     * @ORM\Column(type="string")
     * @Gedmo\UploadableFileName
     */
    protected $fileName;

    /**
     * @ORM\Column(type="string")
     * @Gedmo\UploadableFileMimeType
     */
    protected $mimeType;

    /**
     * @ORM\Column(type="decimal")
     * @Gedmo\UploadableFileSize
     */
    protected $fileSize;

    /**
     * {@inheritdoc}
     */
    public function getImagineImage(
        ImagineInterface $imagine,
        FontCollection $fontCollection,
        $width,
        $height
    ) {
        $watermarkImage = $imagine->open($this->getPath());
        if (null !== $this->getRelativeSize()) {
            $y = (int) $height * $this->getRelativeSize() / 100;
            $factor = $y / $watermarkImage->getSize()->getHeight();
            $x = $watermarkImage->getSize()->getWidth() * $factor;
            $actualWidth = $width - abs($this->positionX);
            if ($x > $actualWidth) {
                $factor = $actualWidth / $x;
                $x = $actualWidth;
                $y *= $factor;
            }
            $watermarkImage->resize(new Box($x, $y));
        }

        return $watermarkImage;
    }

    public function getPathToUploadTo($defaultPath)
    {
        unset($defaultPath);

        return $this->dataDirectory . '/cmfcmf-media-module/watermarks';
    }

    public function getPath()
    {
        return $this->getPathToUploadTo(null) . '/' . $this->fileName;
    }

    public function getFileName()
    {
        return $this->fileName;
    }

    public function getUrl()
    {
        return $this->requestStack->getCurrentRequest()->getBasePath() . '/' . $this->getPath();
    }

    /**
     * {@inheritdoc}
     */
    public function getViewTableContent()
    {
        $src = htmlentities($this->getUrl());
        $title = htmlentities($this->title);

        return <<<EOD
<img src="${src}" alt="${title}" class="img-responsive" style="max-width: 150px; max-height: 100px" />
EOD;
    }
}


text:
package com.intellij.util;

import com.intellij.openapi.application.Application;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.impl.ApplicationInfoImpl;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Condition;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.util.UserDataHolder;
import com.intellij.psi.PsiElement;
import com.intellij.psi.util.CachedValueProvider;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.ref.DebugReflectionUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.Collections;
import java.util.Set;

/**
 * @author peter
 */
class CachedValueLeakChecker {
  private static final Logger LOG = Logger.getInstance("#com.intellij.util.CachedValueChecker");
  private static final boolean DO_CHECKS = ApplicationManager.getApplication().isUnitTestMode();
  private static final Set<String> ourCheckedKeys = ContainerUtil.newConcurrentSet();

  static void checkProvider(@NotNull final CachedValueProvider provider,
                            @NotNull final Key key,
                            @NotNull final UserDataHolder userDataHolder) {
    if (!DO_CHECKS || ApplicationInfoImpl.isInStressTest()) return;
    if (!ourCheckedKeys.add(key.toString())) return; // store strings because keys are created afresh in each (test) project

    if (!SystemInfo.IS_AT_LEAST_JAVA9) {
      findReferencedPsi(provider, userDataHolder, 5);
    }
  }

  private static synchronized void findReferencedPsi(@NotNull final Object root,
                                                     @Nullable final UserDataHolder toIgnore,
                                                     int depth) {
    Condition<Object> shouldExamineValue = value -> {
      if (value == toIgnore) return false;
      if (value instanceof Project || value instanceof Module || value instanceof Application) return false;
      if (value instanceof PsiElement &&
          toIgnore instanceof PsiElement &&
          ((PsiElement)toIgnore).getContainingFile() != null &&
          PsiTreeUtil.isAncestor((PsiElement)value, (PsiElement)toIgnore, true)) {
        // allow to capture PSI parents, assuming that they stay valid at least as long as the element itself
        return false;
      }
      return true;
    };
    DebugReflectionUtil.walkObjects(depth, Collections.singletonList(root), PsiElement.class, shouldExamineValue, (value, backLink) -> {
      if (value instanceof PsiElement) {
        LOG.error(
          "Incorrect CachedValue use. Provider references PSI, causing memory leaks and possible invalid element access, provider=" +
          root + "\n" + backLink);
        return false;
      }
      return true;
    });
  }
}


text:
{% extends "layout.html" %}

{% block page_title %}
 Why do you need an emergency passport?
{% endblock %}

{% block content %}

      <form action="/" method="post" class="form">

          Why do you need an emergency travel document?

              <input id="radio-lost" type="radio" name="why" value="lost">

              My passport has been lost

              <input id="radio-stolen" type="radio" name="why" value="stolen">

             My passport has been stolen

              <input id="radio-expire" type="radio" name="why" value="expire">

              My passport has expired or is about to expire

              <input id="radio-full" type="radio" name="why" value="full">

             My passport is full

              <input id="radio-defaced" type="radio" name="why" value="defaced">

              My passport has been defaced or damaged

              <input id="radio-HMPO" type="radio" name="why" value="HMPO">

             My passport is with HM Passport Office or at a foreign embassy

          <fieldset>

            <legend class="visuallyhidden">previous names</legend>

              <input id="radio-yes" type="radio" name="previousname" value="yes">

              My passport is with HM Passport Office

              <input id="radio-no" type="radio" name="previousname" value="no">

              My passport is with a foreign embassy for visa processing

              <input id="radio-other" type="radio" name="why" value="other">

             Another reason

                If other, tell us the reason

              <input class="form-control" type="text" id="other">

          </fieldset>

      </form>

If your passport is both lost and expired, select lost.

        next

{% endblock %}


text:
import unittest
import unittest.mock
import sys
from copy import deepcopy
from io import StringIO
from datetime import datetime, timedelta

import models.main
from zones.northshire_abbey import NorthshireAbbey, NorthshireValley, NorthshireVineyards
from constants import ZONE_MOVE_BLOCK_SPECIAL_KEY, GARRICK_PADFOOT_GUID

class NorthshireAbbeyTests(unittest.TestCase):
    def setUp(self):
        self.char_mock = unittest.mock.Mock(level=10)
        self.char_mock.has_loaded_script = lambda x: True
        self.char_mock.loaded_script = lambda x: None
        self.char_mock.has_completed_quest = lambda x: False
        self.char_mock.has_killed_monster = lambda x: False
        self.northshire_valley_monster_count = 5
        self.northshire_valley_npc_count = 2
        self.northshire_valley_quest_count = 2
        self.northshire_vineyards_monster_count = 7
        self.northshire_vineyards_npc_count = 0
        self.northshire_vineyards_quest_count = 1
        self.peculiar_hut_monster_count = 1
        self.peculiar_hut_npc_count = 0
        self.peculiar_hut_quest_count = 0

    def tearDown(self):
        """
        Due to the mutability of the static variables, we need to reset them
        on each tearDown. (Since we change them in the tests)
        """
        NorthshireAbbey.loaded_zones = {"Northshire Valley": None,
                                        "Northshire Vineyards": None,
                                        "A Peculiar Hut": None}

    def test_zone(self):
        zone = NorthshireAbbey(self.char_mock)
        # it should have loaded subzones
        self.assertTrue(zone.loaded_zones['Northshire Valley'], NorthshireValley)
        # these should not have been loaded because we have not gone in there
        self.assertIsNone(zone.loaded_zones['Northshire Vineyards'])
        self.assertIsNone(zone.loaded_zones['A Peculiar Hut'])
        # it should hold the monsters in the current subzone
        self.assertEqual(len(zone.cs_alive_monsters.keys()), self.northshire_valley_monster_count)
        self.assertEqual(len(zone.cs_alive_npcs.keys()), self.northshire_valley_npc_count)
        self.assertEqual(len(zone.cs_available_quests.keys()), self.northshire_valley_quest_count)
        self.assertEqual(zone.curr_subzone, 'Northshire Valley')

    def test_move_player_valid(self):
        """
        Move the player to a valid subzone giving valid values
        """

        zone = NorthshireAbbey(self.char_mock)
        self.assertIsNone(zone.loaded_zones['Northshire Vineyards'])
        start_subzone, go_to_subzone = 'Northshire Valley', 'Northshire Vineyards'
        result = zone.move_player(current_subzone=start_subzone, destination=go_to_subzone, character=self.char_mock)

        self.assertTrue(result)
        # Should have loaded the zone for the first time
        self.assertIsNotNone(zone.loaded_zones['Northshire Vineyards'])
        self.assertTrue(isinstance(zone.loaded_zones['Northshire Vineyards'], NorthshireVineyards))
        # should have loaded the npcs from the new subzone
        self.assertEqual(len(zone.cs_alive_monsters.keys()), self.northshire_vineyards_monster_count)
        self.assertEqual(len(zone.cs_alive_npcs.keys()), self.northshire_vineyards_npc_count)
        self.assertEqual(len(zone.cs_available_quests.keys()), self.northshire_vineyards_quest_count)

        self.assertEqual(zone.curr_subzone, 'Northshire Vineyards')

    def test_move_to_peculiar_hut_padfoot_alive(self):
        """
        Since Garry Padfoot is alive, we should not be allowed to move
        """
        std_output = StringIO()
        try:
            sys.stdout = std_output
            zone = NorthshireAbbey(self.char_mock)
            self.assertIsNone(zone.loaded_zones['Northshire Vineyards'])
            start_subzone, mid_zone, go_to_subzone = 'Northshire Valley', 'Northshire Vineyards', 'A Peculiar Hut'
            result = zone.move_player(current_subzone=start_subzone, destination=mid_zone,
                                      character=self.char_mock)
            self.assertTrue(result)
            result = zone.move_player(current_subzone=mid_zone, destination=go_to_subzone,
                                      character=self.char_mock)

            self.assertEqual(zone.curr_subzone, mid_zone)
            self.assertEqual(result, ZONE_MOVE_BLOCK_SPECIAL_KEY)
            self.assertTrue("Garrick Padfoot is blocking the way." in std_output.getvalue())
        finally:
            sys.stdout = sys.__stdout__

    def test_move_to_peculiar_hut_padfoot_dead(self):
        zone = NorthshireAbbey(self.char_mock)
        self.assertIsNone(zone.loaded_zones['Northshire Vineyards'])
        start_subzone, mid_zone, go_to_subzone = 'Northshire Valley', 'Northshire Vineyards', 'A Peculiar Hut'
        result = zone.move_player(current_subzone=start_subzone, destination=mid_zone,
                                  character=self.char_mock)
        self.assertTrue(result)
        del zone.cs_alive_monsters[GARRICK_PADFOOT_GUID]
        zone.cs_monsters_guid_name_set.remove((GARRICK_PADFOOT_GUID, 'Garrick Padfoot'))
        result = zone.move_player(current_subzone=mid_zone, destination=go_to_subzone,
                                  character=self.char_mock)

        # Move should have been successful!
        self.assertTrue(result)
        self.assertEqual(len(zone.cs_alive_monsters.keys()), self.peculiar_hut_monster_count)
        self.assertEqual(len(zone.cs_alive_npcs.keys()), self.peculiar_hut_npc_count)
        self.assertEqual(len(zone.cs_available_quests.keys()), self.peculiar_hut_quest_count)

    def test_kill_monsters_complete_quests_move_player_move_back(self):
        """
        Kill the monsters and complete the quests in a subzone, move to another subzone and come back
        Assert that the monsters/quests have not been loaded again and have save their previous state
        """
        zone = NorthshireAbbey(self.char_mock)
        start_subzone, go_to_subzone = 'Northshire Valley', 'Northshire Vineyards'
        # assert that the values are as expected
        self.assertEqual(zone.curr_subzone, 'Northshire Valley')
        self.assertEqual(len(zone.cs_alive_monsters.keys()), self.northshire_valley_monster_count)
        self.assertEqual(len(zone.cs_available_quests.keys()), self.northshire_valley_quest_count)
        # simulate killing all the monsters and completing the quests
        zone.cs_alive_monsters = {}
        zone.cs_monsters_guid_name_set = set()
        zone.cs_available_quests = {}

        zone.move_player(current_subzone=start_subzone, destination=go_to_subzone, character=self.char_mock)
        zone.move_player(current_subzone=go_to_subzone, destination=start_subzone, character=self.char_mock)
        self.assertEqual(len(zone.cs_alive_monsters.keys()), 0)
        self.assertEqual(len(zone.cs_available_quests.keys()), 0)

    def test_invalid_move(self):
        """
        Moving from Northshire Valley to A Peculiar Hut is not possible.
        You first need to move to Northshire Vineyards and then you can access A Peculiar Hut
        """
        zone = NorthshireAbbey(self.char_mock)
        start_subzone, go_to_subzone = 'Northshire Valley', 'A Peculiar Hut'
        result = zone.move_player(current_subzone=start_subzone, destination=go_to_subzone, character=self.char_mock)

        # Assert that we have not moved
        self.assertFalse(result)
        self.assertEqual(zone.curr_subzone, start_subzone)
        self.assertEqual(len(zone.cs_alive_monsters.keys()), self.northshire_valley_monster_count)
        self.assertEqual(len(zone.cs_alive_npcs.keys()), self.northshire_valley_npc_count)
        self.assertEqual(len(zone.cs_available_quests.keys()), self.northshire_valley_quest_count)

    def test_load_zone(self):
        """
        the _load_zone function creates a Zone object and adds it to our loaded_zones dictionary
        """
        zone = NorthshireAbbey(self.char_mock)
        zones_to_load = ['Northshire Vineyards', 'A Peculiar Hut']
        for z_to_load in zones_to_load:
            self.assertIsNone(zone.loaded_zones[z_to_load])
            zone._load_zone(z_to_load, self.char_mock)
            self.assertIsNotNone(zone.loaded_zones[z_to_load])

    def test_load_zone_invalid_zone(self):
        """
        Loading an invalid zone should not go into any of the if blocks and not do anything.
        """
        zone = NorthshireAbbey(self.char_mock)
        original_loaded_zones = deepcopy(zone.loaded_zones)

        zone._load_zone('Aa', self.char_mock)

        for l_zone, obj in original_loaded_zones.items():
            self.assertTrue(isinstance(zone.loaded_zones[l_zone], type(obj)))

    def test_engage_zone_entered_script(self):
        """
        Given the character's subzone and the fact that he has not loaded the script before,
        the Peculiar Hut script should be engaged
        """
        # Some pre-script mocks
        import combat
        combat.engage_combat = lambda *args: True
        self.char_mock.current_subzone = 'A Peculiar Hut'
        self.char_mock.has_loaded_script = lambda x: False

        # move to the desired zone
        zone = NorthshireAbbey(self.char_mock)
        start_subzone, mid_zone, go_to_subzone = 'Northshire Valley', 'Northshire Vineyards', 'A Peculiar Hut'
        zone.move_player(current_subzone=start_subzone, destination=mid_zone,
                                  character=self.char_mock)
        del zone.cs_alive_monsters[GARRICK_PADFOOT_GUID]
        zone.cs_monsters_guid_name_set.remove((GARRICK_PADFOOT_GUID, 'Garrick Padfoot'))
        zone.move_player(current_subzone=mid_zone, destination=go_to_subzone,
                                  character=self.char_mock)

        # start the test
        start = datetime.now()
        zone.engage_zone_entered_script(self.char_mock)
        end = datetime.now()

        # 5 seconds should have passed at least while the script played out
        duration: timedelta = end - start
        self.assertGreater(duration.seconds, 5)

if __name__ == '__main__':
    unittest.main()