text:
package org.apache.ignite.internal.jdbc;

import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.List;

/**
 * JDBC result set metadata implementation.
 *
 * @deprecated Using Ignite client node based JDBC driver is preferable.
 * See documentation of {@link org.apache.ignite.IgniteJdbcDriver} for details.
 */
@Deprecated
public class JdbcResultSetMetadata implements ResultSetMetaData {
    /** Column width. */
    private static final int COL_WIDTH = 30;

    /** Table names. */
    private final List<String> tbls;

    /** Column names. */
    private final List<String> cols;

    /** Class names. */
    private final List<String> types;

    /**
     * @param tbls Table names.
     * @param cols Column names.
     * @param types Types.
     */
    JdbcResultSetMetadata(List<String> tbls, List<String> cols, List<String> types) {
        assert cols != null;
        assert types != null;

        this.tbls = tbls;
        this.cols = cols;
        this.types = types;
    }

    /** {@inheritDoc} */
    @Override public int getColumnCount() throws SQLException {
        return cols.size();
    }

    /** {@inheritDoc} */
    @Override public boolean isAutoIncrement(int col) throws SQLException {
        return false;
    }

    /** {@inheritDoc} */
    @Override public boolean isCaseSensitive(int col) throws SQLException {
        return false;
    }

    /** {@inheritDoc} */
    @Override public boolean isSearchable(int col) throws SQLException {
        return false;
    }

    /** {@inheritDoc} */
    @Override public boolean isCurrency(int col) throws SQLException {
        return false;
    }

    /** {@inheritDoc} */
    @Override public int isNullable(int col) throws SQLException {
        return columnNullable;
    }

    /** {@inheritDoc} */
    @Override public boolean isSigned(int col) throws SQLException {
        return true;
    }

    /** {@inheritDoc} */
    @Override public int getColumnDisplaySize(int col) throws SQLException {
        return COL_WIDTH;
    }

    /** {@inheritDoc} */
    @Override public String getColumnLabel(int col) throws SQLException {
        return cols.get(col - 1);
    }

    /** {@inheritDoc} */
    @Override public String getColumnName(int col) throws SQLException {
        return cols.get(col - 1);
    }

    /** {@inheritDoc} */
    @Override public String getSchemaName(int col) throws SQLException {
        return "";
    }

    /** {@inheritDoc} */
    @Override public int getPrecision(int col) throws SQLException {
        return 0;
    }

    /** {@inheritDoc} */
    @Override public int getScale(int col) throws SQLException {
        return 0;
    }

    /** {@inheritDoc} */
    @Override public String getTableName(int col) throws SQLException {
        return tbls != null ? tbls.get(col - 1) : "";
    }

    /** {@inheritDoc} */
    @Override public String getCatalogName(int col) throws SQLException {
        return "";
    }

    /** {@inheritDoc} */
    @Override public int getColumnType(int col) throws SQLException {
        return JdbcUtils.type(types.get(col - 1));
    }

    /** {@inheritDoc} */
    @Override public String getColumnTypeName(int col) throws SQLException {
        return JdbcUtils.typeName(types.get(col - 1));
    }

    /** {@inheritDoc} */
    @Override public boolean isReadOnly(int col) throws SQLException {
        return true;
    }

    /** {@inheritDoc} */
    @Override public boolean isWritable(int col) throws SQLException {
        return false;
    }

    /** {@inheritDoc} */
    @Override public boolean isDefinitelyWritable(int col) throws SQLException {
        return false;
    }

    /** {@inheritDoc} */
    @Override public String getColumnClassName(int col) throws SQLException {
        return types.get(col - 1);
    }

    /** {@inheritDoc} */
    @Override public <T> T unwrap(Class<T> iface) throws SQLException {
        if (!isWrapperFor(iface))
            throw new SQLException("Result set meta data is not a wrapper for " + iface.getName());

        return (T)this;
    }

    /** {@inheritDoc} */
    @Override public boolean isWrapperFor(Class<?> iface) throws SQLException {
        return iface == ResultSetMetaData.class;
    }
}


text:
package org.keycloak.dom.saml.v1.protocol;

import org.keycloak.dom.saml.v1.assertion.SAML11AttributeDesignatorType;

import java.net.URI;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * <complexType name="AttributeQueryType"> <complexContent> <extension base="samlp:SubjectQueryAbstractType">
 * <sequence>
 * <element ref="saml:AttributeDesignator" minOccurs="0" maxOccurs="unbounded"/> </sequence>
 *
 * <attribute name="Resource" type="anyURI" use="optional"/> </extension> </complexContent> </complexType>
 *
 * @author Anil.Saldhana@redhat.com
 * @since Jun 22, 2011
 */
public class SAML11AttributeQueryType extends SAML11SubjectQueryAbstractType {

    private static final long serialVersionUID = 1L;

    protected List<SAML11AttributeDesignatorType> attributeDesignator = new ArrayList<SAML11AttributeDesignatorType>();

    protected URI resource;

    public URI getResource() {
        return resource;
    }

    public void setResource(URI resource) {
        this.resource = resource;
    }

    public void add(SAML11AttributeDesignatorType sadt) {
        this.attributeDesignator.add(sadt);
    }

    public boolean remove(SAML11AttributeDesignatorType sadt) {
        return this.attributeDesignator.remove(sadt);
    }

