text:
from __future__ import print_function, division

import numpy as np
from PyQt5 import QtWidgets, QtGui, QtCore
from PyQt5.QtCore import Qt

# Widget which return key presses, however double click replaces backspace
class MixListWidget(QtWidgets.QListWidget):
    # Return signal if key was pressed while in focus
    keyPressedSignal=QtCore.pyqtSignal()
    leaveSignal=QtCore.pyqtSignal()

    def __init__(self, parent=None):
        super(MixListWidget, self).__init__(parent)

    # Update this widgets last pressed key, and return a signal
    def keyPressEvent(self, ev):
        self.key=ev.key()
        if self.key not in [Qt.Key_Insert,Qt.Key_Delete]:
            return
        self.keyPressedSignal.emit()

    # Deselect all items if in a blank space
    def mousePressEvent(self, ev):
        if self.itemAt(ev.pos()) is None:
            self.clearSelection()
        QtWidgets.QListWidget.mousePressEvent(self, ev)

    # Swapping a double click with the backspace button...
    # ...wanted to transmit double click as a key
    def mouseDoubleClickEvent(self,ev):
        # Only allow left-double clicks
        if ev.button()!=1:
            return
        self.key=Qt.Key_Backspace
        self.keyPressedSignal.emit()

    # Ensure that key presses are sent to the widget which the mouse is hovering over
    def enterEvent(self,ev):
        super(MixListWidget, self).enterEvent(ev)
        self.setFocus()

    # If ever the list if left by the mouse, emit (used to trigger ordering of passive functions)
    def leaveEvent(self,ev):
        self.leaveSignal.emit()

    # Return the lists entries in the order which it appears
    def visualListOrder(self):
        txt=np.array([self.item(i).text() for i in range(self.count())])
        args=np.array([self.indexFromItem(self.item(i)).row() for i in range(self.count())])
        return list(txt[np.argsort(args)])

# Generic widget for QListWidget with remove only keyPresses...
# ...currently only used for key bind of delete (if want more keys, must check appropriate lists)
class KeyListWidget(QtWidgets.QListWidget):
    # Return signal if key was pressed while in focus
    keyPressedSignal = QtCore.pyqtSignal()

    def __init__(self, parent=None):
        super(KeyListWidget, self).__init__(parent)

    # Update this widgets last pressed key, and return a signal
    def keyPressEvent(self, ev):
        self.key=ev.key()
        if self.key not in [Qt.Key_Delete]:
            return
        self.keyPressedSignal.emit()

    # Deselect all items if in a blank space
    def mousePressEvent(self, ev):
        if self.itemAt(ev.pos()) is None:
            self.clearSelection()
        QtWidgets.QListWidget.mousePressEvent(self, ev)

    # Ensure that key presses are sent to the widget which the mouse is hovering over
    def enterEvent(self,ev):
        super(KeyListWidget, self).enterEvent(ev)
        self.setFocus()

    # Return a lists entries in the order which is appears
    def visualListOrder(self):
        txt=np.array([self.item(i).text() for i in range(self.count())])
        args=np.array([self.indexFromItem(self.item(i)).row() for i in range(self.count())])
        return list(txt[np.argsort(args)])

# Convert any key press signal to a human readable string (ignores modifiers like shift, ctrl)
def keyPressToString(ev):
    MOD_MASK = (Qt.CTRL | Qt.ALT | Qt.SHIFT | Qt.META)
    keyname = None
    key = ev.key()
    modifiers = int(ev.modifiers())
    if key in [Qt.Key_Shift,Qt.Key_Alt,Qt.Key_Control,Qt.Key_Meta]:
        pass
    elif (modifiers and modifiers & MOD_MASK==modifiers and key>0):
        keyname=QtGui.QKeySequence(modifiers+key).toString()
    else:
        keyname=QtGui.QKeySequence(key).toString()
    return keyname

# Line edit which returns key-bind strings
class KeyBindLineEdit(QtWidgets.QLineEdit):
    keyPressed=QtCore.pyqtSignal(str)

    def __init__(self, parent=None):
        super(KeyBindLineEdit, self).__init__(parent)
        self.MOD_MASK = (Qt.CTRL | Qt.ALT | Qt.SHIFT | Qt.META)

    # If any usual key bind was pressed, return the human recognizable string
    def keyPressEvent(self, ev):
        keyname = keyPressToString(ev)
        if keyname==None:
            return
        self.keyPressed.emit(keyname)

# Line edit which returns signal upon being double cliced
class DblClickLineEdit(QtWidgets.QLineEdit):
    doubleClicked=QtCore.pyqtSignal()

    def __init__(self, parent=None):
        super(DblClickLineEdit, self).__init__(parent)

    def mouseDoubleClickEvent(self,ev):
        self.doubleClicked.emit()

# Line edit which returns a signal upon being hovered out of
class HoverLineEdit(QtWidgets.QLineEdit):
    hoverOut = QtCore.pyqtSignal()

    def __init__(self, parent=None):
        super(HoverLineEdit, self).__init__(parent)
        self.changeState=False
        self.textChanged.connect(self.updateChangeState)

    def leaveEvent(self, ev):
        # Only emit if the text was changed
        if self.changeState:
            self.hoverOut.emit()
            self.changeState=False

    def updateChangeState(self,ev):
        self.changeState=True

# Generic widget for QListWidget with remove only keyPresses
class DblClickLabelWidget(QtWidgets.QLabel):
    # Return signal if label was double clicked
    doubleClicked=QtCore.pyqtSignal()

    def __init__(self, parent=None):
        super(DblClickLabelWidget, self).__init__(parent)

    def mouseDoubleClickEvent(self,ev):
        self.doubleClicked.emit()

# Widget to show/edit the source dictionary
class SourceDictWidget(QtWidgets.QTreeWidget):
    def __init__(self, parent = None):
        QtWidgets.QTreeWidget.__init__(self, parent)
        self.setColumnCount(3)
        self.setHeaderLabels(["Name", "Type", "Value"])
        self.setColumnWidth(0,130)
        self.setColumnWidth(1,90)
        # Check any edits which are made
        self.itemChanged.connect(self.checkEdits)
        # Value of an item prior to edit
        self.oldVal=''
        # Allowed variable data types
        self.varTypes=['str','int','float',
                       'array(str)',
                       'array(int)',
                       'array(float)']
        self.varConverts=[str,int,float,
                          lambda x: np.array(x.split(','),dtype=str),
                          lambda x: np.array(x.split(','),dtype=int),
                          lambda x: np.array(x.split(','),dtype=float)]

    # Keep default mouse presses
    def clickEvent(self,event):
        QtWidgets.QTreeWidget.mousePressEvent(self,event)
        # Clear selection if nothing clicked
        if self.itemAt(event.pos()) is None:
            self.clearSelection()

    def mousePressEvent(self, event):
        self.clickEvent(event)
        # If wanting to make add/remove an item (right click)
        if event.button() == QtCore.Qt.RightButton:
            self.createMenu(event)

    # Make a note of values prior to edits
    def mouseDoubleClickEvent(self,event):
        self.clickEvent(event)
        curItem=self.selectedItem()
        # Do nothing if no item selected
        if curItem is None:
            return
        # Allow group name to be edited, and the variable name/value
        curCol=self.currentColumn()
        if (curItem.parent() is None and curCol==0) or curCol!=1:
            self.oldVal=curItem.text(curCol)
            self.editItem(curItem,curCol)

    # Return list of the current group names
    def currentGroupNames(self):
        return[self.getName(groupItem) for groupItem in self.currentGroupItems()]

    # Return list of the current group items
    def currentGroupItems(self):
        return [self.topLevelItem(i) for i in range(self.topLevelItemCount())]

    # Return list of the variable names in a group item
    def currentVariableNames(self,groupItem):
        return [self.getName(varItem) for varItem in self.currentVariableItems(groupItem)]

    # Return list of variable items in a group item
    def currentVariableItems(self,groupItem):
        return [groupItem.child(i) for i in range(groupItem.childCount())]

    # Get the name of an item
    def getName(self,item):
        return str(item.text(0))

    # Generate widget for a new group
    def addGroup(self,groupName='NewGroup'):
        # Check to see that the default name is not taken
        if groupName in self.currentGroupNames():
            print('Name "'+groupName+'" already taken, edit before adding')
            return
        groupItem=QtWidgets.QTreeWidgetItem([groupName,'',''])
        # Allow the item to be edited
        groupItem.setFlags(groupItem.flags() | QtCore.Qt.ItemIsEditable)
        self.addTopLevelItem(groupItem)
        return groupItem

    # Generate widget for a new variable within a group
    def addVariable(self,groupItem,varName='NewVariable',varVal=None):
        # Check to see that the default name is not taken
        if varName in self.currentVariableNames(groupItem):
            print('Name "'+varName+'" already taken, edit before adding')
            return
        varText,varType=self.getVarTextAndType(varVal)
        # Give default values for new variable
        varItem=QtWidgets.QTreeWidgetItem([varName,'',varText])
        # Allow the item to be edited
        varItem.setFlags(varItem.flags() | QtCore.Qt.ItemIsEditable)
        # Add the variable to the group
        groupItem.addChild(varItem)
        # Show what types are accepted
        comboBox=QtWidgets.QComboBox()
        comboBox.addItems(self.varTypes)
        # Set the current combo item
        comboBox.setCurrentIndex(self.varTypes.index(varType))
        self.setItemWidget(varItem,1,comboBox)
        # Connect to check edits if this value is changed
        comboBox.currentIndexChanged.connect(lambda: self.checkEdits(varItem,1))
        comboBox.highlighted.connect(lambda: self.setOldVal(comboBox.itemText(comboBox.currentIndex())))

    # Used to set the previous comboBox value
    def setOldVal(self,val):
        self.oldVal=val

    # Import and display a given source dictionary
    def showSourceDict(self,sourceDict):
        # Clear the old
        for groupItem in self.currentGroupItems():
           self.removeGroup(groupItem)
        # Load the new
        for groupName in sorted(sourceDict.keys()):
            groupItem=self.addGroup(groupName=str(groupName))
            for varName in sorted(sourceDict[groupName].keys()):
                self.addVariable(groupItem,varName=str(varName),
                                 varVal=sourceDict[groupName][varName])

    # Extract the displayed source dictionary
    def getSourceDict(self):
        sourceDict={}
        for groupItem in self.currentGroupItems():
            groupName=self.getName(groupItem)
            sourceDict[groupName]={self.getName(varItem):self.stringToVarType(varItem)
                                   for varItem in self.currentVariableItems(groupItem)}
        return sourceDict

    # Remove currently selected group
    def removeGroup(self,item):
        self.takeTopLevelItem(self.indexFromItem(item).row())

    # Remove currently selected variable
    def removeVariable(self,item):
        item.parent().takeChild(self.indexFromItem(item).row())

    # Get the user visible value from the value and variable type
    def getVarTextAndType(self,val):
        # If the value is none, convert to string
        if val is None:
            return '','str'
        # Check first if a numpy array
        if type(val)==type(np.array([])):
            for aType in ['float','int','str']:
                match='|S' if aType=='str' else aType
                if match in str(val.dtype):
                    if len(val.shape)==0:
                        return str(val),'array('+aType+')'
                    else:
                        return ','.join(val.astype(str)),'array('+aType+')'
        # Otherwise check float,int,str
        for i in range(3)[::-1]:
            try:
                self.varConverts[i](val)
                return str(val),self.varTypes[i]
            except:
                continue
        return str(val),'str'

    # Convert the variable value to its appropriate type
    def stringToVarType(self,item):
        comboBox=self.itemWidget(item,1)
        varType=comboBox.itemText(comboBox.currentIndex())
        convertFunc=self.varConverts[self.varTypes.index(varType)]
        if item.text(2).replace(' ','')=='':
            return None
        else:
            return convertFunc(item.text(2))

    # Revert to an older value
    def revertEdits(self,item,col,message):
        # Disconnect from changed edits, revert to old value, reconnect
        print(message)
        self.itemChanged.disconnect(self.checkEdits)
        item.setText(col,self.oldVal)
        self.itemChanged.connect(self.checkEdits)

    # Check recent edits for errors
    def checkEdits(self,item,col):
        # Ensure names are unique
        if col==0:
            # Make a list of the names currently present
            if item.parent() is None:
                takenNames=self.currentGroupNames()
            else:
                takenNames=self.currentVariableNames(item.parent())
            # If name already taken, revert to old
            if np.sum(np.array(takenNames,dtype=str)==str(item.text(col)))>1:
                self.revertEdits(item,col,'Name already taken')
        # Ensure type matches the value
        elif col==1 and item.parent() is not None:
            # Do not check if string (should always work)
            comboBox=self.itemWidget(item,1)
            if comboBox.itemText(comboBox.currentIndex())=='str':
                return
            try:
                self.stringToVarType(item)
            except Exception as error:
                # Disconnect from changed edits, revert to type string, reconnect
                print(str(error)+', reverting to old type')
                comboBox.setCurrentIndex(self.varTypes.index(self.oldVal))
        # Ensure value matches the type
        elif col==2 and item.parent() is not None:
            try:
                self.stringToVarType(item)
            except Exception as error:
                self.revertEdits(item,col,str(error)+', reverting to old value')

    # Get the currently selected item
    def selectedItem(self):
        items=self.selectedItems()
        if len(items)==0:
            return None
        else:
            return items[0]

    # Create pop up menu to add/remove groups/variables
    def createMenu(self,event, parent=None):
        self.menu=QtWidgets.QMenu(parent)
        self.menu.addAction('Add Group', self.addGroup)
        if self.selectedItem() is not None:
            if self.selectedItem().parent() is None:
                self.menu.addAction('Add Variable',lambda: self.addVariable(self.selectedItem()))
                self.menu.addSeparator()
                self.menu.addAction('Remove Group',lambda: self.removeGroup(self.selectedItem()))
            elif self.selectedItem().parent().parent() is None:
                self.menu.addAction('Add Variable',lambda: self.addVariable(self.selectedItem().parent()))
                self.menu.addSeparator()
                self.menu.addAction('Remove Variable',lambda: self.removeVariable(self.selectedItem()))
        self.menu.move(self.mapToGlobal(QtCore.QPoint(0,0))+event.pos())
        self.menu.show()


