text:
'use strict';

/**
 * ========= LIBRARIES =========
 */
var express = require('express');
var path = require('path');
var twig = require('twig');
var app = express();
var fs = require("fs");
var sqlite3 = require("sqlite3").verbose();
var bodyParser = require('body-parser')
app.use( bodyParser.json() );       // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({     // to support URL-encoded bodies
    extended: true
}));
app.set("twig options", {
    strict_variables: false
});

app.set('view engine', 'twig');
app.set('views', path.join(__dirname, 'public'));
/**
 * ========= DATABASE =========
 */
var quizdb_name = path.join(__dirname, 'quiz.db');
var exists = fs.existsSync(quizdb_name);
// Database init
var db = new sqlite3.Database(quizdb_name);
db.serialize(function(){
    db.run("PRAGMA foreign_keys = ON;");
    db.run("CREATE TABLE IF NOT EXISTS UTILISATEURS (" +
        "ID INTEGER PRIMARY KEY AUTOINCREMENT," +
        "SEXE BOOLEAN NOT NULL," +
        "AGE INT NOT NULL," +
        "STNAZAIRE BOOLEAN NOT NULL" +
        ")");
    db.run("CREATE TABLE IF NOT EXISTS PROJETS (" +
        "ID INTEGER PRIMARY KEY AUTOINCREMENT," +
        "NOM TEXT(60) NOT NULL" +
        ")");
    db.run("CREATE TABLE IF NOT EXISTS ESTIMATION_PROJET (" +
        "ID_PROJET INT NOT NULL," +
        "ID_UTILISATEUR INT NOT NULL," +
        "ESTIMATION INT NOT NULL," +
        "FOREIGN KEY(ID_PROJET) REFERENCES PROJETS(ID)," +
        "FOREIGN KEY(ID_UTILISATEUR) REFERENCES UTILISATEURS(ID)" +
        ")");
    db.run("CREATE TABLE IF NOT EXISTS NOTE_PROJET (" +
        "ID_PROJET INT NOT NULL," +
        "ID_UTILISATEUR INT NOT NULL," +
        "NOTE INT NOT NULL," +
        "FOREIGN KEY(ID_PROJET) REFERENCES PROJETS(ID)," +
        "FOREIGN KEY(ID_UTILISATEUR) REFERENCES UTILISATEURS(ID)" +
        ")");
});
db.close();
/**
 * ========= ROUTE =========
 */
/**
 *  Route to Quiz
 */
app.all('/quiz', function(req, res){
    res.render('quiz.html.twig');
});

/**
 *  --- BACKEND ---
 */
app.get('/projets/get/all', function(req, res){
    var db = new sqlite3.Database(quizdb_name);
    db.all("SELECT * FROM PROJETS", function(err, rows){
        res.json(rows);
    })
    db.close();
});

app.get('/projets/get/:id', function(req, res){
    var db = new sqlite3.Database(quizdb_name);
    db.all("SELECT * FROM PROJETS WHERE ID = ?", [req.params.id], function(err, rows){
        res.json(rows);
    })
    db.close();
});

app.get('/projets/add', function(req, res){
    var db = new sqlite3.Database(quizdb_name);
    db.serialize(function(){
        var stmt = db.prepare("INSERT INTO PROJETS (NOM) VALUES (?)");
        stmt.run(req.query.nom);
        stmt.finalize();
        res.send("OK");
    });
    db.close();
});

app.get("/utilisateurs/get/all", function(req, res){
    var db = new sqlite3.Database(quizdb_name);
    db.all("SELECT * FROM UTILISATEURS", function(err, rows){
        res.json(rows);
    })
    db.close();
});

app.get("/utilisateurs/get/lastid", function(req, res){
    var db = new sqlite3.Database(quizdb_name);
    db.get("SELECT ID as id FROM UTILISATEURS ORDER BY id DESC LIMIT 1", function(err, rows){
        res.json(rows);
    })
    db.close();
})

app.get('/utilisateurs/get/:id', function(req, res){
    var db = new sqlite3.Database(quizdb_name);
    db.all("SELECT * FROM UTILISATEURS WHERE ID = ?", [req.params.id], function(err, rows){
        res.json(rows);
    })
    db.close();
});

app.get('/utilisateurs/add', function(req, res){
    var db = new sqlite3.Database(quizdb_name);
    db.serialize(function(){
        var stmt = db.prepare("INSERT INTO UTILISATEURS (SEXE, AGE, STNAZAIRE) VALUES (?, ?, ?)");
        stmt.run(req.query.sexe, req.query.age, req.query.stnazaire);
        stmt.finalize();
        res.send("OK");
    });
    db.close();
});

app.get('/estimation/get/all', function(req, res){
    var db = new sqlite3.Database(quizdb_name);
    db.all("SELECT * FROM ESTIMATION_PROJET", function(err, rows){
        res.json(rows);
    })
    db.close();
})

app.get('/estimation/get/counted/:id', function(req, res){
    var db = new sqlite3.Database(quizdb_name);
    db.all("SELECT ESTIMATION AS x, COUNT(ESTIMATION) AS y FROM ESTIMATION_PROJET WHERE ID_PROJET = ? GROUP BY ESTIMATION ORDER BY x ASC", [req.params.id], function(err, rows){
        res.json(rows);
    })
    db.close();
})

app.get('/estimation/add', function(req, res){
    var db = new sqlite3.Database(quizdb_name);
    db.serialize(function(){
        var stmt = db.prepare("INSERT INTO ESTIMATION_PROJET (ID_PROJET, ID_UTILISATEUR, ESTIMATION) VALUES (?, ?, ?)");
        stmt.run(req.query.projet, req.query.utilisateur, req.query.estimation);
        stmt.finalize();
        res.send("OK");
    });
    db.close();
});

app.get('/note/get/all', function(req, res){
    var db = new sqlite3.Database(quizdb_name);
    db.all("SELECT * FROM NOTE_PROJET", function(err, rows){
        res.json(rows);
    })
    db.close();
})

app.get('/note/add', function(req, res){
    var db = new sqlite3.Database(quizdb_name);
    db.serialize(function(){
        var stmt = db.prepare("INSERT INTO NOTE_PROJET (ID_PROJET, ID_UTILISATEUR, NOTE) VALUES (?, ?, ?)");
        stmt.run(req.query.projet, req.query.utilisateur, req.query.note);
        stmt.finalize();
        res.send("OK");
    });
    db.close();
});

/**
 * Default route
 */
app.use(express.static(path.join(__dirname, 'public')));

/**
 * ========= EOF =========
 */
// This module is exported and served by the main server.js located
// at the root of this set of projects. You can access it by lanching the main
// server and visiting http(s)://127.0.0.1:8080/name_of_you_project/ (if on a local server)
// or more generally: http(s)://server_name:port/name_of_you_project/
module.exports = app;


text:
<meta http-equiv="Content-Language" content="en-us">
<meta name="GENERATOR" content="WME DocMaker 2.0">
<meta http-equiv="Content-Type" content="text/html; charset=windows-1250">
<title>Window object</title>
<link rel="stylesheet" type="text/css" href="../../styles.css">

Window object

The Window object allows you to access the properties of your game's windows. Window objects are created  by loading a window definition file using the Game.LoadWindow metod. A special case is the window used for the inventory. It can be queried using the Game.GetInventoryWindow method.

Methods

    SetFont
    Sets a normal font.

    SetImage
    Sets a background image (sprite).

    GetImage
    Returns the filename of the background sprite (or null if no sprite is set)

    GetImageObject
    Returns a reference to the background sprite (or null if no sprite is set)

    Focus
    Focuses the control.

    MoveAfter
    Moves the control in z-order after a given control.

    MoveBefore
    Moves the control in z-order before a given control.

    MoveToTop
    Moves the control to the top of the z-order.

    MoveToBottom
    Moves the control to the bottom of the z-order.

    SkipTo
    Moves an object to a specified location.

    Actions

    GetControl
    Get a reference to a given object contained in this window

    SetInactiveFont
    Sets a font to be used when the window is inactive.

    SetInactiveImage
    Sets a background image (sprite) to be used when this window is inactive.

    GetInactiveImage
    Returns the filename of the inactive background sprite (or null if no sprite is set)

    GetInactiveImageObject
    Returns a reference to the inactive background sprite (or null if no sprite is set)

    Close
    Closes the window.

    GoExclusive
    Makes the window an exclusive object on screen.

    GoSystemExclusive
    Pauses the game and makes the window an exclusive object on screen.

    Center
    Centers the window on screen.

    LoadFromFile
    Loads the window definition from a specified file.

    CreateButton
    Dynamically creates a new button control

    CreateStatic
    Dynamically creates a new static control

    CreateEditor
    Dynamically creates a new editor control

    CreateWindow
    Dynamically creates a new sub-window control

    DeleteButton
    Deletes a button object

    DeleteStatic
    Deletes a static control object

    DeleteEditor
    Deletes an editor object

    DeleteWindow
    Deletes a window object

    Cursor functions

    SetCursor
    Sets the standard cursor.

    GetCursor
    Returns the filename of the cursor sprite (or null if no cursor is set)

    GetCursorObject
    Returns a reference to the cursor sprite (or null if no cursor is set)

    RemoveCursor
    Removes the standard cursor.

    HasCursor
    Queries whether the standard cursor is set.

    Script functions

    AttachScript
    Executes a script file and attaches it to the object.

    DetachScript
    Terminates a specified script file and detaches it from an object.

    IsScriptRunning
    Queries whether a specified script file is running and attached to an object.

    CanHandleMethod
    Queries whether the object supports a method of a specified name.

    Sound functions

    PlaySound
    Plays a sound. If the filename is omitted, the currently assigned sound is played (if any).

    PlaySoundEvent
    Plays a sound and triggers an event when the sound is over. If the filename is omitted, the currently assigned sound is played (if any).

    StopSound
    Stops the currently playing sound (if any).

    PauseSound
    Pauses the currently playing sound.

    ResumeSound
    Resumes a paused sound playback.

    IsSoundPlaying
    Queries whether a sound playback is in progress.

    SetSoundPosition
    Sets the sound's current playing position.

    GetSoundPosition
    Queries the sound's current playing position

    SetSoundVolume
    Sets a volume of the currently playing sound.

    GetSoundVolume
    Gets a volume of the currently playing sound.

    LoadSound
    Initializes a sound from file and makes it ready to be played.

    Sound effects functions

    SoundFXNone
    Removes any sound effect currently assigned to this object.

    SoundFXEcho
    Assigns an echo effect to the sounds played by this object.

    SoundFXReverb
    Assigns a reverb effect to the sounds played by this object.

    Event functions

    ApplyEvent
    Applies a named event to the object.

    CanHandleEvent
    Queries whether the object has an event handler for a specified event.