    public List<SAML11AttributeDesignatorType> get() {
        return Collections.unmodifiableList(attributeDesignator);
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.arquillian.hol.lab05.ui.web;

import java.math.BigDecimal;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;

/**
 * Page object encapsulating "beer details" page.
 */
public class BeerDetailsPage {

    @FindBy(id = "brewery")
    private WebElement breweryElement;

    @FindBy(id = "name")
    private WebElement nameElement;

    @FindBy(className = "voltage")
    private WebElement alcoholElement;

    @FindBy(id = "price")
    private WebElement priceElement;

    public BeerDetailsPage(WebDriver driver) {
        PageFactory.initElements(driver, this);
    }

    public Beer extract() {
        final Beer beer = new Beer(nameElement.getText());
        beer.setBrewery(breweryElement.getText().trim());
        beer.setAlcohol(extractAlcohol());
        beer.setPrice(extractPrice());
        return beer;
    }

    // --- Private methods

    private BigDecimal extractPrice() {
        String priceText = priceElement.getText();
        priceText = priceText.replaceAll("Price: ", "")
                             .replace('$', ' ')
                             .trim();
        return BigDecimal.valueOf(Double.valueOf(priceText));
    }

    private BigDecimal extractAlcohol() {
        String alcoholText = alcoholElement.getText().trim();
        alcoholText = alcoholText.replaceAll("%", "");
        return BigDecimal.valueOf(Double.valueOf(alcoholText));
    }

}


text:
package URI::telnet;

use strict;
use warnings;

our $VERSION = "1.69";

use parent 'URI::_login';

sub default_port { 23 }

1;


text:
"""Manages Reserved Capacity."""
# :license: MIT, see LICENSE for more details.

import importlib
import os

import click

CONTEXT = {'help_option_names': ['-h', '--help'],
           'max_content_width': 999}

class CapacityCommands(click.MultiCommand):
    """Loads module for capacity related commands.

    Will automatically replace _ with - where appropriate.
    I'm not sure if this is better or worse than using a long list of manual routes, so I'm trying it here.
    CLI/virt/capacity/create_guest.py -> slcli vs capacity create-guest
    """

    def __init__(self, **attrs):
        click.MultiCommand.__init__(self, **attrs)
        self.path = os.path.dirname(__file__)

    def list_commands(self, ctx):
        """List all sub-commands."""
        commands = []
        for filename in os.listdir(self.path):
            if filename == '__init__.py':
                continue
            if filename.endswith('.py'):
                commands.append(filename[:-3].replace("_", "-"))
        commands.sort()
        return commands

    def get_command(self, ctx, cmd_name):
        """Get command for click."""
        path = "%s.%s" % (__name__, cmd_name)
        path = path.replace("-", "_")
        try:
            module = importlib.import_module(path)
            return getattr(module, 'cli')
        except ModuleNotFoundError as ex:
            print(ex.name)
            return None

# Required to get the sub-sub-sub command to work.
@click.group(cls=CapacityCommands, context_settings=CONTEXT)
def cli():
    """Base command for all capacity related concerns"""


text:
package org.apache.ibatis.ibator.config.xml;

import java.util.List;

import org.apache.ibatis.ibator.internal.util.messages.Messages;
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

/**
 * @author Jeff Butler
 */
public class ParserErrorHandler implements ErrorHandler {
	private List<String> warnings;

	private List<String> errors;

	/**
	 *
	 */
	public ParserErrorHandler(List<String> warnings, List<String> errors) {
		super();
		this.warnings = warnings;
		this.errors = errors;
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see org.xml.sax.ErrorHandler#warning(org.xml.sax.SAXParseException)
	 */
	public void warning(SAXParseException exception) throws SAXException {
		warnings.add(Messages.getString("Warning.7", //$NON-NLS-1$
		        Integer.toString(exception.getLineNumber()),
		        exception.getMessage()));
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see org.xml.sax.ErrorHandler#error(org.xml.sax.SAXParseException)
	 */
	public void error(SAXParseException exception) throws SAXException {
		errors.add(Messages.getString("RuntimeError.4", //$NON-NLS-1$
		        Integer.toString(exception.getLineNumber()),
		        exception.getMessage()));
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see org.xml.sax.ErrorHandler#fatalError(org.xml.sax.SAXParseException)
	 */
	public void fatalError(SAXParseException exception) throws SAXException {
		errors.add(Messages.getString("RuntimeError.4", //$NON-NLS-1$
		        Integer.toString(exception.getLineNumber()),
		        exception.getMessage()));
	}
}


text:
module Gitlab
  module SidekiqMiddleware
    class CorrelationInjector
      def call(worker_class, job, queue, redis_pool)
        job[Gitlab::CorrelationId::LOG_KEY] ||=
          Gitlab::CorrelationId.current_or_new_id

        yield
      end
    end
  end
end


text:
""" Defines the basic Container class """
from contextlib import contextmanager

from enable.base import empty_rectangle, intersect_bounds
from enable.events import MouseEvent
from kiva import affine
from traits.api import Instance, List, Property

from .component import Component

class Container(Component):
    """ A Container that holds components and other containers.

    This represents a general container class of a composite structure [GoF]_.

    .. [GoF] Design Patterns: Elements of Reusable Object Oriented Software,
             Gamma et al., Addison-Wesley, 1996.
    """

    # The list of components within this frame
    components = Property(List(Component))

    # Shadow trait for self.components
    _components = List(Component)

    # Set of components that last handled a mouse event. This allows us to
    # generate mouse_enter and mouse_leave events of our own.
    _prev_event_handlers = Instance(set, ())

    # -----------------------------------------------------------------------
    # Public methods
    # -----------------------------------------------------------------------

    def add(self, *components):
        """ Adds components to this container """
        for component in components:
            if component.container is not None:
                component.container.remove(component)
            component.container = self
        self._components.extend(components)

    def remove(self, *components):
        for component in components:
            if component is not None:
                assert component.container == self
                self._components.remove(component)
                component.container == None

    def components_at(self, x, y):
        """ Returns components underneath the given point.

        Input point is specified in parent container's coordinate space.
        """
        result = []
        if self.is_in(x, y):
            for component in self._components[::-1]:
                if component.is_in(x - self.x, y - self.y):
                    result.append(component)
        return result

    def cleanup(self, window):
        """ Perform any necessary cleanup. """
        if self._components:
            for component in self._components:
                component.cleanup(window)

    def dispatch(self, event, suffix):
        """ Dispatches mouse event to child components until it is handled.

        Parameters
        ----------
        event : BaseEvent
            A mouse or key event.
        suffix : string
            The name of the mouse event as a suffix to the event state name,
            e.g. "left_down" or "window_enter".
        """
        if event.handled:
            return

        # Get components under event and then transform to local coordinates.
        components = self.components_at(event.x, event.y)
        with self._local_event_transform(event):
            component_set = set(components)
            components_left = self._prev_event_handlers - component_set
            components_entered = component_set - self._prev_event_handlers

            dispatch_mouse_event = self._dispatch_if_mouse_event
            dispatch_mouse_event(components_left, event, 'mouse_leave')
            if suffix != 'mouse_leave':
                dispatch_mouse_event(components_entered, event, 'mouse_enter')

            self._prev_event_handlers = set()
            for component in components:
                component.dispatch(event, suffix)
                # Only add handler if it actually received the event.
                self._prev_event_handlers.add(component)
                if event.handled:
                    break

        if not event.handled:
            super(Container, self).dispatch(event, suffix)

    # -------------------------------------------------------------------------
    #  Protected interface
    # -------------------------------------------------------------------------

    def _main_layers(self, view_rect):
        return self._get_visible_components(view_rect)

    # -----------------------------------------------------------------------
    # Property setters & getters
    # -----------------------------------------------------------------------

    def _get_components(self):
        return self._components

    def _get_layout_needed(self):
        # Override the parent implementation child components.
        return (self._layout_needed
                or any(c.layout_needed for c in self.components))

    # -----------------------------------------------------------------------
    # Event handlers
    # -----------------------------------------------------------------------

    def _component_origin_changed(self):
        """Called by contained objects when their origins change"""
        self._origin_changed()

    def _component_size_changed(self):
        """Called by contained objects when their size change"""
        self._size_changed()

    def _size_changed(self):
        super(Container, self)._size_changed()
        self._layout_needed = True

    def __components_items_changed(self, event):
        self._layout_needed = True

    # -------------------------------------------------------------------------
    # Private interface
    # -------------------------------------------------------------------------

    def _get_visible_components(self, bounds):
        """ Returns a list of this plot's children that are in the bounds. """
        if bounds is None:
            return [c for c in self.components if c.visible]

        return [c for c in self.components
                if intersect_bounds(c.rect, bounds) != empty_rectangle]

    def _get_event_transform(self, event=None):
        return affine.affine_from_translation(-self.x, -self.y)

    def _dispatch_if_mouse_event(self, components, event, suffix):
        if not isinstance(event, MouseEvent):
            return
        for component in components:
            component.dispatch(event, suffix)
            event.handled = False

    @contextmanager
    def _local_event_transform(self, event):
        """ Translate event location to be relative to this container. """
        try:
            transform = self._get_event_transform(event)
            event.push_transform(transform, caller=self)
            yield
        finally:
            event.pop(caller=self)


text:
package com.dexterind.grovepi.sensors.base;

import java.io.IOException;

import com.dexterind.grovepi.*;
import com.dexterind.grovepi.utils.*;

public class DigitalSensor extends Sensor {
  protected int pin = 0;
  protected Debug debug;

  public DigitalSensor(int pin) throws IOException, InterruptedException {
	super();
	this.pin = pin;
  }

  public byte[] readBytes() throws IOException {
	this.board.writeI2c(Commands.DREAD, this.pin, Commands.UNUSED, Commands.UNUSED);
	return this.board.readI2c(1);
  }

  public boolean write(int value) throws IOException {
	this.board.writeI2c(Commands.DWRITE, this.pin, value, Commands.UNUSED);
	return true;
  }
}


text:
import React, { PropTypes } from 'react';
import Radium, { Style } from 'radium';
import styles from '../styles/square';

@Radium
class Square extends React.Component {
    static propTypes = {
        black: PropTypes.bool
    };

    constructor(props) {
        super(props);
    }

    render() {
        // grab props out of this.props
        const { black } = this.props;
        const fill = black ? 'black' : 'white';

        return (
            <div style={[
                styles.base,
                styles[fill]
            ]}>
            { this.props.children }
            </div>
        );
    }
}

export default Square;


text:
using std::make_pair;
using std::vector;

namespace chromeos_update_engine {

class TopologicalSortTest : public ::testing::Test {};

namespace {
// Returns true if the value is found in vect. If found, the index is stored
// in out_index if out_index is not null.
template<typename T>
bool IndexOf(const vector<T>& vect,
             const T& value,
             typename vector<T>::size_type* out_index) {
  for (typename vector<T>::size_type i = 0; i < vect.size(); i++) {
    if (vect[i] == value) {
      if (out_index) {
        *out_index = i;
      }
      return true;
    }
  }
  return false;
}
}  // namespace {}

TEST(TopologicalSortTest, SimpleTest) {
  int counter = 0;
  const Vertex::Index n_a = counter++;
  const Vertex::Index n_b = counter++;
  const Vertex::Index n_c = counter++;
  const Vertex::Index n_d = counter++;
  const Vertex::Index n_e = counter++;
  const Vertex::Index n_f = counter++;
  const Vertex::Index n_g = counter++;
  const Vertex::Index n_h = counter++;
  const Vertex::Index n_i = counter++;
  const Vertex::Index n_j = counter++;
  const Graph::size_type kNodeCount = counter++;

  Graph graph(kNodeCount);

  graph[n_i].out_edges.insert(make_pair(n_j, EdgeProperties()));
  graph[n_i].out_edges.insert(make_pair(n_c, EdgeProperties()));
  graph[n_i].out_edges.insert(make_pair(n_e, EdgeProperties()));
  graph[n_i].out_edges.insert(make_pair(n_h, EdgeProperties()));
  graph[n_c].out_edges.insert(make_pair(n_b, EdgeProperties()));
  graph[n_b].out_edges.insert(make_pair(n_a, EdgeProperties()));
  graph[n_e].out_edges.insert(make_pair(n_d, EdgeProperties()));
  graph[n_e].out_edges.insert(make_pair(n_g, EdgeProperties()));
  graph[n_g].out_edges.insert(make_pair(n_d, EdgeProperties()));
  graph[n_g].out_edges.insert(make_pair(n_f, EdgeProperties()));
  graph[n_d].out_edges.insert(make_pair(n_a, EdgeProperties()));

  vector<Vertex::Index> sorted;
  TopologicalSort(graph, &sorted);

  for (Vertex::Index i = 0; i < graph.size(); i++) {
    vector<Vertex::Index>::size_type src_index = 0;
    EXPECT_TRUE(IndexOf(sorted, i, &src_index));
    for (Vertex::EdgeMap::const_iterator it = graph[i].out_edges.begin();
         it != graph[i].out_edges.end(); ++it) {
      vector<Vertex::Index>::size_type dst_index = 0;
      EXPECT_TRUE(IndexOf(sorted, it->first, &dst_index));
      EXPECT_LT(dst_index, src_index);
    }
  }
}

}  // namespace chromeos_update_engine


text:
<!DOCTYPE html>

	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
	<title>Buttons - UI Elements - PixelAdmin</title>
	<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">

	<link href="http://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,400,600,700,300&subset=latin" rel="stylesheet" type="text/css">

	<link href="assets/stylesheets/bootstrap.min.css" rel="stylesheet" type="text/css">
	<link href="assets/stylesheets/pixel-admin.min.css" rel="stylesheet" type="text/css">
	<link href="assets/stylesheets/widgets.min.css" rel="stylesheet" type="text/css">
	<link href="assets/stylesheets/rtl.min.css" rel="stylesheet" type="text/css">
	<link href="assets/stylesheets/themes.min.css" rel="stylesheet" type="text/css">

		<button type="button" id="main-menu-toggle">HIDE MENU</button>

					PixelAdmin

				<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#main-navbar-collapse"></button>

							Home

							Dropdown

First item

Second item

Third item

									5

									Notifications

SYSTEM

Error 500: Syntax error in index.php at line 461.

12h ago

STORE

You have 9 new orders.

12h ago

CRON DAEMON

Job "Clean DB" has been completed.

12h ago

SYSTEM

Server up.

12h ago

SYSTEM

Warning: Processor load 92%.

12h ago

									MORE NOTIFICATIONS

									10

									Income messages

											Lorem ipsum dolor sit amet, consectetur adipisicing elit.

												from Robert Jang
												  ·
												2h ago

											Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

												from Michelle Bortz
												  ·
												2h ago

											Lorem ipsum dolor sit amet.

												from Timothy Owens
												  ·
												2h ago

											Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

												from Denise Steiner
												  ·
												2h ago

											Lorem ipsum dolor sit amet.

												from Robert Jang
												  ·
												2h ago

											Lorem ipsum dolor sit amet, consectetur adipisicing elit.

												from Robert Jang
												  ·
												2h ago

											Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

												from Michelle Bortz
												  ·
												2h ago

											Lorem ipsum dolor sit amet.

												from Timothy Owens
												  ·
												2h ago

											Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

												from Denise Steiner
												  ·
												2h ago

											Lorem ipsum dolor sit amet.

												from Robert Jang
												  ·
												2h ago

									MORE MESSAGES

								<form class="navbar-form pull-left">
									<input type="text" class="form-control" placeholder="Search">
								</form>

									John Doe

NewProfile

NewAccount

  Settings

  Log Out

Welcome, John

					×

					Dashboard

					LayoutsUpdated

							Grid

							Main menuUpdated

					Stat panels

					Widgets

					UI elements

							Buttons

							Typography

							Tabs & Accordions

							Modals

							Alerts & Tooltips

							Components

							Panels

							jQuery UI

							Icons

							Utility classes

					Form components

							Layouts

							General

							Advanced

							Pickers

							Validation

							Editors

					Tables

					Charts

					Pages16

							Search results

							Plans & pricing

							FAQ

							Profile

							Timeline

							Sign In

							Sign Up

							Sign In Alt

							Sign Up Alt

							Invoice

							Error 404

							Error 500

							Messages

									Inbox

									Show message

									New message

							Blank page

					Complete UI

					Color Builder

					Menu levels6

							Menu level 1.11221

							Menu level 1.2

							Menu level 1.35

									Menu level 2.1

									Menu level 2.2

											Menu level 3.1

													Menu level 4.1

											Menu level 3.2

									Menu level 2.2

				Create Invoice

UI Elements / Buttons

						Default buttons

						<button class="btn">Default</button>
						<button class="btn btn-primary">Primary</button>
						<button class="btn btn-info">Info</button>
						<button class="btn btn-success">Success</button>
						<button class="btn btn-warning">Warning</button>
						<button class="btn btn-danger">Danger</button>

						Rounded buttons

						<button class="btn btn-rounded">Default</button>
						<button class="btn btn-primary btn-rounded">Primary</button>
						<button class="btn btn-info btn-rounded">Info</button>
						<button class="btn btn-success btn-rounded">Success</button>
						<button class="btn btn-warning btn-rounded">Warning</button>
						<button class="btn btn-danger btn-rounded">Danger</button>

						Flat buttons

						<button class="btn btn-flat">Default</button>
						<button class="btn btn-primary btn-flat">Primary</button>
						<button class="btn btn-info btn-flat">Info</button>
						<button class="btn btn-success btn-flat">Success</button>
						<button class="btn btn-warning btn-flat">Warning</button>
						<button class="btn btn-danger btn-flat">Danger</button>

						Buttons with labels

						<button class="btn btn-lg btn-labeled">Large</button>
						<button class="btn btn-labeled btn-primary">Default</button>
						<button class="btn btn-sm btn-labeled btn-success">Small</button>
						<button class="btn btn-xs btn-labeled btn-danger">Extra small</button>

						<button class="btn btn-outline btn-lg btn-labeled">Large</button>
						<button class="btn btn-outline btn-labeled btn-primary">Default</button>
						<button class="btn btn-outline btn-sm btn-labeled btn-success">Small</button>
						<button class="btn btn-outline btn-xs btn-labeled btn-danger">Extra small</button>

						<button class="btn btn-flat btn-lg btn-labeled">Large</button>
						<button class="btn btn-flat btn-labeled btn-primary">Default</button>
						<button class="btn btn-flat btn-sm btn-labeled btn-success">Small</button>
						<button class="btn btn-flat btn-xs btn-labeled btn-danger">Extra small</button>

						<button class="btn btn-rounded btn-lg btn-labeled">Large</button>
						<button class="btn btn-rounded btn-labeled btn-primary">Default</button>
						<button class="btn btn-rounded btn-sm btn-labeled btn-success">Small</button>
						<button class="btn btn-rounded btn-xs btn-labeled btn-danger">Extra small</button>

						<button class="btn btn-labeled btn-block">Text labelBlock button</button>

						Button dropdowns

							<button type="button" class="btn btn-lg dropdown-toggle" data-toggle="dropdown">Large </button>

Action

Another action

Something else here

Separated link

							<button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown">Default </button>

Action

Another action

Something else here

Separated link

							<button type="button" class="btn btn-sm btn-danger dropdown-toggle" data-toggle="dropdown">Small </button>

Action

Another action

Something else here

Separated link

							<button type="button" class="btn btn-xs btn-success dropdown-toggle" data-toggle="dropdown">Extra small </button>

Action

Another action

Something else here

Separated link

						Split button dropdowns

							<button type="button" class="btn">Large</button>
							<button type="button" class="btn dropdown-toggle" data-toggle="dropdown"></button>

Action

Another action

Something else here

Separated linka>

							<button type="button" class="btn btn-primary">Default</button>
							<button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown"></button>

Action

Another action

Something else here

Separated link

							<button type="button" class="btn btn-danger">Small</button>
							<button type="button" class="btn btn-danger dropdown-toggle" data-toggle="dropdown"></button>

Action

Another action

Something else here

Separated link

							<button type="button" class="btn btn-success">Extra small</button>
							<button type="button" class="btn btn-success dropdown-toggle" data-toggle="dropdown"></button>

Action

Another action

Something else here

Separated link

						Bootstrap buttons

STATE BUTTONS

						<button type="button" id="loading-example-btn" data-loading-text="Loading..." class="btn btn-primary">Loading state</button>

SINGLE TOGGLE BUTTONS

						<button type="button" class="btn btn-danger" data-toggle="button">Single toggle</button>

CHECKBOX BUTTONS

								<input type="checkbox"> Option 1

								<input type="checkbox"> Option 2

								<input type="checkbox"> Option 3

RADIO BUTTONS

								<input type="radio" name="options" id="option1"> Option 1

								<input type="radio" name="options" id="option2"> Option 2

								<input type="radio" name="options" id="option3"> Option 3

						Button sizes

						<button class="btn btn-lg">Large</button>
						<button class="btn btn-primary">Default</button>
						<button class="btn btn-info btn-sm">Small</button>
						<button class="btn btn-success btn-xs">Extra small</button>

						Outline buttons

							DARK
							<input type="checkbox" data-class="switcher-sm" id="outline-switcher">

						<button class="btn btn-lg btn-outline">Large</button>
						<button class="btn btn-primary btn-outline">Default</button>
						<button class="btn btn-info btn-sm btn-outline">Small</button>
						<button class="btn btn-success btn-xs btn-outline">Extra small</button>

						<button class="btn btn-lg btn-outline btn-rounded">Large</button>
						<button class="btn btn-primary btn-outline btn-rounded">Default</button>
						<button class="btn btn-info btn-sm btn-outline btn-rounded">Small</button>
						<button class="btn btn-success btn-xs btn-outline btn-rounded">Extra small</button>

						<button class="btn btn-lg btn-outline btn-flat">Large</button>
						<button class="btn btn-primary btn-outline btn-flat">Default</button>
						<button class="btn btn-info btn-sm btn-outline btn-flat">Small</button>
						<button class="btn btn-success btn-xs btn-outline btn-flat">Extra small</button>

						<button class="btn btn-lg btn-outline btn-flat btn-rounded">Large</button>
						<button class="btn btn-primary btn-outline btn-flat btn-rounded">Default</button>
						<button class="btn btn-info btn-sm btn-outline btn-flat btn-rounded">Small</button>
						<button class="btn btn-success btn-xs btn-outline btn-flat btn-rounded">Extra small</button>

						Disabled buttons

						<button class="btn disabled">Default</button>
						<button class="btn btn-primary disabled">Primary</button>
						<button class="btn btn-info disabled">Info</button>
						<button class="btn btn-success disabled">Success</button>
						<button class="btn btn-warning disabled">Warning</button>
						<button class="btn btn-danger disabled">Danger</button>

						<button class="btn btn-rounded disabled">Default</button>
						<button class="btn btn-primary btn-rounded disabled">Primary</button>
						<button class="btn btn-info btn-rounded disabled">Info</button>
						<button class="btn btn-success btn-rounded disabled">Success</button>
						<button class="btn btn-warning btn-rounded disabled">Warning</button>
						<button class="btn btn-danger btn-rounded disabled">Danger</button>

						<button class="btn btn-outline disabled">Default</button>
						<button class="btn btn-primary btn-outline disabled">Primary</button>
						<button class="btn btn-info btn-outline disabled">Info</button>
						<button class="btn btn-success btn-outline disabled">Success</button>
						<button class="btn btn-warning btn-outline disabled">Warning</button>
						<button class="btn btn-danger btn-outline disabled">Danger</button>

						<button class="btn btn-outline btn-rounded disabled">Default</button>
						<button class="btn btn-primary btn-outline btn-rounded disabled">Primary</button>
						<button class="btn btn-info btn-outline btn-rounded disabled">Info</button>
						<button class="btn btn-success btn-outline btn-rounded disabled">Success</button>
						<button class="btn btn-warning btn-outline btn-rounded disabled">Warning</button>
						<button class="btn btn-danger btn-outline btn-rounded disabled">Danger</button>

						<button class="btn btn-flat disabled">Default</button>
						<button class="btn btn-primary btn-flat disabled">Primary</button>
						<button class="btn btn-info btn-flat disabled">Info</button>
						<button class="btn btn-success btn-flat disabled">Success</button>
						<button class="btn btn-warning btn-flat disabled">Warning</button>
						<button class="btn btn-danger btn-flat disabled">Danger</button>

						<button class="btn btn-flat btn-rounded disabled">Default</button>
						<button class="btn btn-primary btn-flat btn-rounded disabled">Primary</button>
						<button class="btn btn-info btn-flat btn-rounded disabled">Info</button>
						<button class="btn btn-success btn-flat btn-rounded disabled">Success</button>
						<button class="btn btn-warning btn-flat btn-rounded disabled">Warning</button>
						<button class="btn btn-danger btn-flat btn-rounded disabled">Danger</button>

						<button class="btn btn-flat btn-outline disabled">Default</button>
						<button class="btn btn-primary btn-flat btn-outline disabled">Primary</button>
						<button class="btn btn-info btn-flat btn-outline disabled">Info</button>
						<button class="btn btn-success btn-flat btn-outline disabled">Success</button>
						<button class="btn btn-warning btn-flat btn-outline disabled">Warning</button>
						<button class="btn btn-danger btn-flat btn-outline disabled">Danger</button>

						<button class="btn btn-flat btn-outline btn-rounded disabled">Default</button>
						<button class="btn btn-primary btn-flat btn-outline btn-rounded disabled">Primary</button>
						<button class="btn btn-info btn-flat btn-outline btn-rounded disabled">Info</button>
						<button class="btn btn-success btn-flat btn-outline btn-rounded disabled">Success</button>
						<button class="btn btn-warning btn-flat btn-outline btn-rounded disabled">Warning</button>
						<button class="btn btn-danger btn-flat btn-outline btn-rounded disabled">Danger</button>

						Button groups

							<button type="button" class="btn">Left</button>
							<button type="button" class="btn">Middle</button>
							<button type="button" class="btn">Right</button>

								<button type="button" class="btn dropdown-toggle" data-toggle="dropdown">Dropdown </button>

Dropdown link

Dropdown link

								<button type="button" class="btn btn-outline">Left</button>
								<button type="button" class="btn btn-outline">Middle</button>
								<button type="button" class="btn btn-outline">Right</button>

									<button type="button" class="btn btn-outline dropdown-toggle" data-toggle="dropdown">Dropdown </button>

Dropdown link

Dropdown link

							<button type="button" class="btn btn-primary">Left</button>
							<button type="button" class="btn btn-primary">Middle</button>
							<button type="button" class="btn btn-primary">Right</button>

								<button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown">Dropdown </button>

Dropdown link

Dropdown link

							<button type="button" class="btn btn-success">Left</button>
							<button type="button" class="btn btn-success">Middle</button>
							<button type="button" class="btn btn-success">Right</button>

								<button type="button" class="btn btn-success dropdown-toggle" data-toggle="dropdown">Dropdown </button>

Dropdown link

Dropdown link

							<button type="button" class="btn btn-info">Left</button>
							<button type="button" class="btn btn-info">Middle</button>
							<button type="button" class="btn btn-info">Right</button>

								<button type="button" class="btn btn-info dropdown-toggle" data-toggle="dropdown">Dropdown </button>

Dropdown link

Dropdown link

							Left
							Middle
							Right

								<button type="button" class="btn">1</button>
								<button type="button" class="btn">2</button>
								<button type="button" class="btn">3</button>
								<button type="button" class="btn">4</button>

								<button type="button" class="btn">5</button>
								<button type="button" class="btn">6</button>
								<button type="button" class="btn">7</button>

								<button type="button" class="btn">8</button>


text:
#ifndef NOMINMAX
#define NOMINMAX
#endif

#include "NetworkClient.h"

#include <sys/stat.h>
#include <fcntl.h>
#include <memory.h>
#include <cstdio>
#include <algorithm>

#include "Core/Utils/CoreUtils.h"
#include "Core/Utils/StringUtils.h"
#include "Core/Logging.h"
#include "CurlShare.h"

#ifdef USE_OPENSSL
#include <openssl/ssl.h>
#include <openssl/err.h>
#include <openssl/crypto.h>
#include <openssl/evp.h>
#include <openssl/conf.h>
#include <openssl/engine.h>
#endif

/*#ifdef _MSC_VER
    #if defined(USE_OPENSSL)
        #pragma comment(lib, "libcurl_openssl.lib")
    #else
        #pragma comment(lib, "libcurl.lib")
    #endif
#endif*/

#if defined(_WIN32) && defined(CURL_WIN32_UTF8_FILENAMES)
    #define UTF8_FILENAME(name) name
#else
    #define UTF8_FILENAME(name) IuCoreUtils::Utf8ToSystemLocale(name)
#endif

namespace NetworkClientInternal {

size_t simple_read_callback(void *ptr, size_t size, size_t nmemb, void *stream)
{
    return  fread(ptr, size, nmemb, static_cast<FILE*>(stream));
}

// We might need this function for avoiding "cannot rewind" error,
// but it is not being called when CURLFORM_STREAM is used.
// KNOWN bug in curl: https://github.com/curl/curl/issues/768
/*int simple_seek_callback(void *userp, curl_off_t offset, int origin)
{
    if (fseek(reinterpret_cast<FILE*>(userp), offset, origin)==0) {
        return CURL_SEEKFUNC_OK;
    }
    return CURL_SEEKFUNC_CANTSEEK;
}*/

#if defined(USE_OPENSSL)
char CertFileName[1024] = "";

/* we have this global to let the callback get easy access to it */
static std::vector<std::mutex*> lockarray;

void lock_callback(int mode, int type, char const *file, int line)
{
    (void)file;
    (void)line;
    if (mode & CRYPTO_LOCK) {
        lockarray[type]->lock();
    } else {
        lockarray[type]->unlock();
    }
}

unsigned long thread_id()
{
#ifdef _WIN32
    return ::GetCurrentThreadId();
#else
    return std::hash<std::thread::id>()(std::this_thread::get_id());
#endif
}

// TODO: remove this function
void init_locks()
{
    int i;

    lockarray.resize(CRYPTO_num_locks());
    for (i = 0; i < CRYPTO_num_locks(); i++) {
        lockarray[i] = new std::mutex();
    }

    CRYPTO_set_id_callback(thread_id);
    CRYPTO_set_locking_callback(lock_callback);
}

void kill_locks()
{
    int i;
    if (lockarray.empty()) {
        return;
    }
    CRYPTO_set_locking_callback(NULL);
    CRYPTO_set_id_callback(NULL);
    for (i = 0; i < CRYPTO_num_locks(); i++)
        delete lockarray[i];
    lockarray.clear();
}
#endif

}

int NetworkClient::set_sockopts(void * clientp, curl_socket_t sockfd, curlsocktype purpose)
{
    #ifdef _WIN32
        // See http://support.microsoft.com/kb/823764
        auto* nm = static_cast<NetworkClient*>(clientp);
        int val = nm->m_UploadBufferSize + 32;
        setsockopt(sockfd, SOL_SOCKET, SO_SNDBUF, reinterpret_cast<const char *>(&val), sizeof(val));
    #endif
    return 0;
}

int NetworkClient::private_static_writer(char *data, size_t size, size_t nmemb, void *buffer_in)
{
    auto* cbd = static_cast<CallBackData*>(buffer_in);
    NetworkClient* nm = cbd->nmanager;
    if(nm)
    {
        if(cbd->funcType == CallBackFuncType::funcTypeBody)
        {
            return nm->private_writer(data, size, nmemb);
        }

        return nm->private_header_writer(data, size, nmemb);
    }

    return 0;
}

void NetworkClient::setProxy(const std::string &host, int port, int type)
{
    curl_easy_setopt(curl_handle, CURLOPT_PROXY, host.c_str());
    if (port) {
        curl_easy_setopt(curl_handle, CURLOPT_PROXYPORT, static_cast<long>(port));
    }
    curl_easy_setopt(curl_handle, CURLOPT_PROXYTYPE, static_cast<long>(type));
#ifdef NDEBUG
    curl_easy_setopt(curl_handle, CURLOPT_NOPROXY, "localhost,127.0.0.1");
#endif
}

void NetworkClient::setProxyUserPassword(const std::string &username, const std::string& password) {
    if (username.empty() && password.empty()) {
        curl_easy_setopt(curl_handle, CURLOPT_PROXYUSERPWD, NULL);
        curl_easy_setopt(curl_handle, CURLOPT_PROXYAUTH, NULL);
    } else {
        std::string authStr = urlEncode(username) + ":" + urlEncode(password);
        curl_easy_setopt(curl_handle, CURLOPT_PROXYUSERPWD, authStr.c_str());
        curl_easy_setopt(curl_handle, CURLOPT_PROXYAUTH, CURLAUTH_ANY);
    }
}

void NetworkClient::clearProxy() {
    curl_easy_setopt(curl_handle, CURLOPT_PROXY, "");
    curl_easy_setopt(curl_handle, CURLOPT_PROXYUSERPWD, NULL);
    curl_easy_setopt(curl_handle, CURLOPT_PROXYAUTH, NULL);
}

int NetworkClient::private_writer(char *data, size_t size, size_t nmemb)
{
    if(!m_OutFileName.empty())
    {
        if(!m_hOutFile)
            if ((m_hOutFile = IuCoreUtils::fopen_utf8(m_OutFileName.c_str(), "wb")) == nullptr) {
                LOG(ERROR) << "Unable to create output file:" << std::endl << m_OutFileName;
                throw NetworkClient::AbortedException("Unable to create output file");
            }

        fwrite(data, size,nmemb, m_hOutFile);
    }
    else
        internalBuffer.append(data, size * nmemb);
    return size * nmemb;
}

int NetworkClient::private_header_writer(char *data, size_t size, size_t nmemb)
{
    m_headerBuffer.append(data, size * nmemb);
    return size * nmemb;
}

int NetworkClient::ProgressFunc(void *clientp, double dltotal, double dlnow, double ultotal, double ulnow)
{
    auto* nm = static_cast<NetworkClient*>(clientp);
    if(nm && nm->m_progressCallbackFunc)
    {
        if  (nm->chunkOffset_>=0 && nm->chunkSize_>0 && nm->m_currentActionType == ActionType::atUpload) {
            ultotal = static_cast<double>(nm->m_CurrentFileSize);
            ulnow = nm->chunkOffset_ + ulnow;
        } else if( ((ultotal<=0 && nm->m_CurrentFileSize>0)) && nm->m_currentActionType == ActionType::atUpload)
            ultotal = double(nm->m_CurrentFileSize);
        return nm->m_progressCallbackFunc(nm, dltotal, dlnow, ultotal, ulnow);
    }
    return 0;
}

void NetworkClient::setMethod(const std::string &str)
{
    m_method = str;
}

bool  NetworkClient::_curl_init = false;

std::mutex NetworkClient::_mutex;

NetworkClient::NetworkClient()
{
    curl_init();
    enableResponseCodeChecking_ = true;
    m_hOutFile = nullptr;
    chunkOffset_ = -1;
    chunkSize_ = -1;
    m_uploadingFileReadBytes = 0;
    chunk_ = nullptr;
    curlShare_ = nullptr;
    m_CurrentFileSize = -1;
    m_uploadingFile = nullptr;
    *m_errorBuffer = 0;
    m_progressCallbackFunc = nullptr;
    curl_handle = curl_easy_init(); // Initializing libcurl
    m_bodyFuncData.funcType = CallBackFuncType::funcTypeBody;
    m_bodyFuncData.nmanager = this;
    m_UploadBufferSize = 1048576;
    m_headerFuncData.funcType = CallBackFuncType::funcTypeHeader;
    m_headerFuncData.nmanager = this;
    m_nUploadDataOffset = 0;
    treatErrorsAsWarnings_ = false;
    logger_ = nullptr;
    proxyProvider_ = nullptr;
    curl_easy_setopt(curl_handle, CURLOPT_COOKIELIST, "");
    m_userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.102 Safari/537.36";

    curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, private_static_writer);
    curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, &m_bodyFuncData);
    curl_easy_setopt(curl_handle, CURLOPT_WRITEHEADER, &m_headerFuncData);
    curl_easy_setopt(curl_handle, CURLOPT_ERRORBUFFER, m_errorBuffer);

    curl_easy_setopt(curl_handle, CURLOPT_PROGRESSFUNCTION, &ProgressFunc);
    curl_easy_setopt(curl_handle, CURLOPT_NOPROGRESS, 0L);
    curl_easy_setopt(curl_handle, CURLOPT_PROGRESSDATA, this);
    curl_easy_setopt(curl_handle, CURLOPT_FOLLOWLOCATION, 1L);
    curl_easy_setopt(curl_handle, CURLOPT_ENCODING, "");
    curl_easy_setopt(curl_handle, CURLOPT_SOCKOPTFUNCTION, &set_sockopts);
    curl_easy_setopt(curl_handle, CURLOPT_SOCKOPTDATA, this);

    /*
    TODO: use new progress callbacks
#if LIBCURL_VERSION_NUM >= 0x072000

    curl_easy_setopt(curl_handle, CURLOPT_XFERINFOFUNCTION, xferinfo);
    curl_easy_setopt(curl_handle, CURLOPT_XFERINFODATA, file);
#endif
     */
#if defined(_WIN32) && defined(USE_OPENSSL)
    curl_easy_setopt(curl_handle, CURLOPT_CAINFO, NetworkClientInternal::CertFileName);
#endif
    //if (_is_openssl || !WinUtils::IsWine())
    {
        curl_easy_setopt(curl_handle, CURLOPT_SSL_VERIFYPEER, 1L);
        curl_easy_setopt(curl_handle, CURLOPT_SSL_VERIFYHOST, 2L);
    }
/*#ifdef _DEBUG
    curl_easy_setopt(curl_handle, CURLOPT_SSL_VERIFYPEER, 0L);
    curl_easy_setopt(curl_handle, CURLOPT_SSL_VERIFYHOST, 0L);
#endif*/
    //We want the referrer field set automatically when following locations
    curl_easy_setopt(curl_handle, CURLOPT_AUTOREFERER, 1L);
    curl_easy_setopt(curl_handle, CURLOPT_MAXREDIRS, 8L);
    curl_easy_setopt(curl_handle, CURLOPT_BUFFERSIZE, 32768L);
    curl_easy_setopt(curl_handle, CURLOPT_VERBOSE, 0L);

    /*
    // enable TCP keep-alive for this transfer
    curl_easy_setopt(curl_handle, CURLOPT_TCP_KEEPALIVE, 1L);
    // keep-alive idle time to 120 seconds
    curl_easy_setopt(curl_handle, CURLOPT_TCP_KEEPIDLE, 120L);
    // interval time between keep-alive probes: 60 seconds
    curl_easy_setopt(curl_handle, CURLOPT_TCP_KEEPIDLE, 60L);
    */
}

NetworkClient::~NetworkClient()
{
    curl_easy_setopt(curl_handle, CURLOPT_PROGRESSFUNCTION, nullptr);
    curl_easy_cleanup(curl_handle);
#ifdef USE_OPENSSL
    ERR_remove_thread_state(nullptr);
#endif
    proxyProvider_ = nullptr;
}

void NetworkClient::addQueryParam(const std::string& name, const std::string& value)
{
    QueryParam newParam;
    newParam.name = name;
    newParam.value = value;
    newParam.isFile = false;
    m_QueryParams.push_back(newParam);
}

void NetworkClient::addQueryParamFile(const std::string& name, const std::string& fileName, const std::string& displayName, const std::string& contentType)
{
    QueryParam newParam;
    newParam.name = name;
    newParam.value = fileName;
    newParam.isFile = true;
    newParam.contentType = contentType;
    newParam.displayName= displayName;
    m_QueryParams.push_back(newParam);
}

void NetworkClient::setUrl(const std::string& url)
{
    m_url = url;
    curl_easy_setopt(curl_handle, CURLOPT_URL, url.c_str());
}

void NetworkClient::closeFileList(std::vector<FILE *>& files)
{
    for(auto* f : files ) {
        fclose(f);
    }
    files.clear();
}

bool NetworkClient::doUploadMultipartData()
{
    private_initTransfer();
    std::vector<FILE *> openedFiles;

    struct curl_httppost *formpost=nullptr;
    struct curl_httppost *lastptr=nullptr;

    {
        std::vector<QueryParam>::iterator it, end = m_QueryParams.end();

        for(it=m_QueryParams.begin(); it!=end; ++it)
        {
            if(it->isFile)
            {
                    curl_easy_setopt(curl_handle, CURLOPT_READFUNCTION, NetworkClientInternal::simple_read_callback);
                    //curl_easy_setopt(curl_handle, CURLOPT_SEEKFUNCTION, NetworkClientInternal::simple_seek_callback);
                                        std::string fileName = it->value;
                    FILE * curFile = IuCoreUtils::fopen_utf8(it->value.c_str(), "rb"); /* open file to upload */
                    if(!curFile)
                    {
                        closeFileList(openedFiles);
                        return false; /* can't continue */
                    }
                    openedFiles.push_back(curFile);
                    // FIXME: > 2gb  file size & unicode filenames support on Windows
                    uint64_t  curFileSize = IuCoreUtils::getFileSize(fileName);

                    // Known bug in curl: https://github.com/curl/curl/issues/768
                    if (/*curFileSize > LONG_MAX*/  true ) {
                        std::string ansiFileName = UTF8_FILENAME(fileName);
                        ;
#if defined(_WIN32) && !defined(CURL_WIN32_UTF8_FILENAMES)
                        //LOG(WARNING) << "Uploading files bigger than 2 GB via multipart/form-data with file names non representable in system locale is not supported";
#endif
                        if (it->contentType.empty())
                            curl_formadd(&formpost,
                            &lastptr,
                            CURLFORM_COPYNAME, it->name.c_str(),
                            CURLFORM_FILENAME, it->displayName.c_str(),
                            CURLFORM_FILE, ansiFileName.c_str(),
                            CURLFORM_END);
                        else
                            curl_formadd(&formpost,
                            &lastptr,
                            CURLFORM_COPYNAME, it->name.c_str(),
                            CURLFORM_FILENAME, it->displayName.c_str(),
                            CURLFORM_FILE, ansiFileName.c_str(),
                            CURLFORM_CONTENTTYPE, it->contentType.c_str(),
                            CURLFORM_END);
                    } /*else {
                        if (it->contentType.empty())
                            curl_formadd(&formpost,
                            &lastptr,
                            CURLFORM_COPYNAME, it->name.c_str(),
                            CURLFORM_FILENAME, it->displayName.c_str(),
                            CURLFORM_STREAM, curFile,
                            CURLFORM_CONTENTSLENGTH, static_cast<long>(curFileSize),
                            CURLFORM_END);
                        else
                            curl_formadd(&formpost,
                            &lastptr,
                            CURLFORM_COPYNAME, it->name.c_str(),
                            CURLFORM_FILENAME, it->displayName.c_str(),
                            CURLFORM_STREAM, curFile,
                            CURLFORM_CONTENTSLENGTH, static_cast<long>(curFileSize),
                            CURLFORM_CONTENTTYPE, it->contentType.c_str(),
                            CURLFORM_END);
                    } */
            }
            else
            {
                 curl_formadd(&formpost,
                        &lastptr,
                        CURLFORM_COPYNAME, it->name.c_str(),
                        CURLFORM_COPYCONTENTS, it->value.c_str(),
                        CURLFORM_END);
            }
        }
    }

    curl_easy_setopt(curl_handle, CURLOPT_HTTPPOST, formpost);
    m_currentActionType = ActionType::atUpload;
    curl_result = curl_easy_perform(curl_handle);
    closeFileList(openedFiles);
    curl_formfree(formpost);
    return private_on_finish_request();
}

bool NetworkClient::private_on_finish_request()
{
    private_checkResponse();
    private_cleanup_after();
    private_parse_headers();
    if (curl_result != CURLE_OK)
    {
        if (curl_result == CURLE_ABORTED_BY_CALLBACK) {
            throw AbortedException("Aborted by callback");
        }
        return false; //fail
    }

    return true;
}

std::string NetworkClient::responseBody()
{
    return internalBuffer;
}

int NetworkClient::responseCode()
{
    long result=-1;
    curl_easy_getinfo(curl_handle, CURLINFO_RESPONSE_CODE, &result);
    return result;
}

void NetworkClient::addQueryHeader(const std::string& name, const std::string& value)
{
    m_QueryHeaders.emplace_back(name, value);
}

bool NetworkClient::doGet(const std::string & url)
{
    if(!url.empty())
        setUrl(url);

    private_initTransfer();
    if(!private_apply_method())
        curl_easy_setopt(curl_handle, CURLOPT_HTTPGET, 1);
    m_currentActionType = ActionType::atGet;
    curl_result = curl_easy_perform(curl_handle);
    return private_on_finish_request();

}

bool NetworkClient::doPost(const std::string& data)
{
    private_initTransfer();
    if(!private_apply_method())
   curl_easy_setopt(curl_handle, CURLOPT_POST, 1L);
    std::string postData;
    std::vector<QueryParam>::iterator it, end = m_QueryParams.end();

        for(it=m_QueryParams.begin(); it!=end; ++it)
        {
            if(!it->isFile)
            {
                postData+= urlEncode(it->name)+"="+urlEncode(it->value)+"&";
            }
        }

    if(data.empty()) {
        curl_easy_setopt(curl_handle, CURLOPT_POSTFIELDS, postData.c_str());
        curl_easy_setopt(curl_handle, CURLOPT_POSTFIELDSIZE, static_cast<long>(postData.length()));
    }
    else {
        curl_easy_setopt(curl_handle, CURLOPT_POSTFIELDS, (const char*)data.data());
        curl_easy_setopt(curl_handle, CURLOPT_POSTFIELDSIZE, (long)data.length());
    }

    m_currentActionType = ActionType::atPost;
    curl_result = curl_easy_perform(curl_handle);
    return private_on_finish_request();
}

std::string NetworkClient::urlEncode(const std::string& str)
{
    char * encoded = curl_easy_escape(curl_handle, str.c_str() , str.length() );
    std::string res = encoded;
    res+="";
    curl_free(encoded);
    return res;
}

std::string NetworkClient::urlDecode(const std::string& str) {
    char * decoded = curl_easy_unescape(curl_handle, str.c_str(), str.length(), nullptr);
    std::string res = decoded;
    res += "";
    curl_free(decoded);
    return res;
}

std::string NetworkClient::errorString()
{
    return m_errorBuffer;
}

void NetworkClient::setUserAgent(const std::string& userAgentStr)
{
    m_userAgent = userAgentStr;
}

void NetworkClient::private_initTransfer()
{
    private_cleanup_before();
    curl_easy_setopt(curl_handle, CURLOPT_USERAGENT, m_userAgent.c_str());

#if defined(_WIN32) && !defined(USE_OPENSSL)
    // See https://github.com/curl/curl/issues/264
    curl_easy_setopt(curl_handle, CURLOPT_SSL_OPTIONS, CURLSSLOPT_NO_REVOKE);
#endif
    std::vector<CustomHeaderItem>::iterator it, end = m_QueryHeaders.end();
    chunk_ = nullptr;

    for(it = m_QueryHeaders.begin(); it!=end; ++it)
    {
        if ( it->value == "\n" ) {
            chunk_ = curl_slist_append(chunk_, (it->name + ";" + it->value).c_str());
        } else {
            chunk_ = curl_slist_append(chunk_, (it->name + ": " + it->value).c_str());
        }

    }

    curl_easy_setopt(curl_handle, CURLOPT_HTTPHEADER, chunk_);
    if (proxyProvider_) {
        proxyProvider_->provideProxyForUrl(this, m_url);
    }
}

void NetworkClient::private_checkResponse()
{
    if ( !enableResponseCodeChecking_ && curl_result == CURLE_OK )  {
        return;
    }
    int code = responseCode();
    if ( (curl_result != CURLE_OK || (code>= 400 && code<=499)) && errorString() != "Callback aborted" ) {
        std::string errorDescr;

        if (!errorLogIdString_.empty()) {
            errorDescr = errorLogIdString_ + "\r\n";
        }

        errorDescr += "Request failed, URL: '" + m_url + "'. \r\n";

        if (curl_result != CURLE_OK) {
            errorDescr += getCurlResultString() + "\r\n";
        }
        if (code) {
            errorDescr += "Response code: " + std::to_string(code) + "\r\n";
        }
        std::string fullErrorString = errorString();
        if (!fullErrorString.empty()) {
            errorDescr += fullErrorString  + "\r\n";
        }
        errorDescr += internalBuffer;
        if (logger_) {
            logger_->logNetworkError(!treatErrorsAsWarnings_, errorDescr);
        } else {
            (treatErrorsAsWarnings_ ? LOG(WARNING) : LOG(ERROR)) << errorDescr;
        }
    }
}

void NetworkClient::curl_init() {
    std::lock_guard<std::mutex> guard(_mutex);
    if (!_curl_init) {
#ifdef USE_OPENSSL
        NetworkClientInternal::init_locks(); // init locks should be called BEFORE curl_global_init
#endif

    curl_global_init(CURL_GLOBAL_ALL);

#if defined(WIN32) && defined(USE_OPENSSL)
            using namespace NetworkClientInternal;
            GetModuleFileNameA(0, CertFileName, 1023);
            int i, len = lstrlenA(CertFileName);
            for (i = len; i >= 0; i--) {
                if (CertFileName[i] == '\\') {
                    CertFileName[i + 1] = 0;
                    break;
                }
            }
            strcat(CertFileName, "curl-ca-bundle.crt");
#endif
        atexit(&curl_cleanup);
        _curl_init = true;
    }
}

void NetworkClient::curl_cleanup()
{
    curl_global_cleanup();
#ifdef USE_OPENSSL
    #if defined(_WIN32) && !defined(OPENSSL_NO_COMP)
        SSL_COMP_free_compression_methods(); // to avoid memory leaks
    #endif
    NetworkClientInternal::kill_locks();
#endif
}

std::string NetworkClient::responseHeaderText()
{
    return m_headerBuffer;
}

void NetworkClient::setProgressCallback(const ProgressCallback& func)
{
    m_progressCallbackFunc = func;
}

void NetworkClient::private_parse_headers()
{
    auto headers = IuStringUtils::SplitSV(m_headerBuffer, "\n");

    for (const auto &it: headers) {
        auto parts = IuStringUtils::SplitSV(it, ":", 2);

        if (parts.size() == 2) {
            std::string name(IuStringUtils::TrimSV(parts[0]));
            std::string value(IuStringUtils::TrimSV(parts[1]));
            m_ResponseHeaders.emplace_back(name, value);
        }
    }
}

std::string NetworkClient::responseHeaderByName(const std::string& name)
{
    std::vector<CustomHeaderItem>::iterator it, end = m_ResponseHeaders.end();

    for(it = m_ResponseHeaders.begin(); it!=end; ++it)
    {
        if(it->name == name)
            return it->value;
    }
    return std::string();

}

int NetworkClient::responseHeaderCount()
{
    return m_ResponseHeaders.size();
}

std::string NetworkClient::responseHeaderByIndex(int index, std::string& name)
{
    if (index >= 0 && static_cast<size_t>(index) < m_ResponseHeaders.size()) {
        name = m_ResponseHeaders[index].name;
        return m_ResponseHeaders[index].value;
    }
    return std::string();
}

void NetworkClient::private_cleanup_before()
{
    std::vector<CustomHeaderItem>::iterator it, end = m_QueryHeaders.end();

    bool add = true;
    for(it = m_QueryHeaders.begin(); it!=end; ++it)
    {
        if(it->name == "Expect" ) { add = false; break; }
    }
    addQueryHeader("Expect", "");
    m_ResponseHeaders.clear();
    internalBuffer.clear();
    m_headerBuffer.clear();
}

void NetworkClient::private_cleanup_after()
{
    m_currentActionType = ActionType::atNone;
    m_QueryHeaders.clear();
    m_QueryParams.clear();
    if(m_hOutFile)
    {
        fclose(m_hOutFile);
        m_hOutFile = nullptr;
    }
    m_OutFileName.clear();
    m_method.clear();
    curl_easy_setopt(curl_handle, CURLOPT_INFILESIZE_LARGE, static_cast<curl_off_t>(-1));

    m_uploadData.clear();
    m_uploadingFile = nullptr;
    chunkOffset_ = -1;
    chunkSize_ = -1;
    enableResponseCodeChecking_ = true;
    m_nUploadDataOffset = 0;
    /*curl_easy_setopt(curl_handle, CURLOPT_READFUNCTION, 0L);
    curl_easy_setopt(curl_handle, CURLOPT_READDATA, 0L);*/
    if(chunk_)
    {
        curl_slist_free_all(chunk_);
        chunk_ = nullptr;
    }
}

size_t NetworkClient::read_callback(void *ptr, size_t size, size_t nmemb, void *stream)
{
    auto* nm = static_cast<NetworkClient*>(stream);
    if(!nm) {
        return 0;
    }
    return nm->private_read_callback(ptr, size, nmemb, stream);
}

size_t NetworkClient::private_read_callback(void *ptr, size_t size, size_t nmemb, void *)
{
    size_t retcode;

    if (m_uploadingFile) {
        int64_t pos = IuCoreUtils::ftell_64(m_uploadingFile);
        if (pos >= chunkOffset_ + m_currentUploadDataSize) {
            return 0;
        }
        retcode = fread(ptr, size, nmemb, m_uploadingFile);
        if (chunkOffset_ != -1) {
            retcode = std::min<>((int64_t)retcode, chunkOffset_ + m_currentUploadDataSize - pos);
        }
        m_uploadingFileReadBytes += retcode;
    } else
    {
        int wantsToRead = size * nmemb;
        // dont even try to remove "<>" brackets!!
        int canRead = std::min<>((int)m_uploadData.size()-m_nUploadDataOffset, (int)wantsToRead);
        memcpy(ptr, m_uploadData.data(), canRead);
        m_nUploadDataOffset += canRead;
        retcode = canRead;
    }
    return retcode;
}

int NetworkClient::private_seek_callback(void *userp, curl_off_t offset, int origin) {
    auto* nc = static_cast<NetworkClient*>(userp);

    if (nc->m_uploadingFile) {
        int64_t newOffset = offset;
        int newOrigin = origin;
        if (origin == SEEK_SET && nc->chunkOffset_ != -1) {
            newOffset = nc->chunkOffset_ + offset;
        } else if (origin == SEEK_END) {
            // not implemented
            return CURL_SEEKFUNC_CANTSEEK;
        }
        return IuCoreUtils::fseek_64(nc->m_uploadingFile, newOffset, newOrigin);
    } else {
        if (origin == SEEK_SET) {
            if (offset < 0 || offset>= nc->m_uploadData.size()) {
                return CURL_SEEKFUNC_CANTSEEK;
            }
            nc->m_nUploadDataOffset = offset;
        } else if (origin == SEEK_CUR) {
            nc->m_nUploadDataOffset += offset;
        } else {
            // not implemented
            return CURL_SEEKFUNC_CANTSEEK;
        }
        return CURL_SEEKFUNC_OK;
    }
}

bool NetworkClient::doUpload(const std::string& fileName, const std::string &data)
{
    if(!fileName.empty())
    {
        m_uploadingFile = IuCoreUtils::fopen_utf8(fileName.c_str(), "rb"); /* open file to upload */
        if(!m_uploadingFile)
        {
            LOG(ERROR)<< "Failed to open file '" << fileName << "'";
            return false; /* can't continue */
        }
        m_CurrentFileSize = IuCoreUtils::getFileSize(fileName);
        m_currentUploadDataSize = m_CurrentFileSize;
        if(m_CurrentFileSize < 0) {
            fclose(m_uploadingFile);
            return false;
        }

        if ( chunkSize_  >0 && chunkOffset_ >= 0 ) {
            m_currentUploadDataSize = chunkSize_;
            if ( IuCoreUtils::fseek_64(m_uploadingFile, chunkOffset_, SEEK_SET)) {
            }
        }
        m_uploadingFileReadBytes = 0;
        m_currentActionType = ActionType::atUpload;
    }
    else
    {
        m_nUploadDataOffset =0;
        m_uploadData = data;
        m_CurrentFileSize = data.length();
        m_currentUploadDataSize = m_CurrentFileSize;
        m_currentActionType = ActionType::atPost;
    }
    curl_easy_setopt(curl_handle, CURLOPT_READFUNCTION, read_callback);
    curl_easy_setopt(curl_handle, CURLOPT_SEEKFUNCTION, private_seek_callback);
    curl_easy_setopt(curl_handle, CURLOPT_SEEKDATA, this);
    if (!private_apply_method()) {
        curl_easy_setopt(curl_handle, CURLOPT_POST, 1L);
    }
    curl_easy_setopt(curl_handle,CURLOPT_POSTFIELDS, NULL);
    curl_easy_setopt(curl_handle, CURLOPT_READDATA, this);

    if ( m_method != "PUT" ) {
        addQueryHeader("Content-Length", IuCoreUtils::int64_tToString(m_currentUploadDataSize));
    }
    private_initTransfer();

    curl_easy_setopt(curl_handle, CURLOPT_INFILESIZE_LARGE, static_cast<curl_off_t>(m_currentUploadDataSize));

    curl_result = curl_easy_perform(curl_handle);
    if(m_uploadingFile)
         fclose(m_uploadingFile);
    bool res = private_on_finish_request();
    return res;
}

bool NetworkClient::private_apply_method()
{
    curl_easy_setopt(curl_handle, CURLOPT_CUSTOMREQUEST,NULL);
    curl_easy_setopt(curl_handle, CURLOPT_UPLOAD, 0L);
    if(m_method == "POST")
        curl_easy_setopt(curl_handle, CURLOPT_POST, 1L);
    else     if(m_method == "GET")
        curl_easy_setopt(curl_handle, CURLOPT_HTTPGET, 1L);
    else if (m_method == "PUT")
            curl_easy_setopt(curl_handle, CURLOPT_UPLOAD, 1L);
    else if (!m_method.empty())
    {
        curl_easy_setopt(curl_handle, CURLOPT_CUSTOMREQUEST,m_method.c_str());
    }
    else
    {
        curl_easy_setopt(curl_handle, CURLOPT_CUSTOMREQUEST,NULL);
        return false;
    }
    return true;

}

void NetworkClient::setReferer(const std::string &str)
{
    curl_easy_setopt(curl_handle, CURLOPT_REFERER, str.c_str());
}

int NetworkClient::getCurlResult()
{
    return curl_result;
}
CURL* NetworkClient::getCurlHandle()
{
    return curl_handle;
}

void NetworkClient::setOutputFile(const std::string &str)
{
    m_OutFileName = str;
}

void NetworkClient::setUploadBufferSize(int size)
{
    m_UploadBufferSize = size;
}

void NetworkClient::setChunkOffset(double offset)
{
    chunkOffset_ = static_cast<uint64_t>(offset);
}

void NetworkClient::setChunkSize(double size)
{
    chunkSize_ = static_cast<uint64_t>(size);
}

void NetworkClient::setTreatErrorsAsWarnings(bool treat)
{
    treatErrorsAsWarnings_ = treat;
}

std::string NetworkClient::getCurlResultString()
{
    const char * str = curl_easy_strerror(curl_result);
    std::string res(str);
    res+="";
    //curl_free(str);
    return res;
}

void NetworkClient::setCurlShare(CurlShare* share)
{
    curlShare_ = share;
    curl_easy_setopt(curl_handle, CURLOPT_SHARE, share->getHandle());
}

void NetworkClient::enableResponseCodeChecking(bool enable)
{
    enableResponseCodeChecking_ = enable;
}

void NetworkClient::setErrorLogId(const std::string& str) {
    errorLogIdString_ = str;
}

void NetworkClient::setLogger(Logger* logger) {
    logger_ = logger;
}

void NetworkClient::setProxyProvider(std::shared_ptr<ProxyProvider> provider) {
    proxyProvider_ = provider;
}

void NetworkClient::setCurlOption(int option, const std::string &value) {
    curl_easy_setopt(curl_handle, static_cast<CURLoption>(option), value.c_str());
}

void NetworkClient::setCurlOptionInt(int option, long value) {
    curl_easy_setopt(curl_handle, static_cast<CURLoption>(option), value);
}

std::string NetworkClient::getCurlInfoString(int option)
{
    char* buf = nullptr;
    curl_easy_getinfo(curl_handle, static_cast<CURLINFO>(option), &buf);
    std::string res = buf ? buf : std::string();
    return res;
}

int NetworkClient::getCurlInfoInt(int option)
{
    long res = 0;
    curl_easy_getinfo(curl_handle, static_cast<CURLINFO>(option), &res);
    return res;
}

double NetworkClient::getCurlInfoDouble(int option)
{
    double res = 0;
    curl_easy_getinfo(curl_handle, static_cast<CURLINFO>(option), &res);
    return res;
}

void NetworkClient::setTimeout(uint32_t timeout)
{
    curl_easy_setopt(curl_handle, CURLOPT_TIMEOUT, static_cast<long>(timeout));
}

void NetworkClient::setConnectionTimeout(uint32_t connection_timeout)
{
    curl_easy_setopt(curl_handle, CURLOPT_CONNECTTIMEOUT, static_cast<long>(connection_timeout));
}

void NetworkClient::setMaxUploadSpeed(uint64_t speed) {
    curl_easy_setopt(curl_handle, CURLOPT_MAX_SEND_SPEED_LARGE, static_cast<curl_off_t>(speed));
}

void NetworkClient::setMaxDownloadSpeed(uint64_t speed) {
    curl_easy_setopt(curl_handle, CURLOPT_MAX_RECV_SPEED_LARGE, static_cast<curl_off_t>(speed));
}


text:
using System.Xml.Serialization;
using StayWell.Interface;
using StayWell.ServiceDefinitions.Content.Objects;

namespace StayWell.ServiceDefinitions.Languages.Objects
{
	[XmlType("Languages")]
	public class LanguageList : ResultList<Language>
	{
	}
}


text:
package ru.semiot.platform.deviceproxyservice.api.drivers;

public interface DeviceDriver {

  public String getDriverName();
}


text:
package utils

import java.util.Date

import org.joda.time.{DateTime, DateTimeZone}
import org.joda.time.format.ISODateTimeFormat
import play.api.libs.json._

/**
 * Play Json formatter that formats Date objects as ISO-8601 strings
 */
object JsonFormats {
  implicit object DateFormat extends Format[Date] {
    val formatter = ISODateTimeFormat.dateTime()

    def reads(json: JsValue) = JsSuccess(new DateTime(json.as[String]).toDate)
    def writes(date: Date) = JsString(formatter.print(new DateTime(date).withZone(DateTimeZone.UTC)))
  }
}


text:
using namespace System;
using namespace System::Collections::Generic;

namespace Examples {
  class Program {
  public:
    // The main entry point for the application.
    static void Main() {
      Array<string> input = {"Brachiosaurus", "Amargasaurus", "Mamenchisaurus"};
      List<string> dinosaurs(input);

      Console::WriteLine("\nCapacity: {0}", dinosaurs.Capacity);

      Console::WriteLine();
      for (string dinosaur : dinosaurs)
        Console::WriteLine(dinosaur);

      Console::WriteLine("\nAddRange(dinosaurs)");
      dinosaurs.AddRange(dinosaurs);

      Console::WriteLine();
      for (string dinosaur : dinosaurs)
        Console::WriteLine(dinosaur);

      Console::WriteLine("\nRemoveRange(2, 2)");
      dinosaurs.RemoveRange(2, 2);

      Console::WriteLine();
      for (string dinosaur : dinosaurs)
        Console::WriteLine(dinosaur);

      input = {"Tyrannosaurus", "Deinonychus", "Velociraptor"};

      Console::WriteLine("\nInsertRange(3, input)");
      dinosaurs.InsertRange(3, input);

      Console::WriteLine();
      for (string dinosaur : dinosaurs)
        Console::WriteLine(dinosaur);

      Console::WriteLine("\noutput = dinosaurs.GetRange(2, 3).ToArray()");
      Array<string> output = dinosaurs.GetRange(2, 3).ToArray();

      Console::WriteLine();
      for (string dinosaur : output)
        Console::WriteLine(dinosaur);
    }
  };
}

startup_(Examples::Program);

// This code example produces the following output:
//
// Capacity: 4
//
// Brachiosaurus
// Amargasaurus
// Mamenchisaurus
//
// AddRange(*dinosaurs)
//
// Brachiosaurus
// Amargasaurus
// Mamenchisaurus
// Brachiosaurus
// Amargasaurus
// Mamenchisaurus
//
// RemoveRange(2, 2)
//
// Brachiosaurus
// Amargasaurus
// Amargasaurus
// Mamenchisaurus
//
// InsertRange(3, input)
//
// Brachiosaurus
// Amargasaurus
// Amargasaurus
// Tyrannosaurus
// Deinonychus
// Velociraptor
// Mamenchisaurus
//
// output = dinosaurs.GetRange(2, 3).ToArray()
//
// Amargasaurus
// Tyrannosaurus
// Deinonychus


text:
<?php

namespace common\models\cf;

use Yii;

/**
 * todo:
 * -какие бывают статусы
 *
 * This is the model class for table "{{%Objects}}".
 *
 * @property integer $ID
 * @property integer $HardID
 * @property string $Name
 * @property integer $Status
 * @property integer $GroupID
 * @property double $CoinPrice
 * @property integer $Disabled
 * @property double $Cost
 * @property double $Area
 * @property integer $IsWithoutDiscount
 * @property integer $Coins
 * @property double $Cash
 * @property integer $PlayTime
 * @property integer $RoomID
 */
class ObjectRecord extends ActiveRecordCashFusion
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%objects}}';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['HardID', 'Name', 'CoinPrice'], 'required'],
            [['HardID', 'Coins', 'PlayTime'], 'integer'],
            [['CoinPrice', 'Cost', 'Area', 'Cash'], 'double'],
            [['Name'], 'string', 'max' => 255],
            [['HardID'], 'integer', 'min'=>257],
            [['HardID'], 'unique'],
//            [['RoomID'], 'exist', 'targetClass'=>RoomRecord::className(), 'targetAttribute'=>'ID'],
            [['GroupID'], 'exist', 'targetClass'=>ObjectGroupRecord::className(), 'targetAttribute'=>'ID'],
            [['GroupID'], 'default', 'value'=>0],
            [['Status'], 'default', 'value'=>0],
            [['Area'], 'default', 'value'=>1],
            [['PlayTime'], 'default', 'value'=>0],
            [['Cash', 'Coins', 'Cost', 'PlayTime', 'RoomID'], 'default', 'value'=>0],
            [['IsWithoutDiscount', 'Disabled'], 'boolean'],
            [['IsWithoutDiscount', 'Disabled', 'Deleted'], 'default', 'value'=>0],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'ID' => Yii::t('models', 'ID'),
            'HardID' => Yii::t('models', 'Hard ID'),
            'Name' => Yii::t('models', 'Object Name'),
            'Status' => Yii::t('models', 'Status'),
            'GroupID' => Yii::t('models', 'Object Group'),
            'CoinPrice' => Yii::t('models', 'Coin Price'),
            'Disabled' => Yii::t('models', 'Disabled'),
            'Cost' => Yii::t('models', 'Cost'),
            'Area' => Yii::t('models', 'Object Area'),
            'IsWithoutDiscount' => Yii::t('models', 'Is Terminator'),
            'Coins' => Yii::t('models', 'Coins'),
            'Cash' => Yii::t('models', 'Cash'),
            'PlayTime' => Yii::t('models', 'Play Time'),
            'RoomID' => Yii::t('models', 'Room'),
            'room.Name' => Yii::t('models', 'Room'),
            'group.Name' => Yii::t('models', 'Group Name'),
        ];
    }

    /**
     * @return ObjectGroupRecord
     */
    public function getGroup()
    {
        return $this->hasOne(ObjectGroupRecord::className(), ['ID' => 'GroupID']);
    }

    /**
     * @return RoomRecord
     */
    public function getRoom()
    {
        return $this->hasOne(RoomRecord::className(), ['ID' => 'RoomID']);
    }

    /**
     * @return ObjectFunctionsRecord
     */
    public function getFunctions()
    {
        return $this->hasMany(ObjectFunctionsRecord::className(), ['ObjectID' => 'ID']);
    }

    /**
     * Does soft delete
     * Update Deleted attribute if exist
     * @return false|int
     * @throws \Exception
     */
    public function delete()
    {
        return $this->updateAttributes([
            'Deleted' => 1,
            'HardID' => null
        ]);
    }
}