text:
<?php
  // Phorum does not require any trimming of messages.  However if you have a
  // disc space limit or some other strange bug with large tables this could
  // be handy.

  // This script will remove messages from a forum that are older than the
  // set number of days.  Run in cron for best results.

  // You will need to change ./ to the path where phorum is located.
  $phorumdir="./";

  $nDays="90"; // Number of days to keep
  $VERBOSE=false; // If true, info about what is happening
                  // will be sent to output

  $olddir=getcwd();
  chdir($phorumdir);
  include "common.php";

  $sSQL="Select name, table from forums";
  $res = new query($DB, $sSQL);
  $rec=$res->getrow();
  while(is_array($rec)){
    echo $rec["name"];
    $table=$rec["table"];
    $cutoff=date("Y-m-d", mktime(0,0,0,date('m'),date('d')-$nDays));
    $sSQL="Select id from $table where datestamp < $cutoff and thread=id";
    $q->query($DB, $sSQL);
    $numthreads=$q->numrows();
    $instr="";
    while($rec=$q->getrow()){
      $instr.="$rec->id,";
    }
    if($instr) $instr=substr($instr, strlen($instr)-1);
    $sSQL="Select count(*) as cnt from $table where thread in ($instr)";
    $q->query($DB, $sSQL);
    $cnt=$q->getrow();
    $count=$cnt["cnt"];
    $sSQL="Delete from $table where thread in ($instr)";
    $q->query($DB, $sSQL);
    $sSQL="Delete from $table"."_bodies where thread in ($instr)";
    $q->query($DB, $sSQL);
    $rec=$res->getrow();
    if($VERBOSE) echo "Forum: $rec[name], Threads Deleted: $numthreads, Messages Deleted: $count\n";
  }

  chdir($olddir);
?>

redpajama_set_name: RedPajamaGithub


text:
<?php

/**
 * Model_UserMessageTable
 *
 * This class has been auto-generated by the Doctrine ORM Framework
 */
class Model_UserMessageTable extends Ext_Doctrine_Table
{
    /**
     * Returns an instance of this class.
     *
     * @return object Model_UserMessageTable
     */
    public static function getInstance()
    {
        return Doctrine_Core::getTable('Model_UserMessage');
    }
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.monitor.models;

import com.azure.core.annotation.Fluent;
import com.azure.core.util.logging.ClientLogger;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;

/**
 * Definition of which syslog data will be collected and how it will be collected. Only collected from Linux machines.
 */
@Fluent
public final class SyslogDataSource {
    @JsonIgnore private final ClientLogger logger = new ClientLogger(SyslogDataSource.class);

    /*
     * List of streams that this data source will be sent to.
     * A stream indicates what schema will be used for this data and usually
     * what table in Log Analytics the data will be sent to.
     */
    @JsonProperty(value = "streams")
    private List<KnownSyslogDataSourceStreams> streams;

    /*
     * The list of facility names.
     */
    @JsonProperty(value = "facilityNames")
    private List<KnownSyslogDataSourceFacilityNames> facilityNames;

    /*
     * The log levels to collect.
     */
    @JsonProperty(value = "logLevels")
    private List<KnownSyslogDataSourceLogLevels> logLevels;

    /*
     * A friendly name for the data source.
     * This name should be unique across all data sources (regardless of type)
     * within the data collection rule.
     */
    @JsonProperty(value = "name")
    private String name;

    /**
     * Get the streams property: List of streams that this data source will be sent to. A stream indicates what schema
     * will be used for this data and usually what table in Log Analytics the data will be sent to.
     *
     * @return the streams value.
     */
    public List<KnownSyslogDataSourceStreams> streams() {
        return this.streams;
    }

    /**
     * Set the streams property: List of streams that this data source will be sent to. A stream indicates what schema
     * will be used for this data and usually what table in Log Analytics the data will be sent to.
     *
     * @param streams the streams value to set.
     * @return the SyslogDataSource object itself.
     */
    public SyslogDataSource withStreams(List<KnownSyslogDataSourceStreams> streams) {
        this.streams = streams;
        return this;
    }

    /**
     * Get the facilityNames property: The list of facility names.
     *
     * @return the facilityNames value.
     */
    public List<KnownSyslogDataSourceFacilityNames> facilityNames() {
        return this.facilityNames;
    }

    /**
     * Set the facilityNames property: The list of facility names.
     *
     * @param facilityNames the facilityNames value to set.
     * @return the SyslogDataSource object itself.
     */
    public SyslogDataSource withFacilityNames(List<KnownSyslogDataSourceFacilityNames> facilityNames) {
        this.facilityNames = facilityNames;
        return this;
    }

    /**
     * Get the logLevels property: The log levels to collect.
     *
     * @return the logLevels value.
     */
    public List<KnownSyslogDataSourceLogLevels> logLevels() {
        return this.logLevels;
    }

    /**
     * Set the logLevels property: The log levels to collect.
     *
     * @param logLevels the logLevels value to set.
     * @return the SyslogDataSource object itself.
     */
    public SyslogDataSource withLogLevels(List<KnownSyslogDataSourceLogLevels> logLevels) {
        this.logLevels = logLevels;
        return this;
    }

    /**
     * Get the name property: A friendly name for the data source. This name should be unique across all data sources
     * (regardless of type) within the data collection rule.
     *
     * @return the name value.
     */
    public String name() {
        return this.name;
    }

    /**
     * Set the name property: A friendly name for the data source. This name should be unique across all data sources
     * (regardless of type) within the data collection rule.
     *
     * @param name the name value to set.
     * @return the SyslogDataSource object itself.
     */
    public SyslogDataSource withName(String name) {
        this.name = name;
        return this;
    }

    /**
     * Validates the instance.
     *
     * @throws IllegalArgumentException thrown if the instance is not valid.
     */
    public void validate() {
    }
}


text:
/** \file platformstl/synch/sleep_functions.h
 *
 * \brief [C, C++] Various time functions
 *   (\ref group__library__synch "Synchronisation" Library).
 */

#ifndef PLATFORMSTL_INCL_PLATFORMSTL_SYNCH_H_SLEEP_FUNCTIONS
#define PLATFORMSTL_INCL_PLATFORMSTL_SYNCH_H_SLEEP_FUNCTIONS

#ifndef STLSOFT_DOCUMENTATION_SKIP_SECTION
# define PLATFORMSTL_VER_PLATFORMSTL_SYNCH_H_SLEEP_FUNCTIONS_MAJOR      1
# define PLATFORMSTL_VER_PLATFORMSTL_SYNCH_H_SLEEP_FUNCTIONS_MINOR      1
# define PLATFORMSTL_VER_PLATFORMSTL_SYNCH_H_SLEEP_FUNCTIONS_REVISION   1
# define PLATFORMSTL_VER_PLATFORMSTL_SYNCH_H_SLEEP_FUNCTIONS_EDIT       7
#endif /* !STLSOFT_DOCUMENTATION_SKIP_SECTION */

/* /////////////////////////////////////////////////////////////////////////
 * Includes
 */

#ifndef PLATFORMSTL_INCL_PLATFORMSTL_H_PLATFORMSTL
# include <platformstl/platformstl.h>
#endif /* !PLATFORMSTL_INCL_PLATFORMSTL_H_PLATFORMSTL */

#if defined(PLATFORMSTL_OS_IS_UNIX)
# ifndef UNIXSTL_INCL_UNIXSTL_SYNCH_H_SLEEP_FUNCTIONS
#  include <unixstl/synch/sleep_functions.h>
# endif /* !UNIXSTL_INCL_UNIXSTL_SYNCH_H_SLEEP_FUNCTIONS */
#elif defined(PLATFORMSTL_OS_IS_WINDOWS)
# ifndef WINSTL_INCL_WINSTL_SYNCH_H_SLEEP_FUNCTIONS
#  include <winstl/synch/sleep_functions.h>
# endif /* !WINSTL_INCL_WINSTL_SYNCH_H_SLEEP_FUNCTIONS */
#else /* ? operating system */
# error Operating system not discriminated
#endif /* operating system */

/* /////////////////////////////////////////////////////////////////////////
 * Namespace
 */

#if !defined(__cplusplus)
 /* Nothing defined in C */
#elif defined(_STLSOFT_NO_NAMESPACE) || \
    defined(STLSOFT_DOCUMENTATION_SKIP_SECTION)
/* There is no stlsoft namespace, so must define ::platformstl */
namespace platformstl
{
#else
/* Define stlsoft::platformstl_project */

namespace stlsoft
{

namespace platformstl_project
{
#endif /* _STLSOFT_NO_NAMESPACE */

/* ////////////////////////////////////////////////////////////////////// */

#if defined(__cplusplus)

# if defined(PLATFORMSTL_OS_IS_UNIX)

#  if defined(_UNIXSTL_NO_NAMESPACE)
    /* There's no unixstl namespace, so we 'use' from the global namespace. */
    using micro_sleep;
#  else /* ? _UNIXSTL_NO_NAMESPACE */
    using unixstl::micro_sleep;
#  endif /* _UNIXSTL_NO_NAMESPACE */

# elif defined(PLATFORMSTL_OS_IS_WINDOWS)

#  if defined(_UNIXSTL_NO_NAMESPACE)
    /* There's no unixstl namespace, so we 'use' from the global namespace. */
    using micro_sleep;
#  else /* ? _UNIXSTL_NO_NAMESPACE */
    using winstl::micro_sleep;
#  endif /* _UNIXSTL_NO_NAMESPACE */

# else /* ? OS */

# error Operating system not discriminated

# endif /* OS */

#endif /* __cplusplus */

/* ////////////////////////////////////////////////////////////////////// */

#if !defined(__cplusplus)
 /* Nothing defined in C */
#elif defined(_STLSOFT_NO_NAMESPACE) || \
    defined(STLSOFT_DOCUMENTATION_SKIP_SECTION)
} /* namespace platformstl */
#else
} /* namespace platformstl_project */
} /* namespace stlsoft */
#endif /* _STLSOFT_NO_NAMESPACE */

/* ////////////////////////////////////////////////////////////////////// */

#endif /* !PLATFORMSTL_INCL_PLATFORMSTL_SYNCH_H_SLEEP_FUNCTIONS */

/* ///////////////////////////// end of file //////////////////////////// */


text:
package VSAP::Server::Modules::vsap::sys::service;

use 5.008004;
use strict;
use warnings;

use VSAP::Server::Sys::Service::Control;
use VSAP::Server::Modules::vsap::logger;
use VSAP::Server::Modules::vsap::sys::monitor;
use VSAP::Server::Modules::vsap::sys::timezone;
use VSAP::Server::Modules::vsap::user::prefs;

our @ISA = qw(Exporter);

our $VERSION = '1.00';

our %_ERR = ( ERR_NOTAUTHORIZED => 100,
              ERR_UNKNOWN_SERVICE => 101,
              ERR_INTERNAL => 102,  # Internal error.
              ERR_NO_SERVICES => 103  # Internal error.
            );

##############################################################################

sub action {
    my $action = shift;
    my $vsap = shift;
    my $xmlobj = shift;
    my $dom = $vsap->{_result_dom};
    my $svc_control;

    unless ($vsap->{server_admin}) {
        $vsap->error($_ERR{ERR_NOTAUTHORIZED} => "not authorized to $action services.");
        return;
    }

    unless ($xmlobj->children_names) {
        $vsap->error( $_ERR{ERR_NO_SERVICES} => "a service must be specified for $action.");
        return;
    }

    ROOT: {
        local $> = $) = 0;  ## regain privileges for a moment
        $svc_control = new VSAP::Server::Sys::Service::Control;
    }