Attributes

    Parent (read only)
    Returns a reference to a parent window of this control (or null)

    ParentNotify
    Specifies whether this control should notify its parent about events

    Width
    A width of the control

    Height
    A height of the control

    Visible
    Specifies whether the control is visible

    Disabled
    Specifies whether the control is disabled

    Text
    A text the control displays

    NextSibling (read only)
    Returns a reference to the next control in z-order

    PrevSibling (read only)
    Returns a reference to the previous control in z-order

    Type (read only)
    Returns always "window"

    NumControls (read only)
    Returns a number of controls contained in this window.

    Exclusive
    Specifies if the window is in exclusive mode.

    SystemExclusive
    Specifies if the window is in system exclusive mode.

    Menu
    Specifies whether this is a "menu" type window (it's closed when the user clicks anywhere outside the window).

    InGame
    Specifies whether this is an "in-game" type window (it's always displayed before the inventory window).

    ClipContents
    Specifies whether the contained controls are clipped when they lie partially outside the window.

    Name
    The internal name of the object.

    Caption
    The caption of the object.

    X
    The X position of the object.

    Y
    The Y position of the object.

    Height (read only)
    Returns the current height of the object. In case of actors and entities the scaling is taken into account.

    Filename (read only)
    Returns the filename.

    Ready (read only)
    Returns whether the object isn't currently performing any action.

    Interactive
    Specifies whether the object recieves user input.

    SoundPanning
    Specifies whether the sounds played by this object are automatically panned depending on object's position on screen.

    NonIntMouseEvents
    Specifies if the object can receive the MouseEntry and MouseLeave events even if the game is in non-interactive mode.

    Movable
    Specifies whether the object can be moved by its sprites (in case the sprite frames have a "move" property set).

    Scalable
    Specifies whether the object is affected by scene's scaling levels.

    Rotatable
    Specifies whether the object is affected by scene's rotation levels.

    Colorable
    Specifies whether the object is affected by scene's color regions.

    AlphaColor
    Specifies an RGBA color of this object (overrides scene coloring); set to 0 to reset default behavior.

    Scale
    Specifies a scale of this object (overrides scene scaling); set to null to reset default behavior.

    ScaleX
    Specifies horizontal scale of this object; set to null to reset default behavior.

    ScaleY
    Specifies vertical scale of this object; set to null to reset default behavior.

    RelativeScale
    Specifies a scale amount to be added to the default scene scale.

    Rotate
    Specifies rotation of this object (in degrees); overrides scene rotation; set to null to reset default behavior; not available in compatibility mode

    RelativeRotate
    Specifies a rotation amount to be added to the default scene rotation.

    FadeColor
    Specifies an alpha color which the background is faded to when this window is being displayed.

    AlphaColor
    Specifies an alpha color which is applied to the entire window.

    PauseMusic
    Specifies whether the music is paused when this window is running in system-exclusive mode.

Low level events

    LeftClick
    The left mouse button has been pressed.

    RightClick
    The right mouse button has been pressed.

    MiddleClick
    The middle mouse button has been pressed.

    LeftDoubleClick
    The left mouse button has been double-clicked.

    LeftRelease
    The left mouse button has been released.

    RightRelease
    The right mouse button has been released.

    MiddleRelease
    The middle mouse button has been released.

    MouseWheelUp
    The mouse wheel has been rolled up.

    MouseWheelDown
    The mouse wheel has been rolled down.

    Keypress
    Some key has been pressed. Use the Keyboard variable to find out the details.

SetFont(Filename)

Sets a normal font.

Parameters

Filename

A filename of a font file to be used.

Return value

If the method succeeds, the return value is true.

SetImage(Filename)

Sets a background image (sprite).

Parameters

Filename

A filename of a sprite file to be used.

Return value

If the method succeeds, the return value is true.

GetImage()

Returns the filename of the background sprite (or null if no sprite is set)

GetImageObject()

Returns a reference to the background sprite (or null if no sprite is set)

Focus()

Focuses the control.

MoveAfter(Control)
MoveAfter(ControlName)

Moves the control in z-order after a given control.

Parameters

Control

A control object we will move our control after

ControlName

A name of a control object we will move our control after

Return value

If the method succeeds, the return value is true.

MoveBefore(Control)
MoveBefore(ControlName)

Moves the control in z-order before a given control.

Parameters

Control

A control object we will move our control before

ControlName

A name of a control object we will move our control before

Return value

If the method succeeds, the return value is true.

MoveToTop()

Moves the control to the top of the z-order.

Return value

If the method succeeds, the return value is true.

MoveToBottom()

Moves the control to the bottom of the z-order.

Return value

If the method succeeds, the return value is true.

SkipTo(X, Y)

Moves an object to a specified location.

Parameters

X

Destination X coordinate.

Y

Destination Y coordinate.

GetControl(ControlIndex)
GetControl(ControlName)

Get a reference to a given object contained in this window

Parameters

ControlIndex

A nuber specifying an index of a control to be returned

ControlName

Name of a control to be returned

Return value

Returns a reference to a requested control or null if such a control doesn't exist

Remarks

This method has been previously called "GetWidget" and this name is still valid for backwards compatibility.

SetInactiveFont(Filename)

Sets a font to be used when the window is inactive.

Parameters

Filename

A filename of a font file to be used.

Return value

If the method succeeds, the return value is true.

SetInactiveImage(Filename)

Sets a background image (sprite) to be used when this window is inactive.

Parameters

Filename

A filename of a sprite file to be used.

Return value

If the method succeeds, the return value is true.

GetInactiveImage()

Returns the filename of the inactive background sprite (or null if no sprite is set)

GetInactiveImageObject()

Returns a reference to the inactive background sprite (or null if no sprite is set)

Close()

Closes the window.

Return value

If the method succeeds, the return value is true.

Remarks

Note that this method only removes window from screen but it stays loaded in memory. If you no longer need the window, you should unload it using the Game.UnloadObject method.

GoExclusive()

Makes the window an exclusive object on screen.

Remarks

The user cannot interact with any other object while the window is in exclusive state. Use the Window.Close() method to cancel the exclusive state.

GoSystemExclusive()

Pauses the game and makes the window an exclusive object on screen.

Remarks

This method is intended for system windows, such as save/load dialogs, because the entire game is frozen while the window is in system exclusive state. Use the Window.Close() method to cancel the exclusive state.

Center()

Centers the window on screen.

LoadFromFile(Filename)

Loads the window definition from a specified file.

Parameters

Filename

A filename of a window file to be loaded.

Return value

If the method succeeds, the return value is true.

CreateButton(Name)

Dynamically creates a new button control

Parameters

Name

The name of the button (optional)

Return value

Returns the newly created button object

Remarks

Use the DeleteButton method to remove the button.

CreateStatic(Name)

Dynamically creates a new static control

Parameters

Name

The name of the control (optional)

Return value

Returns the newly created static control object

Remarks

Use the DeleteStatic method to remove the control.

CreateEditor(Name)

Dynamically creates a new editor control

Parameters

Name

The name of the editor (optional)

Return value

Returns the newly created editor object

Remarks

Use the DeleteEditor method to remove the editor.

CreateWindow(Name)

Dynamically creates a new sub-window control

Parameters

Name

The name of the window (optional)

Return value

Returns the newly created window object

Remarks

Use the DeleteWindow method to remove the window.

DeleteButton(Button)

Deletes a button object

Parameters

Button

The button to be deleted

DeleteStatic(Static)

Deletes a static control object

Parameters

Static

The static control to be deleted

DeleteEditor(Editor)

Deletes an editor object

Parameters

Editor

The editor control to be deleted

DeleteWindow(Window)

Deletes a window object

Parameters

Window

The window control to be deleted

SetCursor(Filename)

Sets the standard cursor.

Parameters

Filename

Filename of a sprite file to be used as a cursor pointer.

Return value

Returns true if the cursor has been set succesfuly.

GetCursor()

Returns the filename of the cursor sprite (or null if no cursor is set)

GetCursorObject()

Returns a reference to the cursor sprite (or null if no cursor is set)

RemoveCursor()

Removes the standard cursor.

HasCursor()

Queries whether the standard cursor is set.

Return value

Returns true if the object has a custom mouse pointer assigned.

AttachScript(Filename)

Executes a script file and attaches it to the object.

Parameters

Filename

The filename of the script file to be executed.

Return value

Returns true if the script hs been executed succesfuly.

Remarks

Each WME object can have multiple scripts attached.

DetachScript(Filename)

Terminates a specified script file and detaches it from an object.

Parameters

Filename

The filename of the (running) script to be terminated and detached.

Return value

Returns true if the script has been detached succesfully.

IsScriptRunning(Filename)

Queries whether a specified script file is running and attached to an object.

Parameters

Filename

The filename of the script to be queried.

Return value

Returns true if a specified script file is attached to an object.

CanHandleMethod(MethodName)

Queries whether the object supports a method of a specified name.

Parameters

MethodName

The name of the method to be checked.

Return value

Returns true if the object is able to handle the specified method.

PlaySound(Filename, Looping, LoopStart)
PlaySound(Looping, LoopStart)

Plays a sound. If the filename is omitted, the currently assigned sound is played (if any).

Parameters

Filename

The filename of the sound file to be played

Looping

Whether the sound should be looped (optional, default = false).

LoopStart

The point from which the sound restarts when looping, in milliseconds (optional, default=0).

Return value

If the method succeeds, the return value is true.

PlaySoundEvent(Filename, EventName)
PlaySoundEvent(EventName)

Plays a sound and triggers an event when the sound is over. If the filename is omitted, the currently assigned sound is played (if any).

Parameters

Filename

The filename of the sound file to be played

EventName

The name of the event to be triggered after the sound finishes.

Return value

If the method succeeds, the return value is true.

StopSound()

Stops the currently playing sound (if any).

Return value

If the method succeeds, the return value is true.

PauseSound()

Pauses the currently playing sound.

Return value

If the method succeeds, the return value is true.

ResumeSound()

Resumes a paused sound playback.

Return value

If the method succeeds, the return value is true.

IsSoundPlaying()

Queries whether a sound playback is in progress.

Return value

If the sound is playing, the return value is true.

SetSoundPosition(Time)

Sets the sound's current playing position.

Parameters

Time

A new playing position (in milliseconds)

Return value

If the method succeeds, the return value is true.

GetSoundPosition()

Queries the sound's current playing position

Return value

Returns the current playing position (in milliseconds).

SetSoundVolume(Volume)

Sets a volume of the currently playing sound.

Parameters

Volume

A new sound volume (in percent).

Return value

If the method succeeds, the return value is true.

GetSoundVolume()

Gets a volume of the currently playing sound.

Return value

Returns the volume of the currently playing sound (in percent).

LoadSound(Filename)

Initializes a sound from file and makes it ready to be played.

Parameters

Filename

The sound file to be loaded

Return value

If the method succeeds, the return value is true.

Remarks

Use this method to pre-cache a sound file. Initializing the sound takes some time and sometimes it's desirable to move all sound initialization to e.g. scene start so that the subsequent PlaySound calls don't slow the game down. That's what LoadSound is for. To play the pre-cached sound simply call PlaySound without specifying a filename, for example SomeObject.PlaySound(false);

SoundFXNone()

Removes any sound effect currently assigned to this object.

SoundFXEcho(WetDryMix, Feedback, LeftDelay, RightDelay)

Assigns an echo effect to the sounds played by this object.

Parameters

WetDryMix

Wet/Dry Mix, in percent (0 to 100)

Feedback

Feedback, in percent (0 to 100)

LeftDelay

Left delay, in milliseconds (1 to 2000)

RightDelay

Right delay, in milliseconds (1 to 2000)

Remarks

Example: actor.SoundFXEcho(50, 50);

SoundFXReverb(InGain, ReverbMix, ReverbTime, HighFreqRTRatio)

Assigns a reverb effect to the sounds played by this object.

Parameters

InGain

In gain, in dB (-96 to 0)

ReverbMix

Reverb mix, in dB (-96 to 0)

ReverbTime

Reverb time, in milliseconds (0.001 to 3000)

HighFreqRTRatio

HighFreq RT Ratio (0.001 to 0.999)

Remarks

Example: actor.SoundFXReverb(0, 0, 2000);

ApplyEvent(EventName)

Applies a named event to the object.

Parameters

EventName

A name of the event to be applied to the object.

Return value

Returns true it the event has been applied succesfuly.

CanHandleEvent(EventName)

Queries whether the object has an event handler for a specified event.

Parameters

EventName

The name of the event to be checked.

Return value

Returns true if the object is able to handle the specified event.

redpajama_set_name: RedPajamaGithub


text:
import asyncio
import inspect
import warnings

from asgiref.sync import sync_to_async

class RemovedInNextVersionWarning(DeprecationWarning):
    pass

class RemovedInDjango40Warning(PendingDeprecationWarning):
    pass

class warn_about_renamed_method:
    def __init__(self, class_name, old_method_name, new_method_name, deprecation_warning):
        self.class_name = class_name
        self.old_method_name = old_method_name
        self.new_method_name = new_method_name
        self.deprecation_warning = deprecation_warning

    def __call__(self, f):
        def wrapped(*args, **kwargs):
            warnings.warn(
                "`%s.%s` is deprecated, use `%s` instead." %
                (self.class_name, self.old_method_name, self.new_method_name),
                self.deprecation_warning, 2)
            return f(*args, **kwargs)
        return wrapped

class RenameMethodsBase(type):
    """
    Handles the deprecation paths when renaming a method.

    It does the following:
        1) Define the new method if missing and complain about it.
        2) Define the old method if missing.
        3) Complain whenever an old method is called.

    See #15363 for more details.
    """

    renamed_methods = ()

    def __new__(cls, name, bases, attrs):
        new_class = super().__new__(cls, name, bases, attrs)

        for base in inspect.getmro(new_class):
            class_name = base.__name__
            for renamed_method in cls.renamed_methods:
                old_method_name = renamed_method[0]
                old_method = base.__dict__.get(old_method_name)
                new_method_name = renamed_method[1]
                new_method = base.__dict__.get(new_method_name)
                deprecation_warning = renamed_method[2]
                wrapper = warn_about_renamed_method(class_name, *renamed_method)

                # Define the new method if missing and complain about it
                if not new_method and old_method:
                    warnings.warn(
                        "`%s.%s` method should be renamed `%s`." %
                        (class_name, old_method_name, new_method_name),
                        deprecation_warning, 2)
                    setattr(base, new_method_name, old_method)
                    setattr(base, old_method_name, wrapper(old_method))

                # Define the old method as a wrapped call to the new method.
                if not old_method and new_method:
                    setattr(base, old_method_name, wrapper(new_method))

        return new_class

class DeprecationInstanceCheck(type):
    def __instancecheck__(self, instance):
        warnings.warn(
            "`%s` is deprecated, use `%s` instead." % (self.__name__, self.alternative),
            self.deprecation_warning, 2
        )
        return super().__instancecheck__(instance)

class MiddlewareMixin:
    sync_capable = True
    async_capable = True

    # RemovedInDjango40Warning: when the deprecation ends, replace with:
    #   def __init__(self, get_response):
    def __init__(self, get_response=None):
        self._get_response_none_deprecation(get_response)
        self.get_response = get_response
        self._async_check()
        super().__init__()

    def _async_check(self):
        """
        If get_response is a coroutine function, turns us into async mode so
        a thread is not consumed during a whole request.
        """
        if asyncio.iscoroutinefunction(self.get_response):
            # Mark the class as async-capable, but do the actual switch
            # inside __call__ to avoid swapping out dunder methods
            self._is_coroutine = asyncio.coroutines._is_coroutine

    def __call__(self, request):
        # Exit out to async mode, if needed
        if asyncio.iscoroutinefunction(self.get_response):
            return self.__acall__(request)
        response = None
        if hasattr(self, 'process_request'):
            response = self.process_request(request)
        response = response or self.get_response(request)
        if hasattr(self, 'process_response'):
            response = self.process_response(request, response)
        return response

    async def __acall__(self, request):
        """
        Async version of __call__ that is swapped in when an async request
        is running.
        """
        response = None
        if hasattr(self, 'process_request'):
            response = await sync_to_async(self.process_request)(request)
        response = response or await self.get_response(request)
        if hasattr(self, 'process_response'):
            response = await sync_to_async(self.process_response)(request, response)
        return response

    def _get_response_none_deprecation(self, get_response):
        if get_response is None:
            warnings.warn(
                'Passing None for the middleware get_response argument is '
                'deprecated.',
                RemovedInDjango40Warning, stacklevel=3,
            )


text:
    <title>用户管理</title>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <meta http-equiv="imagetoolbar" content="no"/>
    <meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
    <meta name="apple-mobile-web-app-capable" content="yes"/>
    <meta name="apple-mobile-web-app-status-bar-style" content="black"/>
    <link rel="apple-touch-icon" href="data/apple-touch-icon.png" />
    <link rel="apple-touch-startup-image" href="data/startup-iphone.png" media="screen and (max-device-width: 320px)"/>
    <link href="resources/css/jquery-ui-themes.css" type="text/css" rel="stylesheet">
    <link href="resources/css/axure_rp_page.css" type="text/css" rel="stylesheet">
    <link href="用户管理_files/axurerp_pagespecificstyles.css" type="text/css" rel="stylesheet">

用户管理

全选

<INPUT id="u11" style="position:absolute; left:-3px; top:-2px;" type="checkbox" value="checkbox"   >

用户名

注册时间

学员数量

学员管理

操作

<INPUT id="u25" style="position:absolute; left:-3px; top:-2px;" type="checkbox" value="checkbox"   >

张帅

2013-07-09  22:20:19

8

详细      |    编辑      |     删除

enter text...

卡片管理

笔记管理

例句管理

添加用户


text:
package com.xujun.funapp.network.exception;

/**
 * @ explain:
 * @ author:xujun on 2016-7-19 14:54
 * @ email:gdutxiaoxu@163.com
 */
public class ServerException extends RuntimeException {
    public int code;
    public String message;
}


text:
Reference
=========

Application
-----------

.. automodule:: prompt_toolkit.application
    :members:

Buffer
------

.. automodule:: prompt_toolkit.buffer
    :members:

Selection
---------

.. automodule:: prompt_toolkit.selection
    :members:

Clipboard
---------

.. automodule:: prompt_toolkit.clipboard.base
    :members:

.. automodule:: prompt_toolkit.clipboard.in_memory
    :members:

.. automodule:: prompt_toolkit.clipboard.pyperclip
    :members:

Auto completion
---------------

.. automodule:: prompt_toolkit.completion
    :members:

Document
--------

.. automodule:: prompt_toolkit.document
    :members:

Enums
-----

.. automodule:: prompt_toolkit.enums
    :members:

History
-------

.. automodule:: prompt_toolkit.history
    :members:

Interface
---------

.. automodule:: prompt_toolkit.interface
    :members:

Keys
----

.. automodule:: prompt_toolkit.keys
    :members:

Style
-----

.. automodule:: prompt_toolkit.styles
    :members:

Reactive
--------

.. automodule:: prompt_toolkit.reactive
    :members:

Shortcuts
---------

.. automodule:: prompt_toolkit.shortcuts
    :members:

Validation
----------

.. automodule:: prompt_toolkit.validation
    :members:

Auto suggestion
---------------

.. automodule:: prompt_toolkit.auto_suggest
    :members:

Renderer
--------

.. automodule:: prompt_toolkit.renderer
    :members:

Layout
------

.. automodule:: prompt_toolkit.layout.containers
    :members:

.. automodule:: prompt_toolkit.layout.controls
    :members:

.. automodule:: prompt_toolkit.layout.dimension
    :members:

.. automodule:: prompt_toolkit.layout.lexers
    :members:

.. automodule:: prompt_toolkit.layout.margins
    :members:

.. automodule:: prompt_toolkit.layout.menus
    :members:

.. automodule:: prompt_toolkit.layout.processors
    :members:

.. automodule:: prompt_toolkit.layout.toolbars
    :members:

.. automodule:: prompt_toolkit.layout.utils
    :members:

.. automodule:: prompt_toolkit.layout.screen
    :members:

Token
-----

.. automodule:: prompt_toolkit.token
    :members:

Filters
-------

.. automodule:: prompt_toolkit.filters
    :members:

.. autoclass:: prompt_toolkit.filters.Filter
    :members:

.. autoclass:: prompt_toolkit.filters.CLIFilter
    :members:

.. autoclass:: prompt_toolkit.filters.SimpleFilter
    :members:

.. autoclass:: prompt_toolkit.filters.Condition
    :members:

Key binding
-----------

.. automodule:: prompt_toolkit.key_binding.registry
    :members:

.. automodule:: prompt_toolkit.key_binding.manager
    :members:

.. automodule:: prompt_toolkit.key_binding.vi_state
    :members:

Eventloop
---------

.. automodule:: prompt_toolkit.eventloop.base
    :members:

.. automodule:: prompt_toolkit.eventloop.posix
    :members:

.. automodule:: prompt_toolkit.eventloop.win32
    :members:

.. automodule:: prompt_toolkit.eventloop.asyncio_base
    :members:

.. automodule:: prompt_toolkit.eventloop.asyncio_win32
    :members:

.. automodule:: prompt_toolkit.eventloop.asyncio_posix
    :members:

.. automodule:: prompt_toolkit.eventloop.callbacks
    :members:

Input and output
----------------

.. automodule:: prompt_toolkit.input
    :members:

.. automodule:: prompt_toolkit.output
    :members:


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class nuevohorariocon extends CI_Controller {

	public function __construct()
	{
	    parent::__construct();

		$this -> load -> model('nuevohorario');
		$this -> load->library('encrypt');
		$this -> load->model('mCatalogo');

	}

	public function index($offset=0){

 $datos['resultado'] = $this->mCatalogo->listarPasante();
		$this->load->helper('form');
		$this->load->view('header');
		$this -> load-> view ('encargado/nuevohorarioview', $datos);
		//$this -> load-> view ('encargado/RegistroPasante');
		$this->load->view('footer');

	}
	//controlador para añadir
    public function add(){
        $param['id_pasante'] = $this -> input -> post('id_pasante');
        $param['pasante'] = $this -> input -> post('pasante');
		$param['dia'] =$this -> input -> post('dia');
		$param['hora_inicio'] =$this -> input -> post('hora_inicio');
		$param['hora_fin'] =$this -> input -> post('hora_fin');

		$this->nuevohorario->nuevo_horario($param);
		redirect('encargado');
    }

}


text:
ng-click with ng-disabled button example

        Click Me!

      times clicked: {{timesClicked}}

The above button is disabled but its click function is called anyway (only Javascript compiled code is affected).

        enable button

        disable button

      button disabled: {{isDisabled}}


text:
namespace DAVA
{
class UIScreenTransition : public UIControl
{
    DAVA_VIRTUAL_REFLECTION(UIScreenTransition, UIControl);

public:
    UIScreenTransition();

protected:
    ~UIScreenTransition() override;

public:
    void Update(float32 timeElapsed) override;
    void Draw(const UIGeometricData& geometricData) override;

    DAVA_DEPRECATED(virtual void SetSourceScreen(UIControl* prevScreen, bool updateScreen = true));
    DAVA_DEPRECATED(virtual void SetDestinationScreen(UIControl* nextScreen, bool updateScreen = true));
    virtual void SetSourceControl(UIControl* prevScreen, bool updateScreen = true);
    virtual void SetDestinationControl(UIControl* nextScreen, bool updateScreen = true);
    virtual void StartTransition();
    virtual void EndTransition();

    virtual void SetDuration(float32 timeInSeconds);

    bool IsComplete() const;

protected:
    void CreateRenderTargets();
    void ReleaseRenderTargets();
    Sprite* renderTargetPrevScreen = nullptr;
    Sprite* renderTargetNextScreen = nullptr;

    Interpolation::Func interpolationFunc;
    float32 currentTime = 0.0f;
    float32 duration = 0.7f;
    float32 normalizedTime = 0.0f;
    float32 scale = 1.0f;
    bool complete = false;
};
};

#endif // __DAVAENGINE_UI_SCREEN_TRANSITION_H__


text:
(function( $ ){

   /*
    * Handle input. Call public functions and initializers
    */

    $.fn.comprasreports = function(data){
        var _this = $(this);
        var plugin = _this.data('comprasreports');

        /*Inicializado ?*/
        if (!plugin) {

            plugin = new $.comprasreports(this, data);

            _this.data('comprasreports', plugin);

            return plugin;
        /*Si ya fue inizializado regresamos el plugin*/
        }else{
            return plugin;
        }

    };

    /*
    * Plugin Constructor
    */

    $.comprasreports = function(container, options){

        var plugin = this;

        /*
        * Default Values
        */

       var defaults = {

       };

       /*
        * Important Components
        */
        var $container = $(container);
        var $table = $container.find('table');

        var settings;

        /*
        * Private methods
        */

        var filter = function(){

            $container.find('tbody').children('tr').show();
            var selected = $("select#proveedor_filter").multipleSelect('getSelects');
            $container.find('td.proveedor_nombre').filter(function (index) {
                if ($.inArray($(this).attr('id'), selected) == -1) {
                    $(this).closest('tr').hide();
                }
            });

            var from = $container.find('#fecha_filter_from').val();
            var to = $container.find('#fecha_filter_to').val();

            if(from != '' && to == ''){

               $container.find('tbody').children('tr').show();

                from = $container.find('#fecha_filter_from').datepicker( "getDate" );
                to = $container.find('#fecha_filter_to').datepicker( "getDate" );

                var selected =  $("select#proveedor_filter").multipleSelect('getSelects');
                $container.find('td.proveedor_nombre').filter(function(index){
                    if($.inArray($(this).attr('id'),selected) == -1){
                         $(this).closest('tr').hide();
                     }
                });

                $container.find('tbody').children('tr:visible').filter(function(index){
                    var datejs = new Date($(this).find('td:first-child').attr('data-time'));
                    if(datejs.getTime() < from.getTime()){
                        $(this).hide();
                    }
                });
            }else if(from != '' && to != ''){
                $container.find('tbody').children('tr').show();

                from = $container.find('#fecha_filter_from').datepicker( "getDate" );
                to = $container.find('#fecha_filter_to').datepicker( "getDate" );

                var selected =  $("select#proveedor_filter").multipleSelect('getSelects');
                $container.find('td.proveedor_nombre').filter(function(index){
                    if($.inArray($(this).attr('id'),selected) == -1){
                         $(this).closest('tr').hide();
                     }
                });

                $container.find('tbody').children('tr:visible').filter(function(index){
                    var datejs = new Date($(this).find('td:first-child').attr('data-time'));
                    if(datejs.getTime() >= from.getTime() && datejs.getTime() <= to.getTime()){
                        $(this).show();
                    }else{
                        $(this).hide();
                    }
                });
            }

            calcularTotalMonto();

        }

        calcularTotalMonto = function(){
            $container.find('#row_report').remove();
            $row_report = $('

');
            $td_report = $row_report.find('td').eq(2);

            var total = 0;
            $container.find('tbody').children('tr:visible').filter(function(index){
                total = (total + accounting.unformat($(this).find('td').eq(2).text()));
            });

            $td_report.text(accounting.formatMoney(total));

            $container.find('tbody').append($row_report);

        }
       /*
        * Public methods
        */

        plugin.init = function(){

            settings = plugin.settings = $.extend({}, defaults, options);

            //Inicializamos el componente autcomplete de conceptos
           $.getJSON(
                '/catalogos/proveedor/getproveedores',
                function(data){

                    $.each(data,function(index,element){
                        //Inicilizamos el filtro de los conceptos
                         $container.find('select#proveedor_filter').append('<option value="'+element.value+'">'+element.label+'</option>');
                    });

                    $("select#proveedor_filter").multipleSelect({
                         selectAll:true,
                         allSelected:'Todos los proveedores',
                         selectAllText:'Todos los proveedores',
                         onClick : filter,
                         onCheckAll:filter,
                         onUncheckAll:filter,
                     });

                     $("select#proveedor_filter").multipleSelect("checkAll");

                }
            );

            //Inicializamos los calendarios
            $container.find('#fecha_filter_from').datepicker({
                dateFormat: 'dd-mm-yy',
                changeMonth: true,
                changeYear: true,
                onClose: function(dateText, inst){
                    filter();
                }
            });
            $container.find('#fecha_filter_to').datepicker({
                dateFormat: 'dd-mm-yy',
                changeMonth: true,
                changeYear: true,
                onClose: function(dateText, inst){
                    filter();
                }
            });

        }

        /*
        * Plugin initializing
        */

        plugin.init();

    }

})( jQuery );


text:
var fs = require('fs');

module.exports = function pathExists(path) {
    var pathExists = true;
    try {
        fs.accessSync(path, fs.constants.F_OK);
    } catch (e) {
        pathExists = false;
    }
    return pathExists;
}


text:
cpp_examples = [
    ("config-store-save", "True", "False"),
]


text:
#ifndef HTMLSourceTracker_h
#define HTMLSourceTracker_h

#include "HTMLInputStream.h"
#include "HTMLToken.h"

namespace WebCore {

class HTMLSourceTracker {
    WTF_MAKE_NONCOPYABLE(HTMLSourceTracker);
public:
    HTMLSourceTracker();

    // FIXME: Once we move "end" into HTMLTokenizer, rename "start" to
    // something that makes it obvious that this method can be called multiple
    // times.
    void start(const HTMLInputStream&, HTMLToken&);
    void end(const HTMLInputStream&, HTMLToken&);

    String sourceForToken(const HTMLToken&);

private:
    String m_sourceFromPreviousSegments;
    SegmentedString m_source;
    String m_cachedSourceForToken;
};

}

#endif


text:
/* eslint-disable camelcase */
function generateRectangle (trackWindowStart, trackWindowLength, { start_time, duration, id }) {
  // Calculate start position as fraction of total width
  const scaledStartPos = start_time > trackWindowStart
    ? (start_time - trackWindowStart) / trackWindowLength
    : 0

  const durationBeforeTrackWindow = start_time < trackWindowStart
    ? trackWindowStart - start_time
    : 0

  const durationAfterTrackWindow = start_time + duration > trackWindowStart + trackWindowLength
    ? (start_time + duration) - (trackWindowStart + trackWindowLength)
    : 0

  const durationInTrackWindow = duration - durationBeforeTrackWindow - durationAfterTrackWindow

  const scaledDuration = durationInTrackWindow / trackWindowLength

  return { scaledStartPos, scaledDuration, id }
}

/**
 * Convert absolute instance values to the fractional values in the given track window
 * @param {Number} trackWindowStart
 * @param {Number} trackWindowLength
 * @param {Array<Object<start_time: Number, duration: Number, id: Number>>} instances
 * @return {Array<Object<scaledStartPos: Number, scaledDuration: Number, id: Number>>} array of converted data
 */
function generateRectangles (trackWindowStart, trackWindowLength, instances) {
  return instances.filter(({ start_time, duration }) => {
    return start_time + duration > trackWindowStart &&
        start_time < trackWindowStart + trackWindowLength
  })
    .map(generateRectangle.bind(null, trackWindowStart, trackWindowLength))
}
/* eslint-enable camelcase */

/**
 * Group rectangles into rows to ensure there are no collisions between rectangles on the same row
 * @param {Array<Object<scaledStartPos: Number, scaledDuration: Number, id: Number>>} rectangles
 * @return {Array<Array<Object<scaledStartPos: Number, scaledDuration: Number, id: Number>>>} array of rows
 */
function arrangeRectanglesIntoRows (rectangles) {
  let rectanglesCopy = Array.from(rectangles)
  rectanglesCopy.sort((a, b) => a.scaledStartPos - b.scaledStartPos)

  const arrangedRows = []

  while (rectanglesCopy.length) {
    const tempArray = []
    let currentInstance = rectanglesCopy.splice(0, 1)[0]
    const row = [currentInstance]

    while (rectanglesCopy.length) {
      const nextInstance = rectanglesCopy.splice(0, 1)[0]
      if (nextInstance.scaledStartPos >= currentInstance.scaledStartPos + currentInstance.scaledDuration) {
        row.push(nextInstance)
        currentInstance = nextInstance
      } else {
        tempArray.push(nextInstance)
      }
    }

    arrangedRows.push(row)
    rectanglesCopy = Array.from(tempArray)
  }

  return arrangedRows
}

/**
 * generate the instructions to draw the instances that should appear on the given track viewport
 * @param {Number} trackWindowStart
 * @param {Number} trackWindowLength
 * @param {Array<Object<start_time: Number, duration: Number, id: String>>} instances
 * @return {Array<Array<Object<scaledStartPos: Number, scaledDuration: Number, id: String>>>} data to draw game board
 */
function calculateInstanceRectangles (trackWindowStart, trackWindowLength, instances) {
  const rectangles = generateRectangles(trackWindowStart, trackWindowLength, instances)
  return arrangeRectanglesIntoRows(rectangles)
}

export {
  calculateInstanceRectangles,
  arrangeRectanglesIntoRows,
  generateRectangles,
  generateRectangle
}


text:
traveling-sales-person
======================

School assignment.

Comments in code is a mixture of English and Norweginan. Program output is all English.


text:
title: Short
written_by:
available: 'January 31st, 2017'
isbn: '9780399186219'
binding: Hardcover
link_to_buy_page:
image_path: 'https://images.booksense.com/images/219/186/9780399186219.jpg'
link:
---

In this heartwarming and funny middle-grade novel by the New York Times bestselling author of Counting by 7s, Julia grows into herself while playing a Munchkin in The Wizard of Oz

Julia is very short for her age, but by the end of the summer run of The Wizard of Oz, she'll realize how big she is inside, where it counts. She hasn't ever thought of herself as a performer, but when the wonderful director of Oz casts her as a Munchkin, she begins to see herself in a new way. As Julia becomes friendly with the poised and wise Olive--one of the adults with dwarfism who've joined the production's motley crew of Munchkins--and with her deeply artistic neighbor, Mrs. Chang, Julia's own sense of self as an artist grows. Soon, she doesn't want to fade into the background--and it's a good thing, because her director has more big plans for Julia

 Bubbling over with humor and tenderness, this is an irresistible story of self-discovery and of the role models who forever change us.


text:
@implementation BLECDeviceData

@end

@implementation BLECDevice

- (instancetype)initWithUUID:(NSUUID *)uuid
{
    self = [super init];
    if (self) {
        _UUID = uuid;
        _peripheral = nil;
        _characteristics = [[NSMutableDictionary alloc] init];
    }
    return self;
}

- (instancetype)initWithPeripheral:(CBPeripheral *)peripheral
{
    self = [super init];
    if (self) {
        _UUID = peripheral.identifier;
        _peripheral = peripheral;
        _characteristics = [[NSMutableDictionary alloc] init];
    }
    return self;
}

- (CBCharacteristic *)characteristicAt:(NSUInteger)characteristicIndex
                           inServiceAt:(NSUInteger)serviceIndex
{
    __block CBCharacteristic *found = nil;
    [_characteristics enumerateKeysAndObjectsUsingBlock:^(CBUUID *key, BLECDeviceData *data, BOOL *stop) {
        if (data.serviceIndex == serviceIndex && data.characteristicIndex == characteristicIndex) {
            found = data.characteristic;
            *stop = YES;
        }
    }];
    return found;
}

- (void)readRSSI
{
    if (_peripheral) {
        [_peripheral readRSSI];
    }
}

- (void)writeValue:(NSData *)value
 forCharacteristic:(CBCharacteristic *)characteristic
      withResponse:(void (^)(NSError *error))response
{
    if (!_peripheral) return;

    if (response == nil) {
        [_peripheral writeValue:value
              forCharacteristic:characteristic
                           type:CBCharacteristicWriteWithoutResponse];
    } else {
        BLECDeviceData *charData = _characteristics[characteristic.UUID];
        if (charData == nil) {
            return;
        }
        if (charData.writeResponse != nil) {
            NSAssert(NO, @"UNREACHABLE");
            return;
        }
        charData.writeResponse = response;
        _characteristics[characteristic.UUID] = charData;
        [_peripheral writeValue:value
              forCharacteristic:characteristic
                           type:CBCharacteristicWriteWithResponse];
    }
}

@end


text:
require 'spec_helper'

describe User do

  before do
    @user = User.new(name: "Example User", email: "user@example.com",
                                          password: "foobar", password_confirmation: "foobar")
  end

  subject { @user }

  it { should respond_to(:name) }
  it { should respond_to(:email) }
  it { should respond_to(:password_digest) }
  it { should respond_to(:password) }
  it { should respond_to(:password_confirmation) }
  it { should respond_to(:remember_token) }
  it { should respond_to(:authenticate) }
  it { should respond_to(:admin) }
  it { should respond_to(:projects) }
  it { should respond_to(:feed) }

  it { should be_valid }
  it { should_not be_admin }

  describe "with admin attribute set to 'true'" do
    before do
      @user.save!
      @user.toggle!(:admin)
    end

    it { should be_admin }
  end

  describe "when name is not present" do
    before { @user.name = " " }
    it { should_not be_valid }
  end

  describe "when email is not present" do
    before { @user.email = " " }
    it { should_not be_valid }
  end

  describe "when name is too long" do
    before { @user.name = "a" * 51 }
    it { should_not be_valid }
  end

 describe "when email format is invalid" do
    it "should be invalid" do
      addresses = %w[user@foo,com user_at_foo.org example.user@foo.
                     foo@bar_baz.com foo@bar+baz.com]
      addresses.each do |invalid_address|
        @user.email = invalid_address
        expect(@user).not_to be_valid
      end
    end
  end

  describe "when email format is valid" do
    it "should be valid" do
      addresses = %w[user@foo.COM A_US-ER@f.b.org frst.lst@foo.jp a+b@baz.cn]
      addresses.each do |valid_address|
        @user.email = valid_address
        expect(@user).to be_valid
      end
    end
  end

  describe "when email address is already taken" do
    before do
      user_with_same_email = @user.dup
      user_with_same_email.save
    end

    it { should_not be_valid }
  end

  describe "when password is not present" do
    before do
      @user = User.new(name: "Example User", email: "user@example.com",
                       password: " ", password_confirmation: " ")
    end
    it { should_not be_valid }
  end

  describe "when password doesn't match confirmation" do
    before { @user.password_confirmation = "mismatch" }
    it { should_not be_valid }
  end

  describe "with a password that's too short" do
    before { @user.password = @user.password_confirmation = "a" * 5 }
    it { should be_invalid }
  end

  describe "return value of authenticate method" do
    before { @user.save }
    let(:found_user) { User.find_by(email: @user.email) }

    describe "with valid password" do
      it { should eq found_user.authenticate(@user.password) }
    end

    describe "with invalid password" do
      let(:user_for_invalid_password) { found_user.authenticate("invalid") }

      it { should_not eq user_for_invalid_password }
      specify { expect(user_for_invalid_password).to be_false }
    end
  end

  describe "email address with mixed case" do
    let(:mixed_case_email) { "Foo@ExAMPle.CoM" }

    it "should be saved as all lower-case" do
      @user.email = mixed_case_email
      @user.save
      expect(@user.reload.email).to eq mixed_case_email.downcase
    end
  end

  describe "remember token" do
    before { @user.save }
    its(:remember_token) { should_not be_blank }
  end

  describe "project associations" do

    before { @user.save }
    let!(:older_project) do
      FactoryGirl.create(:project, user: @user, created_at: 1.day.ago)
    end
    let!(:newer_project) do
      FactoryGirl.create(:project, user: @user, created_at: 1.hour.ago)
    end

    it "should have the right projects in the right order" do
      expect(@user.projects.to_a).to eq [newer_project, older_project]
    end

    it "should destroy associated projects" do
      projects = @user.projects.to_a
      @user.destroy
      expect(projects).not_to be_empty
      projects.each do |project|
        expect(Project.where(id: project.id)).to be_empty
      end
    end

    describe "status" do
      let(:unfollowed_post) do
        FactoryGirl.create(:project, user: FactoryGirl.create(:user))
      end

      its(:feed) { should include(newer_project) }
      its(:feed) { should include(older_project) }
      its(:feed) { should_not include(unfollowed_post) }
    end
  end
end


text:
describe('Given that we are trying to run a jasmine test.', function(){
	beforeEach(function(){
	});
	it('should have d3 defined', function(){
		expect(d3).toBeDefined();
	});
});


text:
var React = require('react');

var Header = React.createClass({

  render: function() {

    return (

          {this.props.title}

    )
  }
});

module.exports = Header;


text:
<?php

namespace app\modules\admin\controllers\system;

use app\common\utils\MsgUtils;
use app\models\b2b2c\search\SysUserSearch;
use app\models\b2b2c\SysParameter;
use app\models\b2b2c\SysParameterType;
use app\models\b2b2c\SysUser;
use app\modules\admin\common\controllers\BaseAuthController;
use app\modules\admin\Module;
use Yii;
use yii\base\UserException;
use yii\web\NotFoundHttpException;

/**
 * SysUserController implements the CRUD actions for SysUser model.
 */
class SysUserController extends BaseAuthController
{
    /**
     * @inheritdoc
     */
     /*
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }
    */

    /**
     * Lists all SysUser models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new SysUserSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        //get data from hasMany
//         $param_type = SysParameterType::findOne(SysParameterType::YES_NO);
//         $params = $param_type->getSysParameters()->all();
//         var_dump($params);

        //LEFT JOIN
        /* not works why? */
       /* $params = SysParameter::find()->joinWith([
		    'type' => function ($query) {
		        $query->onCondition(['type.id' => SysParameterType::YES_NO]);
		    },
		])->all(); */

        /* $params = SysParameter::find()->
        ->leftJoin('t_sys_parameter_type', 'type_id = t_sys_parameter_type.id')
        ->where(['t_sys_parameter_type.id' => SysParameterType::YES_NO])
        ->all();
        var_dump($params); */

       /* $params =  SysParameter::findBySql("select a.id,a.param_val from t_sys_parameter a LEFT JOIN t_sys_parameter_type b on (a.type_id = b.id) WHERE a.type_id=:type_id",['type_id'=>SysParameterType::YES_NO])->all();
       var_dump($params); */

       /*  $params = SysParameterType::getSysParametersById(SysParameterType::YES_NO);
        var_dump($params); */

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        	'yesNoList'=> SysParameterType::getSysParametersById(SysParameterType::YES_NO),
        ]);
    }

    /**
     * Displays a single SysUser model.
     * @param string $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new SysUser model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new SysUser();
        $model->setScenario(SysUser::SCENARIO_NEW_USER);
        //设置默认值
        $model->status = SysParameter::yes;
        $model->is_admin = SysParameter::no;

        if ($model->load(Yii::$app->request->post())) {
        	//创建新用户
//         	$_user = new SysUser();
//         	$_user->user_id = $model->user_id;
//         	$_user->password = md5($model->password);//加密
//         	$_user->is_admin = SysParameter::no;//设置为非超级管理员
//         	$_user->status  = $model->status;
//         	$_user->user_name = $model->user_name;

        	if($model->save()){
        		MsgUtils::success();
        		return $this->redirect(['view', 'id' => $model->id]);
        	}
        }

//         Yii::info($model->getf);
        //         	$model->addError('user_id',Json::encode($model->errors));
        return $this->render('create', [
        		'model' => $model,
        		'yesNoList'=> SysParameterType::getSysParametersById(SysParameterType::YES_NO),
        ]);
    }

    /**
     * Updates an existing SysUser model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param string $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
        	MsgUtils::success();
            return $this->redirect(['view', 'id' => $model->id]);
        }
//         var_dump($model->getErrors());
        return $this->render('update', [
                'model' => $model,
            	'yesNoList'=> SysParameterType::getSysParametersById(SysParameterType::YES_NO),
            ]);

    }

    /**
     * Deletes an existing SysUser model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param string $id
     * @return mixed
     */
    public function actionDelete($id)
    {
    	$model = $this->findModel($id);
    	if($model->is_admin==SysParameter::yes){
    		throw new UserException(Module::t('app',"不能删除超级管理员"));
    	}
    	$model->delete();

//         $this->findModel($id)->delete();
    	MsgUtils::success();
        return $this->redirect(['index']);
    }

    /**
     * Finds the SysUser model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param string $id
     * @return SysUser the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
//     	SysUser::find()->innerJoin($table)
//     	SysUser::find()->leftJoin($table)
//     	SysUser::find()->innerJoin($table)
//     	$model = SysUser::find()->where(["id"=>$id])->one();
//     	var_dump($model);

//     	$model = SysUser::find()->select(["u.*","stat.param_val"])->alias("u")->innerJoinWith("status0 stat")->where([])->all();
//     	var_dump($model);
//     	exit;
//     	if (($model = SysUser::find()->select(["u.*","stat.param_val"])->alias("u")->joinWith("status0 stat")->where(['u.id'=>$id])->one()) !== null) {
    	if (($model = SysUser::find()->alias("u")->joinWith("status0 stat")->where(['u.id'=>$id])->one()) !== null) {
//         if (($model = SysUser::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException(Yii::t('app', 'The requested page does not exist.'));
        }
    }

    /**
     * 修改密码
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param string $id
     * @return mixed
     */
    public function actionChangePwd($id)
    {
    	$model = $this->findModel($id);
    	$model->setScenario(SysUser::SCENARIO_CHANGE_PWD_ADMIN);
    	$model->password = null;
    	$model->confirm_pwd = null;

    	if ($model->load(Yii::$app->request->post())) {
    		$valid = $model->validate();
    		if($valid){
    			$password = md5($model->password);
    			$model->password = $password;
    			$model->confirm_pwd = $password;
    			if($model->save(true,['password'])){
    				MsgUtils::success();
    				return $this->redirect(['view', 'id' => $model->id]);
    			}
    		}

    	}

    	return $this->render('changePwd', [
    			'model' => $model,
    	]);
    }
}