text:
package org.pentaho.di.ui.repository.pur.services;

import java.util.List;

import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.repository.RepositorySecurityManager;
import org.pentaho.di.repository.pur.model.IRole;
/**
 * Repository Security Manager with the Role support
 * @author rmansoor
 *
 */
public interface IRoleSupportSecurityManager extends RepositorySecurityManager{
  /**
   * Constructs the repository version of the IRole implementation
   *
   * @return return the instance of IRole
   * @throws KettleException
   */
  public IRole constructRole()  throws KettleException;
  /**
   * Creates a role in the system with the given information
   *
   * @param role to be created
   * @throws KettleException
   */
  public void createRole(IRole role) throws KettleException;
  /**
   * Retrieves the role with a given name
   *
   * @param name of the role to be searched
   * @return role object matching the name
   * @throws KettleException
   */
  public IRole getRole(String name) throws KettleException;

  /**
   * Retrieves all available roles in the system
   *
   * @return the list of available roles
   * @throws KettleException
   */
  public List<IRole> getRoles() throws KettleException;

  /**
   * Retrieves the default roles in the system.
   *
   * @return the list of default roles
   * @throws KettleException
   */
  public List<IRole> getDefaultRoles() throws KettleException;

  /**
   * Save the list of roles in the system
   *
   * @param list of role objects to be saved
   * @throws KettleException
   */
  public void setRoles(List<IRole> roles) throws KettleException;
  /**
   * Updates a particular role in the system
   *
   * @param role object to be updated
   * @throws KettleException
   */
  public void updateRole(IRole role) throws KettleException;
  /**
   * Deletes a list of roles in the system
   *
   * @param list of role object to be deleted
   * @throws KettleException
   */
  public void deleteRoles(List<IRole> roles) throws KettleException;
  /**
   * Delete a particular role matching the role name
   *
   * @param name of the role to be deleted
   * @throws KettleException
   */
  public void deleteRole(String name) throws KettleException;
}