    if (!$svc_control) {
        $vsap->error($_ERR{ERR_INTERNAL} => 'Error obtaining service control.');
        return;
    }

    my @services = $svc_control->available_services;

    # Check for valid services.
    foreach my $service ($xmlobj->children_names) {
        unless (grep /^$service$/, @services) {
            $vsap->error( $_ERR{ERR_UNKNOWN_SERVICE} => "Unknown service $service.");
            return;
        }
    }

    my $root = $dom->createElement('vsap');
    $root->setAttribute( type => "sys:service:$action");

    foreach my $service ($xmlobj->children_names) {

        my $node = $dom->createElement($service);
        $root->appendChild($node);

        if (($service eq 'httpd') && ($action eq 'restart')) {
            # gracefully restart
            $vsap->need_apache_restart();
        }
        else {
            ROOT: {
                local $> = $) = 0;  ## regain privileges for a moment
                eval {
                    unless ($svc_control->$action($service)) {
                        $node->setAttribute ( error => "unable to $action $service");
                    }
                };
            }

            if ($@) {
                $node->setAttribute ( error => "unable to $action $service: $@");
                VSAP::Server::Modules::vsap::logger::log_error("unable to $action $service: $@");
            }
            else {
                VSAP::Server::Modules::vsap::logger::log_message("$vsap->{username} requested to $action service '$service'");
                if ($action eq "start") {
                    # reset monitor data
                    VSAP::Server::Modules::vsap::sys::monitor::_reset_notification_data($service);
                }
            }
        }
    }

    $dom->documentElement->appendChild($root);

    return;
}

##############################################################################

package VSAP::Server::Modules::vsap::sys::service::enable;

sub handler {
    my $vsap = shift;
    my $xmlobj = shift;
    my $dom = $vsap->{_result_dom};

    VSAP::Server::Modules::vsap::sys::service::action('enable',$vsap,$xmlobj);

    return;
}

##############################################################################

package VSAP::Server::Modules::vsap::sys::service::disable;

sub handler {
    my $vsap = shift;
    my $xmlobj = shift;
    my $dom = $vsap->{_result_dom};

    VSAP::Server::Modules::vsap::sys::service::action('disable',$vsap,$xmlobj);
}

##############################################################################

package VSAP::Server::Modules::vsap::sys::service::stop;

sub handler {
    my $vsap = shift;
    my $xmlobj = shift;

    VSAP::Server::Modules::vsap::sys::service::action('stop',$vsap,$xmlobj);

    return;
}

##############################################################################

package VSAP::Server::Modules::vsap::sys::service::start;

sub handler {
    my $vsap = shift;
    my $xmlobj = shift;

    VSAP::Server::Modules::vsap::sys::service::action('start',$vsap,$xmlobj);

    return;
}

##############################################################################

package VSAP::Server::Modules::vsap::sys::service::restart;

sub handler {
    my $vsap = shift;
    my $xmlobj = shift;

    VSAP::Server::Modules::vsap::sys::service::action('restart',$vsap,$xmlobj);

    return;
}

##############################################################################

package VSAP::Server::Modules::vsap::sys::service::status;

sub handler {
    my $vsap = shift;
    my $xmlobj = shift;
    my $dom = $vsap->{_result_dom};
    my $svc_control;
    my @available_services;

    ROOT: {
        local $> = $) = 0;  ## regain privileges for a moment

        $svc_control = new VSAP::Server::Sys::Service::Control;

        if (!$svc_control) {
            $vsap->error($_ERR{ERR_INTERNAL} => 'Error obtaining service control.');
            return;
        }

        @available_services = $svc_control->available_services;
    }

    # Check for valid services.
    foreach my $service ($xmlobj->children_names) {
        $vsap->error( $_ERR{ERR_UNKNOWN_SERVICE} => "Unknown service $service.")
            unless (grep /^$service$/, @available_services);
        return;
    }

    # Use the services provided or available services if no xml children.
    my @services = $xmlobj->children_names || @available_services;

    my $root = $dom->createElement('vsap');
    $root->setAttribute( type => 'sys:service:status');

    foreach my $service (@available_services) {
        my $node = $dom->createElement($service);

        ROOT: {
            local $> = $) = 0;  ## regain privileges for a moment
            eval {
                $node->appendTextChild( version => $svc_control->version($service));
                $node->appendTextChild( enabled => ($svc_control->is_enabled($service) ? "true" : "false"));
                $node->appendTextChild( running => ($svc_control->is_running($service) ? "true" : "false"));
                $node->appendTextChild( monitor_autorestart => ($svc_control->monitor_autorestart($service) ? "true" : "false"));
                $node->appendTextChild( monitor_notify => ($svc_control->monitor_notify($service) ? "true" : "false"));
                my $stime = $svc_control->last_started($service);
                $node->appendTextChild( last_started_epoch => $stime );
                my $timezone = VSAP::Server::Modules::vsap::user::prefs::get_value($vsap, 'time_zone') ||
                               VSAP::Server::Modules::vsap::sys::timezone::get_timezone();
                my $d = new VSAP::Server::G11N::Date( epoch => $stime, tz => $timezone );
                if ($d) {
                    my $date_node = $node->appendChild($dom->createElement('last_started'));
                    $date_node->appendTextChild( year   => $d->local->year    );
                    $date_node->appendTextChild( month  => $d->local->month   );
                    $date_node->appendTextChild( day    => $d->local->day     );
                    $date_node->appendTextChild( hour   => $d->local->hour    );
                    $date_node->appendTextChild( hour12 => $d->local->hour_12 );
                    $date_node->appendTextChild( minute => $d->local->minute  );
                    $date_node->appendTextChild( second => $d->local->second  );

                    $date_node->appendTextChild( o_year   => $d->original->year    );
                    $date_node->appendTextChild( o_month  => $d->original->month   );
                    $date_node->appendTextChild( o_day    => $d->original->day     );
                    $date_node->appendTextChild( o_hour   => $d->original->hour    );
                    $date_node->appendTextChild( o_hour12 => $d->original->hour_12 );
                    $date_node->appendTextChild( o_minute => $d->original->minute  );
                    $date_node->appendTextChild( o_second => $d->original->second  );
                    $date_node->appendTextChild( o_offset => $d->original->offset  );
                }
            };
        }

        if ($@) {
            $node->removeChildNodes;
            $node->setAttribute('error' => "Error obtaining status: $@");
        }

        $root->appendChild($node);
    }

    $dom->documentElement->appendChild($root);

    return;
}

##############################################################################

1;
__END__

=head1 NAME

VSAP::Server::Modules::vsap::sys::service - VSAP module supporting the control of certain services.

=head1 SYNOPSIS

=head2 sys:service:stop, sys:service:start, sys:service:restart, sys:service:enable, sys:service:disable

All of these methods use the same format for both the request and response. Simply replace $action
in the below example with either stop, start, restart, enable or disable.

    <vsap type='sys:service:$action'>
        <service1/>
        <service2/>
        <service3/>
    </vsap>

Would return

    <vsap type='sys:service:$action'>
        <service1/>
        <service2/>
        <service3 error="some error occured while" />
    </vsap>

=head2 sys:service:status

    <vsap type='sys:service:status'/>

Would return:

    <vsap type='sys:service:status'>
        <service1>
            <running>true</running>
            <enabled>true</enabled>
        </service1>
        <service2/>
            <running>true</running>
            <enabled>true</enabled>
        </service2>
        <service3/>
            <running>true</running>
            <enabled>true</enabled>
        </service3>
        <service4 error="Error x occured while obtaining status"/>
    </vsap>

For the status request, you can also just specify one service and the status will be returned.

Ex:

    <vsap type='sys:service:status'>
        <service1/>
    </vsap>

Would return:

    <vsap type='sys:service:status'>
        <service1>
            <running>true</running>
            <enabled>true</enabled>
        </service1>
    </vsap>

=head1 DESCRIPTION

This vsap module provides control of services on the machine. It provides the ability to
stop, start, restart, enable or disable the services. It also provides methods to enable
or disable the service on the machine. An enabled service starts up automatically when the
machine is booted. A service can be started or stopped indepdent of it being enabled or
disabled. Most of the functionality of this module is taken care of in the another module
called VSAP::Server::Sys::Service::Control. Please refer to this module for additional
information.

The services which are listed and available for control depends on the available services as
obtained by the VSAP::Server::Sys::Service::Control module. A service is determined avaiable
(and will be returned by the status) method typically if its startup script exists. See the
VSAP::Server::Sys::Service::Control and other related modules for more information.

=head2 EXPORT

None by default.

=head1 SEE ALSO

VSAP::Server::Sys::Service::Control

=head1 AUTHOR

James Russo

=head1 COPYRIGHT AND LICENSE

Copyright (C) 2006 by MYNAMESERVER, LLC

No part of this module may be duplicated in any form without written
consent of the copyright holder.

=cut


text:
import math
import time
import random

settingsCache = {}

booted = time.time()

def init(snmpEngine, *args):
    random.seed()

def process(oid, tag, value, **context):
    if not context['nextFlag'] and not context['exactMatch']:
        return context['origOid'], context['errorStatus']  # serve exact OIDs
    if context['setFlag']:
        return context['origOid'], context['errorStatus']  # read-only mode

    if oid not in settingsCache:
        settingsCache[oid] = dict([ x.split('=') for x in value.split(',') ])

    if 'function' in settingsCache[oid]:
        f = getattr(math, settingsCache[oid]['function'])
    else:
        f = lambda x: x
    v = f((time.time() - booted) * float(settingsCache[oid].get('rate', 1))) * float(settingsCache[oid].get('scale', 1)) + float(settingsCache[oid].get('offset', 0))

    d = int(settingsCache[oid].get('deviation', 0))
    if d:
        v += random.randomrange(-d, d)

    if v < int(settingsCache[oid].get('min', 0)):
        v = int(settingsCache[oid].get('min', 0))
    elif v > int(settingsCache[oid].get('max', 0xffffffff)):
        v = int(settingsCache[oid].get('max', 0xffffffff))

    return oid, v

def shutdown(snmpEngine, *args): pass


