text:
/* { dg-options "-O2 -fno-inline-functions" } */
/* { dg-do run } */

/* Gimplification problem exposed by zsh.  All the side-effects in
   function arguments and in the called expression should happen
   before the actual function call.  */
extern void abort (void);
int A;

typedef void (*fnptr) (void);
fnptr *F;

void
foo (int x)
{
  if (A == x)
    abort ();
}

void
bar (int x, int y)
{
  if (x == 5 || y != 3)
    abort ();
}

void
boz (void)
{
  abort ();
}

void
baz (void)
{
  if (*F != boz)
    abort ();
}

fnptr B[2] = { baz, boz };

main ()
{
  int b, c;

  /* The gimplifier was emitting A++ after the call to foo.  */
  A = 5;
  foo (A++);

  /* The increment to 'b' and 'c' must happen before the call.  However,
     the first argument to bar() must be the original value of 'b', while
     the second argument must be the new value of 'c'.  */
  b = 4;
  c = 2;
  bar (b++, ++c);

  /* This call via function pointer *F should go to baz, but F should
     be incremented before the actual call (i.e., right before the
     call F should be pointing to boz).  */
  F = &B[0];
  (*F++) ();

  return 0;
}


text:
from __future__ import unicode_literals

from django.db import migrations, models
import django.utils.timezone

class Migration(migrations.Migration):

    dependencies = [
        ('icekit', '0006_auto_20150911_0744'),
    ]

    operations = [
        migrations.CreateModel(
            name='BarWithLayout',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('layout', models.ForeignKey(related_name='tests_barwithlayout_related', blank=True, to='icekit.Layout', null=True)),
            ],
            options={
                'abstract': False,
            },
        ),
        migrations.CreateModel(
            name='BaseModel',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('created', models.DateTimeField(default=django.utils.timezone.now, editable=False, db_index=True)),
                ('modified', models.DateTimeField(default=django.utils.timezone.now, editable=False, db_index=True)),
            ],
            options={
                'ordering': ('-id',),
                'abstract': False,
                'get_latest_by': 'pk',
            },
        ),
        migrations.CreateModel(
            name='BazWithLayout',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('layout', models.ForeignKey(related_name='tests_bazwithlayout_related', blank=True, to='icekit.Layout', null=True)),
            ],
            options={
                'abstract': False,
            },
        ),
        migrations.CreateModel(
            name='FooWithLayout',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('layout', models.ForeignKey(related_name='tests_foowithlayout_related', blank=True, to='icekit.Layout', null=True)),
            ],
            options={
                'abstract': False,
            },
        ),
        migrations.CreateModel(
            name='ImageTest',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('image', models.ImageField(upload_to=b'testing/')),
            ],
        ),
    ]

redpajama_set_name: RedPajamaGithub


text:
package com.xiantrimble.combinatorics;

import java.util.List;

import javolution.util.FastList;

public abstract class AbstractCombinatoricIteratorTest {
  protected static Integer ONE = 1;
  protected static Integer TWO = 2;
  protected static Integer THREE = 3;
  protected static Integer FOUR = 4;
  protected static Integer FIVE = 5;
  protected static Integer SIX = 6;
  protected static Integer SEVEN = 7;
  protected static Integer EIGHT = 8;

  public static <E> List<E> list(E... elements) {
    FastList<E> list = new FastList<E>();
    for (E element : elements) {
      list.add(element);
    }
    return list;
  }
}


text:
<?php session_start();?>

<?php
if(!isset($_SESSION['inicia'])){
header("location: index.html?**sin-acceso**");
} else {
$e=$_SESSION['inicia'];

} /* Y cerramos el else */
echo "
";
date_default_timezone_set('mexico/general');
$mes=date("m");
?>

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Biogym-Panel</title>

    <link href="../../bower_components/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet">

    <link href="../../bower_components/metisMenu/dist/metisMenu.min.css" rel="stylesheet">

    <link href="../../dist/css/timeline.css" rel="stylesheet">

    <link href="../../dist/css/sb-admin-2.css" rel="stylesheet">

    <link href="../../bower_components/morrisjs/morris.css" rel="stylesheet">

    <link href="../../bower_components/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                    Toggle navigation

                </button>
                Biogym-Panel de control

 User Profile

 Settings

 Logout

                            Inicio

                             Productos

                                    Inventario

                                    Conceptos

                             Info Caja

                                    Caja al dia

                             Asistencia del Personal

                                    Asistencia

                             Asistencia socios

                             Programación

                                    Fijos

                                    Variables

                             Egresos

Programacion de Gastos

                           Listado de gastos

 Nuevo

                                <form action="#" method="POST" >
                            <fieldset>
                       <?php
                        include('../connect.php');
						$mes=date("m");
						$fecha=$_POST['fechap'];
						$concept=$_POST['concept'];
						$importe=$_POST['importe'];
						$pago=$_POST['pago'];
						$t=0;

					$sql = mysql_query("insert into gastos_fijos SET mes='$mes',fecha='$fecha',concepto='$concept',importe='$importe',formapago='$pago',tipo='$t' ");
					if(!$sql){

						echo "
";
                        echo "Tenemos un problema con tu solicitud";
                        echo "
";
					}else{

						echo "
";
                        echo "Producto Registrado";
                        echo "
";
					}
							?>

                                Salir

                            </fieldset>
                        </form>


text:
% ----------------------------------------------------------------------
% BEGIN LICENSE BLOCK
% Version: CMPL 1.1
%
% The contents of this file are subject to the Cisco-style Mozilla Public
% License Version 1.1 (the "License"); you may not use this file except
% in compliance with the License.  You may obtain a copy of the License
% at www.eclipse-clp.org/license.
%
% Software distributed under the License is distributed on an "AS IS"
% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied.  See
% the License for the specific language governing rights and limitations
% under the License.
%
% The Original Code is  The ECLiPSe Constraint Logic Programming System.
% The Initial Developer of the Original Code is  Cisco Systems, Inc.
% Portions created by the Initial Developer are
% Copyright (C) 1995-2006 Cisco Systems, Inc.  All Rights Reserved.
%
% Contributor(s): IC-Parc, Imperal College London
%
% END LICENSE BLOCK
%
% System:	ECLiPSe Constraint Logic Programming System
% Version:	$Id: tracer.pl,v 1.2 2008/07/08 22:31:23 jschimpf Exp $
% ----------------------------------------------------------------------

%
% ECLiPSe II debugger -- Port generation
%
% $Id: tracer.pl,v 1.2 2008/07/08 22:31:23 jschimpf Exp $
%
% Author:	Joachim Schimpf, IC-Parc
%

/*
ECLiPSe II debugger

The engine notifies the debugger only at the following points:

    call(OldStack, NewStack)
    wake(OldStack, NewStack)
    exit(Stack)
    redo(Stack, FailDrop, RedoLevel, Which, ShowNext)
    delay(256, make_suspension(Goal,P,S,M))

These points are synchronous in the execution, so we can easily insert
Prolog execution there.

The handler then generates ports from notifications and calls port/2
for each port. Note that because of the mismatch between notifications
and ports, the artificial ports normally cannot be displayed with
arguments because the engine is already in a different state (e.g
FAIL REDO).

Ports are filtered with of_interest/5 and pre-filtered on engine level:

    ==invoc &&  minlevel=<level=<maxlevel &&
    ( (SPIED|TRACEABLE & tracemode) || tracemode=leap && at_breakpoint)
tracemode,invoc,minlevel,maxlevel can be set via
trace_mode/2.

*/

:- begin_module(sepia_kernel).
:- pragma(nodebug).
:- pragma(system).
:- pragma(noskip).

:- export
	struct(ports(call,exit,'*exit',redo,fail,	% enum, really
		     resume,leave,delay,next,unify,spyterm,modify,else)),
        % tf must correspond to definition in emu_export.h!
	struct(tf(invoc,goal,depth,chp,parent,proc,prio,path,line,from,to,module)),
	struct(trace_line(port,frame)).

:- export
	spy_var/1,
	spy_term/2.

:- export
	new_invoc/1,	% in C
	current_td/1,	% in C
	failure_culprit/2, % in C
	monitor_term/4,
	trace_mode/2,
	find_goal/3,
	get_tf_prop/3,
	debug_port_names/1,
	configure_prefilter/5.

%diagnostics(N) :- nl, writeln(N).
diagnostics(_).

%----------------------------------------------------------------------
% Port generation from notifications
%----------------------------------------------------------------------

% Call and resume notification handler

ncall(OldStack, NewStack) :-
	call_or_wake(OldStack, NewStack, call of ports).

resume(OldStack, NewStack) :-
	call_or_wake(OldStack, NewStack, resume of ports).

    call_or_wake(OldStack, NewStack, Port) :-
	disable_tracing,
	get_priority(P), % Don't wake anything
	set_priority(1),
	diagnostics(ncall(NewStack, OldStack)),
	CurrentB = chp(_),
	timestamp_update(CurrentB, 1),

	( NewStack = tf{parent:Parent} ->		% call port
	    ( OldStack == Parent ->
		raise_init_event % if necessary
	    ;
		trace_exit(OldStack, CurrentB)
	    ),
	    port(Port, NewStack)
	;						% exit port
	    trace_exit(OldStack, CurrentB)
	),
	diagnostics(ncall-done),
	!, set_priority(P), cont_debug.

% Exit notification handler

nexit(Stack) :-
	disable_tracing,
	get_priority(P), % Don't wake anything
	set_priority(1),
	diagnostics(nexit(Stack)),
	CurrentB = chp(_),
	timestamp_update(CurrentB, 1),

	trace_exit(Stack, CurrentB),
	!, cont_debug, set_priority(P).

    trace_exit(Frame, NewB) :-
	( timestamp_older(Frame, chp of tf, NewB, 1) ->
	    port('*exit' of ports, Frame)
	;
	    port(exit of ports, Frame)
	).

% Redo notification handler, called after the failure happened.
% Stack:	the current (restored) stack after the failure
% FailDrop:	how many levels failed (use get_fail_info/2 to get details)
% RedoLevel:	at which level the failure was caught, ie the youngest
%		common ancestor of the failed and the redone goal.
% FailLeave:	fail port or leave port
% ShowNext:	1 if the predicate with the choice point is debuggable,
%		which means that the NEXT-port should be shown.

redo(Stack, FailDrop, RedoLevel, FailLeave, ShowNext) :-
	disable_tracing,
	get_priority(P), % Don't wake anything
	set_priority(1),
	diagnostics(redo(Stack, FailDrop, RedoLevel, FailLeave, ShowNext)),
	trace_fails_redos(Stack, RedoLevel, FailDrop, ShowNext, FailLeave),
	!, set_priority(P), cont_debug,
	% FAIL port: fail for correct state restoration from choicepoint
	% LEAVE port: succeed for state restoration from aux. environment
	FailLeave == (leave of ports).

trace_fails_redos(0, RedoLevel, FailDrop, _ShowNext, FailLeave) :-
	trace_failures(FailDrop, RedoLevel, 0, FailLeave).
trace_fails_redos(Current, RedoLevel, FailDrop, ShowNext, FailLeave) :-
	Current = tf{depth:Depth},
	( Depth > RedoLevel ->
	    trace_fails_redos1(Current, RedoLevel, FailDrop)
	; Depth = RedoLevel ->
	    trace_failures(FailDrop, RedoLevel, Current, FailLeave),
	    ( ShowNext == 0 -> true ; port(ShowNext, Current) )
	;
	    trace_failures(FailDrop, RedoLevel, Current, FailLeave)
	).

    trace_fails_redos1(0, _RedoLevel, _FailDrop).
    trace_fails_redos1(Current, RedoLevel, FailDrop) :-
	Current = tf{depth:Depth,parent:Parent},
	( Depth > RedoLevel ->
	    trace_fails_redos1(Parent, RedoLevel, FailDrop),
	    port(redo of ports, Current)
	; % Depth = RedoLevel
	    trace_failures(FailDrop, RedoLevel, Current, fail of ports)
	).

    trace_failures(0, _Depth, _Stack, _FailLeave) :- !.
    trace_failures(I, Depth, Stack, FailLeave) :-
	I1 is I-1,
	Depth1 is Depth+1,
	get_fail_info(I1, FakeStack),
	( FakeStack \== [] ->
	    % get_fail_info/2 does not fill in depth and parent
	    FakeStack = tf{depth:Depth1,parent:Stack},
	    trace_failures(I1, Depth1, FakeStack, FailLeave),
	    port(FailLeave, FakeStack)
	; % fail info not recorded, ignore
	    trace_failures(I1, Depth1, Stack, FailLeave)
	).