text:
from django.db import connection, DatabaseError
from django.db import models
from django.contrib.admin.sites import NotRegistered
from django.db.models.signals import class_prepared
from django.db.models.loading import cache as app_cache

from django.core.urlresolvers import clear_url_caches
from django.utils.importlib import import_module
from django.core.cache import cache
from django.conf import settings

import logging
from south.db import db

logger = logging.getLogger('surveymaker')

def unregister_from_admin(admin_site, model):
    " Removes the dynamic model from the given admin site "

    # First deregister the current definition
    # This is done "manually" because model will be different
    # db_table is used to check for class equivalence.
    for reg_model in admin_site._registry.keys():
        if model._meta.db_table == reg_model._meta.db_table:
            del admin_site._registry[reg_model]

    # Try the normal approach too
    try:
        admin_site.unregister(model)
    except NotRegistered:
        pass

    # Reload the URL conf and clear the URL cache
    # It's important to use the same string as ROOT_URLCONF
    reload(import_module(settings.ROOT_URLCONF))
    clear_url_caches()

def reregister_in_admin(admin_site, model, admin_class=None):
    " (re)registers a dynamic model in the given admin site "

    # We use our own unregister, to ensure that the correct
    # existing model is found
    # (Django's unregister doesn't expect the model class to change)
    unregister_from_admin(admin_site, model)
    admin_site.register(model, admin_class)

    # Reload the URL conf and clear the URL cache
    # It's important to use the same string as ROOT_URLCONF
    reload(import_module(settings.ROOT_URLCONF))
    clear_url_caches()