text:
"""Tests for Nadam."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import numpy as np

from tensorflow.contrib.opt.python.training import nadam_optimizer
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.python.ops import resource_variable_ops
from tensorflow.python.ops import variables
from tensorflow.python.platform import test

def nadam_update_numpy(param,
                       g_t,
                       t,
                       m,
                       v,
                       alpha=0.001,
                       beta1=0.9,
                       beta2=0.999,
                       epsilon=1e-8):
  alpha_t = alpha * np.sqrt(1 - beta2**t) / (1 - beta1**t)

  m_t = beta1 * m + (1 - beta1) * g_t
  v_t = beta2 * v + (1 - beta2) * g_t * g_t

  m_bar = (1 - beta1) * g_t + beta1 * m_t

  param_t = param - alpha_t * m_bar / (np.sqrt(v_t) + epsilon)
  return param_t, m_t, v_t

class NadamOptimizerTest(test.TestCase):

  def doTestSparse(self, use_resource=False):
    # need to use a larger value of epsilon here so that
    # np.sqrt(v_t) + epsilon doesn't get rounded to 0 when
    # the dtype is half and np.sqrt(v_t) = 0, as is the case
    # when the gradient is 0
    sparse_epsilon = 1e-7
    for dtype in [dtypes.half, dtypes.float32, dtypes.float64]:
      with self.cached_session():
        # Initialize variables for numpy implementation.
        m0, v0, m1, v1 = 0.0, 0.0, 0.0, 0.0
        var0_np = np.array([1.0, 1.0, 2.0], dtype=dtype.as_numpy_dtype)
        grads0_np = np.array([0.1, 0, 0.1], dtype=dtype.as_numpy_dtype)
        var1_np = np.array([3.0, 3.0, 4.0], dtype=dtype.as_numpy_dtype)
        grads1_np = np.array([0.01, 0, 0.01], dtype=dtype.as_numpy_dtype)

        if use_resource:
          var0 = resource_variable_ops.ResourceVariable(var0_np)
          var1 = resource_variable_ops.ResourceVariable(var1_np)
        else:
          var0 = variables.Variable(var0_np)
          var1 = variables.Variable(var1_np)
        grads0_np_indices = np.array([0, 2], dtype=np.int32)
        grads0 = ops.IndexedSlices(
            constant_op.constant(grads0_np[grads0_np_indices]),
            constant_op.constant(grads0_np_indices), constant_op.constant([3]))
        grads1_np_indices = np.array([0, 2], dtype=np.int32)
        grads1 = ops.IndexedSlices(
            constant_op.constant(grads1_np[grads1_np_indices]),
            constant_op.constant(grads1_np_indices), constant_op.constant([3]))
        opt = nadam_optimizer.NadamOptimizer(epsilon=sparse_epsilon)
        update = opt.apply_gradients(zip([grads0, grads1], [var0, var1]))
        variables.global_variables_initializer().run()

        # Fetch params to validate initial values
        self.assertAllClose([1.0, 1.0, 2.0], var0.eval())
        self.assertAllClose([3.0, 3.0, 4.0], var1.eval())

        beta1_power, beta2_power = opt._get_beta_accumulators()

        # Run 3 steps of Nadam
        for t in range(1, 4):
          self.assertAllCloseAccordingToType(0.9**t, beta1_power.eval())
          self.assertAllCloseAccordingToType(0.999**t, beta2_power.eval())
          update.run()

          var0_np, m0, v0 = nadam_update_numpy(var0_np, grads0_np, t, m0, v0,
                                               epsilon=sparse_epsilon)
          var1_np, m1, v1 = nadam_update_numpy(var1_np, grads1_np, t, m1, v1,
                                               epsilon=sparse_epsilon)

          # Validate updated params
          self.assertAllCloseAccordingToType(var0_np, var0.eval())
          self.assertAllCloseAccordingToType(var1_np, var1.eval())

  def testSparse(self):
    self.doTestSparse(use_resource=False)

  def testResourceSparse(self):
    self.doTestSparse(use_resource=True)

  def doTestBasic(self, use_resource=False):
    for dtype in [dtypes.half, dtypes.float32, dtypes.float64]:
      with self.cached_session():
        # Initialize variables for numpy implementation.
        m0, v0, m1, v1 = 0.0, 0.0, 0.0, 0.0
        var0_np = np.array([1.0, 2.0], dtype=dtype.as_numpy_dtype)
        grads0_np = np.array([0.1, 0.1], dtype=dtype.as_numpy_dtype)
        var1_np = np.array([3.0, 4.0], dtype=dtype.as_numpy_dtype)
        grads1_np = np.array([0.01, 0.01], dtype=dtype.as_numpy_dtype)

        if use_resource:
          var0 = resource_variable_ops.ResourceVariable(var0_np)
          var1 = resource_variable_ops.ResourceVariable(var1_np)
        else:
          var0 = variables.Variable(var0_np)
          var1 = variables.Variable(var1_np)
        grads0 = constant_op.constant(grads0_np)
        grads1 = constant_op.constant(grads1_np)
        opt = nadam_optimizer.NadamOptimizer()
        update = opt.apply_gradients(zip([grads0, grads1], [var0, var1]))
        variables.global_variables_initializer().run()

        # Fetch params to validate initial values
        self.assertAllClose([1.0, 2.0], var0.eval())
        self.assertAllClose([3.0, 4.0], var1.eval())

        beta1_power, beta2_power = opt._get_beta_accumulators()

        # Run 3 steps of Nadam
        for t in range(1, 4):
          self.assertAllCloseAccordingToType(0.9**t, beta1_power.eval())
          self.assertAllCloseAccordingToType(0.999**t, beta2_power.eval())
          update.run()

          var0_np, m0, v0 = nadam_update_numpy(var0_np, grads0_np, t, m0, v0)
          var1_np, m1, v1 = nadam_update_numpy(var1_np, grads1_np, t, m1, v1)

          # Validate updated params
          self.assertAllCloseAccordingToType(var0_np, var0.eval())
          self.assertAllCloseAccordingToType(var1_np, var1.eval())

  def testBasic(self):
    self.doTestBasic(use_resource=False)

  def testResourceBasic(self):
    self.doTestBasic(use_resource=True)

if __name__ == "__main__":
  test.main()


text:
/**
 * Name : TableCtrl.js
 * Module : Norris::App::Controller
 * Location : /norris/app/script/controllers/
 *
 * History :
 * Version       Date           Programmer
 * =================================================
 *  0.0.1     2015/04/10       Cardin Andrea
 * -------------------------------------------------
 *  Codifica modulo
 * =================================================
 */
'use strict';

angular.module("Controllers")
  .controller("TableCtrl", ["$scope", "SocketsSvc", "TableSvc", "$window", function($scope, SocketsSvc, TableSvc, $window) {
    // WebSocket opening
    SocketsSvc.open($scope.graph.id, $scope.$parent.nspSock);
    // WebSocket connection message
    SocketsSvc.on($scope.graph.id, 'connect', function() {
      SocketsSvc.emit($scope.graph.id, 'joinRoom', $scope.graph.id);
      console.log("Connected on socket " + $scope.graph.id);
    });
    // WebSocket reconnection message
    SocketsSvc.on($scope.graph.id, "reconnect", function() {
      $window.location.reload();
    });
    // WebSocket disconnect message
    SocketsSvc.on($scope.graph.id, "disconnect", function() {
      alert("Il grafico " + $scope.graph.id
          + " ha perso la connessione al server Norris.");
    });

    var graphG = {};
    graphG.type = "Table";

    // Populating
    graphG.data = TableSvc.fillData($scope.graph.headers,
        $scope.graph.data, $scope.graph.colors, $scope.graph.showBorder);

    // Setting options
    graphG.options = { page: "enable"
                     , allowHtml: true
                     , pageSize: $scope.graph.displayedLines
                     };

    graphG.formatters = { number : [] };

    for (var i = 0; i < $scope.graph.format.length; i++) {
      var formatPattern = "";
      // Sets the value symbol, if not null
      if ($scope.graph.format[i].valueType !== null) {
        if ($scope.graph.format[i].valueType === "euro") {
          formatPattern += "€";
        } else if ($scope.graph.format[i].valueType === "dollars") {
          formatPattern += "$";
        } else if ($scope.graph.format[i].valueType === "pounds") {
          formatPattern += "£";
        }
      }
      formatPattern += " #,##0.";
      // Sets the number of decimal digits
      for (var j = 0; j < $scope.graph.format[i].decimals; j++) {
        formatPattern += "0";
      }
      // Set the correct column formatter
      graphG.formatters.number.push({
        columnNum : $scope.graph.format[i].column,
        pattern : formatPattern
      });
    }

    // Set table sorting
    if ($scope.graph.orderBy.column !== undefined) {
      graphG.options.sortColumn = $scope.graph.orderBy.column;
      if ($scope.graph.orderBy.order == "descending") {
        graphG.options.sortAscending = false;
      } else
        graphG.options.sortAscending = true; // Default ascending
    }

    $scope.Table = graphG;

    // Aaaand update it!
    SocketsSvc.on($scope.graph.id, "update", function(info) {
      var data = JSON.parse(info);
      if (data.type == "inPlace")
        TableSvc.inPlaceUpd(data, graphG.data);
      else
        TableSvc.streamUpd(data, graphG.data, $scope.graph.rowsLimit);
    });
  }]);


text:
<?php

/**
 * Customer flow password info Model
 *
 * @category    Mage
 * @package     Mage_Customer
 * @author      Magento Core Team <core@magentocommerce.com>
 */
class Mage_Customer_Model_Flowpassword extends Mage_Core_Model_Abstract
{
    protected function _construct()
    {
        $this->_init('customer/flowpassword');
    }

    /**
     * Prepare data before save
     *
     * @return Mage_Core_Model_Abstract
     */
    protected function _beforeSave()
    {
        $this->_prepareData();
        return parent::_beforeSave();
    }

    /**
     * Prepare customer flow password data
     *
     * @return Mage_Customer_Model_Flowpassword
     */
    protected function _prepareData()
    {
        $validatorData = Mage::getSingleton('customer/session')->getValidatorData();
        $this->setIp($validatorData[Mage_Customer_Model_Session::VALIDATOR_REMOTE_ADDR_KEY])
            ->setRequestedDate(Mage::getModel('core/date')->date());
        return $this;
    }

    /**
     * Check forgot password requests to times per 24 hours from 1 e-mail
     *
     * @param string $email
     * @return bool
     */
    public function checkCustomerForgotPasswordFlowEmail($email)
    {
        $helper = Mage::helper('customer');
        $checkForgotPasswordFlowTypes = array(
            Mage_Adminhtml_Model_System_Config_Source_Customer_Forgotpassword::FORGOTPASS_FLOW_IP_EMAIL,
            Mage_Adminhtml_Model_System_Config_Source_Customer_Forgotpassword::FORGOTPASS_FLOW_EMAIL
        );

        if (in_array($helper->getCustomerForgotPasswordFlowSecure(), $checkForgotPasswordFlowTypes)) {
            $forgotPassword = $this->getCollection()
                ->addFieldToFilter('email', array('eq' => $email))
                ->addFieldToFilter('requested_date',
                    array('gt' => Mage::getModel('core/date')->date(null, '-1 day')));

            if ($forgotPassword->getSize() > $helper->getCustomerForgotPasswordEmailTimes()) {
                return false;
            }
        }
        return true;
    }

    /**
     * Check forgot password requests to times per hour from 1 IP
     *
     * @return bool
     */
    public function checkCustomerForgotPasswordFlowIp()
    {
        $helper        = Mage::helper('customer');
        $validatorData = Mage::getSingleton('customer/session')->getValidatorData();
        $remoteAddr    = $validatorData[Mage_Customer_Model_Session::VALIDATOR_REMOTE_ADDR_KEY];
        $checkForgotPasswordFlowTypes = array(
            Mage_Adminhtml_Model_System_Config_Source_Customer_Forgotpassword::FORGOTPASS_FLOW_IP_EMAIL,
            Mage_Adminhtml_Model_System_Config_Source_Customer_Forgotpassword::FORGOTPASS_FLOW_IP
        );

        if (in_array($helper->getCustomerForgotPasswordFlowSecure(), $checkForgotPasswordFlowTypes) && $remoteAddr) {
            $forgotPassword = $this->getCollection()
                ->addFieldToFilter('ip', array('eq' => $remoteAddr))
                ->addFieldToFilter('requested_date',
                    array('gt' => Mage::getModel('core/date')->date(null, '-1 hour')));

            if ($forgotPassword->getSize() > $helper->getCustomerForgotPasswordIpTimes()) {
                return false;
            }
        }
        return true;
    }
}


text:
<?php

namespace Jsor\Doctrine\PostGIS\Event;

use Jsor\Doctrine\PostGIS\AbstractFunctionalTestCase;
use Jsor\Doctrine\PostGIS\PointsEntity;
use Jsor\Doctrine\PostGIS\ReservedWordsEntity;

class ORMSchemaEventSubscriberTest extends AbstractFunctionalTestCase
{
    public function testEntity()
    {
        $this->_setUpEntitySchema(array(
            'Jsor\Doctrine\PostGIS\PointsEntity',
        ));

        $em = $this->_getEntityManager();

        $sm = $em->getConnection()->getSchemaManager();
        $table = $sm->listTableDetails('points');
        $this->assertTrue($table->hasIndex('idx_point'));
        $this->assertTrue($table->getIndex('idx_point')->hasFlag('spatial'));

        $entity = new PointsEntity(array(
            'text' => 'foo',
            'geometry' => 'POINT(1 1)',
            'point' => 'POINT(1 1)',
            'point2D' => 'SRID=3785;POINT(1 1)',
            'point3DZ' => 'SRID=3785;POINT(1 1 1)',
            'point3DM' => 'SRID=3785;POINTM(1 1 1)',
            'point4D' => 'SRID=3785;POINT(1 1 1 1)',
            'point2DNullable' => null,
            'point2DNoSrid' => 'POINT(1 1)',
            'geography' => 'SRID=4326;POINT(1 1)',
            'pointGeography2d' => 'SRID=4326;POINT(1 1)',
            'pointGeography2dSrid' => 'POINT(1 1)',
        ));

        $em->persist($entity);
        $em->flush();
        $em->clear();

        $entity = $em->find('Jsor\Doctrine\PostGIS\PointsEntity', 1);

        $this->assertEquals('POINT(1 1)', $entity->getPoint());
        $this->assertEquals('SRID=3785;POINT(1 1)', $entity->getPoint2D());
        $this->assertEquals('SRID=3785;POINT(1 1 1)', $entity->getPoint3DZ());
        $this->assertEquals('SRID=3785;POINTM(1 1 1)', $entity->getPoint3DM());
        $this->assertEquals('SRID=3785;POINT(1 1 1 1)', $entity->getPoint4D());
        $this->assertNull($entity->getPoint2DNullable());
        $this->assertEquals('POINT(1 1)', $entity->getPoint2DNoSrid());
        $this->assertEquals('SRID=4326;POINT(1 1)', $entity->getPointGeography2d());
        $this->assertEquals('SRID=4326;POINT(1 1)', $entity->getPointGeography2dSrid());
    }

    public function testEntityWithReservedWords()
    {
        $this->_setUpEntitySchema(array(
            'Jsor\Doctrine\PostGIS\ReservedWordsEntity',
        ));

        $em = $this->_getEntityManager();

        $entity = new ReservedWordsEntity(array(
            'user' => 'POINT(1 1)',
            'primary' => 'SRID=4326;POINT(1 1)',
        ));

        $em->persist($entity);
        $em->flush();
        $em->clear();

        $entity = $em->find('Jsor\Doctrine\PostGIS\ReservedWordsEntity', 1);

        $this->assertEquals('POINT(1 1)', $entity->getUser());
        $this->assertEquals('SRID=4326;POINT(1 1)', $entity->getPrimary());
    }
}


text:
#undef I3__FILE__
#define I3__FILE__ "config.c"
/*
 * vim:ts=4:sw=4:expandtab
 *
 * i3 - an improved dynamic tiling window manager
 * © 2009 Michael Stapelberg and contributors (see also: LICENSE)
 *
 * config.c: Configuration file (calling the parser (src/config_parser.c) with
 *           the correct path, switching key bindings mode).
 *
 */
#include "all.h"
#include <xkbcommon/xkbcommon.h>

char *current_configpath = NULL;
Config config;
struct modes_head modes;
struct barconfig_head barconfigs = TAILQ_HEAD_INITIALIZER(barconfigs);

/**
 * Ungrabs all keys, to be called before re-grabbing the keys because of a
 * mapping_notify event or a configuration file reload
 *
 */
void ungrab_all_keys(xcb_connection_t *conn) {
    DLOG("Ungrabbing all keys\n");
    xcb_ungrab_key(conn, XCB_GRAB_ANY, root, XCB_BUTTON_MASK_ANY);
}

/*
 * Sends the current bar configuration as an event to all barconfig_update listeners.
 *
 */
void update_barconfig() {
    Barconfig *current;
    TAILQ_FOREACH(current, &barconfigs, configs) {
        ipc_send_barconfig_update_event(current);
    }
}

/*
 * Finds the configuration file to use (either the one specified by
 * override_configpath), the user's one or the system default) and calls
 * parse_file().
 *
 */
bool parse_configuration(const char *override_configpath, bool use_nagbar) {
    char *path = get_config_path(override_configpath, true);
    if (path == NULL) {
        die("Unable to find the configuration file (looked at "
            "~/.i3/config, $XDG_CONFIG_HOME/i3/config, " SYSCONFDIR "/i3/config and $XDG_CONFIG_DIRS/i3/config)");
    }

    LOG("Parsing configfile %s\n", path);
    FREE(current_configpath);
    current_configpath = path;

    /* initialize default bindings if we're just validating the config file */
    if (!use_nagbar && bindings == NULL) {
        bindings = scalloc(sizeof(struct bindings_head));
        TAILQ_INIT(bindings);
    }

    return parse_file(path, use_nagbar);
}

/*
 * (Re-)loads the configuration file (sets useful defaults before).
 *
 */
void load_configuration(xcb_connection_t *conn, const char *override_configpath, bool reload) {
    if (reload) {
        /* First ungrab the keys */
        ungrab_all_keys(conn);

        struct Mode *mode;
        Binding *bind;
        while (!SLIST_EMPTY(&modes)) {
            mode = SLIST_FIRST(&modes);
            FREE(mode->name);

            /* Clear the old binding list */
            bindings = mode->bindings;
            while (!TAILQ_EMPTY(bindings)) {
                bind = TAILQ_FIRST(bindings);
                TAILQ_REMOVE(bindings, bind, bindings);
                binding_free(bind);
            }
            FREE(bindings);
            SLIST_REMOVE(&modes, mode, Mode, modes);
        }

        struct Assignment *assign;
        while (!TAILQ_EMPTY(&assignments)) {
            assign = TAILQ_FIRST(&assignments);
            if (assign->type == A_TO_WORKSPACE)
                FREE(assign->dest.workspace);
            else if (assign->type == A_COMMAND)
                FREE(assign->dest.command);
            match_free(&(assign->match));
            TAILQ_REMOVE(&assignments, assign, assignments);
            FREE(assign);
        }

        /* Clear bar configs */
        Barconfig *barconfig;
        while (!TAILQ_EMPTY(&barconfigs)) {
            barconfig = TAILQ_FIRST(&barconfigs);
            FREE(barconfig->id);
            for (int c = 0; c < barconfig->num_outputs; c++)
                free(barconfig->outputs[c]);
            FREE(barconfig->outputs);
            FREE(barconfig->tray_output);
            FREE(barconfig->socket_path);
            FREE(barconfig->status_command);
            FREE(barconfig->i3bar_command);
            FREE(barconfig->font);
            FREE(barconfig->colors.background);
            FREE(barconfig->colors.statusline);
            FREE(barconfig->colors.focused_workspace_border);
            FREE(barconfig->colors.focused_workspace_bg);
            FREE(barconfig->colors.focused_workspace_text);
            FREE(barconfig->colors.active_workspace_border);
            FREE(barconfig->colors.active_workspace_bg);
            FREE(barconfig->colors.active_workspace_text);
            FREE(barconfig->colors.inactive_workspace_border);
            FREE(barconfig->colors.inactive_workspace_bg);
            FREE(barconfig->colors.inactive_workspace_text);
            FREE(barconfig->colors.urgent_workspace_border);
            FREE(barconfig->colors.urgent_workspace_bg);
            FREE(barconfig->colors.urgent_workspace_text);
            FREE(barconfig->colors.binding_mode_border);
            FREE(barconfig->colors.binding_mode_bg);
            FREE(barconfig->colors.binding_mode_text);
            TAILQ_REMOVE(&barconfigs, barconfig, configs);
            FREE(barconfig);
        }

/* Clear workspace names */
#if 0
        Workspace *ws;
        TAILQ_FOREACH(ws, workspaces, workspaces)
            workspace_set_name(ws, NULL);
#endif

        /* Invalidate pixmap caches in case font or colors changed */
        Con *con;
        TAILQ_FOREACH(con, &all_cons, all_cons)
        FREE(con->deco_render_params);

        /* Get rid of the current font */
        free_font();
    }

    SLIST_INIT(&modes);

    struct Mode *default_mode = scalloc(sizeof(struct Mode));
    default_mode->name = sstrdup("default");
    default_mode->bindings = scalloc(sizeof(struct bindings_head));
    TAILQ_INIT(default_mode->bindings);
    SLIST_INSERT_HEAD(&modes, default_mode, modes);

    bindings = default_mode->bindings;

#define REQUIRED_OPTION(name) \
    if (config.name == NULL)  \
        die("You did not specify required configuration option " #name "\n");

    /* Clear the old config or initialize the data structure */
    memset(&config, 0, sizeof(config));

/* Initialize default colors */
#define INIT_COLOR(x, cborder, cbackground, ctext, cindicator) \
    do {                                                       \
        x.border = get_colorpixel(cborder);                    \
        x.background = get_colorpixel(cbackground);            \
        x.text = get_colorpixel(ctext);                        \
        x.indicator = get_colorpixel(cindicator);              \
    } while (0)

    config.client.background = get_colorpixel("#000000");
    INIT_COLOR(config.client.focused, "#4c7899", "#285577", "#ffffff", "#2e9ef4");
    INIT_COLOR(config.client.focused_inactive, "#333333", "#5f676a", "#ffffff", "#484e50");
    INIT_COLOR(config.client.unfocused, "#333333", "#222222", "#888888", "#292d2e");
    INIT_COLOR(config.client.urgent, "#2f343a", "#900000", "#ffffff", "#900000");

    /* border and indicator color are ignored for placeholder contents */
    INIT_COLOR(config.client.placeholder, "#000000", "#0c0c0c", "#ffffff", "#000000");

    /* the last argument (indicator color) is ignored for bar colors */
    INIT_COLOR(config.bar.focused, "#4c7899", "#285577", "#ffffff", "#000000");
    INIT_COLOR(config.bar.unfocused, "#333333", "#222222", "#888888", "#000000");
    INIT_COLOR(config.bar.urgent, "#2f343a", "#900000", "#ffffff", "#000000");

    config.show_marks = true;

    config.default_border = BS_NORMAL;
    config.default_floating_border = BS_NORMAL;
    config.default_border_width = logical_px(2);
    config.default_floating_border_width = logical_px(2);
    /* Set default_orientation to NO_ORIENTATION for auto orientation. */
    config.default_orientation = NO_ORIENTATION;

    /* Set default urgency reset delay to 500ms */
    if (config.workspace_urgency_timer == 0)
        config.workspace_urgency_timer = 0.5;

    /* Set default zero displays exit delay to 500ms */
    if (config.zero_disp_exit_timer_ms == 0)
        config.zero_disp_exit_timer_ms = 500;

    parse_configuration(override_configpath, true);

    if (reload) {
        translate_keysyms();
        grab_all_keys(conn, false);
    }

    if (config.font.type == FONT_TYPE_NONE) {
        ELOG("You did not specify required configuration option \"font\"\n");
        config.font = load_font("fixed", true);
        set_font(&config.font);
    }

    /* Redraw the currently visible decorations on reload, so that
     * the possibly new drawing parameters changed. */
    if (reload) {
        x_deco_recurse(croot);
        xcb_flush(conn);
    }

#if 0
    /* Set an empty name for every workspace which got no name */
    Workspace *ws;
    TAILQ_FOREACH(ws, workspaces, workspaces) {
            if (ws->name != NULL) {
                    /* If the font was not specified when the workspace name
                     * was loaded, we need to predict the text width now */
                    if (ws->text_width == 0)
                            ws->text_width = predict_text_width(global_conn,
                                            config.font, ws->name, ws->name_len);
                    continue;
            }

            workspace_set_name(ws, NULL);
    }
#endif
}


text:
<!doctype html>

    <title>CodeMirror: Test Suite</title>
    <link rel="stylesheet" href="../lib/codemirror.css">

CodeMirror: Test Suite

A limited set of programmatic sanity tests for CodeMirror.

      <form><textarea id="code" name="code"></textarea><input type=submit value=ok name=submit></form>


text:
import { html, fixture, expect } from '@open-wc/testing'

import '../src/index.esm.js'

const defaultProps = {
    type: 'line',
    percent: 0,
    status: undefined,
    strokeColor: undefined,
    trailColor: undefined,
    textColor: undefined,
    sterokeWidth: undefined,
    width: undefined,
    showInfo: true
  }

describe('Testing o-progress', () => {
  it('test setting type',async () =>{
    const el = await fixture(html` <o-progress type="circle"></o-progress> `)
    const svg = el.shadowRoot.querySelector('svg')
    expect(svg).to.not.be.null
  })

  it('test setting percent',async () =>{
    const el = await fixture(html` <o-progress percent="50"></o-progress> `)
    const percent = el.shadowRoot.querySelector(".o-progress-line__inner-bar").style.width
    expect(percent).to.equal('50%')
  })

  it('test setting width',async () =>{
    const el = await fixture(html` <o-progress width="600"></o-progress> `)
    const width = el.shadowRoot.querySelector(".o-progress-line__outer").style.width
    expect(width).to.equal('600px')
  })

  it('test setting stroke-width',async () =>{
    const el = await fixture(html` <o-progress stroke-width="16"></o-progress> `)
    const strokeWidth = el.shadowRoot.querySelector(".o-progress-line__inner-bar").style.height
    expect(strokeWidth).to.equal('16px')
  })

  it('test setting stroke-color',async () =>{
    const el = await fixture(html` <o-progress stroke-color="red"></o-progress> `)
    const backgroundColor = el.shadowRoot.querySelector(".o-progress-line__inner-bar").style.backgroundColor
    expect(backgroundColor).to.equal('red')
  })

  it('test setting trail-color',async () =>{
    const el = await fixture(html` <o-progress trail-color="red"></o-progress> `)
    const backgroundColor = el.shadowRoot.querySelector(".o-progress-line__bar").style.backgroundColor
    expect(backgroundColor).to.equal('red')
  })

  it('test setting text-color',async () =>{
    const el = await fixture(html` <o-progress text-color="red"></o-progress> `)
    const color = el.shadowRoot.querySelector("span>span").style.color
    expect(color).to.equal('red')
  })

  it('test setting status',async () =>{
    const el = await fixture(html` <o-progress status="error"></o-progress> `)
    const backgroundColor = el.shadowRoot.querySelector(".o-progress-line__inner-bar").style.backgroundColor
    expect(backgroundColor).to.equal('rgb(244, 53, 48)')
  })

  it('test setting show-info',async () =>{
    const el = await fixture(html` <o-progress show-info="false"></o-progress> `)
    const showInfo = el.shadowRoot.querySelector("span")
    expect(showInfo).to.equal(null)
  })

})


text:
package com.example.mylayout.friend;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import com.example.mylayout.R;
import com.example.mylayout.json.friend;

import java.util.List;

/**
 * Created by ShadowAnt on 2017/5/13.
 */

public class FriendAdapter extends ArrayAdapter<friend> {
    private int resourceId;

    public FriendAdapter(Context context, int textViewResourceId, List<friend> objects) {
        super(context, textViewResourceId, objects);
        resourceId = textViewResourceId;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        friend fri = getItem(position);
        View view = LayoutInflater.from(getContext()).inflate(resourceId, parent, false);
        TextView friendName = (TextView) view.findViewById(R.id.friend_name);
        TextView accountView = (TextView) view.findViewById(R.id.account);
        friendName.setText(fri.getDocName());
        accountView.setText(fri.getDocAccount());
        return view;
    }
}


text:
function Iterator(obj){
	if(! (obj instanceof Array) ) {
		throw new SyntaxError("Iterator Only works with Array");
	}

	this.values	= obj;
	this.current = 0;

	this.hasNext = function(){
		if(this.current > this.values.length -1 ) {
			return false;
		} else {
			return true;
		}
	}

	this.next = function(){
		this.current++;
		return this.values[this.current - 1];
	}
}

function HashMap()
{
    this.array = new Array();

    this.Entry = function( key, value ) {
	    this.key = key;
	    this.value = value;
	}

    this.put = function( key, value )	{
	    if( ( typeof key != "undefined" ) && ( typeof value != "undefined" ) )
	    {
	    	if(! (this.containsKey(key) )) {
	        	this.array.push( new this.Entry(key, value) );
	    	} else {
	    		for(var i=0; i<this.array.length; i++) {
	    			if(this.array[i].key == key) {
	    				this.array[i].value = value;
	    			}
	    		}
	    	}
	    }
	}

    this.get = function( key )	{
    	for(var i=0; i<this.array.length; i++) {
    		if(this.array[i].key == key)
    			return this.array[i].value;
    	}
	    return null;
	}

	this.keys = function() {
		var k = new Array();
		for(var i=0; i<this.array.length; i++) {
			k[i] = this.array[i].key;
		}
		return k;
	}

	this.size = function(){
		return this.array.length;
	}

	this.containsKey = function(key){
		for(var i=0; i<this.array.length; i++) {
			if(this.array[i].key == key)
				return true;
		}
		return false;
	}

	this.containsValue = function(value) {
		for(var i=0; i<this.array.length; i++) {
			if(this.array[i].value == value)
				return true;
		}
		return false;
	}

	this.iterator = function(){
		return new Iterator(this.array);
	}
}

/**
 *  Objeto AJAX para comunica��o Assincrona com um servidor de aplica��es WEB
 */
var mtw = {
	Version	:	'2.6.1',

	/**
	 * Returns a DOM element by name or id
	 * @param idOrName
	 * @return DOM
	 */
	getElement: function(idOrName){
		var comp = document.getElementById(idOrName);
		if(comp == null || comp == undefined){
			comp = document.getElementsByName(idOrName)[0];
		}

		return comp;
	},

	removeOptions: function(idOrName) {
		mtw.getElement(idOrName).options.length = 0;
	},

	addOptions: function(idOrName, response, keyDef, valDef){
		comp = mtw.getElement(idOrName);
		comp.options.length = 0;

		if(keyDef !== undefined && valDef !== undefined){
			comp.options[comp.length] = new Option(valDef, keyDef);
		}

		for(i=0;i<response.size();i++){
			map = response.getObject(i);
			comp.options[comp.length] = new Option(map.value, map.key);
		}
	},

	/**
	 * Add a new option for given select
	 *
	 * @param idOrName (String)
	 * @param key (String)
	 * @param value (String)
	 * @param selected (Boolean) - should be selected
	 *
	 * @return true - if added or not
	 */
	addOption: function(idOrName, key, value, selected){
		var comp = mtw.getElement(idOrName);
		if(comp == null || comp == undefined){
			return false;
		}

		var option = new Option(value, key);

		if(selected === true || selected == 'true')
			option.selected = true;

		comp.options[comp.length] = option;

		return true;
	}
}

mtw.request = function(){
	this.url				=	null;
	this.charset			=	_MENTA_DEFAULT_CHARSET;		// Default: UTF-8
	this.metodo				=	"POST";
	this.processaresultado	=	null;
	this.Header				=	[];
	this.processaErro		=	null;
	this.FORMV				=	null;
	this.PARS				=	null;
	this.asynchronous		=	true;
	this.useMessage			=	null;
	this.hashHeader			=	{};
	this.alive				=	false;
	this.aborted			=	false;
	this.processAbort		=	null;
	this.prefunction		=	null;
	this.postfunction		=	null;

	this.preFunction = function(fn) {
    	this.prefunction = fn;
    };

    this.postFunction = function(fn) {
    	this.postfunction = fn;
    };

}

mtw.request.prototype = {

	coc: function() {

		var hasInnerActionPattern = /\x2E*\x2E/g;
		if(hasInnerActionPattern.test(this.url)) {

			var innerHTMLPattern = /(\.)+(innerHTML).*/;
			var innerHTMLSplit = /(\.)+(innerHTML)/;

			if( innerHTMLPattern.test(this.url) ) {
				var splited = this.url.split( innerHTMLSplit );
				var idFinded = splited[3].replace(/(\.)+(mtw)$/, "");

				this.processaresultado = function(trans) {
					new mtw.response(trans).innerHTML(idFinded);
				}

			} else {

				var innerAction = this.url.split(hasInnerActionPattern);
				innerAction = innerAction[1];

				try {
					// Procura uma fun��o com o mesmo nome da innerAction
					eval(innerAction);
					this.processaresultado = eval(innerAction);

				} catch (e) {

				// n�o faz nada com o resultado
				// envia um requisi��o sem resposta
				this.processaresultado = function(){};

				}

			}

		}
	},

	setUrl: function(url) {
			this.url = url;
	},

	setCharset: function(charset){
		this.charset = charset;
	},

	setMethod: function(method){
			if(method == "GET" || method == "POST") {
				this.metodo = method;
			} else {
				this.metodo = 'POST';
			}
	},

	onSuccess: function(fn){
			this.processaresultado = fn;
	},

	notInMentawai: function(fn) {
		this.notInMentawaiFn = fn;
	},

	onError: function(fn){
			this.processaErro = fn;
	},

	onAbort: function(fn){
			this.processAbort = fn;
	},

	addHeader:	function(h,v) {
					this.Header[h] = v;
				},

	delHeader:	function(h) {
					delete(this.Header[h]);
				},

	setHeader:	function() {
					if(this.httprequest==null) { return;}
					var m = "";
					for(var h in this.Header) {
						try {
							this.httprequest.setRequestHeader(h,this.Header[h]);
						} catch (e) {
							// this try is necessary if somebody change Array Object.
						}
					}
				},

	noCache:	function(){
		this.addHeader("Cache-Control", "no-store, no-cache, must-revalidate, post-check=0, pre-check=0");
		this.addHeader("Pragma", "no-cache");
	},

	waitComplete: function() {
		this.asynchronous = false;
	},

	send:	function() {
		if(this.url==null) {
			alert("url not setted!");
			return;
		}
		if(this.processaresultado == null){
			this.coc();
		}

		this.httprequest = null;
	   	if (window.XMLHttpRequest) { // Mozilla, Safari,...
         	this.httprequest = new XMLHttpRequest();
    	} else if (window.ActiveXObject) { // IE
         	try {
		     	 this.httprequest = new ActiveXObject("Msxml2.XMLHTTP");
	     	} catch (e) {
           		try {
	           	 this.httprequest = new ActiveXObject("Microsoft.XMLHTTP");
				} catch (e) {}
			}
		}
		if(this.httprequest!=null&&this.httprequest!=undefined) {
			var obj = this;
			this.httprequest.onreadystatechange = 	function() {
														obj.processaretorno.call(obj);
													}

			if( this.PARS == null)
				this.addParameter('squid','fix');

			if(this.metodo == "GET") {
				this.url += "?" + this.PARS;
				this.addHeader("Content-Type", "charset=" + this.charset );
			} else {
				this.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=" + this.charset );
				this.setHeader('Content-Length', this.PARS.length);
			}

			this.addHeader('MentaAjax-Version', mtw.Version);
			this.addHeader('isAjaxRequest', true);

			if(this.useMessage != null) {
				this.useLoadingMessageFunction(this.useMessage);
			}

			if(typeof this.prefunction == 'function')
				this.prefunction(this);

        	this.httprequest.open(this.metodo,this.url, this.asynchronous);
			this.setHeader();
			this.alive = true;
			this.aborted = false;
	        this.httprequest.send(this.PARS);
		}
	},

	processaretorno:	function() {
		if(this.httprequest.readyState==4) {
			this.alive = false;

			var mv = this.httprequest.getResponseHeader("Mentawai-Version");	// if null, not using mentawai.
			if(mv == null) {
				if( typeof this.notInMentawaiFn == 'function' ) {
					this.notInMentawaiFn(this.httprequest);
				}
				else {
					alert("Error\nCode: "+ this.httprequest.status + " " + this.httprequest.statusText + "\nURL: " + this.url + "\nnotInMentawai");
				}
				return;
			}

			var ctype = this.httprequest.getResponseHeader("Content-Type");
			if( ctype == 'application/javascript') {
				eval( '(' + this.httprequest.responseText + ')()' );
				return;
			}

			// if be aborted, find onAbort method
			if(this.aborted){
				if(this.processAbort != null || ( typeof this.processAbort == 'function' )) {
					this.processAbort(this.httprequest);
				}
				return;
			}

			if(this.httprequest.status==200) {
				this.hideMessageFunction();

				if(typeof this.postfunction == 'function')
					this.postfunction(this);

				this.processaresultado(this.httprequest);
			} else {
				this.hideMessageFunction();

				if(typeof this.postfunction == 'function')
					this.postfunction(this);

				if(this.processaErro == null || ( typeof this.processaErro != 'function' )) {
					this.processaErro = function(){
						alert("Error\nCode: "+ this.httprequest.status + " " + this.httprequest.statusText + "\nURL: " + this.url);
					};
				}
				this.processaErro(this.httprequest);
			}
		}
	},

	isAlive: function(){
		return this.alive;
	},

	abort: function(){

		if( !(this.httprequest == null || this.httprequest === undefined) ) {
			if(this.isAlive()){
				this.aborted = true;
				this.httprequest.abort();
			}
		}

	},

	addParameter: function(key, value){
		if(this.FORMV == null) {
			this.FORMV = document.createElement("form");
			this.FORMV.setAttribute("id", "mtwFormVirtual");
			this.FORMV.style.display = 'none';
			document.body.appendChild(this.FORMV);
		}
		var node = document.createElement("input");
		node.setAttribute("name", key);
		node.setAttribute("value", value);
		this.FORMV.appendChild(node);
		this.PARS = this.serialize();
	},

	// s� para ser utilizada neste objeto
	serialize:	function(){
		var elements = this.FORMV.childNodes;
		var e;
		var result = "";
		for(var i=0; i<elements.length; i++) {
			e = elements.item(i);
			result += encodeURIComponent(e.name) + "=" + encodeURIComponent(e.value);
			if(elements.length > i + 1) {
				result += "&";
			}
		}
		return result;
	},

	useLoadingMessage: function(message) {
		if(typeof message == 'function')
			this.useLoadingMessageFunction = message;

		this.useMessage = (message == undefined) ? "Loading..." : message ;
	},

	hideMessage: function(fn) {
		if(typeof fn == 'function')
			this.hideMessageFunction = fn;
	},

	useLoadingMessageFunction: function(message) {
	  var loadingMessage = message;

	    var disabledZone = document.getElementById('disabledZone');
	    if (!disabledZone) {
	      disabledZone = document.createElement('div');
	      disabledZone.setAttribute('id', 'disabledZone');
	      disabledZone.style.position = "absolute";
	      disabledZone.style.zIndex = "1000";
	      disabledZone.style.left = "0px";
	      disabledZone.style.top = "0px";
	      disabledZone.style.width = "100%";
	      disabledZone.style.height = "100%";
	      document.body.appendChild(disabledZone);
	      var messageZone = document.createElement('div');
	      messageZone.setAttribute('id', 'messageZone');
	      messageZone.style.position = "absolute";
	      messageZone.style.top = "0px";
	      messageZone.style.right = "0px";
	      messageZone.style.background = "blue";
	      messageZone.style.color = "white";
	      messageZone.style.fontFamily = "Arial,Helvetica,sans-serif";
	      messageZone.style.padding = "4px";
	      disabledZone.appendChild(messageZone);
	      var text = document.createTextNode(loadingMessage);
	      messageZone.appendChild(text);
	    }
	    else {
	      document.getElementById('disabledZone').innerHTML = loadingMessage;
	      disabledZone.style.visibility = 'visible';
	    }
	},

    hideMessageFunction:  function() {
	   	if(document.getElementById('disabledZone')){
	   		document.getElementById('disabledZone').style.visibility = 'hidden';
	   	}
    }

}

mtw.response = function(transport){
	this.jsonData = null;
	this.textData = null;

	this.textData = transport.responseText;

	this.constructor = function() {
		if(this.textData != null ) {
			if( this.isJSON(this.textData) ) {
				try {
					this.jsonData = eval('(' + this.textData + ')');
				} catch (e) { }
			}
		}
	}

	this.isJSON = function(string) {
    	var str = string.replace(/\\./g, '@').replace(/"[^"\\\n\r]*"/g, '');
    	return (/^[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]*$/).test(str);
  	},

	this.getObject = function(index){
		if(typeof index == 'undefined') { index = 0 };
		return this.jsonData.obj[index];
	},

	this.getValue = function(key){
		var data = this.jsonData.obj;
		for(var i = 0; i < this.size(); i++){
			if(data[i].key == key) {
				return data[i].value;
			}
		}
		return '';
	},

	this.size = function(){
		if(this.jsonData != null) {
			return this.jsonData.obj.length;
		} else {
			return 0;
		}
	},

	this.getString = function(){
		return this.textData;
	},

	this.innerHTML = function(id){
		document.getElementById(id).innerHTML = this.getString();
	},

	this.replaceOptions = function(id){
		mtw.removeOptions(id);
		mtw.addOptions(id, this);
	},

	this.isMap = function(){
		var obj;
		var result = false;
		for(var i=0; i<this.size(); i++) {
			obj = this.getObject(i);
			if(obj.key && obj.value) {
				result = true;
				if(i > 5) break;
			} else {
				result = false;
				break;
			}
		}
		return result;
	},

	this.hashMap = function(){
		var map = new HashMap();
		if(this.isMap()) {
			for(var i=0; i<this.size(); i++) {
				map.put(this.getObject(i).key, this.getObject(i).value)
			}
		}
		return map;
	}

	this.iterator = function() {
		if(this.isMap()) {
			return this.hashMap().iterator();
		} else {
			// Is List
			var amostra = this.getObject();
			var keys = new Array();
			for(var k in amostra) {
				keys[keys.length] = k;
			}

			var list = new Array();
			for(var i=0; i<this.size(); i++) {
				list[i] = this.getObject(i);
			}

			return new Iterator(list);
		}
	}

	this.constructor();
}


text:
require 'factory_girl'

FactoryGirl.define do
  factory :alpine_workfile, aliases: [:work_flow] do
    owner
    workspace
    description "Using two datasources to #{Faker::Company.bs.downcase}."
    file_name Faker::Lorem.word

    factory :work_flow_with_all_data_sources do
      after(:create) do |workfile, evaluator|
        gpdb = FactoryGirl.create(:gpdb_data_source, owner: workfile.owner)
        oracle = FactoryGirl.create(:oracle_data_source, owner: workfile.owner)
        database = FactoryGirl.create(:gpdb_database, data_source: gpdb)
        hadoop = FactoryGirl.create(:hdfs_data_source, owner: workfile.owner)
        workfile.workfile_execution_locations.create(execution_location: database)
        workfile.workfile_execution_locations.create(execution_location: hadoop)
        workfile.workfile_execution_locations.create(execution_location: oracle)
      end
    end
  end

  factory :workfile do
    owner
    workspace
    description 'A nice description'
    file_name 'workfile.doc'
  end

  factory :chorus_workfile do
    owner
    workspace
    additional_data ''
    description 'A nice description'
    file_name 'chorus_workfile.doc'
  end

  factory :workfile_version do
    association :workfile, :factory => :chorus_workfile
    version_num '1'
    owner
    commit_message 'Factory commit message'
    modifier
  end

  factory :workfile_draft do
    association :workfile, :factory => :chorus_workfile
    owner
    content 'Excellent content'
  end
end


text:
import React from 'react';
import * as firebase from "firebase";
import FlatButton from 'material-ui/FlatButton';

var config = {
    apiKey: "AIzaSyCcdwSaeUisGBVLatMFwvtDJiFOkuEMbV8",
    authDomain: "universal-rider-149309.firebaseapp.com",
    databaseURL: "https://universal-rider-149309.firebaseio.com",
    storageBucket: "universal-rider-149309.appspot.com",
    messagingSenderId: "282294912427"
  };

firebase.initializeApp(config);

var provider = new firebase.auth.GoogleAuthProvider();

class Login extends React.Component{
    constructor(props) {
        super(props);
        this.handleLogin = this.handleLogin.bind(this);
        this.signout = this.signout.bind(this);
        this.state = {
            "user": firebase.auth().currentUser,
            "signnedIn":false
        }
        var _this = this;
        firebase.auth().onAuthStateChanged(function(user) {
            if (user) {
                _this.setState({
                    "signnedIn": true,
                    "user": user
                });
                _this.props.updateHandler(user);
            } else {
                _this.setState({
                    "signnedIn": false
                });
            }
            });
    }

    handleLogin() {
        firebase.auth().signInWithPopup(provider).then(function(result) {
        // This gives you a Google Access Token. You can use it to access the Google API.
        var token = result.credential.accessToken;
        // The signed-in user info.
        var user = result.user;
        // ...
        }).catch(function(error) {
        // Handle Errors here.
        var errorCode = error.code;
        var errorMessage = error.message;
        // The email of the user's account used.
        var email = error.email;
        // The firebase.auth.AuthCredential type that was used.
        var credential = error.credential;
        // ...
        });
    }

    signout() {
        var _this = this;
        firebase.auth().signOut().then(function() {
            // Sign-out successful.
            _this.forceUpdate();
        }, function(error) {
        // An error happened.
        });
    }

    render() {
        if (!this.state.signnedIn){
            return <FlatButton label="Login"  onClick={this.handleLogin} />;
        } else {
            return <FlatButton label={this.state.user.displayName + ", signout?" } onClick={this.signout} />;
        }
    }
}

export default Login;


text:
package org.apache.tools.ant.taskdefs.optional.sos;

import java.io.File;

import org.apache.tools.ant.BuildFileTest;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.types.Commandline;
import org.apache.tools.ant.types.Path;

/**
 *  Testcase to ensure that command line generation and required attributes are
 *  correct.
 *
 */
public class SOSTest extends BuildFileTest {

    private Commandline commandline;

    private static final String VSS_SERVER_PATH = "\\\\server\\vss\\srcsafe.ini";
    private static final String VSS_PROJECT_PATH = "/SourceRoot/Project";
    private static final String DS_VSS_PROJECT_PATH = "$/SourceRoot/Project";
    private static final String SOS_SERVER_PATH = "192.168.0.1:8888";
    private static final String SOS_USERNAME = "ant";
    private static final String SOS_PASSWORD = "rocks";
    private static final String LOCAL_PATH = "testdir";
    private static final String SRC_FILE = "Class1.java";
    private static final String SRC_LABEL = "label1";
    private static final String SRC_COMMENT = "I fixed a bug";
    private static final String SOS_HOME = "/home/user/.sos";
    private static final String VERSION = "007";

    /**
     *  Constructor for the SOSTest object
     *
     * @param  s  Test name
     */
    public SOSTest(String s) {
        super(s);
    }

    /**
     *  The JUnit setup method
     *
     * @throws  Exception
     */
    protected void setUp()
        throws Exception {
        project = new Project();
        project.setBasedir(".");
    }

    /**
     *  The teardown method for JUnit
     *
     * @throws  Exception
     */
    protected void tearDown()
        throws Exception {
        File file = new File(project.getBaseDir(), LOCAL_PATH);
        if (file.exists()) {
            file.delete();
        }
    }

    /**  Test SOSGetFile flags & commandline generation  */
    public void testGetFileFlags() {
        String[] sTestCmdLine = {"soscmd", "-command", "GetFile", "-file",
                SRC_FILE, "-revision", "007", "-server", SOS_SERVER_PATH, "-name",
                SOS_USERNAME, "-password", SOS_PASSWORD, "-database", VSS_SERVER_PATH,
                "-project", DS_VSS_PROJECT_PATH, "-verbose", "-nocompress",
                "-nocache", "-workdir", project.getBaseDir().getAbsolutePath()
                 + File.separator + LOCAL_PATH};

        // Set up a SOSGet task
        SOSGet sosGet = new SOSGet();
        sosGet.setProject(project);
        sosGet.setVssServerPath(VSS_SERVER_PATH);
        sosGet.setSosServerPath(SOS_SERVER_PATH);
        sosGet.setProjectPath(VSS_PROJECT_PATH);
        sosGet.setFile(SRC_FILE);
        sosGet.setUsername(SOS_USERNAME);
        sosGet.setPassword(SOS_PASSWORD);
        sosGet.setVersion(VERSION);
        sosGet.setLocalPath(new Path(project, LOCAL_PATH));
        sosGet.setNoCache(true);
        sosGet.setNoCompress(true);
        sosGet.setVerbose(true);
        sosGet.setRecursive(true);

        commandline = sosGet.buildCmdLine();

        checkCommandLines(sTestCmdLine, commandline.getCommandline());
    }

    /**  Test SOSGetProject flags & commandline generation  */
    public void testGetProjectFlags() {
        String[] sTestCmdLine = {"soscmd", "-command", "GetProject", "-recursive",
                "-label", SRC_LABEL, "-server", SOS_SERVER_PATH, "-name", SOS_USERNAME,
                "-password", "", "-database", VSS_SERVER_PATH, "-project",
                DS_VSS_PROJECT_PATH, "", "", "-soshome", SOS_HOME, "-workdir",
                project.getBaseDir().getAbsolutePath()};

        // Set up a SOSGet task
        SOSGet sosGet = new SOSGet();
        sosGet.setProject(project);
        sosGet.setVssServerPath(VSS_SERVER_PATH);
        sosGet.setSosServerPath(SOS_SERVER_PATH);
        sosGet.setProjectPath(DS_VSS_PROJECT_PATH);
        sosGet.setLabel(SRC_LABEL);
        sosGet.setUsername(SOS_USERNAME);
        sosGet.setSosHome(SOS_HOME);
        sosGet.setNoCache(true);
        sosGet.setNoCompress(false);
        sosGet.setVerbose(false);
        sosGet.setRecursive(true);

        commandline = sosGet.buildCmdLine();

        checkCommandLines(sTestCmdLine, commandline.getCommandline());
    }

    /**  Tests SOSGet required attributes.  */
    public void testGetExceptions() {
        configureProject("src/etc/testcases/taskdefs/optional/sos/sos.xml");
        expectSpecificBuildException("sosget.1", "some cause", "sosserverpath attribute must be set!");
        expectSpecificBuildException("sosget.2", "some cause", "username attribute must be set!");
        expectSpecificBuildException("sosget.3", "some cause", "vssserverpath attribute must be set!");
        expectSpecificBuildException("sosget.4", "some cause", "projectpath attribute must be set!");
    }

    /**  Test CheckInFile option flags  */
    public void testCheckinFileFlags() {
        String[] sTestCmdLine = {"soscmd", "-command", "CheckInFile", "-file",
                SRC_FILE, "-server", SOS_SERVER_PATH, "-name", SOS_USERNAME,
                "-password", SOS_PASSWORD, "-database", VSS_SERVER_PATH, "-project",
                DS_VSS_PROJECT_PATH, "-verbose", "-nocompress", "-nocache",
                "-workdir", project.getBaseDir().getAbsolutePath() + File.separator
                 + LOCAL_PATH, "-log", SRC_COMMENT};

        // Set up a SOSCheckin task
        SOSCheckin sosCheckin = new SOSCheckin();
        sosCheckin.setProject(project);
        sosCheckin.setVssServerPath(VSS_SERVER_PATH);
        sosCheckin.setSosServerPath(SOS_SERVER_PATH);
        sosCheckin.setProjectPath(VSS_PROJECT_PATH);
        sosCheckin.setFile(SRC_FILE);
        sosCheckin.setComment(SRC_COMMENT);
        sosCheckin.setUsername(SOS_USERNAME);
        sosCheckin.setPassword(SOS_PASSWORD);
        sosCheckin.setLocalPath(new Path(project, LOCAL_PATH));
        sosCheckin.setNoCache(true);
        sosCheckin.setNoCompress(true);
        sosCheckin.setVerbose(true);
        sosCheckin.setRecursive(true);

        commandline = sosCheckin.buildCmdLine();

        checkCommandLines(sTestCmdLine, commandline.getCommandline());
    }

    /**  Test CheckInProject option flags  */
    public void testCheckinProjectFlags() {
        String[] sTestCmdLine = {"soscmd", "-command", "CheckInProject",
                "-recursive", "-server", SOS_SERVER_PATH, "-name", SOS_USERNAME,
                "-password", "", "-database", VSS_SERVER_PATH, "-project",
                DS_VSS_PROJECT_PATH, "", "", "-soshome", SOS_HOME, "-workdir",
                project.getBaseDir().getAbsolutePath(), "-log", SRC_COMMENT,};

        // Set up a SOSCheckin task
        SOSCheckin sosCheckin = new SOSCheckin();
        sosCheckin.setProject(project);
        sosCheckin.setVssServerPath(VSS_SERVER_PATH);
        sosCheckin.setSosServerPath(SOS_SERVER_PATH);
        sosCheckin.setProjectPath(DS_VSS_PROJECT_PATH);
        sosCheckin.setComment(SRC_COMMENT);
        sosCheckin.setUsername(SOS_USERNAME);
        sosCheckin.setSosHome(SOS_HOME);
        sosCheckin.setNoCache(true);
        sosCheckin.setNoCompress(false);
        sosCheckin.setVerbose(false);
        sosCheckin.setRecursive(true);

        commandline = sosCheckin.buildCmdLine();

        checkCommandLines(sTestCmdLine, commandline.getCommandline());
    }

    /**  Test SOSCheckIn required attributes.  */
    public void testCheckinExceptions() {
        configureProject("src/etc/testcases/taskdefs/optional/sos/sos.xml");
        expectSpecificBuildException("soscheckin.1", "some cause", "sosserverpath attribute must be set!");
        expectSpecificBuildException("soscheckin.2", "some cause", "username attribute must be set!");
        expectSpecificBuildException("soscheckin.3", "some cause", "vssserverpath attribute must be set!");
        expectSpecificBuildException("soscheckin.4", "some cause", "projectpath attribute must be set!");
    }

    /**  Test CheckOutFile option flags  */
    public void testCheckoutFileFlags() {
        String[] sTestCmdLine = {"soscmd", "-command", "CheckOutFile", "-file",
                SRC_FILE, "-server", SOS_SERVER_PATH, "-name", SOS_USERNAME,
                "-password", SOS_PASSWORD, "-database", VSS_SERVER_PATH, "-project",
                DS_VSS_PROJECT_PATH, "-verbose", "-nocompress", "-nocache",
                "-workdir", project.getBaseDir().getAbsolutePath()
                 + File.separator + LOCAL_PATH};

        // Set up a SOSCheckout task
        SOSCheckout sosCheckout = new SOSCheckout();
        sosCheckout.setProject(project);
        sosCheckout.setVssServerPath(VSS_SERVER_PATH);
        sosCheckout.setSosServerPath(SOS_SERVER_PATH);
        sosCheckout.setProjectPath(DS_VSS_PROJECT_PATH);
        sosCheckout.setFile(SRC_FILE);
        sosCheckout.setUsername(SOS_USERNAME);
        sosCheckout.setPassword(SOS_PASSWORD);
        sosCheckout.setLocalPath(new Path(project, LOCAL_PATH));
        sosCheckout.setNoCache(true);
        sosCheckout.setNoCompress(true);
        sosCheckout.setVerbose(true);
        sosCheckout.setRecursive(true);

        commandline = sosCheckout.buildCmdLine();

        checkCommandLines(sTestCmdLine, commandline.getCommandline());
    }

    /**  Test CheckOutProject option flags  */
    public void testCheckoutProjectFlags() {
        String[] sTestCmdLine = {"soscmd", "-command", "CheckOutProject",
                "-recursive", "-server", SOS_SERVER_PATH, "-name", SOS_USERNAME,
                "-password", "", "-database", VSS_SERVER_PATH, "-project",
                DS_VSS_PROJECT_PATH, "", "", "-soshome", SOS_HOME, "-workdir",
                project.getBaseDir().getAbsolutePath()};

        // Set up a sosCheckout task
        SOSCheckout sosCheckout = new SOSCheckout();
        sosCheckout.setProject(project);
        sosCheckout.setVssServerPath(VSS_SERVER_PATH);
        sosCheckout.setSosServerPath(SOS_SERVER_PATH);
        sosCheckout.setProjectPath(VSS_PROJECT_PATH);
        sosCheckout.setUsername(SOS_USERNAME);
        sosCheckout.setSosHome(SOS_HOME);
        sosCheckout.setNoCache(true);
        sosCheckout.setNoCompress(false);
        sosCheckout.setVerbose(false);
        sosCheckout.setRecursive(true);

        commandline = sosCheckout.buildCmdLine();

        checkCommandLines(sTestCmdLine, commandline.getCommandline());
    }

    /**  Test SOSCheckout required attributes.  */
    public void testCheckoutExceptions() {
        configureProject("src/etc/testcases/taskdefs/optional/sos/sos.xml");
        expectSpecificBuildException("soscheckout.1", "some cause", "sosserverpath attribute must be set!");
        expectSpecificBuildException("soscheckout.2", "some cause", "username attribute must be set!");
        expectSpecificBuildException("soscheckout.3", "some cause", "vssserverpath attribute must be set!");
        expectSpecificBuildException("soscheckout.4", "some cause", "projectpath attribute must be set!");
    }

    /**  Test Label option flags  */
    public void testLabelFlags() {
        String[] sTestCmdLine = {"soscmd", "-command", "AddLabel", "-server",
                SOS_SERVER_PATH, "-name", SOS_USERNAME, "-password", "", "-database",
                VSS_SERVER_PATH, "-project", DS_VSS_PROJECT_PATH, "-label",
                SRC_LABEL, "-verbose", "-log", SRC_COMMENT};

        // Set up a sosCheckout task
        SOSLabel sosLabel = new SOSLabel();
        sosLabel.setVssServerPath(VSS_SERVER_PATH);
        sosLabel.setSosServerPath(SOS_SERVER_PATH);
        sosLabel.setProjectPath(DS_VSS_PROJECT_PATH);
        sosLabel.setUsername(SOS_USERNAME);
        sosLabel.setSosHome(SOS_HOME);
        sosLabel.setComment(SRC_COMMENT);
        sosLabel.setLabel(SRC_LABEL);
        sosLabel.setNoCache(true);
        sosLabel.setNoCompress(false);
        sosLabel.setVerbose(true);

        commandline = sosLabel.buildCmdLine();

        checkCommandLines(sTestCmdLine, commandline.getCommandline());
    }

    /**  Test SOSLabel required attributes.  */
    public void testLabelExceptions() {
        configureProject("src/etc/testcases/taskdefs/optional/sos/sos.xml");
        expectSpecificBuildException("soslabel.1", "some cause", "sosserverpath attribute must be set!");
        expectSpecificBuildException("soslabel.2", "some cause", "username attribute must be set!");
        expectSpecificBuildException("soslabel.3", "some cause", "vssserverpath attribute must be set!");
        expectSpecificBuildException("soslabel.4", "some cause", "projectpath attribute must be set!");
        expectSpecificBuildException("soslabel.5", "some cause", "label attribute must be set!");
    }

    /**
     *  Iterate through the generated command line comparing it to reference
     *  one.
     *
     * @param  sTestCmdLine       The reference command line;
     * @param  sGeneratedCmdLine  The generated command line;
     */
    private void checkCommandLines(String[] sTestCmdLine, String[] sGeneratedCmdLine) {
        int length = sTestCmdLine.length;
        for (int i = 0; i < length; i++) {
            try {
                assertEquals("arg # " + String.valueOf(i),
                        sTestCmdLine[i],
                        sGeneratedCmdLine[i]);
            } catch (ArrayIndexOutOfBoundsException aioob) {
                fail("missing arg " + sTestCmdLine[i]);
            }
        }
        if (sGeneratedCmdLine.length > sTestCmdLine.length) {
            // We have extra elements
            fail("extra args");
        }
    }
}


text:
package ru.job4j.storages;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import ru.job4j.storages.entity.User;

import javax.sql.DataSource;
import java.sql.ResultSet;
import java.sql.SQLException;

public class JdbcStorage implements Storage {

    JdbcTemplate jdbctemplate;
    DataSource dataSource;

    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
        this.jdbctemplate = new JdbcTemplate(dataSource);
    }

    public JdbcStorage() {
    }

    @Override
    public void add(User user) {
        jdbctemplate.update("INSERT INTO userstor (id, first_name, last_name, email) VALUES(?, ?, ?, ?)", user.getId(), user.getFirstName(), user.getLastName(), user.getEmail());
    }

    public User get(int id) {
        return jdbctemplate.queryForObject("SELECT * FROM userstor WHERE id = ?", new Object[]{id}, new UserMapper());
    }

    public class UserMapper implements RowMapper<User> {
        @Override
        public User mapRow(ResultSet resultSet, int i) throws SQLException {
            User user = new User();

            user.setId(resultSet.getInt("id"));
            user.setFirstName(resultSet.getString("first_name"));
            user.setLastName(resultSet.getString("last_name"));
            user.setEmail(resultSet.getString("email"));

            return user;
        }
    }
}


text:
<!DOCTYPE html>

<meta charset="utf-8"/>
<title>cjk-decimal, 0-9</title>
<link rel='author' title='Richard Ishida' href='mailto:ishida@w3.org'>
<link rel='help' href='http://www.w3.org/TR/css-counter-styles-3/#simple-numeric'>
<link rel="reviewer" title="Chris Lilley" href="mailto:chris@w3.org" />
<meta name='flags' content='font'>
<meta name="assert" content="list-style-type: cjk-decimal produces numbers up to 9 items per the spec.">

Test passes if the two columns are the same, IGNORING the suffix.

<bdi>一、</bdi>一

<bdi>二、</bdi>二

<bdi>三、</bdi>三

<bdi>四、</bdi>四

<bdi>五、</bdi>五

<bdi>六、</bdi>六

<bdi>七、</bdi>七

<bdi>八、</bdi>八

<bdi>九、</bdi>九