% Delay notification handler for make_suspension/3,4
% This is currently a bit funny, because it is implemented as an
% error handler for make_suspension/4, and it is raised after the
% suspension has been created, but before it has been unified with S.
% That's why the latter has to be done here in the handler.

ndelay(_, MakeSuspension) :-
	disable_tracing,
	get_priority(P), % Don't wake anything
	set_priority(1),
	current_td(Parent),
	extract_suspension(MakeSuspension, S),
	last_suspension(S),	% unify S
	diagnostics(ndelay(MakeSuspension)),
	Parent = tf{depth:D},
	D1 is D+1,
	trace_delays(Parent, D1, [S]),
	!, set_priority(P), cont_debug.

    extract_suspension(make_suspension(_,_,S), S).
    extract_suspension(make_suspension(_,_,S,_), S).

% Delay notification handler for suspensions created inside externals.
% It is the external predicate's responsibility to raise the DEBUG_SUSP_EVENT
% if any of the suspensions created within it need to be traced.

bip_delay :-
	disable_tracing,
	get_priority(P), % Don't wake anything
	set_priority(1),
	delay_port_susps(Susps), % get a list of new, traceable suspensions
	diagnostics(bip_delay(Susps)),
	current_td(Parent),
	Parent = tf{depth:D},
	D1 is D+1,
	trace_delays(Parent, D1, Susps),
	!, set_priority(P), cont_debug.

    trace_delays(_, _, []).
    trace_delays(Parent, Depth, [S|Susps]) :-
	susp_to_tf(S, Stack),
	Stack = tf{depth:Depth,parent:Parent},
	port((delay) of ports, Stack),
	trace_delays(Parent, Depth, Susps).

:- set_flag(bip_delay/0, invisible, on).

% Tracing of inline-compiled builtins like +/3, arg/3, =/2, ...
% Done via exception-events raised by the debug_call_simple and
% debug_exit_simple instructions.
% These handlers are executed under priority 1 because of exception mechanism.

:- export bip_call/0.
:- set_flag(bip_call/0, invisible, on).
bip_call :-
	% CALL port, frame already pushed
	% If we had the OldStack, we'd call ncall(OldStack,TD)
	current_td(TD),
	( TD = tf{parent:Parent} ->		% call port
	    ncall(Parent,TD)
	;
	    writeln(error, "Illegal state in bip_call handler - ignored"),
	    cont_debug
	).

:- export bip_exit/0.
:- set_flag(bip_exit/0, invisible, on).
bip_exit :-
	disable_tracing,
	current_td(Stack),
	port(exit of ports, Stack),
	pop_tf,
	cont_debug.

/* might be needed if we re-introduce shallow choicepoints
bip_fail :-
	disable_tracing,
	current_td(Stack),
	port(fail of ports, Stack),
	pop_tf,
	!,
	cont_debug.
*/

% Builtins for generating user-defined debugger ports

:- export trace_call_port/3.
:- tool(trace_call_port/3, trace_call_port/4).
:- set_flag(trace_call_port/3, invisible, on).
:- set_flag(trace_call_port/4, invisible, on).
trace_call_port(Port, Invoc, Goal0, M) :-
	( integer(Invoc) ; var(Invoc) ), !,
	( tracing ->
	    disable_tracing,
	    get_priority(P),			% Don't wake anything
	    set_priority(1),
	    lookup_module(Goal0, M, Goal, LM),
	    make_tf(1, Invoc, Goal, M, LM, P, Stack),	% push frame
	    port_name_to_number(Port, PortNr),
	    port(PortNr, Stack),
	    !,
	    set_priority(P),
	    cont_debug
	;
	    true
	).

    :- mode lookup_module(+,+,-,-).
    lookup_module(LM0:G0, _, G, LM) ?- G = G0, LM = LM0.
    lookup_module(G, M, G, M).

:- export trace_point_port/3.
:- tool(trace_point_port/3, trace_point_port/4).
:- set_flag(trace_point_port/3, invisible, on).
:- set_flag(trace_point_port/4, invisible, on).
trace_point_port(Port, Invoc, Goal0, M) :-
	( integer(Invoc) ; var(Invoc) ), !,
	( tracing ->
	    trace_point_port_unchecked(Port, Invoc, Goal0, M)
	;
	    true
	).

trace_point_port_unchecked(Port, Invoc, Goal0, M) :-
	    disable_tracing,
	    get_priority(P),			% Don't wake anything
	    set_priority(1),
	    lookup_module(Goal0, M, Goal, LM),
	    make_tf(0, Invoc, Goal, M, LM, P, Stack),	% temporary frame
	    port_name_to_number(Port, PortNr),
	    port(PortNr, Stack),
	    !,
	    set_priority(P),
	    cont_debug.

:- export trace_exit_port/0.
:- set_flag(trace_exit_port/0, invisible, on).
trace_exit_port :-
	( tracing ->
	    disable_tracing,
	    get_priority(P),			% Don't wake anything
	    set_priority(1),
	    current_td(Stack),
	    ( Stack = tf{} ->
		CurrentB = chp(_),
		timestamp_update(CurrentB, 1),
		trace_exit(Stack, CurrentB),
		pop_tf
	    ;
		true	% no parent to exit
	    ),
	    !,
	    set_priority(P),
	    cont_debug
	;
	    true
	).

:- export trace_parent_port/1.
:- set_flag(trace_parent_port/1, invisible, on).
trace_parent_port(Port) :-
	( tracing ->
	    disable_tracing,
	    get_priority(P),			% Don't wake anything
	    set_priority(1),
	    current_td(Stack),			% use parent frame
	    ( Stack = tf{} ->
		port_name_to_number(Port, PortNr),
		port(PortNr, Stack)
	    ;
		true	% no parent
	    ),
	    !,
	    set_priority(P),
	    cont_debug
	;
	    true
	).

% A simple term-spy implementation

:- tool(spy_var/1, spy_var/2).
:- set_flag(spy_var/1, invisible, on).
:- set_flag(spy_var/2, invisible, on).
spy_var(Var, M) :-
	( tracing ->
	    spy_term(Var, Var->constrained, M)
	;
	    true
	).

:- tool(spy_term/2, spy_term/3).
:- set_flag(spy_term/2, invisible, on).
:- set_flag(spy_term/3, invisible, on).
spy_term(Term, Cond, Module) :-
	( tracing ->
	    disable_tracing,
	    suspend(monitor_term(I, Term, Module, Susp), 1, Cond, Susp),
	    trace_point_port_unchecked(spyterm, I, Term, Module)
	;
	    true
	).

:- demon monitor_term/4.
:- set_flag(monitor_term/4, invisible, on).
monitor_term(Invoc, Term, Module, Susp) :-
	( nonground(Term) -> true ; kill_suspension(Susp) ),
	trace_point_port_unchecked(modify, Invoc, Term, Module).
%monitor_term(Invoc, Term, Module, _Susp) :-
%	trace_point_port_unchecked(unmod, Invoc, Term, Module),
%	fail.

%----------------------------------------------------------------------
% Port filtering
% PortNr can be an integer (index of a built-in port) or an atom
%----------------------------------------------------------------------

port(PortNr, Stack) :-
	Stack = tf{invoc:Invoc,depth:Depth,proc:Proc},
	get_tf_prop(Stack, break, BrkPt),
%	diagnostics( of_interest(PortNr, Invoc, Depth, Proc, BrkPt)),
	( of_interest(PortNr, Invoc, Depth, Proc, BrkPt) ->
	    port_name(PortNr, Port),
	    Current = trace_line{port:Port,frame:Stack},
	    % This handler is allowed to cut_to, fail and abort
	    error(252, Current)		% trace line event
	;
%	    diagnostics(no_interest),
	    true
	).

configure_prefilter(Invoc, Depth, Ports, Preds, Module) :-
	decode_range(Invoc, MinInvoc, MaxInvoc),
	decode_range(Depth, MinDepth, MaxDepth),
	port_spec_to_mask(Ports, 0, PortMask),
	diagnostics(portMask=PortMask),
%	nospy(_),
	( Preds == spied -> LeapFlag = 1
	; Preds == all -> LeapFlag = 0
	; set_spypoints(Preds, Module, LeapFlag)
	),
	!,
	trace_mode(6, MinDepth),
	trace_mode(7, MaxDepth),
	trace_mode(8, MinInvoc),
	trace_mode(9, MaxInvoc),
	trace_mode(5, PortMask),
	trace_mode(11, LeapFlag).
configure_prefilter(Invoc, Depth, Ports, Preds, Module) :-
	error(6, configure_prefilter(Invoc, Depth, Ports, Preds, Module)).

    decode_range(N, 0, Max) :- var(N), !, maxint(Max).
    decode_range(N, N, N) :- integer(N).
    decode_range(=(N), N, N).
    decode_range(..(Min,Max), Min, Max).
    decode_range(Min-Max, Min, Max).
    decode_range(>(L), Min, Max) :- Min is L+1, maxint(Max).
    decode_range(<(H), 0, Max) :- Max is H-1.
    decode_range(=<(Max), 0, Max).
    decode_range(>=(Min), Min, Max) :- maxint(Max).

    :- mode port_spec_to_mask(?, +, -).
    port_spec_to_mask(Var, Mask0, Mask) :- var(Var), !,
	Mask is Mask0 \/ any_port_mask.
    port_spec_to_mask([], Mask, Mask) :- !.
    port_spec_to_mask(List, Mask0, Mask) :- List = [_|_],
	port_list_to_mask(List, Mask0, Mask).
    port_spec_to_mask(~Ps, Mask0, Mask) :-
	Mask is Mask0 \/ any_port_mask /\ \port_spec_to_mask(Ps, 0).
    port_spec_to_mask(P, Mask0, Mask) :- atom(P),
	Mask is Mask0 \/ port_name_to_mask_bit(P).

    :- mode port_list_to_mask(?, +, -).
    port_list_to_mask([], Mask, Mask).
    port_list_to_mask([P|Ps], Mask0, Mask) :-
	atom(P),
	Mask1 is Mask0 \/ port_name_to_mask_bit(P),
	port_list_to_mask(Ps, Mask1, Mask).

    :- mode set_spypoints(?, +, -).
    set_spypoints(Var, _Module, 0) :- var(Var), !.
    set_spypoints([], _Module, 0) :- !.
    set_spypoints([P|Ps], Module, 1) :- !,
	set_spypoint(P, Module),
	set_spypoints(Ps, Module, _).
    set_spypoints(P, Module, 1) :-
	set_spypoint(P, Module).

    set_spypoint(Module:N/A, _) ?-
    	spy(N/A)@Module.
    set_spypoint(N/A, Module) ?-
    	spy(N/A)@Module.

%----------------------------------------------------------------------
% Auxiliary
%----------------------------------------------------------------------

port_name(I, Name) :-
	integer(I),
	arg(I, ports{
	    call:call,
	    exit:exit,
	    '*exit':'*exit',
	    redo:redo,
	    fail:fail,
	    resume:resume,
	    leave:leave,
	    (delay):(delay),
	    next:next,
	    unify:unify,
	    spyterm:spyterm,
	    modify:modify,
	    else:else},
	Name).
port_name(I, Name) :-
	atom(I), I = Name.

:- mode debug_port_names(-).
debug_port_names(Names) :-
	Names = [call,
	         exit,
		 '*exit',
		 redo,
		 fail,
		 resume,
		 leave,
		 (delay),
		 next,
		 unify,
		 spyterm,
		 modify,
		 else].