def when_classes_prepared(app_name, dependencies, fn):
    """ Runs the given function as soon as the model dependencies are available.
        You can use this to build dyanmic model classes on startup instead of
        runtime.

        app_name       the name of the relevant app
        dependencies   a list of model names that need to have already been
                       prepared before the dynamic classes can be built.
        fn             this will be called as soon as the all required models
                       have been prepared

        NB: The fn will be called as soon as the last required
            model has been prepared. This can happen in the middle of reading
            your models.py file, before potentially referenced functions have
            been loaded. Becaue this function must be called before any
            relevant model is defined, the only workaround is currently to
            move the required functions before the dependencies are declared.

        TODO: Allow dependencies from other apps?
    """
    dependencies = [x.lower() for x in dependencies]

    def _class_prepared_handler(sender, **kwargs):
        """ Signal handler for class_prepared.
            This will be run for every model, looking for the moment when all
            dependent models are prepared for the first time. It will then run
            the given function, only once.
        """
        sender_name = sender._meta.object_name.lower()
        already_prepared = set(app_cache.app_models.get(app_name,{}).keys() + [sender_name])

        if (sender._meta.app_label == app_name and sender_name in dependencies
          and all([x in already_prepared for x in dependencies])):
            db.start_transaction()
            try:
                fn()
            except DatabaseError:
                # If tables are  missing altogether, not much we can do
                # until syncdb/migrate is run. "The code must go on" in this
                # case, without running our function completely. At least
                # database operations will be rolled back.
                db.rollback_transaction()
            else:
                db.commit_transaction()
                # TODO Now that the function has been run, should/can we
                # disconnect this signal handler?

    # Connect the above handler to the class_prepared signal
    # NB: Although this signal is officially documented, the documentation
    # notes the following:
    #     "Django uses this signal internally; it's not generally used in
    #      third-party applications."
    class_prepared.connect(_class_prepared_handler, weak=False)