text:
body{
  color:#000080;
}
a{
  color:#800080;
}
a:visited{
  color:#ff0000;
}
html{
  background-color:white;
}

table {
  width:100%;
  border-bottom:1px solid black;
}

li {
  padding:10px 10px 10px 10px;
}

td {
  vertical-align:top;
}
h1::first-letter{
  font-size:40px;
}
#h{
  font-size:40px;
}
#inc{
  font-size:20px;
}
header{
  text-align:center;
  font-weight:bold;
  border-bottom:1px solid black;
}
h2{
  font-size:20px;
  padding:0;
  margin:0;
}
header p{
  padding:0;
  margin:0;
}
#geico{
  text-align:center;
  font-size:10px;
  border-bottom:1px solid black;
}
#email{
  border-bottom:1px solid black;
  font-size:10px;
}
/*
Reflection:

What is important to know when linking an external file (like a stylesheet) to an HTML file?

A link to an external file should include the following:
<link rel="stylesheet" type="text/css" href="location of the file>
This references the file's location and attaches it to the html document. It does not need a closing tag. It goes inside the <head> tag.

What tricks did you use to help you with positioning? How hard was it to get the site as you wanted it?

The hardest element to position was the table. We were having a little trouble figuring out exactly how to get the rows ad columns set up properly with the unordered list. We ended up deciding on 1 row and 2 columns. We then couldn't get the table to go accross the entire page; when we couldn't figure out exactly what was going on, we added a border to the table so we could see the columns.

Other than that, we really didn't have any trouble moving things around. Because the page was set up so simply with a header, body, and footer, all we had to do was add a few sections with ids to space things out properly. Everything else was positioned without having to use float, etc. We used vertical-align and text-align to center things in the table and the text on the page.

What CSS did you use to modify the element style?

We used a lot of text-align and vertical-align to set things up in the table. We also used color:"#" to set up the hexadecimal color for the font and links. We used border-bottom:1px solid black to put lines on the page. We also used font-size to change the size of the font and font-weight to make the font bold.

Did you modify the HTML to include classes or ids? If so, which did you choose and why?

We used ids. We used ids instead of classes because the sections of our html that needed to be separately formatted were a one-time thing. For example, the H in Hathaway had to be styled differently than anything else in the page. We gave it an id so we could style it efficiently.
Classes are used if different elements need the same formatting; if you have to specify a format for different elements, use classes.

When you compared your site to the actual code base, which do you think had cleaner code that followed best practices and why?

I definitely think our site had a cleaner code base. They set up their table with many trs and 2 tds in each tr. It was a little unclear as to why they didn't set it up the way we did. It was also a lot more confusing with multiple divs because each one had to have a separate class and id. Ours simple had a header, table, and footer.

*/