any_port_mask(2'1111111111111111).

:- mode port_name_to_mask_bit(+,-).
port_name_to_mask_bit(call,	2'0000000000000001) :- !.
port_name_to_mask_bit(exit,	2'0000000000000010) :- !.
port_name_to_mask_bit('*exit',	2'0000000000000100) :- !.
port_name_to_mask_bit(redo,	2'0000000000001000) :- !.
port_name_to_mask_bit(fail,	2'0000000000010000) :- !.
port_name_to_mask_bit(resume,	2'0000000000100000) :- !.
port_name_to_mask_bit(leave,	2'0000000001000000) :- !.
port_name_to_mask_bit((delay),	2'0000000010000000) :- !.
port_name_to_mask_bit(next,	2'0000000100000000) :- !.
port_name_to_mask_bit(unify,	2'0000001000000000) :- !.
port_name_to_mask_bit(spyterm,	2'0000010000000000) :- !.
port_name_to_mask_bit(modify,	2'0000100000000000) :- !.
port_name_to_mask_bit(else,	2'0001000000000000) :- !.
port_name_to_mask_bit(_other,	2'1000000000000000).

:- mode port_name_to_number(+,-).
port_name_to_number(call,	1) :- !.
port_name_to_number(exit,	2) :- !.
port_name_to_number('*exit',	3) :- !.
port_name_to_number(redo,	4) :- !.
port_name_to_number(fail,	5) :- !.
port_name_to_number(resume,	6) :- !.
port_name_to_number(leave,	7) :- !.
port_name_to_number((delay),	8) :- !.
port_name_to_number(next,	9) :- !.
port_name_to_number(unify,	10) :- !.
port_name_to_number(spyterm,	11) :- !.
port_name_to_number(modify,	12) :- !.
port_name_to_number(else,	13) :- !.
port_name_to_number(Other,	Other).

find_goal(Invoc, Stack, Frame) :-
	find_ancestor(Invoc, Stack, Frame), !.
find_goal(Invoc, _Stack, Frame) :-
    	suspensions(Susps),
	find_susp_with_invoc(Invoc, Susps, Frame).

    find_ancestor(Invoc, Frame, Found) :-
    	Frame = tf{invoc:I,parent:Parent},		% may fail
	( I =:= Invoc ->
	    Frame = Found
	;
	    find_ancestor(Invoc, Parent, Found)
	).

    find_susp_with_invoc(Invoc, [S|Susps], Frame) :-
	( get_suspension_data(S, invoc, Invoc) ->
	    susp_to_tf(S, Frame),
	    Frame = tf{depth:0,parent:0}
	;
	    find_susp_with_invoc(Invoc, Susps, Frame)
	).

%----------------------------------------------------------------------
% Settings
%----------------------------------------------------------------------

:- set_default_error_handler(253, ncall/2), reset_error_handler(253).
:- set_default_error_handler(254, nexit/1), reset_error_handler(254).
:- set_default_error_handler(255, redo/5), reset_error_handler(255).
:- set_default_error_handler(256, ndelay/2), reset_error_handler(256).
:- set_default_error_handler(257, resume/2), reset_error_handler(257).
:- set_default_error_handler(258, bip_call/0), reset_error_handler(258).
:- set_default_error_handler(259, bip_exit/0), reset_error_handler(259).
%:- set_default_error_handler(251, bip_fail/0), reset_error_handler(251).
:- set_default_error_handler(249, bip_delay/0), reset_error_handler(249).


text:
using Example.DAL;
using Example.Domain;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Example.BLL
{
    public class DepartmentBLL : IDepartmentBLL
    {
        private readonly IEmployeeBLL employeeBLL;
        private readonly IRepository repository;

        public DepartmentBLL(IRepository repository, IEmployeeBLL employeeBll)
        {
            this.employeeBLL = employeeBll;
            this.repository = repository;
        }

        public Department CreateNew(string name)
        {
            var result = new Department(name);

            return this.repository.Save(result);
        }

        public void MoveAllEmployeesTo(Department source, Department target)
        {
            if (source == target)
            {
                throw new ArgumentException($"Employees cannot be move to same department \"{source.Name}\"");
            }

            while (source.Employees.Any())
            {
                this.employeeBLL.Move(source.Employees.First(), target);
            }

            this.repository.Save(source, target);
        }

        public ICollection<Department> GetAll()
        {
            return this.repository.GetAllDepartments();
        }

        public Department GetById(Guid id)
        {
            return this.repository.GetDepartmentById(id);
        }
    }
}


text:
package com.errpro.design_patterns.strategy;

//策略1 高表现性能策略
public class EnergySavingStrategy implements PowerStrategy {
	public void apply() {
		System.out.println("*** Energy-saving power strategy ***");
		System.out.println("trun off monitor: 5 minutes");
		System.out.println("trun off harddisk: 15 minutes");
		System.out.println("system standby: 30 minutes");
		System.out.println("system hibernates: 1 hour");
	}
}


text:
<link rel='stylesheet' type='text/css' href='http://fonts.googleapis.com/css?family=ABeeZee:regular:latin'>
<style type='text/css'>
       #warped {position: relative; display: block; width:600px; height:100px;}

       #warped>span[class^=w]:nth-of-type(n+0){display:block; position:absolute;
       -moz-transform-origin:50% 100%; -webkit-transform-origin:50% 100%; -o-transform-origin:50%
       100%; -ms-transform-origin:50% 100%; transform-origin:50% 100%; }

       #warped span{font-family:'ABeeZee';font-size:38px;font-weight:regular;font-style:normal;
       line-height:0.65; white-space:pre; overflow:visible; padding:0px;}

       #warped .w0 {-moz-transform: rotate(-7.84rad);-webkit-transform: rotate(-7.84rad);-o-transform:
       rotate(-7.84rad);-ms-transform: rotate(-7.84rad); transform: rotate(-7.84rad);
       width: 24px; height: 24px; left: 105px; top: 61.8px;}

       #warped .w1 {-moz-transform: rotate(-7.34rad);-webkit-transform: rotate(-7.34rad);-o-transform:
       rotate(-7.34rad);-ms-transform: rotate(-7.34rad); transform: rotate(-7.34rad);
       width: 23px; height: 24px; left: 112.03px; top: 35.57px;}

       #warped .w2 {-moz-transform: rotate(-6.77rad);-webkit-transform: rotate(-6.77rad);-o-transform:
       rotate(-6.77rad);-ms-transform: rotate(-6.77rad); transform: rotate(-6.77rad);
       width: 23px; height: 24px; left: 132.34px; top: 16.55px;}

       #warped .w3 {-moz-transform: rotate(-6.48rad);-webkit-transform: rotate(-6.48rad);-o-transform:
       rotate(-6.48rad);-ms-transform: rotate(-6.48rad); transform: rotate(-6.48rad);
       width: 15px; height: 24px; left: 159.74px; top: 8.75px;}

       #warped .w4 {-moz-transform: rotate(-6.33rad);-webkit-transform: rotate(-6.33rad);-o-transform:
       rotate(-6.33rad);-ms-transform: rotate(-6.33rad); transform: rotate(-6.33rad);
       width: 18px; height: 24px; left: 179.02px; top: 6.38px;}

       #warped .w5 {-moz-transform: rotate(-6.24rad);-webkit-transform: rotate(-6.24rad);-o-transform:
       rotate(-6.24rad);-ms-transform: rotate(-6.24rad); transform: rotate(-6.24rad);
       width: 11px; height: 24px; left: 203px; top: 6.45px;}

       #warped .w6 {-moz-transform: rotate(-6.16rad);-webkit-transform: rotate(-6.16rad);-o-transform:
       rotate(-6.16rad);-ms-transform: rotate(-6.16rad); transform: rotate(-6.16rad);
       width: 28px; height: 24px; left: 218.56px; top: 8.59px;}

       #warped .w7 {-moz-transform: rotate(-6.1rad);-webkit-transform: rotate(-6.1rad);-o-transform:
       rotate(-6.1rad);-ms-transform: rotate(-6.1rad); transform: rotate(-6.1rad);
       width: 11px; height: 24px; left: 251.24px; top: 12.42px;}

       #warped .w8 {-moz-transform: rotate(-6.06rad);-webkit-transform: rotate(-6.06rad);-o-transform:
       rotate(-6.06rad);-ms-transform: rotate(-6.06rad); transform: rotate(-6.06rad);
       width: 20px; height: 24px; left: 266.76px; top: 16.58px;}

       #warped .w9 {-moz-transform: rotate(-6.03rad);-webkit-transform: rotate(-6.03rad);-o-transform:
       rotate(-6.03rad);-ms-transform: rotate(-6.03rad); transform: rotate(-6.03rad);
       width: 10px; height: 24px; left: 290.65px; top: 21.19px;}

       #warped .w10 {-moz-transform: rotate(-6.01rad);-webkit-transform: rotate(-6.01rad);-o-transform:
       rotate(-6.01rad);-ms-transform: rotate(-6.01rad); transform: rotate(-6.01rad);
       width: 18px; height: 24px; left: 306.09px; top: 26.56px;}

       #warped .w11 {-moz-transform: rotate(-5.97rad);-webkit-transform: rotate(-5.97rad);-o-transform:
       rotate(-5.97rad);-ms-transform: rotate(-5.97rad); transform: rotate(-5.97rad);
       width: 23px; height: 24px; left: 327.54px; top: 33.93px;}

</style>


text:
<?php

declare(strict_types=1);

namespace JMS\Serializer\Metadata\Driver;

use JMS\Serializer\Metadata\ClassMetadata;
use Metadata\ClassMetadata as BaseClassMetadata;
use Metadata\Driver\DriverInterface;

class NullDriver implements DriverInterface
{
    public function loadMetadataForClass(\ReflectionClass $class): ?BaseClassMetadata
    {
        $classMetadata = new ClassMetadata($name = $class->name);
        $fileResource =  $class->getFilename();
        if (false !== $fileResource) {
            $classMetadata->fileResources[] = $fileResource;
        }

        return $classMetadata;
    }
}


text:
package com.adaptris.core.util;

import java.util.Collection;

import com.adaptris.annotation.ComponentProfile;
import com.adaptris.core.MetadataCollection;
import com.adaptris.core.MetadataElement;
import com.adaptris.core.MetadataLogger;
import com.thoughtworks.xstream.annotations.XStreamAlias;

/**
 * MetadataLogger implementation that that logs metadata keys only
 *
 * @config message-logging-with-metadata-keys-only
 */
@ComponentProfile(summary = "Log metadata keys only", since = "3.8.4")
@XStreamAlias("message-logging-with-metadata-keys-only")
public class MetadataKeysOnly implements MetadataLogger {

  @Override
  public String toString(Collection<MetadataElement> elements) {
    return String.format("Metadata Keys : %s", format(elements).toString());
  }

  private Collection<MetadataElement> format(Collection<MetadataElement> set) {
    MetadataCollection metadata = new MetadataCollection();
    set.stream().forEach(e -> {
      metadata.add(new KeysOnly(e.getKey(), e.getValue()));
    });
    return metadata;
  }

  private class KeysOnly extends MetadataElement {

    private static final long serialVersionUID = 2019040201L;

    public KeysOnly(String key, String value) {
      super(key, value);
    }

    @Override
    public String toString() {
      return String.format("[%s]", getKey());
    }
  }

}


text:
package myra.datamining;

import static myra.Config.CONFIG;
import static myra.datamining.Algorithm.RANDOM_GENERATOR;
import static myra.datamining.Dataset.COVERED;
import static myra.datamining.Dataset.NOT_COVERED;

import java.util.ArrayList;
import java.util.HashMap;

import myra.datamining.Dataset.Instance;

/**
 * This class can be used to partition de data in-memory.
 *
 * @author Fernando Esteban Barril Otero
 */
public class Partitioner {
    /**
     * The number of partitions to generate.
     */
    private int size;

    /**
     * The dataset to partition.
     */
    private Dataset dataset;

    /**
     * The dataset partitions.
     */
    private Instance[][] partitions;

    /**
     * Default constructor.
     *
     * @param dataset
     *            the dataset to partition.
     * @param slices
     *            the number of partitions.
     */
    public Partitioner(Dataset dataset, int slices) {
        this.size = slices;
        this.dataset = dataset;
        partitions = new Instance[slices][];
    }

    /**
     * Partitions the dataset respecting the class attribute values' frequency.
     */
    public void stratified() {
        HashMap<Integer, ArrayList<Integer>> instances =
                new HashMap<Integer, ArrayList<Integer>>();

        for (int i = 0; i < dataset.size(); i++) {
            int klass = (int) dataset.value(i, dataset.classIndex());
            ArrayList<Integer> indexes = instances.get(klass);

            if (indexes == null) {
                indexes = new ArrayList<Integer>();
                instances.put(klass, indexes);
            }

            indexes.add(i);
        }

        for (int i = 0; i < partitions.length; i++) {
            partitions[i] = Instance.newArray(dataset.size());
            Instance.markAll(partitions[i], COVERED);
        }

        int current = 0;

        for (int i = 0; i < instances.size(); i++) {
            ArrayList<Integer> indexes = instances.get(i);

            while (indexes != null && !indexes.isEmpty()) {
                for (int j = current; j < partitions.length; j++) {
                    int index = CONFIG.get(RANDOM_GENERATOR)
                            .nextInt(indexes.size());
                    partitions[j][indexes.get(index)].flag = NOT_COVERED;

                    indexes.remove(index);
                    current = j;

                    if (indexes.isEmpty()) {
                        break;
                    }
                }

                current = ((current + 1) < partitions.length) ? current + 1 : 0;
            }
        }

        // sanity check

        // for (int i = current; i < partitions.length; i++)
        // {
        // System.out.print("Partition " + i + ": ");
        // printFrequencies(dataset, partitions[i]);
        // }
    }

    /**
     * Returns training and validation datasets according to the partitions.
     *
     * @param training
     *            number of training partitions.
     * @param validation
     *            number of validation partitions.
     *
     * @return training and validation datasets according to the partitions.
     */
    public Dataset[] split(int training, int validation) {
        if ((training + validation) > size) {
            throw new IllegalArgumentException("Invalid number of partitions: "
                    + (training + validation) + " found; " + size
                    + " expected");
        }

        Dataset[] split = new Dataset[2];
        Instance[] instances = Instance.newArray(dataset.size());
        Instance.markAll(instances, COVERED);

        for (int i = 0; i < training; i++) {
            for (int j = 0; j < partitions[i].length; j++) {
                if (partitions[i][j].flag == NOT_COVERED) {
                    instances[j].flag = NOT_COVERED;
                }
            }
        }

        split[0] = Dataset.filter(dataset, instances, NOT_COVERED);
        Instance.markAll(instances, COVERED);

        for (int i = training; i < (training + validation); i++) {
            for (int j = 0; j < partitions[i].length; j++) {
                if (partitions[i][j].flag == NOT_COVERED) {
                    instances[j].flag = NOT_COVERED;
                }
            }
        }

        split[1] = Dataset.filter(dataset, instances, NOT_COVERED);

        return split;
    }
}


text:
package mtr.block;

import mtr.mappings.BlockDirectionalMapper;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.util.StringRepresentable;
import net.minecraft.world.item.context.BlockPlaceContext;
import net.minecraft.world.level.BlockGetter;
import net.minecraft.world.level.LevelAccessor;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.block.state.StateDefinition;
import net.minecraft.world.level.block.state.properties.EnumProperty;
import net.minecraft.world.level.block.state.properties.IntegerProperty;
import net.minecraft.world.phys.shapes.CollisionContext;
import net.minecraft.world.phys.shapes.Shapes;
import net.minecraft.world.phys.shapes.VoxelShape;

public class BlockPlatform extends BlockDirectionalMapper {

	private final boolean isIndented;

	public static final EnumProperty<EnumDoorType> DOOR_TYPE = EnumProperty.create("door_type", EnumDoorType.class);
	public static final IntegerProperty SIDE = IntegerProperty.create("side", 0, 4);

	public BlockPlatform(Properties settings, boolean isIndented) {
		super(settings);
		this.isIndented = isIndented;
		registerDefaultState(defaultBlockState().setValue(DOOR_TYPE, EnumDoorType.NONE));
	}

	@Override
	public BlockState updateShape(BlockState state, Direction direction, BlockState newState, LevelAccessor world, BlockPos pos, BlockPos posFrom) {
		return getActualState(world, pos, state);
	}

	@Override
	public BlockState getStateForPlacement(BlockPlaceContext ctx) {
		return defaultBlockState().setValue(FACING, ctx.getHorizontalDirection());
	}

	@Override
	public VoxelShape getShape(BlockState state, BlockGetter world, BlockPos pos, CollisionContext context) {
		if (isIndented) {
			final Direction facing = IBlock.getStatePropertySafe(state, FACING);
			return Shapes.or(IBlock.getVoxelShapeByDirection(0, 0, 6, 16, 13, 16, facing), Block.box(0, 13, 0, 16, 16, 16));
		} else {
			return super.getShape(state, world, pos, context);
		}
	}

	@Override
	protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> builder) {
		builder.add(FACING, DOOR_TYPE, SIDE);
	}

	private BlockState getActualState(BlockGetter world, BlockPos pos, BlockState state) {
		Direction facing = IBlock.getStatePropertySafe(state, FACING);

		final BlockState stateAbove = world.getBlockState(pos.above());
		final Block blockAbove = stateAbove.getBlock();

		EnumDoorType doorType;
		if (blockAbove instanceof BlockPSDDoor || blockAbove instanceof BlockPSDGlass || blockAbove instanceof BlockPSDGlassEnd) {
			doorType = EnumDoorType.PSD;
			facing = IBlock.getStatePropertySafe(stateAbove, FACING);
		} else if (blockAbove instanceof BlockAPGDoor || blockAbove instanceof BlockAPGGlass || blockAbove instanceof BlockAPGGlassEnd) {
			doorType = EnumDoorType.APG;
			facing = IBlock.getStatePropertySafe(stateAbove, FACING);
		} else {
			doorType = EnumDoorType.NONE;
		}

		final boolean aboveIsDoor = blockAbove instanceof BlockPSDAPGDoorBase;

		final BlockState stateLeftAbove = world.getBlockState(pos.above().relative(facing.getCounterClockWise()));
		final boolean leftAboveIsDoor = stateLeftAbove.getBlock() instanceof BlockPSDAPGDoorBase;

		final BlockState stateRightAbove = world.getBlockState(pos.above().relative(facing.getClockWise()));
		final boolean rightAboveIsDoor = stateRightAbove.getBlock() instanceof BlockPSDAPGDoorBase;

		final int side;
		if (aboveIsDoor && rightAboveIsDoor) {
			side = 2;
		} else if (aboveIsDoor && leftAboveIsDoor) {
			side = 3;
		} else if (rightAboveIsDoor) {
			side = 1;
			facing = IBlock.getStatePropertySafe(stateRightAbove, FACING);
		} else if (leftAboveIsDoor) {
			side = 4;
			facing = IBlock.getStatePropertySafe(stateLeftAbove, FACING);
		} else {
			side = 0;
		}

		return state.setValue(FACING, facing).setValue(DOOR_TYPE, doorType).setValue(SIDE, side);
	}

	private enum EnumDoorType implements StringRepresentable {

		NONE("none"), PSD("psd"), APG("apg");
		private final String name;

		EnumDoorType(String nameIn) {
			name = nameIn;
		}

		@Override
		public String getSerializedName() {
			return name;
		}
	}
}


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