def get_cached_model(app_label, model_name, regenerate=False, get_local_hash=lambda i: i._hash):

    # If this model has already been generated, we'll find it here
    previous_model = models.get_model(app_label, model_name)

    # Before returning our locally cached model, check that it is still current
    if previous_model is not None and not regenerate:
        CACHE_KEY = utils.HASH_CACHE_TEMPLATE % (app_label, model_name)
        if cache.get(CACHE_KEY) != get_local_hash(previous_model):
            logging.debug("Local and shared dynamic model hashes are different: %s (local) %s (shared)" % (get_local_hash(previous_model), cache.get(CACHE_KEY)))
            regenerate = True

    # We can force regeneration by disregarding the previous model
    if regenerate:
        previous_model = None
        # Django keeps a cache of registered models, we need to make room for
        # our new one
        utils.remove_from_model_cache(app_label, model_name)

    return previous_model

def remove_from_model_cache(app_label, model_name):
    """ Removes the given model from the model cache. """
    try:
        del app_cache.app_models[app_label][model_name.lower()]
    except KeyError:
        pass

def create_db_table(model_class):
    """ Takes a Django model class and create a database table, if necessary.
    """
    # XXX Create related tables for ManyToMany etc

    db.start_transaction()
    table_name = model_class._meta.db_table

    # Introspect the database to see if it doesn't already exist
    if (connection.introspection.table_name_converter(table_name)
                        not in connection.introspection.table_names()):

        fields = _get_fields(model_class)

        db.create_table(table_name, fields)
        # Some fields are added differently, after table creation
        # eg GeoDjango fields
        db.execute_deferred_sql()
        logger.debug("Created table '%s'" % table_name)

    db.commit_transaction()