text:
'use strict';

var mongoose = require('mongoose');

var donation = function() {
    var schema = mongoose.Schema({
        'id': String,
        'donorid': String,
        'institution': String,
        'date': {
            type: Date,
            default: Date.now,
        },
        'slot': [String],
        'category': [String],
        'amount': Number,
        'present': {
            type: Boolean,
            default: false
        }
    });
    return mongoose.model('donations', schema);
};

module.exports = donation();


text:
package com.google.gerrit.acceptance.server.project;

import static com.google.common.truth.Truth.assertThat;
import static com.google.gerrit.acceptance.testsuite.project.TestProjectUpdate.allow;

import com.google.common.collect.ImmutableList;
import com.google.gerrit.acceptance.AbstractDaemonTest;
import com.google.gerrit.acceptance.NoHttpd;
import com.google.gerrit.acceptance.PushOneCommit;
import com.google.gerrit.acceptance.TestAccount;
import com.google.gerrit.acceptance.testsuite.project.ProjectOperations;
import com.google.gerrit.acceptance.testsuite.request.RequestScopeOperations;
import com.google.gerrit.entities.AccountGroup;
import com.google.gerrit.entities.Address;
import com.google.gerrit.entities.NotifyConfig;
import com.google.gerrit.entities.NotifyConfig.NotifyType;
import com.google.gerrit.entities.Permission;
import com.google.gerrit.entities.Project;
import com.google.gerrit.extensions.api.changes.ReviewInput;
import com.google.gerrit.extensions.common.GroupInfo;
import com.google.gerrit.testing.FakeEmailSender.Message;
import com.google.inject.Inject;
import java.util.EnumSet;
import java.util.List;
import org.eclipse.jgit.internal.storage.dfs.InMemoryRepository;
import org.eclipse.jgit.junit.TestRepository;
import org.junit.Test;

