text:
package sql

// Copyright (c) Microsoft and contributors.  All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

import (
	"github.com/Azure/go-autorest/autorest"
	"github.com/Azure/go-autorest/autorest/azure"
	"net/http"
)

// CapabilitiesClient is the the Azure SQL Database management API provides a RESTful set of web services that interact
// with Azure SQL Database services to manage your databases. The API enables you to create, retrieve, update, and
// delete databases.
type CapabilitiesClient struct {
	ManagementClient
}

// NewCapabilitiesClient creates an instance of the CapabilitiesClient client.
func NewCapabilitiesClient(subscriptionID string) CapabilitiesClient {
	return NewCapabilitiesClientWithBaseURI(DefaultBaseURI, subscriptionID)
}

// NewCapabilitiesClientWithBaseURI creates an instance of the CapabilitiesClient client.
func NewCapabilitiesClientWithBaseURI(baseURI string, subscriptionID string) CapabilitiesClient {
	return CapabilitiesClient{NewWithBaseURI(baseURI, subscriptionID)}
}

// ListByLocation gets the capabilities available for the specified location.
//
// locationID is the location id whose capabilities are retrieved.
func (client CapabilitiesClient) ListByLocation(locationID string) (result LocationCapabilities, err error) {
	req, err := client.ListByLocationPreparer(locationID)
	if err != nil {
		err = autorest.NewErrorWithError(err, "sql.CapabilitiesClient", "ListByLocation", nil, "Failure preparing request")
		return
	}

	resp, err := client.ListByLocationSender(req)
	if err != nil {
		result.Response = autorest.Response{Response: resp}
		err = autorest.NewErrorWithError(err, "sql.CapabilitiesClient", "ListByLocation", resp, "Failure sending request")
		return
	}

	result, err = client.ListByLocationResponder(resp)
	if err != nil {
		err = autorest.NewErrorWithError(err, "sql.CapabilitiesClient", "ListByLocation", resp, "Failure responding to request")
	}

	return
}

// ListByLocationPreparer prepares the ListByLocation request.
func (client CapabilitiesClient) ListByLocationPreparer(locationID string) (*http.Request, error) {
	pathParameters := map[string]interface{}{
		"locationId":     autorest.Encode("path", locationID),
		"subscriptionId": autorest.Encode("path", client.SubscriptionID),
	}

	const APIVersion = "2014-04-01"
	queryParameters := map[string]interface{}{
		"api-version": APIVersion,
	}

	preparer := autorest.CreatePreparer(
		autorest.AsGet(),
		autorest.WithBaseURL(client.BaseURI),
		autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Sql/locations/{locationId}/capabilities", pathParameters),
		autorest.WithQueryParameters(queryParameters))
	return preparer.Prepare(&http.Request{})
}

// ListByLocationSender sends the ListByLocation request. The method will close the
// http.Response Body if it receives an error.
func (client CapabilitiesClient) ListByLocationSender(req *http.Request) (*http.Response, error) {
	return autorest.SendWithSender(client, req)
}