def delete_db_table(model_class):
    table_name = model_class._meta.db_table
    db.start_transaction()
    db.delete_table(table_name)
    logger.debug("Deleted table '%s'" % table_name)
    db.commit_transaction()

def _get_fields(model_class):
    """ Return a list of fields that require table columns. """
    return [(f.name, f) for f in model_class._meta.local_fields]

def add_necessary_db_columns(model_class):
    """ Creates new table or relevant columns as necessary based on the model_class.
        No columns or data are renamed or removed.
        This is available in case a database exception occurs.
    """
    db.start_transaction()

    # Create table if missing
    create_db_table(model_class)

    # Add field columns if missing
    table_name = model_class._meta.db_table
    fields = _get_fields(model_class)
    db_column_names = [row[0] for row in connection.introspection.get_table_description(connection.cursor(), table_name)]

    for field_name, field in fields:
        if field.column not in db_column_names:
            logger.debug("Adding field '%s' to table '%s'" % (field_name, table_name))
            db.add_column(table_name, field_name, field)

    # Some columns require deferred SQL to be run. This was collected
    # when running db.add_column().
    db.execute_deferred_sql()

    db.commit_transaction()

def rename_db_column(model_class, old_name, new_name):
    """ Rename a sensor's database column. """
    table_name = model_class._meta.db_table
    db.start_transaction()
    db.rename_column(table_name, old_name, new_name)
    logger.debug("Renamed column '%s' to '%s' on %s" % (old_name, new_name, table_name))
    db.commit_transaction()

def notify_model_change(model):
    """ Notifies other processes that a dynamic model has changed.
        This should only ever be called after the required database changes have been made.
    """
    CACHE_KEY = HASH_CACHE_TEMPLATE % (model._meta.app_label, model._meta.object_name)
    cache.set(CACHE_KEY, model._hash)
    logger.debug("Setting \"%s\" hash to: %s" % (model._meta.verbose_name, model._hash))

HASH_CACHE_TEMPLATE = 'dynamic_model_hash_%s-%s'


text:
import meta from './tooltip.json'
import template from './tooltip.html'
import snippet from './snippet.html'
import vsTooltip from 'src/components/tooltip'
import docsDemo from 'vuestrap-docs/src/components/demo'

export default {
  route: {
    url: '/tooltip',
    name: 'tooltip',
    title: 'Tooltip',
  },
  template: template,
  data() {
    return {
      meta: meta,
      snippet: snippet,
    }
  },
  components: {
    vsTooltip,
    docsDemo,
  },
}