@NoHttpd
public class ProjectWatchIT extends AbstractDaemonTest {
  @Inject private ProjectOperations projectOperations;
  @Inject private RequestScopeOperations requestScopeOperations;

  @Test
  public void newPatchSetsNotifyConfig() throws Exception {
    ImmutableList<String> messageFilters =
        ImmutableList.of("message:subject-with-tokens", "message:subject-with-tokens=secret");
    ImmutableList.Builder<Address> watchers = ImmutableList.builder();
    try (ProjectConfigUpdate u = updateProject(project)) {
      for (int i = 0; i < messageFilters.size(); i++) {
        Address addr = Address.create("Watcher#" + i, String.format("watcher-%s@example.com", i));
        watchers.add(addr);
        NotifyConfig.Builder nc = NotifyConfig.builder();
        nc.addAddress(addr);
        nc.setName("new-patch-set" + i);
        nc.setHeader(NotifyConfig.Header.CC);
        nc.setNotify(EnumSet.of(NotifyType.NEW_PATCHSETS));
        nc.setFilter(messageFilters.get(i));
        u.getConfig().putNotifyConfig("watch" + i, nc.build());
      }
      u.save();
    }

    PushOneCommit.Result r =
        pushFactory
            .create(admin.newIdent(), testRepo, "original subject", "a", "a1")
            .to("refs/for/master");
    r.assertOkStatus();

    r =
        pushFactory
            .create(
                admin.newIdent(),
                testRepo,
                "super sekret subject\n\nsubject-with-tokens=secret subject",
                "a",
                "a2",
                r.getChangeId())
            .to("refs/for/master");
    r.assertOkStatus();

    r =
        pushFactory
            .create(admin.newIdent(), testRepo, "back to original subject", "a", "a3")
            .to("refs/for/master");
    r.assertOkStatus();

    List<Message> messages = sender.getMessages();
    assertThat(messages).hasSize(1);
    Message m = messages.get(0);
    assertThat(m.rcpt()).containsExactlyElementsIn(watchers.build());
    assertThat(m.body()).contains("Change subject: super sekret subject\n");
    assertThat(m.body()).contains("Gerrit-PatchSet: 2\n");
  }