package org.apache.ambari.server.ldap.service.ads;

import java.util.Map;
import java.util.Set;

import org.apache.ambari.server.configuration.AmbariServerConfigurationKey;
import org.apache.ambari.server.ldap.domain.AmbariLdapConfiguration;
import org.apache.ambari.server.ldap.service.AmbariLdapException;
import org.apache.ambari.server.ldap.service.LdapConfigurationService;
import org.apache.directory.api.ldap.model.message.SearchRequest;
import org.apache.directory.api.ldap.model.message.SearchRequestImpl;
import org.apache.directory.api.ldap.model.message.SearchScope;
import org.apache.directory.api.ldap.model.name.Dn;
import org.apache.directory.ldap.client.template.ConnectionCallback;
import org.apache.directory.ldap.client.template.EntryMapper;
import org.apache.directory.ldap.client.template.LdapConnectionTemplate;
import org.easymock.EasyMock;
import org.easymock.EasyMockRule;
import org.easymock.EasyMockSupport;
import org.easymock.Mock;
import org.easymock.MockType;
import org.easymock.TestSubject;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

public class DefaultLdapConfigurationServiceTest extends EasyMockSupport {
  @Rule
  public EasyMockRule mocks = new EasyMockRule(this);

  @Mock(type = MockType.STRICT)
  private LdapConnectionTemplateFactory ldapConnectionTemplateFactory;

  @Mock(type = MockType.STRICT)
  private LdapConnectionTemplate ldapConnectionTemplateMock;

  @TestSubject
  private LdapConfigurationService ldapConfigurationService = new DefaultLdapConfigurationService();

  @Before
  public void before() {
    resetAll();
  }

  @Test
  public void testShouldConnectionCheckSucceedWhenConnectionCallbackSucceeds() throws Exception {
    // GIVEN
    AmbariLdapConfiguration ambariLdapConfiguration = new AmbariLdapConfiguration(Maps.newHashMap());

    // the cllback returns TRUE
    EasyMock.expect(ldapConnectionTemplateMock.execute(EasyMock.anyObject(ConnectionCallback.class))).andReturn(Boolean.TRUE);
    EasyMock.expect(ldapConnectionTemplateFactory.create(ambariLdapConfiguration)).andReturn(ldapConnectionTemplateMock);

    replayAll();
    // WHEN
    ldapConfigurationService.checkConnection(ambariLdapConfiguration);

    // THEN
    // no exceptions are thrown

  }

  @Test(expected = AmbariLdapException.class)
  public void testShouldConnectionCheckFailWhenConnectionCallbackFails() throws Exception {

    // GIVEN
    AmbariLdapConfiguration ambariLdapConfiguration = new AmbariLdapConfiguration(Maps.newHashMap());

    // the callback returns FALSE
    EasyMock.expect(ldapConnectionTemplateMock.execute(EasyMock.anyObject(ConnectionCallback.class))).andReturn(Boolean.FALSE);
    EasyMock.expect(ldapConnectionTemplateFactory.create(ambariLdapConfiguration)).andReturn(ldapConnectionTemplateMock);

    replayAll();
    // WHEN
    ldapConfigurationService.checkConnection(ambariLdapConfiguration);

    // THEN
    // exception is thrown

  }

  @Test
  public void testShouldUserAttributeConfigurationCheckSucceedWhenUserDnIsFound() throws Exception {
    // GIVEN
    Map<String, String> configMap = Maps.newHashMap();
    configMap.put(AmbariServerConfigurationKey.USER_OBJECT_CLASS.key(), "person");
    configMap.put(AmbariServerConfigurationKey.USER_NAME_ATTRIBUTE.key(), "uid");

    AmbariLdapConfiguration ambariLdapConfiguration = new AmbariLdapConfiguration(configMap);

    // the callback returns FALSE
    EasyMock.expect(ldapConnectionTemplateFactory.create(ambariLdapConfiguration)).andReturn(ldapConnectionTemplateMock);
    // users found with dn
    EasyMock.expect(ldapConnectionTemplateMock.searchFirst(EasyMock.anyObject(Dn.class), EasyMock.anyString(), EasyMock.anyObject(SearchScope.class),
      EasyMock.anyObject(EntryMapper.class))).andReturn("dn");

    replayAll();
    // WHEN
    String userDn = ldapConfigurationService.checkUserAttributes("testUser", "testPassword", ambariLdapConfiguration);

    // THEN
    Assert.assertEquals("The found userDn is not the expected one", userDn, "dn");

  }