// ListByLocationResponder handles the response to the ListByLocation request. The method always
// closes the http.Response Body.
func (client CapabilitiesClient) ListByLocationResponder(resp *http.Response) (result LocationCapabilities, err error) {
	err = autorest.Respond(
		resp,
		client.ByInspecting(),
		azure.WithErrorUnlessStatusCode(http.StatusOK),
		autorest.ByUnmarshallingJSON(&result),
		autorest.ByClosing())
	result.Response = autorest.Response{Response: resp}
	return
}


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

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace ApiAuth.Controllers
{
    [Authorize, ApiController, Route("user")]
    public class UserController : Controller
    {
        [HttpGet, Route("")]
        public dynamic GetAll()
        {
            var user = User;
            Dictionary<string, string> claims = user.Claims.ToDictionary(c => c.Type, c => c.Value);
            return claims;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
import random
##----------------------------------------------------------------##
from gii.core        import app, signals
from gii.qt          import QtEditorModule

from gii.qt.IconCache                  import getIcon
from gii.qt.controls.GenericTreeWidget import GenericTreeWidget
from gii.qt.controls.GenericListWidget import GenericListWidget
from gii.qt.controls.CategoryList      import CategoryList

from gii.moai.MOAIRuntime import MOAILuaDelegate
from gii.SceneEditor      import SceneEditorModule, getSceneSelectionManager
from gii.qt.helpers   import addWidgetWithLayout, QColorF, unpackQColor

##----------------------------------------------------------------##
from PyQt4           import QtCore, QtGui, uic
from PyQt4.QtCore    import Qt, pyqtSignal

##----------------------------------------------------------------##
from mock import _MOCK, isMockInstance
##----------------------------------------------------------------##

from SceneTool import *

def _getModulePath( path ):
	import os.path
	return os.path.dirname( __file__ ) + '/' + path

def _fixDuplicatedName( names, name, id = None ):
	if id:
		testName = name + '_%d' % id
	else:
		id = 0
		testName = name
	#find duplicated name
	if testName in names:
		return _fixDuplicatedName( names, name, id + 1)
	else:
		return testName

##----------------------------------------------------------------##
class SceneToolBox( SceneEditorModule ):
	name = 'scene_tool_box'
	dependency = [ 'scene_tool_manager' ]

	def onLoad( self ):
		self.window = self.requestDockWindow( 'SceneToolBox',
			title     = 'Tools',
			size      = (120,120),
			minSize   = (120,120),
			dock      = 'bottom'
		)
		ui = self.window.addWidgetFromFile(
			_getModulePath('SceneToolBox.ui')
		)
		self.window.setStayOnTop( True )
		self.window.show()
		self.window.setObjectName( 'SceneToolBox' )

		self.treeCategory = SceneToolCategoryTreeWidget(
					multiple_selection = False,
					editable           = False,
					drag_mode          = 'internal'
				)
		treeLayout = QtGui.QVBoxLayout( ui.containerTree )
		treeLayout.addWidget( self.treeCategory )
		treeLayout.setMargin( 0 )
		treeLayout.setSpacing( 0 )
		self.treeCategory.parentModule = self

		self.listTools = SceneToolListWidget()
		listLayout = QtGui.QVBoxLayout( ui.containerList )
		listLayout.addWidget( self.listTools )
		listLayout.setMargin( 0 )
		listLayout.setSpacing( 0 )
		self.listTools.parentModule = self
		self.listTools.setIconSize( QtCore.QSize( 64, 64 ) )
		# self.listTools.setGridSize( QtCore.QSize( 80, 6464 ) )

		self.currentCategory = None
		self.currentTool     = None
		self.refreshingTools = False

		signals.connect( 'tool.change',  self.onSceneToolChanged )
		signals.connect( 'tool_category.update',  self.onSceneToolCategoryUpdate )

	def onStart( self ):
		self.treeCategory.rebuild()

	def onCategorySelectionChanged( self ):
		for category in self.treeCategory.getSelection():
			self.currentCategory = category
			self.rebuildListTools()
			return
		self.currentCategory = None
		self.rebuildListTools()

	def rebuildListTools( self ):
		self.refreshingTools = True
		self.listTools.rebuild()
		activeTool = self.getSceneToolManager().getActiveTool()
		if activeTool and self.listTools.hasNode( activeTool ):
			self.listTools.selectNode( activeTool, goto = True )
		self.refreshingTools = False

	def getToolsInCurrentCategory( self ):
		category = self.currentCategory
		if category:
			return category.getToolList()
		else:
			return []

	def setActiveTool( self, tool ):
		if self.refreshingTools: return
		if not tool: return
		self.currentTool = tool
		self.getSceneToolManager().setActiveTool( tool )

	def onSceneToolChanged( self, tool ):
		if tool == self.currentTool: return
		category = tool.getCategory()
		if not self.treeCategory.hasNode( category ): return
		self.treeCategory.selectNode( category )
		if not self.listTools.hasNode( tool ):
			self.listTools.selectNode( None )
		else:
			self.listTools.selectNode( tool, goto = True )

	def onSceneToolCategoryUpdate( self, category ):
		if category == self.currentCategory:
			self.rebuildListTools()

##----------------------------------------------------------------##
class SceneToolCategoryTreeItemDelegate( QtGui.QStyledItemDelegate ):
	def sizeHint( self, option, index ):
		return QtCore.QSize( 10, 24 )

##----------------------------------------------------------------##
class SceneToolCategoryTreeWidget( GenericTreeWidget ):
	def __init__( self, *arg, **kwargs ):
		super( SceneToolCategoryTreeWidget, self ).__init__( *arg, **kwargs )
		self.headerItem().setHidden( True )
		self.setAttribute(Qt.WA_MacShowFocusRect, False)
		self.setItemDelegate( SceneToolCategoryTreeItemDelegate() )

	def getHeaderInfo( self ):
		return [ ('Name',100) ]

	def getRootNode( self ):
		return app.getModule( 'scene_tool_manager' ).getRootCategory()

	def getNodeParent( self, node ): # reimplemnt for target node
		return node.getParent()

	def getNodeChildren( self, node ):
		return node.getChildren()

	def updateItemContent( self, item, node, **option ):
		iconName = node.getIcon()
		item.setIcon( 0, getIcon( iconName ) )
		item.setText( 0, node.getName() )

	def onItemSelectionChanged(self):
		selections = self.getSelection()
		self.parentModule.onCategorySelectionChanged()

##----------------------------------------------------------------##
class SceneToolListWidget( GenericListWidget ):
	def __init__( self, *args, **option ):
		super( SceneToolListWidget, self ).__init__( *args )
		self.setAttribute(Qt.WA_MacShowFocusRect, False)
		self.setWrapping( True )
		self.setResizeMode( QtGui.QListView.Adjust  )

	def getItemFlags( self, node ):
		return {}

	def getDefaultOptions( self ):
		return None

	def getNodes( self ):
		return self.parentModule.getToolsInCurrentCategory()

	def updateItemContent( self, item, node, **option ):
		item.setText( node.getName() )
		item.setIcon( getIcon( node.getIcon() ) )

	def onItemSelectionChanged(self):
		node = self.getFirstSelection()
		self.parentModule.setActiveTool( node )


text:
package ly.stealth.mesos.kafka

import java.util
import scala.collection.JavaConversions._
import scala.util.parsing.json.JSON
import java.io.{File, IOException}
import java.net.{Inet4Address, InetAddress, NetworkInterface}

object Util {
  Class.forName(kafka.utils.Json.getClass.getName) // init class
  private def parseNumber(s: String): Number =
    if (s.contains(".")) {
      s.toDouble
    } else {
      try { java.lang.Integer.parseInt(s) }
      catch { case e: java.lang.NumberFormatException => s.toLong }
    }

  JSON.globalNumberParser = parseNumber
  JSON.perThreadNumberParser = parseNumber
  private val jsonLock = new Object

  def parseJson(json: String): Map[String, Object] = {
    jsonLock synchronized {
      val node: Map[String, Object] = JSON.parseFull(json).getOrElse(null).asInstanceOf[Map[String, Object]]
      if (node == null) throw new IllegalArgumentException("Failed to parse json: " + json)
      node
    }
  }

  var terminalWidth: Int = getTerminalWidth
  private def getTerminalWidth: Int = {
    val file: File = File.createTempFile("getTerminalWidth", null)
    file.delete()

    var width = 80
    try {
      new ProcessBuilder(List("bash", "-c", "tput cols"))
        .inheritIO().redirectOutput(file).start().waitFor()

      val source = scala.io.Source.fromFile(file)
      width = try Integer.valueOf(source.mkString.trim) finally source.close()
    } catch {
      case e: IOException => /* ignore */
      case e: NumberFormatException => /* ignore */
    }

    file.delete()
    width
  }

  class BindAddress(s: String) {
    private var _source: String = null
    private var _value: String = null

    def source: String = _source
    def value: String = _value

    parse
    def parse {
      val idx = s.indexOf(":")
      if (idx != -1) {
        _source = s.substring(0, idx)
        _value = s.substring(idx + 1)
      } else
        _value = s

      if (source != null && source != "if")
        throw new IllegalArgumentException(s)
    }

    def resolve(): String = {
      _source match {
        case null => resolveAddress(_value)
        case "if" => resolveInterfaceAddress(_value)
        case _ => throw new IllegalStateException("Failed to resolve " + s)
      }
    }

    def resolveAddress(addressOrMask: String): String = {
      if (!addressOrMask.endsWith("*")) return addressOrMask
      val prefix = addressOrMask.substring(0, addressOrMask.length - 1)

      for (ni <- NetworkInterface.getNetworkInterfaces) {
        val address = ni.getInetAddresses.find(_.getHostAddress.startsWith(prefix)).getOrElse(null)
        if (address != null) return address.getHostAddress
      }

      throw new IllegalStateException("Failed to resolve " + s)
    }

    def resolveInterfaceAddress(name: String): String = {
      val ni = NetworkInterface.getNetworkInterfaces.find(_.getName == name).getOrElse(null)
      if (ni == null) throw new IllegalStateException("Failed to resolve " + s)

      val addresses: util.Enumeration[InetAddress] = ni.getInetAddresses
      val address = addresses.find(_.isInstanceOf[Inet4Address]).getOrElse(null)
      if (address != null) return address.getHostAddress

      throw new IllegalStateException("Failed to resolve " + s)
    }

    override def hashCode(): Int = 31 * _source.hashCode + _value.hashCode

    override def equals(o: scala.Any): Boolean = {
      if (!o.isInstanceOf[BindAddress]) return false
      val address = o.asInstanceOf[BindAddress]
      _source == address._source && _value == address._value
    }

    override def toString: String = s
  }

  def readLastLines(file: File, n: Int, maxBytes: Int = 102400): String = {
    require(n > 0)

    val raf = new java.io.RandomAccessFile(file, "r")
    val fileLength: Long = raf.length()
    var line = 0
    var pos: Long = fileLength - 1
    var found = false
    var nlPos = pos

    try {
      while (pos != -1 && !found) {
        raf.seek(pos)

        if (raf.readByte() == 10) {
          if (pos != fileLength - 1) {
            line += 1
          }
          nlPos = pos
        }

        if (line == n) found = true
        if (fileLength - pos > maxBytes) found = true

        if (!found) pos -= 1
      }

      if (pos == -1) pos = 0

      if (line == n) {
        pos = pos + 1
      } else if (fileLength - pos > maxBytes) {
        pos = nlPos + 1
      }

      raf.seek(pos)

      val buffer = new Array[Byte]((fileLength - pos).toInt)

      raf.read(buffer, 0, buffer.length)

      val str = new String(buffer, "UTF-8")

      str
    } finally {
      raf.close()
    }
  }
}


text:
namespace TheCodeBookProject.Data.Models
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel.DataAnnotations.Schema;
    using System.Threading.Tasks;
    using System.Security.Claims;

    using Microsoft.AspNet.Identity;
    using Microsoft.AspNet.Identity.EntityFramework;

    public class User : IdentityUser
    {
        private ICollection<Project> allProjects;
        private ICollection<ProjectNotification> invitations;
        private ICollection<ProjectNotification> applications;

        public User()
            : base()
        {
            this.allProjects = new HashSet<Project>();
            this.invitations = new HashSet<ProjectNotification>();
            this.applications = new HashSet<ProjectNotification>();
        }

        public bool IsDeactivated { get; set; }

        [Required]
        [MaxLength(30)]
        public string FirstName { get; set; }

        [Required]
        [MaxLength(30)]
        public string LastName { get; set; }

        [Column(TypeName = "Date")]
        public DateTime DateOfBirth { get; set; }

        public int Rating { get; set; }

        public int Votes { get; set; }

        [MaxLength(300)]
        public string AboutMe { get; set; }

        [MaxLength(100)]
        public string Knowledge { get; set; }

        [MaxLength(100)]
        public string Skills { get; set; }

        public int? MyCompanyId { get; set; }

        public virtual Company MyCompany { get; set; }

        [MaxLength(100)]
        public string ImageUrl { get; set; }

        public virtual ICollection<ProjectNotification> Invitations
        {
            get { return this.invitations; }
            set { this.invitations = value; }
        }

        public virtual ICollection<ProjectNotification> Applications
        {
            get { return this.applications; }
            set { this.applications = value; }
        }

        public virtual ICollection<Project> Projects
        {
            get { return this.allProjects; }
            set { this.allProjects = value; }
        }

        public ClaimsIdentity GenerateUserIdentity(UserManager<User> manager)
        {
            ClaimsIdentity userIdentity = manager
                .CreateIdentity(this, DefaultAuthenticationTypes.ApplicationCookie);
            return userIdentity;
        }

        public Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<User> manager)
        {
            return Task.FromResult(GenerateUserIdentity(manager));
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!-- From: file:/C:/Users/David/SkyDrive/Android%20Studio%20Projects/DistoApp/Application/src/main/res/values-v21/base-template-styles.xml -->
    <eat-comment/>
    <style name="Theme.Base" parent="android:Theme.Material.Light">
    </style>
</resources>


text:
template <typename T>
T gsin(T num){
	return static_cast<T>(sin(num));
}
template <typename T>
T gcos(T num){
	return static_cast<T>(cos(num));
}

template <typename T>
T between(T value, T min, T max){
	return MAX(min, MIN(value, max));
};

float interpolateLinear(float minValue, float maxValue, float scale) {
    return between((maxValue - minValue) * scale + minValue, minValue, maxValue);
};

template <typename T>
T interpolateSmooth(T a, T b, float scale) {
    float f = (T)(1.0 - cos(scale * M_PI)) * 0.5;

    return a * (1.0 - f) + b * f;
};

template <typename T>
T random(T min, T max){
	return min + static_cast <T>(rand()) / ( static_cast <T>(RAND_MAX / (max - min)));
};


text:
module Timeline
  class Track < ActiveRecord::Base
    serialize :model_changes
    attr_accessible :action, :item_id, :model_changes, :model_name
    default_scope order('created_at DESC')
  end
end


text:
# pico

    require_once 'pico.php';

    $app = new Pico;

    $app->get('/', function() {
      return 'hello world!';
    });

    $app->run();

pico is a fun project written in php and for developers who know what they do.
!!! use it at your own risk !!! :-)

## features + examples

### ... uses regex for routing

    $app->get('/profile/(\d+)', function($id) {
      return "profile #$id";
    });

    $app->get('/([a-zA-Z]+)?', function($name = 'world') {
      return "hello $name!";
    });

### ... supports all http verbs

    $app->get('/user/(\d+)', function() { /* ... */ });
    $app->put('/user/(\d+)', function() { /* ... */ });
    $app->post('/users', function() { /* ... */ });
    $app->delete('/user/(\d+)', function() { /* ... */ });

and anything that the client/browser sends as request method, for instance:

    $app->foo('/bar', function() {
      return 'yes';
    });

    $ curl --insecure -X FOO https://localhost:8080/app.php/bar
    yes

### ... is fat free and comes without any helper

    function redirect($url, $statusCode = 303, $message = null) {
      header('Location: ' . $url, true, $statusCode); die($message);
    };

    $app->get('/', function() {
      redirect('/foo');
    });

### ... debug handling

if (php_sapi_name() == 'cli-server') {
  ini_set('display', true);
  error_reporting(-1);
  mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
}

### ... db connections

    function connectToDb() {
      $host = "localhost";
      $db = $username = $password = "pico";

      $db = new mysqli($host, $username, $password, $db);

      if ($db->connect_errno) {
        die("failed to connect to db: (" . $db->connect_errno . ") " . $db->connect_error);
      }

      return $db;
    }

    // app initialization

    $app->get('/(a-zA-Z0-9){3,}', function($username) {
      $db = connectToDb();

      if ($stmt = $db->prepare("SELECT name, email FROM be_sessions WHERE username = ? LIMIT 1")) {
        $stmt->bind_param('s', $username);
        $stmt->execute();
        $stmt->bind_result($name, $email);
        $stmt->fetch();

        $response = "$name <$email>";

        $stmt->close();
      } else {
        $response = 'unknown user';
      }

      return $response;
    });

    // other routes


text:
import { Replacer } from './replacer';

export class Rule {
  matchers: RegExp[];
  replacer: Replacer;

  constructor(matchers: RegExp[], replacer: Replacer) {
    this.matchers = matchers;
    this.replacer = replacer;
  }
  toString() {
    return `Rule{matchers: ${this.matchers}, replacer: ${this.replacer}}`;
  }
}


text:
package org.jkiss.dbeaver.ext.mysql.edit;

import org.jkiss.code.Nullable;
import org.jkiss.dbeaver.DBException;
import org.jkiss.dbeaver.ext.mysql.MySQLConstants;
import org.jkiss.dbeaver.ext.mysql.model.MySQLTable;
import org.jkiss.dbeaver.ext.mysql.model.MySQLTableBase;
import org.jkiss.dbeaver.ext.mysql.model.MySQLTableColumn;
import org.jkiss.dbeaver.model.DBPDataKind;
import org.jkiss.dbeaver.model.DBPEvaluationContext;
import org.jkiss.dbeaver.model.DBUtils;
import org.jkiss.dbeaver.model.edit.DBECommandContext;
import org.jkiss.dbeaver.model.edit.DBEObjectRenamer;
import org.jkiss.dbeaver.model.edit.DBEObjectReorderer;
import org.jkiss.dbeaver.model.edit.DBEPersistAction;
import org.jkiss.dbeaver.model.impl.DBSObjectCache;
import org.jkiss.dbeaver.model.impl.edit.DBECommandAbstract;
import org.jkiss.dbeaver.model.impl.edit.SQLDatabasePersistAction;
import org.jkiss.dbeaver.model.impl.sql.edit.struct.SQLTableColumnManager;
import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor;
import org.jkiss.dbeaver.model.sql.SQLUtils;
import org.jkiss.dbeaver.model.struct.DBSDataType;
import org.jkiss.dbeaver.model.struct.DBSObject;
import org.jkiss.utils.CommonUtils;

import java.sql.Types;
import java.util.List;
import java.util.Locale;
import java.util.Map;

/**
 * MySQL table column manager
 */
public class MySQLTableColumnManager extends SQLTableColumnManager<MySQLTableColumn, MySQLTableBase>
    implements DBEObjectRenamer<MySQLTableColumn>, DBEObjectReorderer<MySQLTableColumn>
{

    private final ColumnModifier<MySQLTableColumn> MySQLDataTypeModifier = (monitor, column, sql, command) ->
        sql.append(' ').append(column.getFullTypeName());

    private final ColumnModifier<MySQLTableColumn> CharsetModifier = (monitor, column, sql, command) -> {
        if (column.getDataKind() == DBPDataKind.STRING && column.getCharset() != null) {
            sql.append(" CHARACTER SET ").append(column.getCharset().getName()); //$NON-NLS-1$
        }
    };

    private final ColumnModifier<MySQLTableColumn> CollationModifier = (monitor, column, sql, command) -> {
        if (column.getDataKind() == DBPDataKind.STRING && column.getCollation() != null) {
            sql.append(" COLLATE ").append(column.getCollation().getName()); //$NON-NLS-1$
        }
    };

    private final ColumnModifier<MySQLTableColumn> ExtraInfoModifier = (monitor, column, sql, command) -> {
        if (!CommonUtils.isEmpty(column.getExtraInfo())) {
            if (MySQLConstants.EXTRA_INFO_VIRTUAL_GENERATED.equalsIgnoreCase(column.getExtraInfo())) {
                if (!CommonUtils.isEmpty(column.getGenExpression())) {
                    sql.append(" GENERATED ALWAYS AS (").append(column.getGenExpression()).append(") VIRTUAL"); //$NON-NLS-1$ //$NON-NLS-2$
                } else {
                    log.debug("No virtual column generate expression found for " + column.getName());
                }
            } else {
                sql.append(" ").append(column.getExtraInfo()); //$NON-NLS-1$
            }
        }
    };

    @Nullable
    @Override
    public DBSObjectCache<? extends DBSObject, MySQLTableColumn> getObjectsCache(MySQLTableColumn object)
    {
        return object.getParentObject().getContainer().getTableCache().getChildrenCache(object.getParentObject());
    }

    protected ColumnModifier[] getSupportedModifiers(MySQLTableColumn column, Map<String, Object> options)
    {
        return new ColumnModifier[] {MySQLDataTypeModifier, CharsetModifier, CollationModifier, DefaultModifier, ExtraInfoModifier, NullNotNullModifier};
    }

    @Override
    public StringBuilder getNestedDeclaration(DBRProgressMonitor monitor, MySQLTableBase owner, DBECommandAbstract<MySQLTableColumn> command, Map<String, Object> options)
    {
        StringBuilder decl = super.getNestedDeclaration(monitor, owner, command, options);
        final MySQLTableColumn column = command.getObject();
        if (column.isAutoGenerated() &&
            (CommonUtils.isEmpty(column.getExtraInfo()) || !column.getExtraInfo().toLowerCase(Locale.ENGLISH).contains(MySQLConstants.EXTRA_AUTO_INCREMENT)))
        {
            decl.append(" AUTO_INCREMENT"); //$NON-NLS-1$
        }
        if (!CommonUtils.isEmpty(column.getComment())) {
            decl.append(" COMMENT ").append(SQLUtils.quoteString(column, column.getComment())); //$NON-NLS-1$
        }
        return decl;
    }

    @Override
    protected MySQLTableColumn createDatabaseObject(final DBRProgressMonitor monitor, final DBECommandContext context, final Object container, Object copyFrom, Map<String, Object> options)
    {
        MySQLTable table = (MySQLTable) container;

        MySQLTableColumn column = new MySQLTableColumn(table);
        DBSDataType columnType = findBestDataType(table.getDataSource(), "varchar"); //$NON-NLS-1$
        column.setName(getNewColumnName(monitor, context, table));
        final String typeName = columnType == null ? "integer" : columnType.getName().toLowerCase();
        column.setTypeName(typeName); //$NON-NLS-1$
        column.setMaxLength(columnType != null && columnType.getDataKind() == DBPDataKind.STRING ? 100 : 0);
        column.setValueType(columnType == null ? Types.INTEGER : columnType.getTypeID());
        column.setOrdinalPosition(table.getCachedAttributes().size() + 1);
        column.setFullTypeName(DBUtils.getFullTypeName(column));
        return column;
    }

    @Override
    protected void addObjectModifyActions(DBRProgressMonitor monitor, List<DBEPersistAction> actionList, ObjectChangeCommand command, Map<String, Object> options)
    {
        final MySQLTableColumn column = command.getObject();

        actionList.add(
            new SQLDatabasePersistAction(
                "Modify column",
                "ALTER TABLE " + column.getTable().getFullyQualifiedName(DBPEvaluationContext.DDL) + " MODIFY COLUMN " + getNestedDeclaration(monitor, column.getTable(), command, options))); //$NON-NLS-1$ //$NON-NLS-2$
    }

    @Override
    public void renameObject(DBECommandContext commandContext, MySQLTableColumn object, String newName) throws DBException {
        processObjectRename(commandContext, object, newName);
    }

    @Override
    protected void addObjectRenameActions(DBRProgressMonitor monitor, List<DBEPersistAction> actions, ObjectRenameCommand command, Map<String, Object> options)
    {
        final MySQLTableColumn column = command.getObject();

        actions.add(
            new SQLDatabasePersistAction(
                "Rename column",
                "ALTER TABLE " + column.getTable().getFullyQualifiedName(DBPEvaluationContext.DDL) + " CHANGE " +
                    DBUtils.getQuotedIdentifier(column.getDataSource(), command.getOldName()) + " " +
                    getNestedDeclaration(monitor, column.getTable(), command, options)));
    }

    @Override
    protected void addObjectReorderActions(DBRProgressMonitor monitor, List<DBEPersistAction> actions, ObjectReorderCommand command, Map<String, Object> options) {
        final MySQLTableColumn column = command.getObject();
        String order = "FIRST";
        if (column.getOrdinalPosition() > 0) {
            for (MySQLTableColumn col : command.getObject().getTable().getCachedAttributes()) {
                if (col.getOrdinalPosition() == column.getOrdinalPosition() - 1) {
                    order = "AFTER " + DBUtils.getQuotedIdentifier(col);
                    break;
                }
            }
        }
        actions.add(
            new SQLDatabasePersistAction(
                "Reorder column",
                "ALTER TABLE " + column.getTable().getFullyQualifiedName(DBPEvaluationContext.DDL) + " CHANGE " +
                    DBUtils.getQuotedIdentifier(command.getObject()) + " " +
                    getNestedDeclaration(monitor, column.getTable(), command, options) + " " + order));
    }

    ///////////////////////////////////////////////
    // Reorder

    @Override
    public int getMinimumOrdinalPosition(MySQLTableColumn object) {
        return 1;
    }

    @Override
    public int getMaximumOrdinalPosition(MySQLTableColumn object) {
        return object.getTable().getCachedAttributes().size();
    }

    @Override
    public void setObjectOrdinalPosition(DBECommandContext commandContext, MySQLTableColumn object, List<MySQLTableColumn> siblingObjects, int newPosition) throws DBException {
        processObjectReorder(commandContext, object, siblingObjects, newPosition);
    }
}


text:
<repast.simphony.visualization.engine.CartesianDisplayDescriptor>
  <name>2D Display</name>
  <type>2D</type>
  <styles>
    <entry>
      <string>Schelling.Agent</string>
      <string>Schelling.AgentStyle2D</string>
    </entry>
  </styles>
  <editedStyles/>
  <netStyles/>
  <editedNetStyles/>
  <frequency>ON_MOVE</frequency>
  <schedParams>
    <start>1.0</start>
    <interval>1.0</interval>
    <priority>-Infinity</priority>
    <duration>-1.0</duration>
    <frequency>REPEAT</frequency>
    <hashCode>0</hashCode>
  </schedParams>
  <layoutClassName>foo.bar.baz</layoutClassName>
  <layoutProjection>Grid</layoutProjection>
  <layoutInterval>0</layoutInterval>
  <layerOrder/>
  <projections>
    <repast.simphony.scenario.data.ProjectionData>
      <id>Grid</id>
      <attributes/>
      <type>grid</type>
    </repast.simphony.scenario.data.ProjectionData>
  </projections>
  <visualizationProperties class="repast.simphony.visualization.UnitSizeLayoutProperties">
    <unitSize>10.0</unitSize>
  </visualizationProperties>
  <projectionDescriptors>
    <entry>
      <string>Grid</string>
      <repast.simphony.visualization.grid.GridProjectionDescriptor>
        <proj reference="../../../../projections/repast.simphony.scenario.data.ProjectionData"/>
        <props>
          <entry>
            <string>repast.simphony.visualization.grid.GridDecorator</string>
            <map>
              <entry>
                <string>UNIT_SIZE</string>
                <float>10.0</float>
              </entry>
              <entry>
                <string>SHOW</string>
                <boolean>false</boolean>
              </entry>
              <entry>
                <string>COLOR</string>
                <int>-16777216</int>
              </entry>
            </map>
          </entry>
        </props>
      </repast.simphony.visualization.grid.GridProjectionDescriptor>
    </entry>
  </projectionDescriptors>
  <props/>
  <valueLayers/>
</repast.simphony.visualization.engine.CartesianDisplayDescriptor>


text:
FROM iron/java:1.8

MAINTAINER Daniel Zohar <daniel@memrise.com>

RUN mkdir -p /etc/snowplow/ && \
    mkdir -p /opt/snowplow/

ENV SNOWPLOW_ZIP snowplow_kinesis_elasticsearch_sink_0.8.0_rc1_2x.zip
ENV SNOWPLOW_JAR snowplow-elasticsearch-sink-0.8.0-rc1-2x

WORKDIR /opt/snowplow/
RUN wget http://dl.bintray.com/snowplow/snowplow-generic/${SNOWPLOW_ZIP} && \
    unzip ${SNOWPLOW_ZIP} && \
    rm ${SNOWPLOW_ZIP} && \
    mv ${SNOWPLOW_JAR} snowplow-elasticsearch-sink.jar

ENTRYPOINT ["/usr/bin/java", "-jar", "snowplow-elasticsearch-sink.jar", "--config", "/etc/snowplow/elasticsearch-sink.conf"]


text:
'''
Created on Mar 22, 2014

@author: Simon
'''
import pickle

def load_object(file_name):
    pkl_file = open(file_name, 'rb')
    obj = pickle.load(pkl_file)
    pkl_file.close()
    return obj

def save_object(file_name, obj):
    output = open(file_name, 'wb')
    # use highest protocol version available
    pickle.dump(obj, output, -1)
    output.close()


text:
    Détails de la sonde Météo

    Détails de la sonde d'arrosage

Température de l'air : {{ meteo.temp }} °C

Humidité ambiante : {{ meteo.humidity }} %

Pression atmosphérique : {{ meteo.pressure }} hpa

Luminosité : {{ meteo.lux }}

    <md-divider></md-divider>

Graphique de la température

    <sr-chart sonde="meteo.id"
              type="temp"
              parser="meteoParser"></sr-chart>

Graphique de la pression atmosphérique

    <sr-chart sonde="meteo.id"
              type="temp"
              parser="pressureParser"></sr-chart>

Graphique de l'humidité ambiante

    <sr-chart sonde="meteo.id"
              type="temp"
              parser="humidityParser"></sr-chart>

        Humidité de la terre :
        {{ humidity.humidity }} %

        Arrosage en cours :
        Oui
        Non

        Arrosage automatique :
        {{ humidity.autoBool ? 'Oui' : 'Non' }}
        ({{ humidity.autoThreshold }}%)

    <md-button class="md-raised md-secondary"
               ng-if="!humidity.watering"
               ng-click="setWaterSwitch(true)">
        Lancer l'arrosage manuel (15 s.)
    </md-button>

    <md-divider></md-divider>

    <md-checkbox class="auto-watering-checkbox"
                 ng-model="humidity.autoBool"
                 ng-change="setWaterAuto(humidity.autoBool)"
                 aria-label="Arrosage automatique">
        Arrosage automatique
    </md-checkbox>

Seuil d'arrosage automatique

        <md-slider flex
                   min="1"
                   max="100"
                   ng-model="humidity.autoThreshold"
                   ng-change="setWaterThreshold(humidity.autoThreshold)"
                   aria-label="Seuil d'arrosage automatique">
        </md-slider>

            <input flex
                   type="number"
                   ng-model="humidity.autoThreshold"
                   aria-label="Seuil d'arrosage automatique">

    <md-divider></md-divider>

Historique de l'humidité

    <sr-chart sonde="humidity.id"
              type="temp"
              parser="humidityParser"></sr-chart>


text:
import logging
import subprocess
import re
from git import GitCommandError

import gifi.epic
import gifi.git_hub
from gifi.command import AggregatedCommand, Command, CommandException
from gifi.git_hub import PULL_REQUEST_COMMIT_TAG
from gifi.utils import git_utils
from gifi.utils.configuration import Configuration, configuration_command
from gifi.utils.git_utils import get_repo, check_repo_is_clean, get_from_last_commit_message

class Feature:
    @staticmethod
    def parse(branch):
        parts = branch.split('/')
        target_remote = parts[0]
        target_branch = '/'.join(parts[1:-1])
        feature = parts[-1]
        return Feature(target_remote, target_branch, feature)

    def __init__(self, target_remote, target_branch, name):
        self.target_remote = target_remote
        self.target_branch = target_branch
        self.name = name

    def to_branch_name(self):
        return "%s/%s/%s" % (self.target_remote, self.target_branch, self.name)

def _start(feature=None, e=None):
    repo = get_repo()

    if e is None:
        e = gifi.epic.select()
    else:
        e = gifi.epic.Epic.parse(e)

    numbered_epic_features = list(map(
        lambda head: head.name.replace(e.to_string() + '/', ''),
        [head for head in repo.heads if re.match(r'%s/[0-9].*' % e.to_string(), head.name)]))
    feature_id = 1
    if len(numbered_epic_features) > 0:
        feature_id = 1 + max(map(
            lambda epic_feature: int('0' + re.sub('_.*', '', epic_feature)),
            numbered_epic_features))

    feature_branch = '%s/%03d' % (e.to_string(), feature_id)
    if feature:
        feature_branch = '%s_%s' % (feature_branch, feature)

    git_utils.check_repo_is_clean(repo)

    print('Starting ', feature_branch)

    _fetch(repo, e.remote)
    repo.create_head(feature_branch, e.to_string())
    repo.heads[feature_branch].set_tracking_branch(repo.remotes[e.remote].refs[e.branch])
    repo.heads[feature_branch].checkout()

def _fetch(repo, remote):
    try:
        repo.git.fetch(remote)
    except GitCommandError as e:
        logging.warn('Unable to fetch: %s' % e)
        print('WARNING: Unable to fetch changes.')

def _publish(message=None):
    repo = get_repo()
    check_repo_is_clean(repo)
    config = configuration(repo)
    _push_working_branch(config, repo)
    if config.publish_with_pull_request:
        gifi.git_hub.request(repo, message)

def _push_working_branch(config, repo):
    current_branch = _current_feature_branch(repo)
    push_params = [config.working_remote, 'HEAD:%s' % current_branch]
    try:
        repo.git.push('-u', *push_params)
    except GitCommandError as e:
        logging.warn('Unable push (publish) feature branch without force: %s' % e)
        message = 'Unable to push your changes ("git push -u %s %s"). Would you like to use force?'
        question = message % tuple(push_params)
        if ask(question):
            repo.git.push('-f', '-u', *push_params)
        else:
            raise CommandException('Manual pull and rebase is required')

def ask(question):
    while True:
        answer = input('%s [yes|no]: ' % question).strip().lower()
        if answer == 'yes':
            return True
        elif answer == 'no':
            return False

def _finish():
    repo = get_repo()
    check_repo_is_clean(repo)
    config = configuration(repo)
    _current_feature_branch(repo)
    _rebase(repo, config)
    feature = current(repo)
    _push_working_branch(config, repo)
    repo.git.push(feature.target_remote, 'HEAD:%s' % feature.target_branch)
    _discard()

def _rebase(repo=None, config=None):
    repo = get_repo(repo)
    if config is None:
        config = configuration(repo)
    feature = current(repo)
    _fetch(repo, feature.target_remote)
    interactive = '-i' if config.finish_with_rebase_interactive else ''
    rebase_cmd = 'git rebase %s/%s %s' % (feature.target_remote, feature.target_branch, interactive)
    rebase_status = subprocess.call(rebase_cmd, shell=True)
    if rebase_status != 0:
        message = 'Rebase finished with an error, please fix it manually and then use "git rebase --continue"'
        raise CommandException(message)

def _discard():
    repo = get_repo()
    config = configuration(repo)
    feature = current(repo)
    if repo.is_dirty():
        if ask("There are uncommitted changes, would you like to remove them"):
            repo.git.reset('--hard', 'HEAD')
        else:
            return
    repo.git.checkout(feature.target_branch)
    try:
        repo.git.push(config.working_remote, ':%s' % feature.to_branch_name())
    except GitCommandError as e:
        logging.warn('Unable to drop remote feature branch: %s' % e)
        print('WARNING: Unable to remove remote feature branch. Maybe it was not yet created?')
    repo.git.branch('-D', feature.to_branch_name())
    repo.git.rebase('%s/%s' % (feature.target_remote, feature.target_branch))
    repo.git.fetch('%s' % config.working_remote, '--prune')

def configuration(repo=None):
    repo = get_repo(repo)
    return Configuration(repo, 'feature', {
        'finish-with-rebase-interactive': (False, 'Should do a rebase interactive during feature finishing'),
        'publish-with-pull-request': (False, 'Should create a pull request during feature publishing'),
        'working-remote': ('origin', 'On which remote you are working at')
    })

def is_on_feature_branch(repo):
    current_branch = git_utils.get_current_branch(repo)
    return current_branch.count('/') > 1

def _current_feature_branch(repo):
    current_branch = git_utils.get_current_branch(repo)
    if not current_branch.count('/') > 1:
        raise CommandException('Please checkout to a feature branch.')
    return current_branch

def current(repo):
    return Feature.parse(_current_feature_branch(repo))

command = AggregatedCommand('feature', 'Manages a feature branches.', [
    Command('start', 'Creates a new feature branch.', _start, '<feature name>'),
    Command('publish', 'Publishes a feature branch to review.', _publish),
    Command('finish', 'Closes and pushes a feature to a feature epic branch.', _finish),
    Command('discard', 'Closes a feature branch without a push.', _discard),
    Command('rebase', 'Rebases current feature on recent epic.', _rebase),
    configuration_command(configuration, 'Configure feature behaviour.')
])


text:
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Fingerprint2 spec runner</title>

  <link rel="shortcut icon" type="image/png" href="lib/jasmine-2.3.4/jasmine_favicon.png">
  <link rel="stylesheet" href="lib/jasmine-2.3.4/jasmine.css">

  <script src="lib/jasmine-2.3.4/jasmine.js"></script>
  <script src="lib/jasmine-2.3.4/jasmine-html.js"></script>
  <script src="lib/jasmine-2.3.4/boot.js"></script>
  <script src="lib/jasmine-2.3.4/terminal.js"></script>

  <!-- include source files here... -->
  <script src="../fingerprint2.js"></script>

  <!-- include spec files here... -->
  <script src="./specs.js"></script>

  <script>
    if(navigator.userAgent.match(/phantom/i)) {
      jasmine.getEnv().addReporter(new jasmineReporters.TerminalReporter({
        verbosity: 3,
        color: true,
        showStack: true
      }));
    }
  </script>
</head>

<body>
</body>
</html>


text:
<?php
namespace app\models;
use Yii;
use yii\db\ActiveRecord;
use yii\data\ActiveDataProvider;
//security login
use yii\web\IdentityInterface;
use yii\base\NotSupportedException; //if not supported exception

class User extends ActiveRecord implements IdentityInterface {

    public $user_created;
    public $user_bulk;
    public $user_password_confirm;
    public $passtext_confirm;
    public $passtext_new;
    public $passtext_new_confirm;
    public $remember_me;
    private $_user=false;

    public static function tableName(){
        return 'sys_user';
    }

    public function rules(){
        return [
            [['passtext','passtext_confirm','passtext_new','passtext_new_confirm'],'required','on'=>'update_password'],
            [['passtext_confirm'], 'validatePasswordOldConfirm','on'=>'update_password'],
        ];
    }

    public function scenarios(){
	$scenarios = parent::scenarios();
	$scenarios['user_add'] = ['user_name','user_password'];//Scenario Values Only Accepted
	return $scenarios;
    }

    public function attributeLabels(){
        return [
            'passtext' => Yii::t('app','password old'),
            'passtext_confirm' => Yii::t('app','confirm password'),
	    'passtext_new' => Yii::t('app','new password'),
	    'passtext_new_confirm' => Yii::t('app','confirm password'),
        ];
    }

    public function getUserData($params)
    {
        $query = User::find()
        ->select(['u.user_id','u.user_name','u.user_email','u2.user_name as user_created','u.user_created_date'])
        ->from('user u')
        ->join('left join','user u2','u2.user_id = u.user_created_by');

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
            'pagination' =>[
                'pageSize' => Yii::$app->params['per_page']
            ]
        ]);

        $dataProvider->setSort([
            'attributes' => [
                'user_name',
                'user_email',
                'user_created' => [
                    'asc' => ['u2.user_name' => SORT_ASC],
                    'desc' => ['u2.user_name' => SORT_DESC],
                    'label' => Yii::t('app/backend','created by'),
                    'default' => SORT_ASC
                ],

            ]
        ]);

        if ((!$this->load($params)) && ($this->validate())) {
            return $dataProvider;
        }

        $query->andFilterWhere([
            'user_id' => $this->user_id,
        ]);
        $query->andFilterWhere(['like', 'u.user_name',  $this->user_name]);
        $query->andFilterWhere(['like', 'u.user_email', $this->user_email]);
        $query->andFilterWhere(['like', 'u2.user_name', $this->user_created]);
        return $dataProvider;
    }

    public function validatePasswordConfirm($attribute,$params){
        if($this->user_password_confirm!=$this->user_password)
            return $this->addError($attribute,Yii::t('app/message','msg not password same'));
    }

    public static function findByUsername($username){
        return static::findOne(['user_name' => $username]);
    }

    public function validateUsername($attribute,$params){
        if(static::findByUsername($this->user_name))
            return $this->addError($attribute,Yii::t('app/message','msg username has already'));
    }

    public function getSave(){
       $user = new User();
       $user->user_name  = $this->user_name;
       $user->user_email = $this->user_email;
       $user->user_password = Yii::$app->security->generatePasswordHash($this->user_password);
       $user->user_created_by = Yii::$app->user->getId();
       $user->user_created_date = date('Y-m-d H:m:s');
       $user->save();
       return true;
    }

    public function getUpdate($key){
       $user = new User();
       $user = $user->findOne($key);
       $user->user_email = $this->user_email;
       $user->user_updated_by = Yii::$app->user->getId();
       $user->user_updated_date = date('Y-m-d H:m:s');
       $user->update();
       return true;
    }

    public function getUpdatePassword($key){
       if($this->validate()){
	    $user = new User();
	    $user = $user->find()->where(['employee_id'=>$key])->one();
	    $user->passtext = $this->passtext_new;
	    $user->sysuser = Yii::$app->user->getId();
	    $user->sysdate = date('Y-m-d H:m:s');
	    $user->update();
	    return true;
       }
    }

    /**
     * Section Under Login Security
     **/
    public function getLogin(){
        if($this->validate())
            return Yii::$app->user->login($this->getUser(),$this->remember_me ? 3600 * 24 * 30 : 0);
        else return false;
    }

    /**
     * Finds user by [[user_name]]
     * @return User|null
     * getUser from getLogin
     */
    public function getUser(){
        if ($this->_user === false) {
            $this->_user = User::findByUsername($this->user_name);
        }
        return $this->_user;
    }

    public function validatePasswordOldConfirm($attribute,$params){
        if (!$this->hasErrors()) {
            if ($this->passtext != $this->passtext_confirm) {
                $this->addError($attribute, Yii::t('app/message','msg password old confirm not same'));
            }
        }
    }

    public function validatePasswordNewConfirm($attribute,$params){
        if (!$this->hasErrors()) {
            if ($this->passtext_new != $this->passtext_new_confirm) {
                $this->addError($attribute, Yii::t('app/message','msg password new confirm not same'));
            }
        }
    }

    /**
     * abstract model identity interface $app->user->login
     * findIdentity , findIdentityByAccessToken , getId , getAuthKey , validateAuthKey
     */

    public static function findIdentity($id){
        return static::findOne(['user_id' => $id]);
    }

    public static function findIdentityByAccessToken($token, $type = null){
        throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.');
    }

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

    public function getAuthKey(){
        return $this->user_auth_key;
    }

    public function validateAuthKey($authKey){
        return $this->getAuthKey() === $authKey;
    }

    /**
     * Validate Login Password
     * */

    public function validatePassword($password){
        return Yii::$app->security->validatePassword($password, $this->user_password);
    }
}


text:
require 'national_identification_number/base'

module NationalIdentificationNumber
  class Danish < Base
    attr_reader :date

    protected

    def repair
      super
      @number.gsub!(/[^0-9]/, '')
      if (matches = @number.match(/\A(?<birthday>[0-9]{6})(?<checksum>[0-9]{4})\z/))
        birthday, checksum = %w[birthday checksum].map { |group| matches[group] }
        @number = "#{birthday}-#{checksum}"
      end
    end

    def validate
      if (matches = @number.match(/\A(?<day>\d{2})(?<month>\d{2})(?<year>\d{2})-(?<serial>\d{3})(?<checksum>\d{1})\z/))
        day, month, year, serial, checksum = %i[day month year serial checksum].map { |group| matches[group] }
        begin
          @date = Date.parse("#{full_year(serial, year)}-#{month}-#{day}")
          @valid = true
          @number = "#{day}#{month}#{year}-#{serial}#{checksum}"
        rescue ArgumentError
        end
      end
    end

    private

    def full_year(serial, year)
      century(serial, year.to_i) + year.to_i
    end

    def century(serial, year)
      first_digit = serial[0].to_i
      return 1800 if (5..8).include?(first_digit) && year > 57
      return 2000 if (4..9).include?(first_digit) && year < 37
      1900
    end
  end
end


text:
#if !defined(CETTY_CHANNEL_CHANNELMESSAGETRANSFER_H)
#define CETTY_CHANNEL_CHANNELMESSAGETRANSFER_H

/*
 * Copyright (c) 2010-2012 frankee zhou (frankee.zhou at gmail dot com)
 *
 * Distributed under under the Apache License, version 2.0 (the "License").
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at:
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */

#include <vector>
#include <cetty/buffer/ChannelBufferPtr.h>
#include <cetty/channel/ChannelHandlerContext.h>
#include <cetty/channel/ChannelMessageContainer.h>

namespace cetty {
namespace channel {

using namespace cetty::buffer;

enum TransferDirection {
    TRANSFER_INBOUND,
    TRANSFER_OUTBOUND
};

template<typename T, typename U, int TransferType>
class ChannelMessageTransfer {
public:
    U* nextContainer();

    void resetNextContainer();
    void resetNextContainer(U*);

    bool unfoldAndAdd(const T& msg);
    void write(const T& msg, const ChannelFuturePtr& future);
};

template<>
class ChannelMessageTransfer<VoidMessage, VoidMessageContainer, TRANSFER_INBOUND> {
public:
    ChannelMessageTransfer(ChannelHandlerContext& ctx) {}

    VoidMessageContainer* nextContainer() { return NULL; }

    void resetNextContainer() {}
    void resetNextContainer(VoidMessageContainer*) {}

    bool unfoldAndAdd(const VoidMessage& msg) { return false; }
    void write(const VoidMessage& msg, const ChannelFuturePtr& future) {}
};

template<>
class ChannelMessageTransfer<VoidMessage, VoidMessageContainer, TRANSFER_OUTBOUND> {
public:
    ChannelMessageTransfer(ChannelHandlerContext& ctx) {}

    VoidMessageContainer* nextContainer() { return NULL; }

    void resetNextContainer() {}
    void resetNextContainer(VoidMessageContainer*) {}

    bool unfoldAndAdd(const VoidMessage& msg) { return false; }
    void write(const VoidMessage& msg, const ChannelFuturePtr& future) {}
};

template<class T>
class ChannelMessageTransfer<T, ChannelMessageContainer<T, MESSAGE_BLOCK>, TRANSFER_INBOUND> {
public:
    typedef ChannelMessageContainer<T, MESSAGE_BLOCK> MessageContainer;

public:
    ChannelMessageTransfer(ChannelHandlerContext& ctx)
        : ctx_(ctx),
          container_() {
    }

    ChannelMessageTransfer(ChannelPipeline& pipeline) {}

    void resetNextContainer() {
        container_ = NULL;
    }

    void resetNextContainer(MessageContainer* container) {
        container_ = container;
    }

    MessageContainer* nextContainer() {
        return container_;
    }

    bool unfoldAndAdd(const T& msg) {
        if (!container_) {
            container_ = ctx_.nextInboundMessageContainer<MessageContainer>();
        }

        if (container_ && !!msg) {
            container_->addMessage(msg);
            return true;
        }

        return false;
    }

    void write(const T& msg, const ChannelFuturePtr& future) {
        BOOST_ASSERT("InboundMessage Transfer does not support write");
    }

private:
    ChannelHandlerContext& ctx_;
    MessageContainer* container_;
};

template<typename T>
class ChannelMessageTransfer<T, ChannelMessageContainer<T, MESSAGE_BLOCK>, TRANSFER_OUTBOUND> {
public:
    typedef ChannelMessageContainer<T, MESSAGE_BLOCK> MessageContainer;

public:
    ChannelMessageTransfer(ChannelHandlerContext& ctx)
        : ctx_(ctx),
          container_() {
    }

    MessageContainer* nextContainer() {
        return container_;
    }

    void resetNextContainer() {
        container_ = NULL;
    }

    void resetNextContainer(MessageContainer* container) {
        container_ = container;
    }

    bool unfoldAndAdd(const T& msg) {
        if (!container_) {
            container_ = ctx_.nextOutboundMessageContainer<MessageContainer>();
        }

        if (container_&& !!msg) {
            container_->addMessage(msg);
            return true;
        }

        if (!!msg) {
            LOG_WARN << "have not found the next container for the message";
        }

        return false;
    }

    void write(const T& msg, const ChannelFuturePtr& future) {
        if (unfoldAndAdd(msg)) {
            ctx_.flush(future);
        }
    }

private:
    ChannelHandlerContext& ctx_;
    MessageContainer* container_;
};

template<>
class ChannelMessageTransfer<ChannelBufferPtr, ChannelBufferContainer, TRANSFER_INBOUND> {
public:
    ChannelMessageTransfer(ChannelHandlerContext& ctx)
        : ctx_(ctx),
          container_() {
    }

    ChannelBufferContainer* nextContainer() {
        return container_;
    }

    void resetNextContainer() {
        container_ = NULL;
    }

    void resetNextContainer(ChannelBufferContainer* container) {
        container_ = container;
    }

    bool unfoldAndAdd(const ChannelBufferPtr& msg) {
        if (!container_) {
            ctx_.nextInboundMessageContainer<ChannelBufferContainer>();
        }

        if (container_ && msg) {
            container_->addMessage(msg);
            return true;
        }

        return false;
    }

    void write(const ChannelBufferPtr& msg, const ChannelFuturePtr& future) {
        BOOST_ASSERT("InboundBuffer Transfer does not support write");
    }

private:
    ChannelHandlerContext& ctx_;
    ChannelBufferContainer* container_;
};

template<>
class ChannelMessageTransfer<ChannelBufferPtr, ChannelBufferContainer, TRANSFER_OUTBOUND> {
public:
    ChannelMessageTransfer(ChannelHandlerContext& ctx)
        : ctx_(ctx),
          container_() {
    }

    ChannelBufferContainer* nextContainer() {
        return container_;
    }

    void resetNextContainer() {
        container_ = NULL;
    }

    void resetNextContainer(ChannelBufferContainer* container) {
        container_ = container;
    }

    bool unfoldAndAdd(const ChannelBufferPtr& msg) {
        if (!container_) {
            container_ = ctx_.nextOutboundMessageContainer<ChannelBufferContainer>();
        }

        if (container_ && msg) {
            container_->addMessage(msg);
            return true;
        }

        return false;
    }

    void write(const ChannelBufferPtr& msg,
               const ChannelFuturePtr& future) {
        if (unfoldAndAdd(msg)) {
            ctx_.flush(future);
        }
    }

private:
    ChannelHandlerContext& ctx_;
    ChannelBufferContainer* container_;
};

}
}

#endif //#if !defined(CETTY_CHANNEL_CHANNELMESSAGETRANSFER_H)

// Local Variables:
// mode: c++
// End:


text:
#ifndef HALM_GENERIC_POINTER_ARRAY_H_
#define HALM_GENERIC_POINTER_ARRAY_H_
/*----------------------------------------------------------------------------*/
#include <xcore/containers/tg_array.h>
#include <xcore/helpers.h>
/*----------------------------------------------------------------------------*/
BEGIN_DECLS

DEFINE_ARRAY(void *, Pointer, pointer)

END_DECLS
/*----------------------------------------------------------------------------*/
#endif /* HALM_GENERIC_POINTER_ARRAY_H_ */


text:
require "lexigen/version"
require "matrix"
require "lexigen/state_machine"
require "lexigen/token"
require "lexigen/generator"
require "lexigen/generators/ruby_generator"

module Lexigen

  # Easily define a set of state machines and their transitions
  # @example
  # Lexigen.define do
  #   from(0).to(1).if(/\d/)
  #   from(1).to(1).if(/\d/)
  #   from(1).unless(/\d/).return_as(:integer)
  # end
  def self.define(&block)
    definition = StateMachine.new
    definition.instance_eval(&block)
    definition.to_matrix
  end

end


text:
package com.asakusafw.operator.model;

import java.util.List;
import java.util.Objects;

import javax.lang.model.element.TypeElement;

/**
 * Represents a class with operators.
 */
public class OperatorClass {

    private final TypeElement declaration;

    private final List<OperatorElement> elements;

    /**
     * Creates a new instance.
     * @param declaration declaring type
     * @param elements operator elements
     * @throws IllegalArgumentException if some parameters were {@code null}
     */
    public OperatorClass(TypeElement declaration, List<OperatorElement> elements) {
        this.declaration = Objects.requireNonNull(declaration, "declaration must not be null"); //$NON-NLS-1$
        this.elements = Objects.requireNonNull(elements, "elements must not be null"); //$NON-NLS-1$
    }

    /**
     * Returns the declaring class of this.
     * @return the declaring class
     */
    public TypeElement getDeclaration() {
        return declaration;
    }

    /**
     * Returns the operator elements.
     * @return the elements
     */
    public List<OperatorElement> getElements() {
        return elements;
    }
}


text:
#ifndef _win32c_net_tcp_threaded_server_hpp__
#define _win32c_net_tcp_threaded_server_hpp__

// Copyright(c) Andre Caron, 2009-2010
//
// This document is covered by the Artistic License 2.0 (Open Source Initiative
// approved license). A copy of the license should have been provided alongside
// this software package (see "license.rtf"). If not, the license is available
// online at "http://www.opensource.org/licenses/artistic-license-2.0.php".

#include <w32.net.hpp>

namespace {

    int transaction
        ( int argc, wchar_t ** argv, w32::net::sockstream& channel );

}

#endif /* _win32c_net_tcp_threaded_server_hpp__ */


text:
public class Solution {
    public ListNode removeElements(ListNode head, int val) {
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode prev = dummy;
        while (prev.next != null) {
            if (prev.next.val == val) {
                ListNode curr = prev.next;
                prev.next = curr.next;
                curr.next = null;
            } else {
                prev = prev.next;
            }
        }

        return dummy.next;
    }
}


text:
package org.jhotdraw.samples.teddy;

import org.jhotdraw.app.*;

/**
 * Main entry point of the Teddy sample application. Creates an {@link Application}
 * depending on the operating system we run, sets the {@link TeddyApplicationModel}
 * and then launches the application. The application then creates
 * {@link TeddyView}s and menu bars as specified by the application model.
 *
 * @author Werner Randelshofer.
 * @version $Id: Main.java 731 2011-01-22 09:21:06Z rawcoder $
 */
public class Main {
    public final static String NAME = "JHotDraw Teddy";
    public final static String COPYRIGHT = "© 1996-2010 by the original authors of JHotDraw and all its contributors.";

    /**
     * Launches the application.
     *
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        TeddyApplicationModel tam = new TeddyApplicationModel();
        tam.setCopyright(COPYRIGHT);
        tam.setName(NAME);
        tam.setViewClassName("org.jhotdraw.samples.teddy.TeddyView");
        tam.setVersion(Main.class.getPackage().getImplementationVersion());

        Application app;
        if (System.getProperty("os.name").toLowerCase().startsWith("mac os x")) {
            app = new OSXApplication();
        } else if (System.getProperty("os.name").toLowerCase().startsWith("win")) {
            //app = new DefaultMDIApplication();
            app = new SDIApplication();
        } else {
            app = new SDIApplication();
        }
        app.setModel(tam);
        app.launch(args);
    }
}


text:
//
//  BaseDAOProtocol.h
//  LSWearable
//
//  Created by rolandxu on 16/1/1.
//  Copyright © 2016年 lifesense. All rights reserved.
//

#import <Foundation/Foundation.h>

@protocol BaseDAOProtocol <NSObject>

@optional

- (NSError *)saveEntity:(id)entity;
- (void)saveEntity:(id)entity callback:(void (^)(BOOL))callback;

/**
 *  保存单个entity
 *
 *  @param entity        希望保存的entity
 *  @param callbackQueue 回调queue,传nil默认回调到mainQueue
 *  @param callback      回调block
 */
- (void)saveEntity:(id)entity callbackQueue:(dispatch_queue_t)callbackQueue callback:(void (^)(BOOL))callback;

- (NSError *)saveEntityWithArray:(NSArray *)array;
- (void)saveEntityWithArray:(NSArray *)array callback:(void (^)(NSError *error))callback;

/**
 *  批量保存多个entity
 *
 *  @param array         entity数组
 *  @param callbackQueue 回调queue,nil默认回调到mainQueue
 *  @param callback      回调block
 */
- (void)saveEntityWithArray:(NSArray *)array callbackQueue:(dispatch_queue_t)callbackQueue callback:(void (^)(NSError *error))callback;

- (id)loadEntityWithKey:(NSString *)key;
- (NSArray *)loadEntityWithWhere:(NSString *)where order:(NSString *)order;
- (NSArray *)loadEntityWithWhere:(NSString *)where order:(NSString *)order offset:(NSInteger)offset count:(NSInteger)count;
- (void)loadEntityWithWhere:(NSString *)where order:(NSString *)order offset:(NSInteger)offset count:(NSInteger)count callback:(void (^)(NSMutableArray *))block ;

/**
 *  查询数据
 *
 *  @param where         where语句
 *  @param order         order
 *  @param offset        offset
 *  @param count         count
 *  @param callbackQueue 回调queue,传nil默认回调到mainQueue
 *  @param block         回调block
 */
- (void)loadEntityWithWhere:(NSString *)where order:(NSString *)order offset:(NSInteger)offset count:(NSInteger)count callbackQueue:(dispatch_queue_t)callbackQueue callback:(void (^)(NSMutableArray *))block;

//复杂查询可以用这个方法,自己写SQL
- (void)loadEntityWithSQL:(NSString *)sql callback:(void (^)(NSMutableArray *array))block;

/**
 *  使用sql语句查询数据库
 *
 *  @param sql           sql语句
 *  @param callbackQueue 回调queue,传nil默认回调到mainQueue
 *  @param block         回调block
 */
- (void)loadEntityWithSQL:(NSString *)sql callbackQueue:(dispatch_queue_t)callbackQueue callback:(void (^)(NSMutableArray *array))block;

- (NSInteger)countWithWhere:(NSString *)where;

- (NSError *)deleteEntity:(id)entity;
- (NSError *)deleteEntityWithKey:(NSString *)key;
- (NSError *)deleteEntityWithWhere:(NSString *)where;

- (void)deleteAllEntity;

- (BOOL)isExistEntity:(id)entity;

@end


text:
package org.jai.search.config;

import org.jai.search.actors.SetupIndexMasterActor;
import org.jai.search.data.SampleDataGeneratorService;
import org.jai.search.index.IndexProductDataService;
import org.jai.search.setup.SetupIndexService;
import org.springframework.beans.factory.annotation.Autowire;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;

import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.actor.Props;

import com.typesafe.config.ConfigFactory;

/**
 * The application configuration.
 */
@Configuration
class AppConfiguration {
	@Autowired
	private ApplicationContext applicationContext;

	/**
	 * Actor system singleton for this application.
	 */
	@Bean(autowire = Autowire.BY_NAME, name = "actorSystem")
	public ActorSystem actorSystem() {
		return ActorSystem.create("SearchIndexingSystem", ConfigFactory.load("application-akka-es.conf")
				.getConfig("SearchIndexingSystem"));
	}

	@Bean(autowire = Autowire.BY_NAME, name = "setupIndexMasterActor")
	// @Scope("prototype")
	@DependsOn(value = { "actorSystem" })
	public ActorRef setupIndexMasterActor() {
		final ActorSystem system = applicationContext
				.getBean(ActorSystem.class);
		final SetupIndexService setupIndexService = applicationContext
				.getBean(SetupIndexService.class);
		final SampleDataGeneratorService sampleDataGeneratorService = applicationContext
				.getBean(SampleDataGeneratorService.class);
		final IndexProductDataService indexProductData = applicationContext
				.getBean(IndexProductDataService.class);
		return system.actorOf(
				Props.create(SetupIndexMasterActor.class, setupIndexService,
						sampleDataGeneratorService, indexProductData)
						.withDispatcher("setupIndexMasterActorDispatch"),
				"setupIndexMasterActor");
	}
}


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2012.09.11 at 02:04:50 PM CDT
//

package com.github.stinkbird.helpspot.private_api.response_for.user.get_filters;

import java.io.Serializable;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for anonymous complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType>
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "")
@XmlRootElement(name = "isunread")
public class Isunread implements Serializable {

	private static final long serialVersionUID = 2968408777850466114L;

}


text:
package org.apache.calcite.sql.parser;

import org.apache.calcite.avatica.util.Casing;
import org.apache.calcite.avatica.util.Quoting;
import org.apache.calcite.config.Lex;
import org.apache.calcite.runtime.CalciteContextException;
import org.apache.calcite.sql.SqlNode;
import org.apache.calcite.sql.parser.impl.SqlParserImpl;

import com.google.common.base.Preconditions;

import java.io.StringReader;

/**
 * A SqlParser parses a SQL statement.
 */
public class SqlParser {
  public static final int DEFAULT_IDENTIFIER_MAX_LENGTH = 128;

  //~ Instance fields --------------------------------------------------------
  private final SqlAbstractParserImpl parser;
  private final String originalInput;

  //~ Constructors -----------------------------------------------------------
  private SqlParser(String s, SqlAbstractParserImpl parser,
      Config config) {
    this.originalInput = s;
    this.parser = parser;
    parser.setTabSize(1);
    parser.setQuotedCasing(config.quotedCasing());
    parser.setUnquotedCasing(config.unquotedCasing());
    parser.setIdentifierMaxLength(config.identifierMaxLength());
    switch (config.quoting()) {
    case DOUBLE_QUOTE:
      parser.switchTo("DQID");
      break;
    case BACK_TICK:
      parser.switchTo("BTID");
      break;
    case BRACKET:
      parser.switchTo("DEFAULT");
      break;
    }
  }

  //~ Methods ----------------------------------------------------------------

  /**
   * Creates a SqlParser to parse the given string using
   * Calcite's parser implementation.
   *
   *
The default lexical policy is similar to Oracle.
   *
   * @see Lex#ORACLE
   *
   * @param s An SQL statement or expression to parse.
   * @return A parser
   */
  public static SqlParser create(String s) {
    return create(s, configBuilder().build());
  }

  /**
   * Creates a SqlParser to parse the given string using the
   * parser implementation created from given {@link SqlParserImplFactory}
   * with given quoting syntax and casing policies for identifiers.
   *
   * @param sql A SQL statement or expression to parse.
   * @param config The parser configuration (identifier max length, etc.)
   * @return A parser
   */
  public static SqlParser create(String sql, Config config) {
    SqlAbstractParserImpl parser =
        config.parserFactory().getParser(new StringReader(sql));

    return new SqlParser(sql, parser, config);
  }

  /**
   * Parses a SQL expression.
   *
   * @throws SqlParseException if there is a parse error
   */
  public SqlNode parseExpression() throws SqlParseException {
    try {
      return parser.parseSqlExpressionEof();
    } catch (Throwable ex) {
      if ((ex instanceof CalciteContextException)
          && (originalInput != null)) {
        ((CalciteContextException) ex).setOriginalStatement(
            originalInput);
      }
      throw parser.normalizeException(ex);
    }
  }

  /**
   * Parses a SELECT statement.
   *
   * @return A {@link org.apache.calcite.sql.SqlSelect} for a regular
   * SELECT statement; a {@link org.apache.calcite.sql.SqlBinaryOperator}
   * for a UNION, INTERSECT, or EXCEPT.
   * @throws SqlParseException if there is a parse error
   */
  public SqlNode parseQuery() throws SqlParseException {
    try {
      return parser.parseSqlStmtEof();
    } catch (Throwable ex) {
      if ((ex instanceof CalciteContextException)
          && (originalInput != null)) {
        ((CalciteContextException) ex).setOriginalStatement(
            originalInput);
      }
      throw parser.normalizeException(ex);
    }
  }

  /**
   * Parses an SQL statement.
   *
   * @return top-level SqlNode representing stmt
   * @throws SqlParseException if there is a parse error
   */
  public SqlNode parseStmt() throws SqlParseException {
    try {
      return parser.parseSqlStmtEof();
    } catch (Throwable ex) {
      if ((ex instanceof CalciteContextException)
          && (originalInput != null)) {
        ((CalciteContextException) ex).setOriginalStatement(
            originalInput);
      }
      throw parser.normalizeException(ex);
    }
  }

  /**
   * Get the parser metadata.
   *
   * @return {@link SqlAbstractParserImpl.Metadata} implementation of
   *     underlying parser.
   */
  public SqlAbstractParserImpl.Metadata getMetadata() {
    return parser.getMetadata();
  }

  /**
   * Builder for a {@link Config}.
   */
  public static ConfigBuilder configBuilder() {
    return new ConfigBuilder();
  }

  /**
   * Builder for a {@link Config} that starts with an existing {@code Config}.
   */
  public static ConfigBuilder configBuilder(Config config) {
    return new ConfigBuilder().setConfig(config);
  }

  /**
   * Interface to define the configuration for a SQL parser.
   *
   * @see ConfigBuilder
   */
  public interface Config {
    /** Default configuration. */
    Config DEFAULT = configBuilder().build();

    int identifierMaxLength();
    Casing quotedCasing();
    Casing unquotedCasing();
    Quoting quoting();
    boolean caseSensitive();
    SqlParserImplFactory parserFactory();
  }

  /** Builder for a {@link Config}. */
  public static class ConfigBuilder {
    private Casing quotedCasing = Lex.ORACLE.quotedCasing;
    private Casing unquotedCasing = Lex.ORACLE.unquotedCasing;
    private Quoting quoting = Lex.ORACLE.quoting;
    private int identifierMaxLength = DEFAULT_IDENTIFIER_MAX_LENGTH;
    private boolean caseSensitive = Lex.ORACLE.caseSensitive;
    private SqlParserImplFactory parserFactory = SqlParserImpl.FACTORY;

    private ConfigBuilder() {}

    /** Sets configuration identical to a given {@link Config}. */
    public ConfigBuilder setConfig(Config config) {
      this.quotedCasing = config.quotedCasing();
      this.unquotedCasing = config.unquotedCasing();
      this.quoting = config.quoting();
      this.identifierMaxLength = config.identifierMaxLength();
      this.parserFactory = config.parserFactory();
      return this;
    }

    public ConfigBuilder setQuotedCasing(Casing quotedCasing) {
      this.quotedCasing = Preconditions.checkNotNull(quotedCasing);
      return this;
    }

    public ConfigBuilder setUnquotedCasing(Casing unquotedCasing) {
      this.unquotedCasing = Preconditions.checkNotNull(unquotedCasing);
      return this;
    }

    public ConfigBuilder setQuoting(Quoting quoting) {
      this.quoting = Preconditions.checkNotNull(quoting);
      return this;
    }

    public ConfigBuilder setCaseSensitive(boolean caseSensitive) {
      this.caseSensitive = caseSensitive;
      return this;
    }

    public ConfigBuilder setIdentifierMaxLength(int identifierMaxLength) {
      this.identifierMaxLength = identifierMaxLength;
      return this;
    }

    public ConfigBuilder setParserFactory(SqlParserImplFactory factory) {
      this.parserFactory = Preconditions.checkNotNull(factory);
      return this;
    }

    public ConfigBuilder setLex(Lex lex) {
      setCaseSensitive(lex.caseSensitive);
      setUnquotedCasing(lex.unquotedCasing);
      setQuotedCasing(lex.quotedCasing);
      setQuoting(lex.quoting);
      return this;
    }

    /** Builds a
     * {@link Config}. */
    public Config build() {
      return new ConfigImpl(identifierMaxLength, quotedCasing,
          unquotedCasing, quoting, caseSensitive, parserFactory);
    }
  }

  /** Implementation of
   * {@link Config}.
   * Called by builder; all values are in private final fields. */
  private static class ConfigImpl implements Config {
    private final int identifierMaxLength;
    private final boolean caseSensitive;
    private final Casing quotedCasing;
    private final Casing unquotedCasing;
    private final Quoting quoting;
    private final SqlParserImplFactory parserFactory;

    private ConfigImpl(int identifierMaxLength, Casing quotedCasing,
        Casing unquotedCasing, Quoting quoting, boolean caseSensitive,
        SqlParserImplFactory parserFactory) {
      this.identifierMaxLength = identifierMaxLength;
      this.caseSensitive = caseSensitive;
      this.quotedCasing = Preconditions.checkNotNull(quotedCasing);
      this.unquotedCasing = Preconditions.checkNotNull(unquotedCasing);
      this.quoting = Preconditions.checkNotNull(quoting);
      this.parserFactory = Preconditions.checkNotNull(parserFactory);
    }

    public int identifierMaxLength() {
      return identifierMaxLength;
    }

    public Casing quotedCasing() {
      return quotedCasing;
    }

    public Casing unquotedCasing() {
      return unquotedCasing;
    }

    public Quoting quoting() {
      return quoting;
    }

    public boolean caseSensitive() {
      return caseSensitive;
    }

    public SqlParserImplFactory parserFactory() {
      return parserFactory;
    }
  }
}

// End SqlParser.java


text: CodeIgniter Bootshop, by Steve King.


text:
namespace P01_StudentSystem.Data.Configurations
{
    using Microsoft.EntityFrameworkCore;
    using Microsoft.EntityFrameworkCore.Metadata.Builders;
    using P01_StudentSystem.Data.Models;

    public class StudentCourseConfiguration : IEntityTypeConfiguration<StudentCourse>
    {
        public void Configure(EntityTypeBuilder<StudentCourse> builder)
        {
            builder.HasKey(e => new { e.StudentId, e.CourseId });

            builder.HasOne(e => e.Student)
                .WithMany(s => s.CourseEnrollments)
                .HasForeignKey(e => e.StudentId);

            builder.HasOne(e => e.Course)
                .WithMany(c => c.StudentsEnrolled)
                .HasForeignKey(e => e.CourseId);
        }
    }
}


text:
package org.kie.dockerui.backend.service;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import org.kie.dockerui.backend.util.KieDockerUtils;
import org.kie.dockerui.backend.util.Timer;
import org.kie.dockerui.client.service.SettingsService;
import org.kie.dockerui.shared.model.KieImageType;
import org.kie.dockerui.shared.model.impl.H2Type;
import org.kie.dockerui.shared.model.impl.MySQLType;
import org.kie.dockerui.shared.model.impl.PostgreSQLType;
import org.kie.dockerui.shared.settings.Settings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Properties;

public class SettingsServiceImpl extends RemoteServiceServlet implements SettingsService {

    private static final Logger LOGGER = LoggerFactory.getLogger(SettingsServiceImpl.class.getName());

    public static final String APP_PROPERTIES = "org/kie/dockerui/backend/service/app.properties";
    /* If this webapp is inside a container, can have different network settings. */
    public static final String APP_PROPERTY_HOST_PRIVATE = "docker.host.private";
    public static final String APP_PROPERTY_HOST_PUBLIC = "docker.host.public";
    public static final String APP_PROPERTY_SSH_USER = "docker.host.ssh.user";
    public static final String APP_PROPERTY_REGISTRY_ENABLED = "docker.registry.enabled";
    public static final String APP_PROPERTY_REGISTRY_PORT = "docker.registry.port";
    public static final String APP_PROPERTY_RESTAPI_PROTOCOL = "docker.restapi.protocol";
    public static final String APP_PROPERTY_RESTAPI_PORT = "docker.restapi.port";
    public static final String APP_PROPERTY_KIE_REPOSITORY = "docker.kie.images.repository";
    public static final String APP_PROPERTY_MYSQL_IMAGE  = "docker.image.type.mysql";
    public static final String APP_PROPERTY_POSTGRES_IMAGE = "docker.image.type.postgresql";
    public static final String APP_PROPERTY_JENKINS_URL = "docker.jenkins.url";
    public static final String APP_PROPERTY_ARTIFACTS_PATH = "docker.kie.artifacts.path";
    public static final String APP_PROPERTY_STATUS_MANAGER_ENABLED = "docker.statusManager.enabled";
    public static final String APP_PROPERTY_STATUS_MANAGER_PULL_ENABLED = "docker.statusManager.pull.enabled";
    public static final String APP_PROPERTY_STATUS_MANAGER_PULL_INTERVAL = "docker.statusManager.pull.interval";

    private static Settings settings;

    @Override
    public synchronized Settings getSettings() {
        if (settings == null) {
            settings = readSettings();
            if (settings == null) {
                LOGGER.error("ERROR - Cannot read application settings.");
                return null;
            }
        }
        return settings;
    }

    @Override
    public String getDefaultImageForType(KieImageType type) {
        final Properties p = KieDockerUtils.getProperties(APP_PROPERTIES);
        if (MySQLType.INSTANCE.equals(type)) return p.getProperty(APP_PROPERTY_MYSQL_IMAGE);
        if (PostgreSQLType.INSTANCE.equals(type)) return p.getProperty(APP_PROPERTY_POSTGRES_IMAGE);
        if (H2Type.INSTANCE.equals(type)) return null;
        return null;
    }

    private Settings readSettings() {
        final Properties appProperties = KieDockerUtils.getProperties(APP_PROPERTIES);

        Timer timer = new Timer();
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Starting to read settings from environment or configuration file.");
            timer.start();
        }

        // Application properties.
        String hostPrivate = readSetting(appProperties, APP_PROPERTY_HOST_PRIVATE);
        String hostPublic = readSetting(appProperties, APP_PROPERTY_HOST_PUBLIC);
        String user = readSetting(appProperties, APP_PROPERTY_SSH_USER);
        String artifactsPath = readSetting(appProperties, APP_PROPERTY_ARTIFACTS_PATH);
        String jenkinsJobURL = readSetting(appProperties, APP_PROPERTY_JENKINS_URL);
        String registryPort = readSetting(appProperties, APP_PROPERTY_REGISTRY_PORT);
        String _registryEnabled = readSetting(appProperties, APP_PROPERTY_REGISTRY_ENABLED);
        boolean registryEnabled = Boolean.valueOf(_registryEnabled);
        String restProtocol = readSetting(appProperties, APP_PROPERTY_RESTAPI_PROTOCOL);
        String restPort = readSetting(appProperties, APP_PROPERTY_RESTAPI_PORT);
        String kieRepo = readSetting(appProperties, APP_PROPERTY_KIE_REPOSITORY);
        String _isStatusManagerMEnabled = readSetting(appProperties, APP_PROPERTY_STATUS_MANAGER_ENABLED);
        boolean isStatusManagerMEnabled = Boolean.valueOf(_isStatusManagerMEnabled);
        boolean pullEnabled = false;
        long pullInterval = 0;
        if(isStatusManagerMEnabled) {
            String _pullEnabled = readSetting(appProperties, APP_PROPERTY_STATUS_MANAGER_PULL_ENABLED);
            pullEnabled = Boolean.valueOf(_pullEnabled);
            String _pullInterval = readSetting(appProperties, APP_PROPERTY_STATUS_MANAGER_PULL_INTERVAL);
            pullInterval = Long.decode(_pullInterval);
        }

        final Settings settings = new Settings();
        settings.setProtocol(restProtocol);
        settings.setPrivateHost(hostPrivate);
        settings.setPublicHost(hostPublic);
        settings.setUser(user);
        settings.setRestApiPort(Integer.decode(restPort));
        settings.setRegistryEnabled(registryEnabled);
        settings.setRegistryPort(Integer.decode(registryPort));
        settings.setKieRepositoryName(kieRepo);
        settings.setArtifactsPath(artifactsPath);
        settings.setJenkinsJobURL(jenkinsJobURL);
        settings.setIsStatusManagerEnabled(isStatusManagerMEnabled);
        settings.setPullEnabled(pullEnabled);
        settings.setPullInterval(pullInterval);
        settings.setMysqlImage(getDefaultImageForType(MySQLType.INSTANCE));
        settings.setPostgresImage(getDefaultImageForType(PostgreSQLType.INSTANCE));

        if (LOGGER.isDebugEnabled()) {
            timer.end();
            LOGGER.debug("Settings read. Elapsed time = " + timer.getTotalTime());
        }

        return settings;
    }

    private String readSetting(final Properties appProperties, final String key) {
        String result = System.getProperty(key);
        if (result == null || result.trim().length() == 0) {
            result = appProperties.getProperty(key);
        }
        return result;
    }

}


text:
******************************
rmgpy.data.thermo.ThermoGroups
******************************

.. autoclass:: rmgpy.data.thermo.ThermoGroups


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Simocybe centunculus f. tetraspora

### Remarks
null