  @Test
  public void noNotificationForPrivateChangesForWatchersInNotifyConfig() throws Exception {
    Address addr = Address.create("Watcher", "watcher@example.com");
    NotifyConfig.Builder nc = NotifyConfig.builder();
    nc.addAddress(addr);
    nc.setName("team");
    nc.setHeader(NotifyConfig.Header.TO);
    nc.setNotify(EnumSet.of(NotifyType.NEW_CHANGES, NotifyType.ALL_COMMENTS));

    try (ProjectConfigUpdate u = updateProject(project)) {
      u.getConfig().putNotifyConfig("team", nc.build());
      u.save();
    }

    sender.clear();
    PushOneCommit.Result r =
        pushFactory
            .create(admin.newIdent(), testRepo, "private change", "a", "a1")
            .to("refs/for/master%private");
    r.assertOkStatus();

    assertThat(sender.getMessages()).isEmpty();

    requestScopeOperations.setApiUser(admin.id());
    ReviewInput in = new ReviewInput();
    in.message = "comment";
    gApi.changes().id(r.getChangeId()).current().review(in);

    assertThat(sender.getMessages()).isEmpty();
  }

  @Test
  public void noNotificationForChangeThatIsTurnedPrivateForWatchersInNotifyConfig()
      throws Exception {
    Address addr = Address.create("Watcher", "watcher@example.com");
    NotifyConfig.Builder nc = NotifyConfig.builder();
    nc.addAddress(addr);
    nc.setName("team");
    nc.setHeader(NotifyConfig.Header.TO);
    nc.setNotify(EnumSet.of(NotifyType.NEW_PATCHSETS));

    try (ProjectConfigUpdate u = updateProject(project)) {
      u.getConfig().putNotifyConfig("team", nc.build());
      u.save();
    }

    PushOneCommit.Result r =
        pushFactory.create(admin.newIdent(), testRepo, "subject", "a", "a1").to("refs/for/master");
    r.assertOkStatus();

    sender.clear();

    r =
        pushFactory
            .create(admin.newIdent(), testRepo, "subject", "a", "a2", r.getChangeId())
            .to("refs/for/master%private");
    r.assertOkStatus();

    assertThat(sender.getMessages()).isEmpty();
  }

  @Test
  public void noNotificationForWipChangesForWatchersInNotifyConfig() throws Exception {
    Address addr = Address.create("Watcher", "watcher@example.com");
    NotifyConfig.Builder nc = NotifyConfig.builder();
    nc.addAddress(addr);
    nc.setName("team");
    nc.setHeader(NotifyConfig.Header.TO);
    nc.setNotify(EnumSet.of(NotifyType.NEW_CHANGES, NotifyType.ALL_COMMENTS));

    try (ProjectConfigUpdate u = updateProject(project)) {
      u.getConfig().putNotifyConfig("team", nc.build());
      u.save();
    }

    sender.clear();
    PushOneCommit.Result r =
        pushFactory
            .create(admin.newIdent(), testRepo, "wip change", "a", "a1")
            .to("refs/for/master%wip");
    r.assertOkStatus();

    assertThat(sender.getMessages()).isEmpty();

    requestScopeOperations.setApiUser(admin.id());
    ReviewInput in = new ReviewInput();
    in.message = "comment";
    gApi.changes().id(r.getChangeId()).current().review(in);

    assertThat(sender.getMessages()).isEmpty();
  }

  @Test
  public void noNotificationForChangeThatIsTurnedWipForWatchersInNotifyConfig() throws Exception {
    Address addr = Address.create("Watcher", "watcher@example.com");
    NotifyConfig.Builder nc = NotifyConfig.builder();
    nc.addAddress(addr);
    nc.setName("team");
    nc.setHeader(NotifyConfig.Header.TO);
    nc.setNotify(EnumSet.of(NotifyType.NEW_PATCHSETS));

    try (ProjectConfigUpdate u = updateProject(project)) {
      u.getConfig().putNotifyConfig("team", nc.build());
      u.save();
    }

    PushOneCommit.Result r =
        pushFactory.create(admin.newIdent(), testRepo, "subject", "a", "a1").to("refs/for/master");
    r.assertOkStatus();

    sender.clear();

    r =
        pushFactory
            .create(admin.newIdent(), testRepo, "subject", "a", "a2", r.getChangeId())
            .to("refs/for/master%wip");
    r.assertOkStatus();

    assertThat(sender.getMessages()).isEmpty();
  }

  @Test
  public void watchProject() throws Exception {
    // watch project
    String watchedProject = projectOperations.newProject().create().get();
    requestScopeOperations.setApiUser(user.id());
    watch(watchedProject);

    // push a change to watched project -> should trigger email notification
    requestScopeOperations.setApiUser(admin.id());
    TestRepository<InMemoryRepository> watchedRepo =
        cloneProject(Project.nameKey(watchedProject), admin);
    PushOneCommit.Result r =
        pushFactory
            .create(admin.newIdent(), watchedRepo, "TRIGGER", "a", "a1")
            .to("refs/for/master");
    r.assertOkStatus();

    // push a change to non-watched project -> should not trigger email
    // notification
    String notWatchedProject = projectOperations.newProject().create().get();
    TestRepository<InMemoryRepository> notWatchedRepo =
        cloneProject(Project.nameKey(notWatchedProject), admin);
    r =
        pushFactory
            .create(admin.newIdent(), notWatchedRepo, "DONT_TRIGGER", "a", "a1")
            .to("refs/for/master");
    r.assertOkStatus();

    // assert email notification
    List<Message> messages = sender.getMessages();
    assertThat(messages).hasSize(1);
    Message m = messages.get(0);
    assertThat(m.rcpt()).containsExactly(user.getNameEmail());
    assertThat(m.body()).contains("Change subject: TRIGGER\n");
    assertThat(m.body()).contains("Gerrit-PatchSet: 1\n");
  }