  @Test(expected = AmbariLdapException.class)
  public void testShouldUserAttributeConfigurationCheckFailWhenNoUsersFound() throws Exception {
    // GIVEN
    Map<String, String> configMap = Maps.newHashMap();
    configMap.put(AmbariServerConfigurationKey.USER_OBJECT_CLASS.key(), "posixAccount");
    configMap.put(AmbariServerConfigurationKey.USER_NAME_ATTRIBUTE.key(), "dn");

    AmbariLdapConfiguration ambariLdapConfiguration = new AmbariLdapConfiguration(configMap);

    // the callback returns FALSE
    EasyMock.expect(ldapConnectionTemplateFactory.create(ambariLdapConfiguration)).andReturn(ldapConnectionTemplateMock);

    // no users found, the returned dn is null
    EasyMock.expect(ldapConnectionTemplateMock.searchFirst(EasyMock.anyObject(Dn.class), EasyMock.anyString(),
      EasyMock.anyObject(SearchScope.class),
      EasyMock.anyObject(EntryMapper.class))).andReturn(null);

    replayAll();
    // WHEN
    String userDn = ldapConfigurationService.checkUserAttributes("testUser", "testPassword",
      ambariLdapConfiguration);

    // THEN
    Assert.assertEquals("The found userDn is not the expected one", userDn, "dn");

  }

  @Test
  public void testShouldGroupAttributeConfigurationCheckSucceedWhenGroupForUserDnIsFound() throws Exception {
    // GIVEN

    Map<String, String> configMap = groupConfigObjectMap();

    SearchRequest sr = new SearchRequestImpl();

    AmbariLdapConfiguration ambariLdapConfiguration = new AmbariLdapConfiguration(configMap);

    // the callback returns FALSE
    EasyMock.expect(ldapConnectionTemplateFactory.create(ambariLdapConfiguration)).andReturn(ldapConnectionTemplateMock);

    EasyMock.expect(ldapConnectionTemplateMock.newSearchRequest(EasyMock.anyObject(Dn.class), EasyMock.anyString(),
      EasyMock.anyObject(SearchScope.class))).andReturn(sr);

    EasyMock.expect(ldapConnectionTemplateMock.search(EasyMock.anyObject(SearchRequest.class), EasyMock.anyObject(EntryMapper.class)))
      .andReturn(Lists.newArrayList("userGroup"));

    replayAll();
    // WHEN
    Set<String> userGroups = ldapConfigurationService.checkGroupAttributes("userDn", ambariLdapConfiguration);

    // THEN
    Assert.assertNotNull("No groups found", userGroups);

  }

  @Test(expected = AmbariLdapException.class)
  public void testShouldGroupAttributeConfigurationCheckFailWhenNoGroupsForUserDnFound() throws Exception {
    // GIVEN

    Map<String, String> configMap = groupConfigObjectMap();

    SearchRequest sr = new SearchRequestImpl();

    AmbariLdapConfiguration ambariLdapConfiguration = new AmbariLdapConfiguration(configMap);

    // the callback returns FALSE
    EasyMock.expect(ldapConnectionTemplateFactory.create(ambariLdapConfiguration)).andReturn(ldapConnectionTemplateMock);

    EasyMock.expect(ldapConnectionTemplateMock.newSearchRequest(EasyMock.anyObject(Dn.class), EasyMock.anyString(),
      EasyMock.anyObject(SearchScope.class))).andReturn(sr);

    EasyMock.expect(ldapConnectionTemplateMock.search(EasyMock.anyObject(SearchRequest.class), EasyMock.anyObject(EntryMapper.class)))
      .andReturn(Lists.newArrayList());

    replayAll();
    // WHEN
    Set<String> userGroups = ldapConfigurationService.checkGroupAttributes("userDn", ambariLdapConfiguration);

    // THEN
    Assert.assertNotNull("No groups found", userGroups);

  }

  private Map<String, String> groupConfigObjectMap() {
    Map<String, String> configMap = Maps.newHashMap();
    configMap.put(AmbariServerConfigurationKey.GROUP_OBJECT_CLASS.key(), "groupOfNames");
    configMap.put(AmbariServerConfigurationKey.GROUP_SEARCH_BASE.key(), "dc=example,dc=com");
    configMap.put(AmbariServerConfigurationKey.GROUP_NAME_ATTRIBUTE.key(), "uid");
    configMap.put(AmbariServerConfigurationKey.GROUP_MEMBER_ATTRIBUTE.key(), "member");
    return configMap;
  }

}


text:
require 'rails'

require 'kraut'
require 'kraut/rails/authentication'

module Kraut

  module Rails

    class Engine < ::Rails::Engine

      config.after_initialize do
        ActionController::Base.class_eval do
          include Kraut::Rails::Authentication
        end
      end

      def self.resolve_authorization_aliases(authorizations, aliases)
        authorizations.inject({}) do |resolved, (action, groups)|
          resolved[action] = groups.map { |group| aliases[group] }
          resolved
        end
      end

    end

  end

end


text:
@interface DoraemonDemoCommonViewController : DoraemonDemoBaseViewController

@end


text:
"""Support for Supla cover - curtains, rollershutters, entry gate etc."""
from __future__ import annotations

import logging
from pprint import pformat
from typing import Any

from homeassistant.components.cover import ATTR_POSITION, CoverDeviceClass, CoverEntity
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType

from . import DOMAIN, SUPLA_COORDINATORS, SUPLA_SERVERS, SuplaChannel

_LOGGER = logging.getLogger(__name__)

SUPLA_SHUTTER = "CONTROLLINGTHEROLLERSHUTTER"
SUPLA_GATE = "CONTROLLINGTHEGATE"

async def async_setup_platform(
    hass: HomeAssistant,
    config: ConfigType,
    async_add_entities: AddEntitiesCallback,
    discovery_info: DiscoveryInfoType | None = None,
) -> None:
    """Set up the Supla covers."""
    if discovery_info is None:
        return

    _LOGGER.debug("Discovery: %s", pformat(discovery_info))

    entities: list[CoverEntity] = []
    for device in discovery_info.values():
        device_name = device["function_name"]
        server_name = device["server_name"]

        if device_name == SUPLA_SHUTTER:
            entities.append(
                SuplaCover(
                    device,
                    hass.data[DOMAIN][SUPLA_SERVERS][server_name],
                    hass.data[DOMAIN][SUPLA_COORDINATORS][server_name],
                )
            )

        elif device_name == SUPLA_GATE:
            entities.append(
                SuplaGateDoor(
                    device,
                    hass.data[DOMAIN][SUPLA_SERVERS][server_name],
                    hass.data[DOMAIN][SUPLA_COORDINATORS][server_name],
                )
            )

    async_add_entities(entities)

class SuplaCover(SuplaChannel, CoverEntity):
    """Representation of a Supla Cover."""

    @property
    def current_cover_position(self) -> int | None:
        """Return current position of cover. 0 is closed, 100 is open."""
        if state := self.channel_data.get("state"):
            return 100 - state["shut"]
        return None

    async def async_set_cover_position(self, **kwargs: Any) -> None:
        """Move the cover to a specific position."""
        await self.async_action("REVEAL", percentage=kwargs.get(ATTR_POSITION))

    @property
    def is_closed(self) -> bool | None:
        """Return if the cover is closed."""
        if self.current_cover_position is None:
            return None
        return self.current_cover_position == 0

    async def async_open_cover(self, **kwargs: Any) -> None:
        """Open the cover."""
        await self.async_action("REVEAL")

    async def async_close_cover(self, **kwargs: Any) -> None:
        """Close the cover."""
        await self.async_action("SHUT")

    async def async_stop_cover(self, **kwargs: Any) -> None:
        """Stop the cover."""
        await self.async_action("STOP")

class SuplaGateDoor(SuplaChannel, CoverEntity):
    """Representation of a Supla gate door."""

    @property
    def is_closed(self) -> bool | None:
        """Return if the gate is closed or not."""
        state = self.channel_data.get("state")
        if state and "hi" in state:
            return state.get("hi")
        return None

    async def async_open_cover(self, **kwargs: Any) -> None:
        """Open the gate."""
        if self.is_closed:
            await self.async_action("OPEN_CLOSE")

    async def async_close_cover(self, **kwargs: Any) -> None:
        """Close the gate."""
        if not self.is_closed:
            await self.async_action("OPEN_CLOSE")

    async def async_stop_cover(self, **kwargs: Any) -> None:
        """Stop the gate."""
        await self.async_action("OPEN_CLOSE")

    async def async_toggle(self, **kwargs: Any) -> None:
        """Toggle the gate."""
        await self.async_action("OPEN_CLOSE")

    @property
    def device_class(self) -> CoverDeviceClass:
        """Return the class of this device, from component DEVICE_CLASSES."""
        return CoverDeviceClass.GARAGE


text:
ALLUXIO_CLIENT_JAR=$(ls /alluxio/core/client/target/alluxio-core-client-*-jar-with-dependencies.jar)
echo "export HADOOP_CLASSPATH=\${HADOOP_CLASSPATH}:${ALLUXIO_CLIENT_JAR}" >> /hadoop/conf/hadoop-env.sh

NODES=$(cat /vagrant/files/workers)

# setup hadoop
rm -f /hadoop/conf/slaves
for node in ${NODES[@]}; do
  echo ${node} >> /hadoop/conf/slaves
done

# choose the last node as namenode
namenode=${node}
echo ${namenode} > /hadoop/conf/masters

# use /disk0, /disk1... as local storage
EXTRA_DISKS=$(ls / | grep '^disk')
DN=""
NN=""
TMP=""
for disk in ${EXTRA_DISKS}; do
  DN=/${disk}/dfs/dn,${DN}
  NN=/${disk}/dfs/nn,${NN}
  TMP=/${disk}/hadoop-tmpstore,${TMP}
done

[[ "$TMP" == "" ]] && TMP=/tmp/hadoop-tmpstore
cat > /hadoop/conf/core-site.xml << EOF
<configuration>
<property>
  <name>hadoop.tmp.dir</name>
  <value>${TMP}</value>
</property>
<property>
  <name>fs.default.name</name>
  <value>hdfs://${namenode}:9000</value>
</property>
<property>
  <name>fs.alluxio.impl</name>
  <value>alluxio.hadoop.FileSystem</value>
</property>
<property>
  <name>fs.alluxio-ft.impl</name>
  <value>alluxio.hadoop.FaultTolerantFileSystem</value>
</property>
</configuration>
EOF

[[ "$DN" == "" ]] && DN=/tmp/hdfs-datanode
[[ "$NN" == "" ]] && NN=/tmp/hdfs-namenode
cat > /hadoop/conf/hdfs-site.xml << EOF
<configuration>
<property>
 <name>dfs.replication</name>
 <value>1</value>
</property>
<property>
 <name>dfs.data.dir</name>
 <value>${DN}</value>
</property>
<property>
 <name>dfs.name.dir</name>
 <value>${NN}</value>
</property>
<property>
 <name>dfs.support.broken.append</name>
 <value>true</value>
</property>
<property>
 <name>dfs.webhdfs.enabled</name>
 <value>true</value>
</property>
</configuration>
EOF

cat > /hadoop/conf/mapred-site.xml << EOF
<configuration>
<property>
 <name>mapred.job.tracker</name>
 <value>${namenode}:9001</value>
</property>
</configuration>
EOF


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>com.github.jbrasileiro</groupId>
    <artifactId>resume-online</artifactId>
    <version>J7.1.1.6</version>
  </parent>
  <artifactId>resume-online-backend</artifactId>
  <packaging>pom</packaging>
  <modules>
		<!--
		<module>../Frameworks</module>
		 -->
		<module>resume-online-db</module>
		<module>resume-online-core</module>
		<module>resume-online-entity</module>
		<module>resume-online-dao-imp</module>
		<module>resume-online-SOA</module>
		<module>resume-online-commons</module>
		<module>resume-online-ws</module>
		<module>resume-online-ws-springboot</module>
		<module>resume-online-ws-microprofile</module>
  </modules>
</project>