  @Test
  public void watchFile() throws Exception {
    String watchedProject = projectOperations.newProject().create().get();
    String otherWatchedProject = projectOperations.newProject().create().get();
    requestScopeOperations.setApiUser(user.id());

    // watch file in project as user
    watch(watchedProject, "file:a.txt");

    // watch other project as user
    watch(otherWatchedProject);

    // push a change to watched file -> should trigger email notification for
    // user
    requestScopeOperations.setApiUser(admin.id());
    TestRepository<InMemoryRepository> watchedRepo =
        cloneProject(Project.nameKey(watchedProject), admin);
    PushOneCommit.Result r =
        pushFactory
            .create(admin.newIdent(), watchedRepo, "TRIGGER", "a.txt", "a1")
            .to("refs/for/master");
    r.assertOkStatus();

    // assert email notification for user
    List<Message> messages = sender.getMessages();
    assertThat(messages).hasSize(1);
    Message m = messages.get(0);
    assertThat(m.rcpt()).containsExactly(user.getNameEmail());
    assertThat(m.body()).contains("Change subject: TRIGGER\n");
    assertThat(m.body()).contains("Gerrit-PatchSet: 1\n");
    sender.clear();

    // watch project as user2
    TestAccount user2 = accountCreator.create("user2", "user2@example.com", "User2", null);
    requestScopeOperations.setApiUser(user2.id());
    watch(watchedProject);

    // push a change to non-watched file -> should not trigger email
    // notification for user, only for user2
    r =
        pushFactory
            .create(admin.newIdent(), watchedRepo, "TRIGGER_USER2", "b.txt", "b1")
            .to("refs/for/master");
    r.assertOkStatus();

    // assert email notification
    messages = sender.getMessages();
    assertThat(messages).hasSize(1);
    m = messages.get(0);
    assertThat(m.rcpt()).containsExactly(user2.getNameEmail());
    assertThat(m.body()).contains("Change subject: TRIGGER_USER2\n");
    assertThat(m.body()).contains("Gerrit-PatchSet: 1\n");
  }

  @Test
  public void watchKeyword() throws Exception {
    String watchedProject = projectOperations.newProject().create().get();
    requestScopeOperations.setApiUser(user.id());

    // watch keyword in project as user
    watch(watchedProject, "multiprimary");

    // push a change with keyword -> should trigger email notification
    requestScopeOperations.setApiUser(admin.id());
    TestRepository<InMemoryRepository> watchedRepo =
        cloneProject(Project.nameKey(watchedProject), admin);
    PushOneCommit.Result r =
        pushFactory
            .create(admin.newIdent(), watchedRepo, "Document multiprimary setup", "a.txt", "a1")
            .to("refs/for/master");
    r.assertOkStatus();

    // assert email notification for user
    List<Message> messages = sender.getMessages();
    assertThat(messages).hasSize(1);
    Message m = messages.get(0);
    assertThat(m.rcpt()).containsExactly(user.getNameEmail());
    assertThat(m.body()).contains("Change subject: Document multiprimary setup\n");
    assertThat(m.body()).contains("Gerrit-PatchSet: 1\n");
    sender.clear();

    // push a change without keyword -> should not trigger email notification
    r =
        pushFactory
            .create(admin.newIdent(), watchedRepo, "Cleanup cache implementation", "b.txt", "b1")
            .to("refs/for/master");
    r.assertOkStatus();

    // assert email notification
    assertThat(sender.getMessages()).isEmpty();
  }

  @Test
  public void watchAllProjects() throws Exception {
    String anyProject = projectOperations.newProject().create().get();
    requestScopeOperations.setApiUser(user.id());

    // watch the All-Projects project to watch all projects
    watch(allProjects.get());

    // push a change to any project -> should trigger email notification
    requestScopeOperations.setApiUser(admin.id());
    TestRepository<InMemoryRepository> anyRepo = cloneProject(Project.nameKey(anyProject), admin);
    PushOneCommit.Result r =
        pushFactory.create(admin.newIdent(), anyRepo, "TRIGGER", "a", "a1").to("refs/for/master");
    r.assertOkStatus();

    // assert email notification
    List<Message> messages = sender.getMessages();
    assertThat(messages).hasSize(1);
    Message m = messages.get(0);
    assertThat(m.rcpt()).containsExactly(user.getNameEmail());
    assertThat(m.body()).contains("Change subject: TRIGGER\n");
    assertThat(m.body()).contains("Gerrit-PatchSet: 1\n");
  }

  @Test
  public void watchFileAllProjects() throws Exception {
    String anyProject = projectOperations.newProject().create().get();
    requestScopeOperations.setApiUser(user.id());

    // watch file in All-Projects project as user to watch the file in all
    // projects
    watch(allProjects.get(), "file:a.txt");

    // push a change to watched file in any project -> should trigger email
    // notification for user
    requestScopeOperations.setApiUser(admin.id());
    TestRepository<InMemoryRepository> anyRepo = cloneProject(Project.nameKey(anyProject), admin);
    PushOneCommit.Result r =
        pushFactory
            .create(admin.newIdent(), anyRepo, "TRIGGER", "a.txt", "a1")
            .to("refs/for/master");
    r.assertOkStatus();

    // assert email notification for user
    List<Message> messages = sender.getMessages();
    assertThat(messages).hasSize(1);
    Message m = messages.get(0);
    assertThat(m.rcpt()).containsExactly(user.getNameEmail());
    assertThat(m.body()).contains("Change subject: TRIGGER\n");
    assertThat(m.body()).contains("Gerrit-PatchSet: 1\n");
    sender.clear();

    // watch project as user2
    TestAccount user2 = accountCreator.create("user2", "user2@example.com", "User2", null);
    requestScopeOperations.setApiUser(user2.id());
    watch(anyProject);

    // push a change to non-watched file in any project -> should not trigger
    // email notification for user, only for user2
    r =
        pushFactory
            .create(admin.newIdent(), anyRepo, "TRIGGER_USER2", "b.txt", "b1")
            .to("refs/for/master");
    r.assertOkStatus();

    // assert email notification
    messages = sender.getMessages();
    assertThat(messages).hasSize(1);
    m = messages.get(0);
    assertThat(m.rcpt()).containsExactly(user2.getNameEmail());
    assertThat(m.body()).contains("Change subject: TRIGGER_USER2\n");
    assertThat(m.body()).contains("Gerrit-PatchSet: 1\n");
  }

  @Test
  public void watchKeywordAllProjects() throws Exception {
    String anyProject = projectOperations.newProject().create().get();
    requestScopeOperations.setApiUser(user.id());

    // watch keyword in project as user
    watch(allProjects.get(), "multiprimary");

    // push a change with keyword to any project -> should trigger email
    // notification
    requestScopeOperations.setApiUser(admin.id());
    TestRepository<InMemoryRepository> anyRepo = cloneProject(Project.nameKey(anyProject), admin);
    PushOneCommit.Result r =
        pushFactory
            .create(admin.newIdent(), anyRepo, "Document multiprimary setup", "a.txt", "a1")
            .to("refs/for/master");
    r.assertOkStatus();

    // assert email notification for user
    List<Message> messages = sender.getMessages();
    assertThat(messages).hasSize(1);
    Message m = messages.get(0);
    assertThat(m.rcpt()).containsExactly(user.getNameEmail());
    assertThat(m.body()).contains("Change subject: Document multiprimary setup\n");
    assertThat(m.body()).contains("Gerrit-PatchSet: 1\n");
    sender.clear();

    // push a change without keyword to any project -> should not trigger email
    // notification
    r =
        pushFactory
            .create(admin.newIdent(), anyRepo, "Cleanup cache implementation", "b.txt", "b1")
            .to("refs/for/master");
    r.assertOkStatus();

    // assert email notification
    assertThat(sender.getMessages()).isEmpty();
  }

  @Test
  public void watchProjectNoNotificationForPrivateChange() throws Exception {
    // watch project
    String watchedProject = projectOperations.newProject().create().get();
    requestScopeOperations.setApiUser(user.id());
    watch(watchedProject);

    // push a private change to watched project -> should not trigger email notification
    requestScopeOperations.setApiUser(admin.id());
    TestRepository<InMemoryRepository> watchedRepo =
        cloneProject(Project.nameKey(watchedProject), admin);
    PushOneCommit.Result r =
        pushFactory
            .create(admin.newIdent(), watchedRepo, "private change", "a", "a1")
            .to("refs/for/master%private");
    r.assertOkStatus();

    // assert email notification
    assertThat(sender.getMessages()).isEmpty();
  }

  @Test
  public void watchProjectNotifyOnPrivateChange() throws Exception {
    String watchedProject = projectOperations.newProject().create().get();

    // create group that can view all private changes
    GroupInfo groupThatCanViewPrivateChanges =
        gApi.groups().create("groupThatCanViewPrivateChanges").get();
    projectOperations
        .project(Project.nameKey(watchedProject))
        .forUpdate()
        .add(
            allow(Permission.VIEW_PRIVATE_CHANGES)
                .ref("refs/*")
                .group(AccountGroup.uuid(groupThatCanViewPrivateChanges.id)))
        .update();

    // watch project as user that can't view private changes
    requestScopeOperations.setApiUser(user.id());
    watch(watchedProject);

    // watch project as user that can view all private change
    TestAccount userThatCanViewPrivateChanges =
        accountCreator.create(
            "user2", "user2@example.com", "User2", null, groupThatCanViewPrivateChanges.name);
    requestScopeOperations.setApiUser(userThatCanViewPrivateChanges.id());
    watch(watchedProject);

    // push a private change to watched project -> should trigger email notification for
    // userThatCanViewPrivateChanges, but not for user
    requestScopeOperations.setApiUser(admin.id());
    TestRepository<InMemoryRepository> watchedRepo =
        cloneProject(Project.nameKey(watchedProject), admin);
    PushOneCommit.Result r =
        pushFactory
            .create(admin.newIdent(), watchedRepo, "TRIGGER", "a", "a1")
            .to("refs/for/master%private");
    r.assertOkStatus();

    // assert email notification
    List<Message> messages = sender.getMessages();
    assertThat(messages).hasSize(1);
    Message m = messages.get(0);
    assertThat(m.rcpt()).containsExactly(userThatCanViewPrivateChanges.getNameEmail());
    assertThat(m.body()).contains("Change subject: TRIGGER\n");
    assertThat(m.body()).contains("Gerrit-PatchSet: 1\n");
  }
}


text:
'use strict';

const serverMock = require('../../../spec/helpers/server.mock');
const session = require('./session');

describe('session', function() {
  describe('urlInsertSessionId', function() {
    var testUrl = 'scheme://host:port/root/path?query=value';
    it('should not alter the URL if leakSessionId is false', function() {
      expect(session.urlInsertSessionId({ sessionID: '123' }, testUrl)).toBe(testUrl);
      expect(session.urlInsertSessionId({ sessionID: '123', session: {} }, testUrl)).toBe(testUrl);
      expect(session.urlInsertSessionId({ sessionID: '123', session: { payload: { cookie: true } } }, testUrl)).toBe(testUrl);
    });
    it('should append the session ID to the URL if leakSessionId is true', function() {
      var sessionUrl = testUrl.replace('/path', '/path/session/123');
      expect(session.urlInsertSessionId({ sessionID: '123', session: { payload: {} } }, testUrl)).toBe(sessionUrl);
      expect(session.urlInsertSessionId({ sessionID: '123', session: { payload: { cookie: false } } }, testUrl)).toBe(sessionUrl);
    });
  });

  describe('session tracking', function() {
    var agent = serverMock.newAgent(); // this instance keeps the cookie
    var sessionId;

    it('should set session cookie on authorize', function authorize(done) { // note: we bypass /api/initialize
      agent
        .get('/api/test/authorize') // TODO: put login API here
        .expect(200)
        .expect('set-cookie', /express.sess=.*/, function(err, res) {
          expect(err).toBeFalsy();
          sessionId = /"sessionId":"([^"]*)"/.exec(res.text)[1];
          expect(sessionId).toBeTruthy();
          done();
        });
    });

    it('should not allow access to a protected API with no session ID', function(done) {
      serverMock.newAgent() // new instance has no cookie
        .get('/api/test/isauthorized')
        .expect(401, done);
    });

    it('should allow access to a protected API by passing the session ID in a cookie', function(done) {
      agent
        .get('/api/test/isauthorized')
        .expect(200, done);
    });

    it('should allow access to a protected API by passing the session ID in the Authorize header', function(done) {
      serverMock.newAgent() // new instance has no cookie
        .get('/api/test/isauthorized')
        .set('Authorization', 'Bearer ' + sessionId)
        .expect(200, done);
    });

    it('should allow access to a protected API by passing the session ID in the URL path', function(done) {
      serverMock.newAgent() // new instance has no cookie
        .get('/api/test/isauthorized/session/' + sessionId)
        .expect(200, done);
    });
  });
});


text:
<?php

namespace Flarum\Event;

use DateTime;
use Flarum\Api\Serializer\AbstractSerializer;

/**
 * Prepare API attributes.
 *
 * This event is fired when a serialize is constructing an array of resource
 * attributes for API output.
 */
class PrepareApiAttributes
{
    /**
     * The class doing the serializing.
     *
     * @var AbstractSerializer
     */
    public $serializer;

    /**
     * The model being serialized.
     *
     * @var object
     */
    public $model;

    /**
     * The serialized attributes of the resource.
     *
     * @var array
     */
    public $attributes;

    /**
     * @var \Flarum\Core\User
     */
    public $actor;

    /**
     * @param AbstractSerializer $serializer The class doing the serializing.
     * @param object|array $model The model being serialized.
     * @param array $attributes The serialized attributes of the resource.
     */
    public function __construct(AbstractSerializer $serializer, $model, array &$attributes)
    {
        $this->serializer = $serializer;
        $this->model = $model;
        $this->attributes = &$attributes;
        $this->actor = $serializer->getActor();
    }

    /**
     * @param string $serializer
     * @return bool
     */
    public function isSerializer($serializer)
    {
        return $this->serializer instanceof $serializer;
    }

    /**
     * @param DateTime|null $date
     * @return string|null
     */
    public function formatDate(DateTime $date = null)
    {
        if ($date) {
            return $date->format(DateTime::RFC3339);
        }
    }
}


text:
package net.blerf.ftl.parser;

import net.blerf.ftl.model.ShipLayout;
import net.blerf.ftl.xml.*;

import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

public abstract class DataManager implements Closeable {

	private static DataManager instance = null;

	protected boolean dlcEnabledByDefault = false;

	public static void setInstance(DataManager dataManager) {
		instance = dataManager;
	}

	public static DataManager getInstance() {
		return instance;
	}

	public static DataManager get() {
		return instance;
	}

	@Override
	public void close() {
	}

	public void setDLCEnabledByDefault(boolean b) {
		dlcEnabledByDefault = b;
	}

	public boolean isDLCEnabledByDefault() {
		return dlcEnabledByDefault;
	}

	public boolean hasDataInputStream(String innerPath) {
		throw new UnsupportedOperationException();
	}

	public InputStream getDataInputStream(String innerPath) throws IOException {
		throw new UnsupportedOperationException();
	}

	public boolean hasResourceInputStream(String innerPath) {
		throw new UnsupportedOperationException();
	}

	public InputStream getResourceInputStream(String innerPath) throws IOException {
		throw new UnsupportedOperationException();
	}

	public void extractDataDat(File extractDir) throws IOException {
		throw new UnsupportedOperationException();
	}

	public void extractResourceDat(File extractDir) throws IOException {
		throw new UnsupportedOperationException();
	}

	public AugBlueprint getAugment(String id, boolean dlcEnabled) {
		throw new UnsupportedOperationException();
	}

	/**
	 * A frontend using the global DLC default.
	 */
	public AugBlueprint getAugment(String id) {
		return getAugment(id, dlcEnabledByDefault);
	}

	public Map<String, AugBlueprint> getAugments(boolean dlcEnabled) {
		throw new UnsupportedOperationException();
	}

	/**
	 * A frontend using the global DLC default.
	 */
	public Map<String, AugBlueprint> getAugments() {
		return getAugments(dlcEnabledByDefault);
	}

	public CrewBlueprint getCrew(String id, boolean dlcEnabled) {
		throw new UnsupportedOperationException();
	}

	/**
	 * A frontend using the global DLC default.
	 */
	public CrewBlueprint getCrew(String id) {
		return getCrew(id, dlcEnabledByDefault);
	}

	public Map<String, CrewBlueprint> getCrews(boolean dlcEnabled) {
		throw new UnsupportedOperationException();
	}

	/**
	 * A frontend using the global DLC default.
	 */
	public Map<String, CrewBlueprint> getCrews() {
		return getCrews(dlcEnabledByDefault);
	}

	public DroneBlueprint getDrone(String id, boolean dlcEnabled) {
		throw new UnsupportedOperationException();
	}

	/**
	 * A frontend using the global DLC default.
	 */
	public DroneBlueprint getDrone(String id) {
		return getDrone(id, dlcEnabledByDefault);
	}

	public Map<String, DroneBlueprint> getDrones(boolean dlcEnabled) {
		throw new UnsupportedOperationException();
	}

	/**
	 * A frontend using the global DLC default.
	 */
	public Map<String, DroneBlueprint> getDrones() {
		return getDrones(dlcEnabledByDefault);
	}

	public SystemBlueprint getSystem(String id, boolean dlcEnabled) {
		throw new UnsupportedOperationException();
	}

	/**
	 * A frontend using the global DLC default.
	 */
	public SystemBlueprint getSystem(String id) {
		return getSystem(id, dlcEnabledByDefault);
	}

	public WeaponBlueprint getWeapon(String id, boolean dlcEnabled) {
		throw new UnsupportedOperationException();
	}

	/**
	 * A frontend using the global DLC default.
	 */
	public WeaponBlueprint getWeapon(String id) {
		return getWeapon(id, dlcEnabledByDefault);
	}

	public Map<String, WeaponBlueprint> getWeapons(boolean dlcEnabled) {
		throw new UnsupportedOperationException();
	}

	public Map<String, WeaponBlueprint> getWeapons() {
		return getWeapons(dlcEnabledByDefault);
	}

	public ShipBlueprint getShip(String id, boolean dlcEnabled) {
		throw new UnsupportedOperationException();
	}

	/**
	 * A frontend using the global DLC default.
	 */
	public ShipBlueprint getShip(String id) {
		return getShip(id, dlcEnabledByDefault);
	}

	public Map<String, ShipBlueprint> getShips(boolean dlcEnabled) {
		throw new UnsupportedOperationException();
	}

	/**
	 * A frontend using the global DLC default.
	 */
	public Map<String, ShipBlueprint> getShips() {
		return getShips(dlcEnabledByDefault);
	}

	public Map<String, ShipBlueprint> getAutoShips(boolean dlcEnabled) {
		throw new UnsupportedOperationException();
	}

	/**
	 * A frontend using the global DLC default.
	 */
	public Map<String, ShipBlueprint> getAutoShips() {
		return getAutoShips(dlcEnabledByDefault);
	}

	public Map<String, ShipBlueprint> getPlayerShips(boolean dlcEnabled) {
		throw new UnsupportedOperationException();
	}

	/**
	 * A frontend using the global DLC default.
	 */
	public Map<String, ShipBlueprint> getPlayerShips() {
		return getPlayerShips(dlcEnabledByDefault);
	}

	public List<String> getPlayerShipBaseIds(boolean dlcEnabled) {
		throw new UnsupportedOperationException();
	}

	/**
	 * A frontend using the global DLC default.
	 */
	public List<String> getPlayerShipBaseIds() {
		return getPlayerShipBaseIds(dlcEnabledByDefault);
	}

	public ShipBlueprint getPlayerShipVariant(String baseId, int n, boolean dlcEnabled) {
		throw new UnsupportedOperationException();
	}

	/**
	 * A frontend using the global DLC default.
	 */
	public ShipBlueprint getPlayerShipVariant(String baseId, int n) {
		return getPlayerShipVariant(baseId, n, dlcEnabledByDefault);
	}

	/**
	 * A frontend using the global DLC default.
	 */

	public ShipLayout getShipLayout(String id) {
		throw new UnsupportedOperationException();
	}

	public ShipChassis getShipChassis(String id) {
		throw new UnsupportedOperationException();
	}

	public FTLEvent getEventById(String id, boolean dlcEnabled) {
		throw new UnsupportedOperationException();
	}

	/**
	 * A frontend using the global DLC default.
	 */
	public FTLEvent getEventById(String id) {
		return getEventById(id, dlcEnabledByDefault);
	}

	public FTLEventList getEventListById(String id, boolean dlcEnabled) {
		throw new UnsupportedOperationException();
	}

	/**
	 * A frontend using the global DLC default.
	 */
	public FTLEventList getEventListById(String id) {
		return getEventListById(id, dlcEnabledByDefault);
	}

	public Map<String, Encounters> getEncounters(boolean dlcEnabled) {
		throw new UnsupportedOperationException();
	}

	/**
	 * A frontend using the global DLC default.
	 */
	public Map<String, Encounters> getEncounters() {
		return getEncounters(dlcEnabledByDefault);
	}

	public ShipEvent getShipEventById(String id, boolean dlcEnabled) {
		throw new UnsupportedOperationException();
	}

	/**
	 * A frontend using the global DLC default.
	 */
	public ShipEvent getShipEventById(String id) {
		return getShipEventById(id, dlcEnabledByDefault);
	}

	public Map<String, ShipEvent> getShipEvents(boolean dlcEnabled) {
		throw new UnsupportedOperationException();
	}

	/**
	 * A frontend using the global DLC default.
	 */
	public Map<String, ShipEvent> getShipEvents() {
		return getShipEvents(dlcEnabledByDefault);
	}

	public boolean getCrewSex() {
		throw new UnsupportedOperationException();
	}

	public String getCrewName(boolean isMale) {
		throw new UnsupportedOperationException();
	}

	public SectorType getSectorTypeById(String id, boolean dlcEnabled) {
		throw new UnsupportedOperationException();
	}

	/**
	 * A frontend using the global DLC default.
	 */
	public SectorType getSectorTypeById(String id) {
		return getSectorTypeById(id, dlcEnabledByDefault);
	}

	public SectorDescription getSectorDescriptionById(String id) {
		throw new UnsupportedOperationException();
	}

}