text:
'use strict';
angular.module('Lunch.chats', ['Lunch.factory.storedUserData'])
.config(function($stateProvider){
  $stateProvider
  .state('app.chats', {
    url: '/chats',
    views: {
      'menuContent' :{
        templateUrl: 'templates/chats.html',
        controller: 'ChatsCtrl'
      }
    }
  });
})
.controller('ChatsCtrl', function($scope, $state, storedUserData, storedChat) {
  $scope.seeProfile = function() {
    $state.go('app.matched');
  };

  $scope.inputtext = '';

  // Get past messages
  $scope.chatMessages = storedChat.getChats();

  // Post new messages
  $scope.postMessage = function(text) {
    var payload = {
      message: text,
      timestamp: new Date().toISOString(),
      self: true
    };

    storedChat.postChat(payload);

    $scope.inputtext = '';
  };

  // Listen for incoming messages
  window.storedChat = storedChat;
  storedChat.getChat().then(null, null, function(post) {
    $scope.chatMessages.push(post);
  });

});


text:
package com.ibm.wala.core.tests.basic;

import java.util.Iterator;
import java.util.Map;

import org.junit.Assert;
import org.junit.Test;

import com.ibm.wala.util.collections.HashMapFactory;
import com.ibm.wala.util.graph.Graph;
import com.ibm.wala.util.graph.NumberedGraph;
import com.ibm.wala.util.graph.impl.DelegatingNumberedGraph;
import com.ibm.wala.util.graph.impl.NodeWithNumberedEdges;
import com.ibm.wala.util.graph.traverse.WelshPowell;
import com.ibm.wala.util.graph.traverse.WelshPowell.ColoredVertices;

public class WelshPowellTest {

  public static <T> void assertColoring(Graph<T> G, Map<T,Integer> colors, boolean fullColor) {
    for(T n : G) {
      for(Iterator<T> ss = G.getSuccNodes(n); ss.hasNext(); ) {
        T succ = ss.next();
        if (!fullColor &&  (!colors.containsKey(n) || !colors.containsKey(succ)) ) {
          continue;
        }
        Assert.assertTrue(n + " and succ: " + succ + " have same color: " + colors.get(n).intValue(), colors.get(n).intValue() != colors.get(succ).intValue());
      }
      for(Iterator<T> ps = G.getPredNodes(n); ps.hasNext(); ) {
        T pred = ps.next();
        if (!fullColor && (!colors.containsKey(n) || !colors.containsKey(pred)) ) {
          continue;
        }
        Assert.assertTrue(n + " and pred: " + pred + " have same color:" + colors.get(n).intValue(), colors.get(n).intValue() != colors.get(pred).intValue());
      }
    }
  }

  private class TypedNode<T> extends NodeWithNumberedEdges {
    private final T data;

    private TypedNode(T data) {
      this.data = data;
    }

    @Override
    public String toString() {
      return data.toString();
    }
  }

  private <T> NumberedGraph<TypedNode<T>> buildGraph(T[][] data) {
    DelegatingNumberedGraph<TypedNode<T>> G = new DelegatingNumberedGraph<TypedNode<T>>();
    Map<T,TypedNode<T>> nodes = HashMapFactory.make();
    for(int i = 0; i < data.length; i++) {
      TypedNode<T> n = new TypedNode<T>(data[i][0]);
      nodes.put(data[i][0], n);
      G.addNode(n);
    }
    for(int i = 0; i < data.length; i++) {
      for(int j = 1; j < data[i].length; j++) {
        G.addEdge(nodes.get(data[i][0]), nodes.get(data[i][j]));
      }
    }

    return G;
  }

    @Test
    public void testOne() {
      NumberedGraph<TypedNode<Integer>> G =
        buildGraph(new Integer[][]{
            new Integer[]{1, 6, 7, 8},
            new Integer[]{2, 5, 7, 8},
            new Integer[]{3, 5, 6, 8},
            new Integer[]{4, 7, 6, 5},
            new Integer[]{5, 2, 4, 3},
            new Integer[]{6, 3, 1, 4},
            new Integer[]{7, 1, 2, 4},
            new Integer[]{8, 1, 2, 3}});
      ColoredVertices<TypedNode<Integer>> colors = new WelshPowell<TypedNode<Integer>>().color(G);
      System.err.println(colors.getColors());
      assertColoring(G, colors.getColors(), true);
      Assert.assertTrue(colors.getNumColors() <= 4);
    }

    @Test
    public void testTwo() {
      NumberedGraph<TypedNode<String>> G =
        buildGraph(new String[][] {
           new String[]{"poly1", "poly2", "star1", "poly5"},
           new String[]{"poly2", "poly1", "star2", "poly3"},
           new String[]{"poly3", "poly2", "star3", "poly4"},
           new String[]{"poly4", "poly3", "star4", "poly5"},
           new String[]{"poly5", "poly4", "star5", "poly1"},
           new String[]{"star1", "poly1", "star3", "star4"},
           new String[]{"star2", "poly2", "star4", "star5"},
           new String[]{"star3", "poly3", "star1", "star5"},
           new String[]{"star4", "poly4", "star1", "star2"},
           new String[]{"star5", "poly5", "star2", "star3"}});
      ColoredVertices<TypedNode<String>> colors = new WelshPowell<TypedNode<String>>().color(G);
      System.err.println(colors.getColors());
      assertColoring(G, colors.getColors(), true);
      Assert.assertTrue(colors.getNumColors() == 3);
    }
 }


text:
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace WebChat {

    public partial class ChildChat {

        /// <summary>
        /// tbMessages control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Panel tbMessages;

        /// <summary>
        /// btnFinish control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Button btnFinish;

        /// <summary>
        /// lblActiveStatus control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Label lblActiveStatus;

        /// <summary>
        /// Panel1 control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Panel Panel1;

        /// <summary>
        /// tbNewMessage control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.TextBox tbNewMessage;

        /// <summary>
        /// btnSend control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Button btnSend;

        /// <summary>
        /// lblBeginTxt control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Label lblBeginTxt;

        /// <summary>
        /// lblBegin control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Label lblBegin;

        /// <summary>
        /// lblLastMessageTxt control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Label lblLastMessageTxt;

        /// <summary>
        /// lblLastMessage control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Label lblLastMessage;
    }
}


text:
<?php

declare(strict_types=1);

namespace Orchid\Tests\Unit\Screen\Fields;

use Orchid\Screen\Actions\Link;
use Orchid\Tests\Unit\Screen\TestFieldsUnitCase;

/**
 * Class LinkTest.
 */
class LinkTest extends TestFieldsUnitCase
{
    public function testLinkInstance(): void
    {
        $link = Link::make('About');
        $view = self::renderField($link);

        $this->assertStringContainsString('About', $view);
        $this->assertStringContainsString('href="#!"', $view);
        $this->assertStringContainsString('data-turbo="true"', $view);
    }

    public function testLinkTarget(): void
    {
        $link = Link::make('About')
            ->target('_blank');

        $view = self::renderField($link);

        $this->assertStringContainsString('target="_blank"', $view);
    }

    public function testLinkDownload(): void
    {
        $link = Link::make('About')
            ->download();

        $view = self::renderField($link);

        $this->assertStringContainsString('download', $view);
    }

    public function testLinkTitle(): void
    {
        $link = Link::make('About')
            ->title('Please click to download the file.')
            ->download();

        $view = self::renderField($link);

        $this->assertStringContainsString('Please click to download the file.', $view);
    }

    public function testLinkHref(): void
    {
        $link = Link::make('About')
            ->href('https://google.com');

        $view = self::renderField($link);

        $this->assertStringContainsString('href="https://google.com"', $view);
    }

    public function testLinkDisableTurbolinks(): void
    {
        $link = Link::make('About')
            ->href('https://google.com')
            ->rawClick();

        $view = self::renderField($link);

        $this->assertStringContainsString('data-turbo="false"', $view);
    }
}


text:
package org.apache.syncope.core.persistence.jpa.entity.policy;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.apache.syncope.core.persistence.api.entity.policy.PushCorrelationRuleEntity;
import org.apache.syncope.core.persistence.api.entity.policy.PushPolicy;

@Entity
@Table(name = JPAPushPolicy.TABLE)
public class JPAPushPolicy extends AbstractProvisioningPolicy implements PushPolicy {

    private static final long serialVersionUID = -5875589156893921113L;

    public static final String TABLE = "PushPolicy";

    @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER, mappedBy = "pushPolicy")
    private List<JPAPushCorrelationRuleEntity> correlationRules = new ArrayList<>();

    @Override
    public boolean add(final PushCorrelationRuleEntity filter) {
        checkType(filter, JPAPushCorrelationRuleEntity.class);
        return this.correlationRules.add((JPAPushCorrelationRuleEntity) filter);
    }

    @Override
    public Optional<? extends PushCorrelationRuleEntity> getCorrelationRule(final String anyType) {
        return correlationRules.stream().
                filter(rule -> anyType != null && anyType.equals(rule.getAnyType().getKey())).findFirst();
    }

    @Override
    public List<? extends PushCorrelationRuleEntity> getCorrelationRules() {
        return correlationRules;
    }
}


text:
using System;
using System.Linq;
using System.Web.Mvc;
using Teleritter.Models;
using Microsoft.AspNet.Identity;
using System.Collections.Generic;
using System.Net;

namespace Teleritter.Controllers
{
    [ValidateInput(false)]
    public class HomeController : BaseController
    {
        private IQueryable<Telereet> AllTelereets()
        {
            return this.data.Telreets.All()
                .OrderByDescending(t => t.PostedOn);

        }

        public ActionResult Index()
        {
            var telereets = this.AllTelereets().Take(6).Select(TelereetViewModel.FromTelereet);
            ViewBag.Message = "Last 6 telereets";
            return View(telereets);
        }

        public ActionResult Search(string text)
        {
            if (text == null)
            {
                return Redirect("Index");
            }

            CacheSearch(text);

            ViewBag.Message = this.HttpContext.Cache[text + "message"].ToString();
            return View("Index", this.HttpContext.Cache[text]);
        }

        private void CacheSearch(string text)
        {
            if (this.HttpContext.Cache[text] == null)
            {
                var found = this.AllTelereets();
                found = found
                             .Where(t => t.Tags.Any(tag => tag.Name.Contains(text)));

                var viewModel = found.Select(TelereetViewModel.FromTelereet);

                var message = "Show by tag.|" + text + "| Cached at " + DateTime.Now;

                this.HttpContext.Cache.Add(text, viewModel, null, DateTime.Now.AddMinutes(15), TimeSpan.Zero, System.Web.Caching.CacheItemPriority.Normal, null);
                this.HttpContext.Cache.Add(text + "message", message, null, DateTime.Now.AddMinutes(15), TimeSpan.Zero, System.Web.Caching.CacheItemPriority.Normal, null);
            }
        }

        public ActionResult PostNewTelereet(NewTelereetViewModel model)
        {
            try
            {
                var userId = User.Identity.GetUserId();

                if (string.IsNullOrEmpty(userId))
	            {
		            return new HttpStatusCodeResult(HttpStatusCode.BadRequest, string.Join(", ", "User must be logged for new Telereet"));
	            }
                if (ModelState.IsValid)
                {
                    var newPost = CreateTelereet(userId, model);

                    this.data.Telreets.Add(newPost);
                    this.data.SaveChanges();

                    var newTelereet = CreateTelereetViewModel(newPost);

                    return PartialView("_TelereetPartial", newTelereet);
                }
                else
                {
                    var errorsMessages = ModelState.Values.Where(v => v.Errors.Count > 0)
                        .SelectMany(v => v.Errors.Select(e => e.ErrorMessage));

                    return new HttpStatusCodeResult(HttpStatusCode.BadRequest, string.Join(", ", errorsMessages));
                }
            }
            catch
            {
                return new HttpStatusCodeResult(HttpStatusCode.InternalServerError, "Database connection lost");
            }
        }

        public ActionResult UserHomePage()
        {
            var userId = User.Identity.GetUserId();
            if (userId == null)
	        {
		        throw new Exception("You are not allowed in here.");
	        }
            var usersTlereets = this.AllTelereets().Where(t => t.Author.Id == userId).Select(TelereetViewModel.FromTelereet);

            return View(usersTlereets);
        }

        public ActionResult ByTag(int? tagId)
        {
            if (tagId == null)
            {
                throw new Exception("Search by tag must contai tag to search by!");
            }

            var tagName = this.data.Tags.All().First(tag => tag.Id == tagId).Name;

            CacheSearch(tagName);

            ViewBag.Message = this.HttpContext.Cache[tagName + "message"];

            return View("Index", this.HttpContext.Cache[tagName]);
        }

        private TelereetViewModel CreateTelereetViewModel(Telereet newPost)
        {
            var newTelereet = new TelereetViewModel
            {
                Author = newPost.Author.UserName,
                Text = newPost.Text,
                PostedOn = newPost.PostedOn,
                Tags = newPost.Tags.AsQueryable().Select(TagViewModel.FromTag),
            };
            return newTelereet;
        }

        private Telereet CreateTelereet(string userId, NewTelereetViewModel model)
        {
            var newPost = new Telereet
            {
                PostedOn = DateTime.Now,
                Author = this.data.Users.All().FirstOrDefault(u => u.Id == userId),
                Text = model.Text,
                Tags = GetTags(model.Tags).ToList()
            };
            return newPost;
        }

        private IEnumerable<Tag> GetTags(string tagsString)
        {
            if (tagsString == null)
            {
                return new List<Tag>();
            }

            var tags = tagsString
                .Trim()
                .Split(new string[] { ", " }, StringSplitOptions.RemoveEmptyEntries)
                .Select(s => new Tag{Name = s});

            var tagsInBase = new List<Tag>();

            foreach (var tag in tags)
            {
                var tagInBase = this.data.Tags.All()
                    .FirstOrDefault(t => t.Name == tag.Name);

                if (tagInBase == null)
                {
                    tagInBase = tag;
                }

                tagsInBase.Add(tagInBase);
            }

            return tagsInBase;
        }
    }
}


text:
<?php

namespace WuCore\FrontBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class WuCoreFrontBundle extends Bundle
{
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>Search — pymunk 4.0.0 documentation</title>

    <link rel="stylesheet" href="_static/pymunk.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />

    <link rel="shortcut icon" href="_static/pymunk_favicon.ico"/>
    <link rel="top" title="pymunk 4.0.0 documentation" href="index.html" />

Navigation

          index

          modules |

pymunk 4.0.0 documentation »

Search

    Please activate JavaScript to enable the search
    functionality.

    From here you can search these documents. Enter your search
    words into the box below and click "search". Note that the search
    function will automatically search for all of the words. Pages
    containing fewer words won't appear in the result list.

  <form action="" method="get">
    <input type="text" name="q" value="" />
    <input type="submit" value="search" />

  </form>

Table Of Contents

Readme

News

Installation

API Reference

Examples

Tutorials

Advanced

Issue Tracker

Source Repository

Downloads

License

Navigation

          index

          modules |

pymunk 4.0.0 documentation »

        © Copyright 2013, Victor Blomqvist.
      Created using Sphinx 1.2b1.


text:
import {Component,ViewChild,ElementRef,ComponentFactoryResolver,ViewContainerRef,forwardRef,ContentChildren,QueryList} from '@angular/core';
import { base } from './base';
// Ext Class - Ext.Img
export class imagecomponentMetaData {
	public static XTYPE: string = 'imagecomponent';
	public static INPUTNAMES: string[] = [
		'activeCounter',
		'alignOnScroll',
		'alignTarget',
		'alt',
		'alwaysOnTop',
		'anchor',
		'animateShadow',
		'ariaAttributes',
		'ariaDescribedBy',
		'ariaLabel',
		'ariaLabelledBy',
		'autoEl',
		'autoRender',
		'autoScroll',
		'autoShow',
		'baseCls',
		'bind',
		'border',
		'childEls',
		'cls',
		'columnWidth',
		'componentCls',
		'componentLayout',
		'constrain',
		'constraintInsets',
		'constrainTo',
		'contentEl',
		'controller',
		'data',
		'defaultAlign',
		'defaultListenerScope',
		'disabled',
		'disabledCls',
		'dock',
		'draggable',
		'fixed',
		'flex',
		'floating',
		'focusCls',
		'focusOnToFront',
		'formBind',
		'frame',
		'glyph',
		'glyph',
		'height',
		'hidden',
		'hideMode',
		'html',
		'id',
		'imgCls',
		'itemId',
		'keyMap',
		'keyMapEnabled',
		'keyMapTarget',
		'liquidLayout',
		'listeners',
		'liveDrag',
		'loader',
		'margin',
		'maskDefaults',
		'maskElement',
		'maxHeight',
		'maxWidth',
		'minHeight',
		'minWidth',
		'modal',
		'modelValidation',
		'nameable',
		'overCls',
		'overflowX',
		'overflowY',
		'padding',
		'plugins',
		'publishes',
		'reference',
		'region',
		'renderConfig',
		'renderData',
		'renderSelectors',
		'renderTo',
		'renderTpl',
		'resizable',
		'resizeHandles',
		'saveDelay',
		'scrollable',
		'session',
		'shadow',
		'shadowOffset',
		'shareableName',
		'shim',
		'shrinkWrap',
		'src',
		'stateEvents',
		'stateful',
		'stateId',
		'style',
		'tabIndex',
		'title',
		'toFrontOnShow',
		'touchAction',
		'tpl',
		'tplWriteMode',
		'twoWayBindable',
		'ui',
		'uiCls',
		'userCls',
		'viewModel',
		'weight',
		'width',
		'xtype',
		'flex',
		'platformConfig',
		'responsiveConfig',
		'fitToParent',
		'config'
];
	public static OUTPUTS: any[] = [
		{name:'activate',parameters:'image'},
		{name:'added',parameters:'image,container,pos'},
		{name:'afterlayoutanimation',parameters:'image'},
		{name:'afterrender',parameters:'image'},
		{name:'beforeactivate',parameters:'image'},
		{name:'beforedeactivate',parameters:'image'},
		{name:'beforedestroy',parameters:'image'},
		{name:'beforehide',parameters:'image'},
		{name:'beforerender',parameters:'image'},
		{name:'beforeshow',parameters:'image'},
		{name:'beforestaterestore',parameters:'image,state'},
		{name:'beforestatesave',parameters:'image,state'},
		{name:'blur',parameters:'image,event'},
		{name:'boxready',parameters:'image,width,height'},
		{name:'deactivate',parameters:'image'},
		{name:'destroy',parameters:'image'},
		{name:'disable',parameters:'image'},
		{name:'enable',parameters:'image'},
		{name:'focus',parameters:'image,event'},
		{name:'focusenter',parameters:'image,event'},
		{name:'focusleave',parameters:'image,event'},
		{name:'hide',parameters:'image'},
		{name:'move',parameters:'image,x,y'},
		{name:'removed',parameters:'image,ownerCt'},
		{name:'render',parameters:'image'},
		{name:'resize',parameters:'image,width,height,oldWidth,oldHeight'},
		{name:'show',parameters:'image'},
		{name:'staterestore',parameters:'image,state'},
		{name:'statesave',parameters:'image,state'},
		{name:'ready',parameters:''}
];
	public static OUTPUTNAMES: string[] = [
		'activate',
		'added',
		'afterlayoutanimation',
		'afterrender',
		'beforeactivate',
		'beforedeactivate',
		'beforedestroy',
		'beforehide',
		'beforerender',
		'beforeshow',
		'beforestaterestore',
		'beforestatesave',
		'blur',
		'boxready',
		'deactivate',
		'destroy',
		'disable',
		'enable',
		'focus',
		'focusenter',
		'focusleave',
		'hide',
		'move',
		'removed',
		'render',
		'resize',
		'show',
		'staterestore',
		'statesave',
		'ready'
];
}
@Component({
  selector: imagecomponentMetaData.XTYPE,
	inputs: imagecomponentMetaData.INPUTNAMES,
	outputs: imagecomponentMetaData.OUTPUTNAMES,
	providers: [{provide: base, useExisting: forwardRef(() => imagecomponent)}],
	template: '<ng-template #dynamic></ng-template>'
})
export class imagecomponent extends base {
	constructor(eRef:ElementRef,resolver:ComponentFactoryResolver,vcRef:ViewContainerRef) {
		super(eRef,resolver,vcRef,imagecomponentMetaData);
	}
	//@ContentChildren(base,{read:ViewContainerRef}) extbaseRef:QueryList<ViewContainerRef>;
	@ContentChildren(base,{read: base}) extbaseRef: QueryList<base>;
	@ViewChild('dynamic',{read:ViewContainerRef}) dynamicRef:ViewContainerRef;
	ngAfterContentInit() {this.AfterContentInit(this.extbaseRef);}
	ngOnInit() {this.OnInit(this.dynamicRef,imagecomponentMetaData);}
}


text:
namespace cc {

StickyPositionConstraint::StickyPositionConstraint()
    : is_anchored_left(false),
      is_anchored_right(false),
      is_anchored_top(false),
      is_anchored_bottom(false),
      left_offset(0.f),
      right_offset(0.f),
      top_offset(0.f),
      bottom_offset(0.f) {}

StickyPositionConstraint::StickyPositionConstraint(
    const StickyPositionConstraint& other) = default;

bool StickyPositionConstraint::operator==(
    const StickyPositionConstraint& other) const {
  return is_anchored_left == other.is_anchored_left &&
         is_anchored_right == other.is_anchored_right &&
         is_anchored_top == other.is_anchored_top &&
         is_anchored_bottom == other.is_anchored_bottom &&
         left_offset == other.left_offset &&
         right_offset == other.right_offset && top_offset == other.top_offset &&
         bottom_offset == other.bottom_offset &&
         constraint_box_rect == other.constraint_box_rect &&
         scroll_container_relative_sticky_box_rect ==
             other.scroll_container_relative_sticky_box_rect &&
         scroll_container_relative_containing_block_rect ==
             other.scroll_container_relative_containing_block_rect &&
         nearest_element_shifting_sticky_box ==
             other.nearest_element_shifting_sticky_box &&
         nearest_element_shifting_containing_block ==
             other.nearest_element_shifting_containing_block;
}

bool StickyPositionConstraint::operator!=(
    const StickyPositionConstraint& other) const {
  return !(*this == other);
}

}  // namespace cc


text:
class CluesController < ApplicationController
  include UsersHelper
  include SessionsHelper
  def create
    redirect_to root_path unless valid_user_check
  end

  def new
    redirect_to root_path unless valid_user_check
  end

  def edit
    redirect_to root_path unless valid_user_check
  end

  def show
    redirect_to root_path unless valid_user_check
  end

  def update
    redirect_to root_path unless valid_user_check
  end

  def destroy
    redirect_to root_path unless valid_user_check
  end
end


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>AJAX-паук</title>

AJAX-паук

The AJAX Spider add-on integrates in ZAP a crawler of AJAX rich sites called
		Crawljax. You can use it to identify the pages of the targeted site. You can combine it
		with the (normal) spider for better results.

		The spider is configured using the Options AJAX Spider screen.

		This add-on supports the Automation Framework.

Accessed via

			AJAX Spider tab

			History tab
			'Attack/AJAX Spider...' right click menu item

			Sites tab
			'Attack/AJAX Spider...' right click menu item

See also

			Options AJAX Spider screen
			for an overview of the AJAX Spider Options

			AJAX Spider tab
			for an overview of the AJAX Spider Tab

			AJAX Spider dialog
			for an overview of the AJAX Spider Dialog


text:
<!DOCTYPE html>

	<meta charset="utf-8">

	<title>BITTelemetryContext Class Reference</title>

	<link rel="stylesheet" href="../css/style.css">
	<meta name="viewport" content="initial-scale=1, maximum-scale=1.4">
	<meta name="generator" content="appledoc 2.2.1 (build 1334)">

				HockeySDK-iOS 4.0.1

				Bit Stadium GmbH

Index

Hierarchy

							On This Page

							<select id="jump-to">
	<option value="top">Jump To…</option>

	<option value="overview">Overview</option>

	<option value="tasks">Tasks</option>

	<optgroup label="Properties">

		<option value="//api/name/appIdentifier">appIdentifier</option>

		<option value="//api/name/application">application</option>

		<option value="//api/name/device">device</option>

		<option value="//api/name/internal">internal</option>

		<option value="//api/name/operationsQueue">operationsQueue</option>

		<option value="//api/name/persistence">persistence</option>

		<option value="//api/name/session">session</option>

		<option value="//api/name/tags">tags</option>

		<option value="//api/name/user">user</option>

	</optgroup>

	<optgroup label="Instance Methods">

		<option value="//api/name/contextDictionary">- contextDictionary</option>

		<option value="//api/name/initWithAppIdentifier:persistence:">- initWithAppIdentifier:persistence:</option>

	</optgroup>

</select>

BITTelemetryContext Class Reference

	Inherits from
	NSObject

	Declared in
	BITTelemetryContext.h

Overview

Context object which contains information about the device, user, session etc.

Initialisation

  persistence

The persistence instance used to save/load metadata.

@property (nonatomic, strong) BITPersistence *persistence

Declared In

BITTelemetryContext.h

  appIdentifier

The instrumentation key of the app.

@property (nonatomic, copy) NSString *appIdentifier

Declared In

BITTelemetryContext.h

  operationsQueue

A queue which makes array operations thread safe.

@property (nonatomic, strong) dispatch_queue_t operationsQueue

Declared In

BITTelemetryContext.h

  application

The application context.

@property (nonatomic, strong, readonly) BITApplication *application

Declared In

BITTelemetryContext.h

  device

The device context.

@property (nonatomic, strong, readonly) BITDevice *device

Declared In

BITTelemetryContext.h

  session

The session context.

@property (nonatomic, strong, readonly) BITSession *session

Declared In

BITTelemetryContext.h

  user

The user context.

@property (nonatomic, strong, readonly) BITUser *user

Declared In

BITTelemetryContext.h

  internal

The internal context.

@property (nonatomic, strong, readonly) BITInternal *internal

Declared In

BITTelemetryContext.h

– initWithAppIdentifier:persistence:

Initializes a telemetry context.

- (instancetype)initWithAppIdentifier:(NSString *)appIdentifier persistence:(BITPersistence *)persistence

Parameters

						appIdentifier

the appIdentifier of the app

						persistence

the persistence used to save and load metadata

Return Value

the telemetry context

Declared In

BITTelemetryContext.h

Helper

  tags

A dictionary which holds static tag fields for the purpose of caching

@property (nonatomic, strong) BITOrderedDictionary *tags

Declared In

BITTelemetryContext.h

– contextDictionary

Returns context objects as dictionary.

- (BITOrderedDictionary *)contextDictionary

Return Value

a dictionary containing all context fields

Declared In

BITTelemetryContext.h

Copyright © 2016 Bit Stadium GmbH. All rights reserved. Updated: 2016-05-12

Generated by appledoc 2.2.1 (build 1334).


text:
package org.apache.hadoop.yarn.server.resourcemanager.webapp;

import static org.apache.hadoop.yarn.util.StringHelper.join;
import static org.apache.hadoop.yarn.webapp.YarnWebParams.QUEUE_NAME;

import org.apache.hadoop.yarn.server.resourcemanager.ResourceManager;
import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMAppState;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.ResourceScheduler;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity.CapacityScheduler;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair.FairScheduler;
import org.apache.hadoop.yarn.util.StringHelper;
import org.apache.hadoop.yarn.webapp.Controller;
import org.apache.hadoop.yarn.webapp.WebAppException;
import org.apache.hadoop.yarn.webapp.YarnWebParams;

import com.google.inject.Inject;

// Do NOT rename/refactor this to RMView as it will wreak havoc
// on Mac OS HFS as its case-insensitive!
public class RmController extends Controller {

  @Inject
  RmController(RequestContext ctx) {
    super(ctx);
  }

  @Override public void index() {
    setTitle("Applications");
  }

  public void about() {
    setTitle("About the Cluster");
    render(AboutPage.class);
  }

  public void app() {
    render(AppPage.class);
  }

  public void nodes() {
    render(NodesPage.class);
  }

  public void scheduler() {
    // limit applications to those in states relevant to scheduling
    set(YarnWebParams.APP_STATE, StringHelper.cjoin(
        RMAppState.NEW.toString(),
        RMAppState.NEW_SAVING.toString(),
        RMAppState.SUBMITTED.toString(),
        RMAppState.ACCEPTED.toString(),
        RMAppState.RUNNING.toString(),
        RMAppState.FINISHING.toString()));

    ResourceManager rm = getInstance(ResourceManager.class);
    ResourceScheduler rs = rm.getResourceScheduler();
    if (rs == null || rs instanceof CapacityScheduler) {
      setTitle("Capacity Scheduler");
      render(CapacitySchedulerPage.class);
      return;
    }

    if (rs instanceof FairScheduler) {
      setTitle("Fair Scheduler");
      render(FairSchedulerPage.class);
      return;
    }

    setTitle("Default Scheduler");
    render(DefaultSchedulerPage.class);
  }

  public void queue() {
    setTitle(join("Queue ", get(QUEUE_NAME, "unknown")));
  }

  public void submit() {
    setTitle("Application Submission Not Allowed");
  }
}


text:
<?php

namespace DvsaCommon\Dto\Site;

use DvsaCommon\Dto\AbstractDataTransferObject;
use DvsaCommon\Dto\CommonTrait\CommonIdentityDtoTrait;

/**
 * Class FacilityDto
 *
 * @package DvsaCommon\Dto\Site
 */
class FacilityDto extends AbstractDataTransferObject
{
    use CommonIdentityDtoTrait;

    /** @var  SiteDto */
    private $site;
    /** @var  string */
    private $name;
    /** @var  FacilityTypeDto */
    private $type;

    /**
     * @return SiteDto
     */
    public function getSite()
    {
        return $this->site;
    }

    /**
     * @param SiteDto $site
     *
     * @return $this
     */
    public function setSite($site)
    {
        $this->site = $site;
        return $this;
    }

    /**
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * @return $this
     */
    public function setName($name)
    {
        $this->name = $name;
        return $this;
    }

    /**
     * @return FacilityTypeDto
     */
    public function getType()
    {
        return $this->type;
    }

    /**
     * @param FacilityTypeDto $type
     *
     * @return $this
     */
    public function setType($type)
    {
        $this->type = $type;
        return $this;
    }
}


text:
      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
        Toggle navigation

      </button>
      NoSpoil

        {% if 'last_viewed' in request.session %}

              Last Viewed

              {% for playoff in request.session.last_viewed %}

{{ playoff.title }}

              {% endfor %}

        {% endif %}

All Playoffs

Add Playoff

        {% if request.user.is_authenticated %}

My Profile

Logout

        {% else %}

Login

Register

        {% endif %}


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Tephrosia nematophylla F.Muell.

### Remarks
null


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:beans="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:security="http://www.springframework.org/schema/security"
	xmlns:util="http://www.springframework.org/schema/util" xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:jee="http://www.springframework.org/schema/jee" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
	xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd
		http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
		http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
		http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.2.xsd
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
		http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.1.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">

	<!-- DispatcherServlet Context: defines this servlet's request-processing
		infrastructure -->

	<!-- Enables the Spring MVC @Controller programming model -->
	<context:annotation-config />

	<mvc:annotation-driven />

	<!-- Handles HTTP GET requests for /resources/** by efficiently serving
		up static resources in the ${webappRoot}/resources directory -->
	<mvc:resources mapping="/resources/**" location="/resources/" />

	<!-- Resolves views selected for rendering by @Controllers to .jsp resources
		in the /WEB-INF/views directory -->
	<beans:bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<beans:property name="prefix" value="/WEB-INF/views/" />
		<beans:property name="suffix" value=".jsp" />
	</beans:bean>

	<!-- MVC Internationalization -->
	<!-- <beans:bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver">
		<beans:property name="defaultLocale" value="en" /> </beans:bean> <beans:bean
		id="localeChangeInterceptor" class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
		<beans:property name="paramName" value="language" /> </beans:bean> <beans:bean
		class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping">
		<beans:property name="interceptors"> <beans:list> <beans:ref bean="localeChangeInterceptor"
		/> </beans:list> </beans:property> </beans:bean> -->

	<!-- Registers the messages.properties -->
	<beans:bean id="messageSource"
		class="org.springframework.context.support.ResourceBundleMessageSource">
		<beans:property name="basename" value="messages" />
	</beans:bean>
	<!-- <mvc:interceptors> <beans:bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"
		> <beans:property name="paramName" value="language"></beans:property> </beans:bean>
		</mvc:interceptors> -->
	<!-- @Component annotations for bean definitions -->
	<context:component-scan base-package="edu.university.roombooking" />

	<context:property-placeholder location="classpath:mail.properties" />

	<tx:annotation-driven proxy-target-class="true"></tx:annotation-driven>

	<beans:bean id="jpaVendorAdapter"
		class="org.springframework.orm.jpa.vendor.EclipseLinkJpaVendorAdapter">
		<beans:property name="database" value="POSTGRESQL"></beans:property>
		<beans:property name="databasePlatform"
			value="org.eclipse.persistence.platform.database.PostgreSQLPlatform"></beans:property>
	</beans:bean>

	<beans:bean id="entityManagerFactory"
		class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
		<beans:property name="dataSource" ref="dataSource" />
		<beans:property name="persistenceUnitName" value="Main" />
		<beans:property name="jpaDialect" ref="jpaDialect" />
		<beans:property name="jpaVendorAdapter" ref="jpaVendorAdapter" />
		<!-- <beans:property name="loadTimeWeaver"> <beans:bean class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver"
			/> </beans:property> -->
	</beans:bean>

	<beans:bean id="dataSource"
		class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<beans:property name="username" value="postgres" />
		<beans:property name="password" value="ppp" />
		<beans:property name="driverClassName" value="org.postgresql.Driver" />
		<beans:property name="url"
			value="jdbc:postgresql://localhost:5432/test-rb?encoding=utf8" />
	</beans:bean>

	<beans:bean class="org.springframework.jdbc.core.JdbcTemplate">
		<beans:property name="dataSource" ref="dataSource"></beans:property>
	</beans:bean>

	<!-- <jdbc:initialize-database data-source="dataSource"> <jdbc:script location="classpath:statements.sql"/>
		</jdbc:initialize-database> -->
	<beans:bean
		class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />

	<beans:bean
		class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor">
		<beans:property name="proxyTargetClass" value="true" />
	</beans:bean>

	<!-- <jee:jndi-lookup jndi-name="jdbc/PostgreSQL" id="dataSource" resource-ref="true"
		/> -->
	<beans:bean id="jpaDialect"
		class="org.springframework.orm.jpa.vendor.EclipseLinkJpaDialect" />

	<beans:bean class="org.springframework.orm.jpa.JpaTransactionManager"
		id="transactionManager">
		<!--<beans:property name="transactionManagerName" value="java:jboss/TransactionManager"></beans:property> -->
		<!-- <beans:property name="allowCustomIsolationLevels" value="true"></beans:property> -->
		<beans:property name="entityManagerFactory" ref="entityManagerFactory"></beans:property>
	</beans:bean>

	<security:global-method-security
		pre-post-annotations="enabled" proxy-target-class="true"></security:global-method-security>

	<security:http pattern="/resources" security="none" />

	<security:http auto-config="true" use-expressions="true">

		<!-- <security:csrf /> -->

		<security:remember-me key="45nx84nbd872hfd82hsd823hf"
			token-validity-seconds="864000" />

		<security:form-login login-page="/login"
			authentication-failure-url="/login?failure" default-target-url="/" />

		<security:access-denied-handler
			error-page="/denied" />

		<security:logout invalidate-session="true"
			logout-success-url="/login?logged-out" logout-url="/logout" />
	</security:http>

	<security:authentication-manager>
		<security:authentication-provider
			user-service-ref="groupManagement">
			<security:password-encoder ref="passwordEncoder" />
		</security:authentication-provider>
	</security:authentication-manager>

	<!-- Use a Md5 encoder since the user's passwords are stored as Md5 in the
		database -->
	<beans:bean
		class="org.springframework.security.authentication.encoding.Md5PasswordEncoder"
		id="passwordEncoder"></beans:bean>

</beans:beans>