text:
import { runAppend, runDestroy } from 'ember-runtime/tests/utils';
import ComponentLookup from 'ember-views/component_lookup';
import Component from 'ember-views/components/component';
import EventDispatcher from 'ember-views/system/event_dispatcher';
import compile from 'ember-template-compiler/system/compile';
import run from 'ember-metal/run_loop';
import isEmpty from 'ember-metal/is_empty';
import { OWNER } from 'container/owner';
import buildOwner from 'container/tests/test-helpers/build-owner';

let component, owner;

import isEnabled from 'ember-metal/features';
if (!isEnabled('ember-glimmer')) {
  // jscs:disable

QUnit.module('ember-htmlbars: closure component helper', {
  setup() {
    owner = buildOwner();

    owner.registerOptionsForType('template', { instantiate: false });
    owner.register('component-lookup:main', ComponentLookup);
  },

  teardown() {
    runDestroy(component);
    runDestroy(owner);
    owner = component = null;
  }
});

QUnit.test('renders with component helper', function() {
  let expectedText = 'Hodi';
  owner.register(
    'template:components/-looked-up',
    compile(expectedText)
  );

  let template = compile('{{component (component "-looked-up")}}');
  component = Component.extend({
    [OWNER]: owner,
    template
  }).create();

  runAppend(component);
  equal(component.$().text(), expectedText, '-looked-up component rendered');
});

QUnit.test('renders with component helper with invocation params, hash', function() {
  let LookedUp = Component.extend();
  LookedUp.reopenClass({
    positionalParams: ['name']
  });
  owner.register(
    'component:-looked-up',
    LookedUp
  );
  owner.register(
    'template:components/-looked-up',
    compile(`{{greeting}} {{name}}`)
  );

  let template = compile(
    `{{component (component "-looked-up") "Hodari" greeting="Hodi"}}`
  );
  component = Component.extend({
    [OWNER]: owner,
    template
  }).create();

  runAppend(component);
  equal(component.$().text(), 'Hodi Hodari', '-looked-up component rendered');
});

QUnit.test('renders with component helper with curried params, hash', function() {
  let LookedUp = Component.extend();
  LookedUp.reopenClass({
    positionalParams: ['name']
  });
  owner.register(
    'component:-looked-up',
    LookedUp
  );
  owner.register(
    'template:components/-looked-up',
    compile(`{{greeting}} {{name}}`)
  );

  let template = compile(
    `{{component (component "-looked-up" "Hodari" greeting="Hodi") greeting="Hola"}}`
  );
  component = Component.extend({
    [OWNER]: owner,
    template
  }).create();

  runAppend(component);
  equal(component.$().text(), 'Hola Hodari', '-looked-up component rendered');
});

QUnit.test('updates when component path is bound', function() {
  let Mandarin = Component.extend();
  owner.register(
    'component:-mandarin',
    Mandarin
  );
  owner.register(
    'template:components/-mandarin',
    compile(`ni hao`)
  );
  owner.register(
    'template:components/-hindi',
    compile(`Namaste`)
  );

  let template = compile('{{component (component lookupComponent)}}');
  component = Component.extend({
    [OWNER]: owner,
    template,
    lookupComponent: '-mandarin'
  }).create();

  runAppend(component);

  equal(component.$().text(), `ni hao`,
        'mandarin lookupComponent renders greeting');
  run(() => {
    component.set('lookupComponent', '-hindi');
  });
  equal(component.$().text(), `Namaste`,
        'hindi lookupComponent renders greeting');
});

QUnit.test('updates when curried hash argument is bound', function() {
  owner.register(
    'template:components/-looked-up',
    compile(`{{greeting}}`)
  );

  let template = compile(
    `{{component (component "-looked-up" greeting=greeting)}}`
  );

  component = Component.extend({
    [OWNER]: owner,
    template
  }).create();

  runAppend(component);
  equal(component.$().text(), '', '-looked-up component rendered');
  run(() => {
    component.set('greeting', 'Hodi');
  });
  equal(component.$().text(), `Hodi`,
        'greeting is bound');
});

QUnit.test('updates when curried hash arguments is bound in block form', function() {
  owner.register(
    'template:components/-looked-up',
    compile(`{{greeting}}`)
  );

  let template = compile(
    `{{#with (hash comp=(component "-looked-up" greeting=greeting)) as |my|}}
      {{#my.comp}}{{/my.comp}}
    {{/with}}`
  );

  component = Component.extend({
    [OWNER]: owner,
    template
  }).create();

  runAppend(component);
  equal(component.$().text().trim(), '', '-looked-up component rendered');
  run(() => {
    component.set('greeting', 'Hodi');
  });
  equal(component.$().text().trim(), `Hodi`,
        'greeting is bound');
});

QUnit.test('nested components overwrites named positional parameters', function() {
  let LookedUp = Component.extend();
  LookedUp.reopenClass({
    positionalParams: ['name', 'age']
  });
  owner.register(
    'component:-looked-up',
    LookedUp
  );
  owner.register(
    'template:components/-looked-up',
    compile(`{{name}} {{age}}`)
  );

  let template = compile(
    `{{component
        (component (component "-looked-up" "Sergio" 28)
                   "Marvin" 21)
        "Hodari"}}`
  );

  component = Component.extend({
    [OWNER]: owner,
    template
  }).create();

  runAppend(component);
  equal(component.$().text(), 'Hodari 21', '-looked-up component rendered');
});

QUnit.test('nested components overwrites hash parameters', function() {
  owner.register(
    'template:components/-looked-up',
    compile(`{{greeting}} {{name}} {{age}}`)
  );

  let template = compile(
    `{{component (component (component "-looked-up"
                                greeting="Hola" name="Dolores" age=33)
                            greeting="Hej" name="Sigmundur")
                  greeting=greeting}}`
  );

  component = Component.extend({
    [OWNER]: owner,
    template,
    greeting: 'Hodi'
  }).create();

  runAppend(component);

  equal(component.$().text(), 'Hodi Sigmundur 33', '-looked-up component rendered');
});

QUnit.test('bound outer named parameters get updated in the right scope', function() {
  let InnerComponent = Component.extend();
  InnerComponent.reopenClass({
    positionalParams: ['comp']
  });
  owner.register(
    'component:-inner-component',
    InnerComponent
  );
  owner.register(
    'template:components/-inner-component',
    compile(`{{component comp "Inner"}}`)
  );

  let LookedUp = Component.extend();
  LookedUp.reopenClass({
    positionalParams: ['name', 'age']
  });
  owner.register(
    'component:-looked-up',
    LookedUp
  );
  owner.register(
    'template:components/-looked-up',
    compile(`{{name}} {{age}}`)
  );

  let template = compile(
    `{{component "-inner-component" (component "-looked-up" outerName outerAge)}}`
  );
  component = Component.extend({
    [OWNER]: owner,
    template,
    outerName: 'Outer',
    outerAge: 28
  }).create();

  runAppend(component);
  equal(component.$().text(), 'Inner 28', '-looked-up component rendered');
});

QUnit.test('bound outer hash parameters get updated in the right scope', function() {
  let InnerComponent = Component.extend();
  InnerComponent.reopenClass({
    positionalParams: ['comp']
  });
  owner.register(
    'component:-inner-component',
    InnerComponent
  );
  owner.register(
    'template:components/-inner-component',
    compile(`{{component comp name="Inner"}}`)
  );

  let LookedUp = Component.extend();
  LookedUp.reopenClass({
  });
  owner.register(
    'component:-looked-up',
    LookedUp
  );
  owner.register(
    'template:components/-looked-up',
    compile(`{{name}} {{age}}`)
  );

  let template = compile(
    `{{component "-inner-component" (component "-looked-up" name=outerName age=outerAge)}}`
  );
  component = Component.extend({
    [OWNER]: owner,
    template,
    outerName: 'Outer',
    outerAge: 28
  }).create();

  runAppend(component);
  equal(component.$().text(), 'Inner 28', '-looked-up component rendered');
});

QUnit.test('conflicting positional and hash parameters raise and assertion if in the same closure', function() {
  let LookedUp = Component.extend();
  LookedUp.reopenClass({
    positionalParams: ['name']
  });
  owner.register(
    'component:-looked-up',
    LookedUp
  );
  owner.register(
    'template:components/-looked-up',
    compile(`{{greeting}} {{name}}`)
  );

  let template = compile(
    `{{component (component "-looked-up" "Hodari" name="Sergio") "Hodari" greeting="Hodi"}}`
  );
  component = Component.extend({
    [OWNER]: owner,
    template
  }).create();

  expectAssertion(function() {
    runAppend(component);
  }, `You cannot specify both a positional param (at position 0) and the hash argument \`name\`.`);
});

QUnit.test('conflicting positional and hash parameters does not raise and assertion if rerendered', function() {
  let LookedUp = Component.extend();
  LookedUp.reopenClass({
    positionalParams: ['name']
  });
  owner.register(
    'component:-looked-up',
    LookedUp
  );
  owner.register(
    'template:components/-looked-up',
    compile(`{{greeting}} {{name}}`)
  );

  let template = compile(
    `{{component (component "-looked-up" name greeting="Hodi")}}`
  );

  component = Component.extend({
    [OWNER]: owner,
    template,
    name: 'Hodari'
  }).create();

  runAppend(component);
  equal(component.$().text(), 'Hodi Hodari', 'component is rendered');

  run(() => component.set('name', 'Sergio'));

  equal(component.$().text(), 'Hodi Sergio', 'component is rendered');
});

QUnit.test('conflicting positional and hash parameters does not raise and assertion if in the different closure', function() {
  let LookedUp = Component.extend();
  LookedUp.reopenClass({
    positionalParams: ['name']
  });
  owner.register(
    'component:-looked-up',
    LookedUp
  );
  owner.register(
    'template:components/-looked-up',
    compile(`{{greeting}} {{name}}`)
  );

  let template = compile(
    `{{component (component "-looked-up" "Hodari") name="Sergio" greeting="Hodi"}}`
  );
  component = Component.extend({
    [OWNER]: owner,
    template
  }).create();

  runAppend(component);
  equal(component.$().text(), 'Hodi Sergio', 'component is rendered');
});

QUnit.test('raises an assertion when component path is null', function() {
  let template = compile(`{{component (component lookupComponent)}}`);
  component = Component.extend({
    [OWNER]: owner,
    template
  }).create();

  expectAssertion(() => {
    runAppend(component);
  });
});

QUnit.test('raises an assertion when component path is not a component name', function() {
  let template = compile(`{{component (component "not-a-component")}}`);
  component = Component.extend({
    [OWNER]: owner,
    template
  }).create();

  expectAssertion(() => {
    runAppend(component);
  }, `The component helper cannot be used without a valid component name. You used "not-a-component" via (component "not-a-component")`);

  template = compile(`{{component (component compName)}}`);
  component = Component.extend({
    [OWNER]: owner,
    template,
    compName: 'not-a-component'
  }).create();

  expectAssertion(() => {
    runAppend(component);
  }, `The component helper cannot be used without a valid component name. You used "not-a-component" via (component compName)`);
});

QUnit.test('renders with dot path', function() {
  let expectedText = 'Hodi';
  owner.register(
    'template:components/-looked-up',
    compile(expectedText)
  );

  let template = compile('{{#with (hash lookedup=(component "-looked-up")) as |object|}}{{object.lookedup}}{{/with}}');
  component = Component.extend({
    [OWNER]: owner,
    template
  }).create();

  runAppend(component);
  equal(component.$().text(), expectedText, '-looked-up component rendered');
});

QUnit.test('renders with dot path and attr', function() {
  let expectedText = 'Hodi';
  owner.register(
    'template:components/-looked-up',
    compile('{{expectedText}}')
  );

  let template = compile('{{#with (hash lookedup=(component "-looked-up")) as |object|}}{{object.lookedup expectedText=expectedText}}{{/with}}');
  component = Component.extend({
    [OWNER]: owner,
    template
  }).create({
    expectedText
  });

  runAppend(component);
  equal(component.$().text(), expectedText, '-looked-up component rendered');
});

QUnit.test('renders with dot path curried over attr', function() {
  let expectedText = 'Hodi';
  owner.register(
    'template:components/-looked-up',
    compile('{{expectedText}}')
  );

  let template = compile('{{#with (hash lookedup=(component "-looked-up" expectedText=expectedText)) as |object|}}{{object.lookedup}}{{/with}}');
  component = Component.extend({
    [OWNER]: owner,
    template
  }).create({
    expectedText
  });

  runAppend(component);
  equal(component.$().text(), expectedText, '-looked-up component rendered');
});

QUnit.test('renders with dot path and with rest positional parameters', function() {
  let LookedUp = Component.extend();
  LookedUp.reopenClass({
    positionalParams: 'params'
  });
  owner.register(
    'component:-looked-up',
    LookedUp
  );
  let expectedText = 'Hodi';
  owner.register(
    'template:components/-looked-up',
    compile('{{params}}')
  );

  let template = compile('{{#with (hash lookedup=(component "-looked-up")) as |object|}}{{object.lookedup expectedText "Hola"}}{{/with}}');
  component = Component.extend({
    [OWNER]: owner,
    template
  }).create({
    expectedText
  });

  runAppend(component);
  equal(component.$().text(), `${expectedText},Hola`, '-looked-up component rendered with rest params');
});

QUnit.test('renders with dot path and rest parameter does not leak', function() {
  let value = false;
  let MyComponent = Component.extend({
    didReceiveAttrs() {
      value = this.getAttr('value');
    }
  });

  MyComponent.reopenClass({
    positionalParams: ['value']
  });

  owner.register(
    'component:my-component',
    MyComponent
  );

  let template = compile(
    `{{#with (hash my-component=(component 'my-component')) as |c|}}
      {{c.my-component }}
     {{/with}}`
  );

  component = Component.extend({
    [OWNER]: owner,
    template
  }).create();

  runAppend(component);

  ok(isEmpty(value), 'value is an empty parameter');
});

QUnit.test('renders with dot path and updates attributes', function() {
  owner.register(
    'component:my-nested-component',
    Component.extend({
      didReceiveAttrs() {
        this.set('myProp', this.getAttr('my-parent-attr'));
      }
    })
  );

  owner.register(
    'template:components/my-nested-component',
    compile(`<span id='nested-prop'>{{myProp}}</span>`)
  );

  owner.register(
    'template:components/my-component',
    compile(`{{yield (hash my-nested-component=(component 'my-nested-component' my-parent-attr=attrs.my-attr))}}`)
  );

  let template = compile(`{{#my-component my-attr=myProp as |api|}}
                           {{api.my-nested-component}}
                         {{/my-component}}

                         <button onclick={{action 'changeValue'}}>Change value</button>`);
  component = Component.extend({
    [OWNER]: owner,
    template,
    myProp: 1,
    actions: {
      changeValue() { this.incrementProperty(`myProp`); }
    }
  }).create({ });

  runAppend(component);

  component.$('button').click();

  equal(component.$('#nested-prop').text(), '2', 'value got updated');

  component.$('button').click();

  equal(component.$('#nested-prop').text(), '3', 'value got updated again');
});

QUnit.test('adding parameters to a closure component\'s instance does not add it to other instances', function(assert) {
  owner.register(
    'template:components/select-box',
    compile('{{yield (hash option=(component "select-box-option"))}}')
  );

  owner.register(
    'template:components/select-box-option',
    compile('{{label}}')
  );

  let template = compile(
    '{{#select-box as |sb|}}{{sb.option label="Foo"}}{{sb.option}}{{/select-box}}'
  );

  component = Component.extend({
    [OWNER]: owner,
    template
  }).create();

  runAppend(component);
  equal(component.$().text(), 'Foo', 'there is only one Foo');
});

QUnit.test('parameters in a closure are mutable when closure is a param', function(assert) {
  let dispatcher = EventDispatcher.create();
  dispatcher.setup();

  let ChangeButton = Component.extend().reopenClass({
    positionalParams: ['val']
  });

  owner.register(
    'component:change-button',
    ChangeButton
  );
  owner.register(
    'template:components/change-button',
    compile('<button {{action (action (mut val) 10)}} class="my-button">Change to 10</button>')
  );

  let template = compile('{{component (component "change-button" val2)}}{{val2}}');

  component = Component.extend({
    [OWNER]: owner,
    template
  }).create({
    val2: 8
  });

  runAppend(component);

  assert.equal(component.$('.value').text(), '8', 'initial state is right');

  run(() => component.$('.my-button').click());

  assert.equal(component.$('.value').text(), '10', 'Value gets updated');

  runDestroy(dispatcher);
});

QUnit.test('parameters in a closure are mutable when closure is in a nested param', function(assert) {
  let dispatcher = EventDispatcher.create();
  dispatcher.setup();

  let ChangeButton = Component.extend().reopenClass({
    positionalParams: ['val']
  });

  owner.register(
    'component:change-button',
    ChangeButton
  );
  owner.register(
    'template:components/change-button',
    compile('<button {{action (action (mut val) 10)}} class="my-button">Change to 10</button>')
  );

  owner.register(
    'component:my-comp',
    Component.extend().reopenClass({
      positionalParams: ['components']
    })
  );
  owner.register(
    'template:components/my-comp',
    compile('{{component components.comp}}')
  );

  let template = compile('{{my-comp (hash comp=(component "change-button" val2))}}{{val2}}');

  component = Component.extend({
    [OWNER]: owner,
    template
  }).create({
    val2: 8
  });

  runAppend(component);

  assert.equal(component.$('.value').text(), '8', 'initial state is right');

  run(() => component.$('.my-button').click());

  assert.equal(component.$('.value').text(), '10', 'Value gets updated');

  runDestroy(dispatcher);
});

QUnit.test('parameters in a closure are mutable when closure is a hash value', function(assert) {
  let dispatcher = EventDispatcher.create();
  dispatcher.setup();

  owner.register(
    'template:components/change-button',
    compile('<button {{action (action (mut val) 10)}} class="my-button">Change to 10</button>')
  );

  owner.register(
    'template:components/my-comp',
    compile('{{component component}}')
  );

  let template = compile('{{my-comp component=(component "change-button" val=val2)}}{{val2}}');

  component = Component.extend({
    [OWNER]: owner,
    template
  }).create({
    val2: 8
  });

  runAppend(component);

  assert.equal(component.$('.value').text(), '8', 'initial state is right');

  run(() => component.$('.my-button').click());

  assert.equal(component.$('.value').text(), '10', 'Value gets updated');

  runDestroy(dispatcher);
});

QUnit.test('parameters in a closure are mutable when closure is a nested hash value', function(assert) {
  let dispatcher = EventDispatcher.create();
  dispatcher.setup();

  owner.register(
    'template:components/change-button',
    compile('<button {{action (action (mut val) 10)}} class="my-button">Change to 10</button>')
  );

  owner.register(
    'template:components/my-comp',
    compile('{{component components.button}}')
  );

  let template = compile('{{my-comp components=(hash button=(component "change-button" val=val2))}}{{val2}}');

  component = Component.extend({
    [OWNER]: owner,
    template
  }).create({
    val2: 8
  });

  runAppend(component);

  assert.equal(component.$('.value').text(), '8', 'initial state is right');

  run(() => component.$('.my-button').click());

  assert.equal(component.$('.value').text(), '10', 'Value gets updated');

  runDestroy(dispatcher);
});

}


text:
<!doctype html>

        <meta charset="utf-8">
        <meta http-equiv="x-ua-compatible" content="ie=edge">
        <title>Bob's Ferry Pilot Service</title>
        <link rel="stylesheet" href="css/main.css" type="text/css">
        <link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Carter+One" />

        <link rel="icon" href="img/favicon.png" type="image/x-icon">

Home

Quotes for Service

Our Crew

Track Your Asset

Fly With Us

                    Need your aircraft moved from A to B?

                    Need an asset recovered?

                    Need a second seat you can trust?

                    <form id="login-form-1" action="uc/index.html">

                            Login to see your account and asset status!

                        <input id="login" type="submit" name="loginButton" value="Log In" />

                            <input id="username" type="text" placeholder="Username" />

                            <input id="password" type="password" placeholder="Password" />

                            Register

                            Forgot your password?

                    </form>

                        X

Forgot your password?

                    <form id="pwModal" action="uc/index.html" class="modal-body" onsubmit="return validatefForgotPwForm()">

                            Your Email:
                            <input id="emailLost" name="emailLost" type="email" placeholder="youremail@mail.com" />

                            <input id="lostPw" type="submit" name="lostPwButton" value="Reset Password"/>

                    </form>

                        X

Register for full access!

                    <form id="regModal" action="uc/index.html" class="modal-body" onsubmit="return validateRegForm()">

                            Your Full Name:
                            <input id="namesignup" name="nameSignup" type="text" placeholder="John Doe" />

                            Username:
                            <input id="usernamesignup" name="usernamesignup" type="text" placeholder="username" />

                             Your Email:
                            <input id="emailsignup" name="emailsignup" type="email" placeholder="youremail@mail.com"/>

                            Phone Number:
                            <input id="phoneignup" name="phoneSignup" type="text" placeholder="(xxx) xxx-xxxx" />

                            Your password:
                            <input id="passwordsignup" name="passwordsignup" type="password" placeholder="password"/>

                            Please confirm your password:
                            <input id="passwordsignup_confirm" name="passwordsignup_confirm" type="password" placeholder="confirm password"/>

                            <input id="signUp" type="submit" name="signupButton" value="Sign up"/>

                    </form>

					If it has wings, Bob's can fly it for you!

Bob's  Ferry Pilots

                    Home
                    ·
                    Quotes
                    ·
                    Our Crew
                    ·
                    Tracking
                    ·
                    Fly With Us

Bob's Ferry Pilot's © 2016

This work is licensed under a Creative Commons License

                <form method="post" name="contactFooter" action="http://webdevbasics.net/scripts/demo.php" onsubmit="return validateContactForm()">

                        Contact Us

                        <input type="text" name="email" placeholder="Email" />

                        <textarea name="message" placeholder="Type your message here"></textarea>

                        <input name="sendButton" id="send" type="submit" value="Send"  />

                </form>

redpajama_set_name: RedPajamaGithub


text:
if (window.jQuery) {
 $(function(){
    // Tamaño container
    $(".container").css({"min-height":$(document).height()});
    $('body').on('click', '#accordion h3', function(event) {
      event.preventDefault();
      $(this).next('div').slideToggle();
      return false;
    });

    $(window).load(function(){
      $(".menupie ul li").css({"height":$("li.carrito a img").height()});
      $(".pedidotar").css({"bottom":$("li.carrito a img").height()});
      $(".contpag").css({"bottom":$("li.carrito a img").height()});
      $(".latermenu").css({"margin-top":$(".menusup").height()});
      $(".botones").css({"bottom":$("li.carrito a img").height()+"px"});
    });
    //fin tamaño container

    //Mostrar menu lateral
    $(".verlatermenu").click(function(event){
      event.preventDefault();
      var img= $(".menusup button.ico-menu span").css('background-image').split("flecha_atras");
      if(img[1] && img[1].length>0){
        $(".menusup button.ico-menu span").css("background","url(images/linmenu.png)");
            //window.history.back();
            var pago= window.location.href.search("pago");
            var ins= window.location.href.search("ins");
            var edit= window.location.href.search("edit");

            if(localStorage.cuenta){
              $(".mi_cuenta").attr("href","internal.html#/mi_cuenta");
            }

            var redir="internal.html#/carta";
            if(ins>0)redir= "internal.html#/menu";
            if(edit>0)redir= "internal.html#/compras";
            if(pago>0)redir= "internal.html#/compras";
            window.location = redir;
          }else{
            var position = $(".latermenu").position();
            if(position.left==0){
              $(".latermenu").animate({"left":-412},200);
            }else{
              $(".latermenu").animate({"left":0},400);
            }
            $(".container").animate({
             scrollTop:0
           },"slow");
          }
        });
  $(".td a").click(function(){
    $(".latermenu").animate({"left":-412},200);
  });
  $(".menupie").hover(function(){
    $(".latermenu").animate({"left":-412},200);
  });
  $(document).on("click", ".dirs", function() {
    var dat= this.title.split('~');
    $(".address").val('');
    if(dat.length>0){
      if(dat[0]!=""){
        var dirFull= dat[0].split("|");
        if(dirFull[0]!=null && dirFull[0]!=""){$("#dir1 option[value='"+dirFull[0]+"']").prop('selected', true);}else{$("#dir1 option[value='Calle']").prop('selected', true);}
        if(dirFull[1]!=null && dirFull[1]!=""){$("#dir2").val(dirFull[1]);}else{$("#dir2").val('');}
        if(dirFull[2]!=null && dirFull[2]!=""){$("#dir3").val(dirFull[2]);}else{$("#dir3").val('');}
        if(dirFull[3]!=null && dirFull[3]!=""){$("#dir4").val(dirFull[3]);}else{$("#dir4").val('');}
        codeAddress();
      }
      if(dat[1]!="")$("#numero").val(dat[1]);
      if(dat[2]!="")$("#referencia").val(dat[2]);
    }
  });
  $(document).on("change", ".vrdirc input,select", function() {
    codeAddress();
  });
  $(document).on("click", ".glyphicon-minus-sign", function() {
    var dat= this.title.split('|');
    if(dat.length>0){
      var orden= $(this).prev().attr("title").split("|");
      ajaxrest.removeAddress(encodeURIComponent(orden[0]),encodeURIComponent(orden[1]),encodeURIComponent(orden[2]));
      $(this).parents('li').remove();
    }
  });
  $(document).on("click", ".close_guia", function() {
    localStorage.setItem("show_guia","1");
    window.location.href = 'internal.html#/carta';
  });
  $(document).on("click", ".audio_play", function(event) {
    event.preventDefault();
    var audio= this.title;
    $("#audio_"+audio).attr("src",localStorage.domain+"resources/audio/"+audio+".mp3");
    $( this ).toggleClass( "audio_stop", 1000, "audio_play" );
    if($( this ).attr("class")!='audio_play ng-scope')
    {
      $("#audio_"+audio).trigger('play');
    }
    else
    {
      $("#audio_"+audio).trigger('pause');
    }
    return false;
  });

    //Activar menus
    $(".menupie li a").click(function(){
      $("li").removeClass("active");
      $(this).parent().addClass("active");
    });
  })
} else {
  alert("Internet es requerido!");
}
/* Funciones */
function hiddeMenu(){
  $(".latermenu").animate({"left":-412},200);
}
function shareBono(){
  var precio= $("#precio_bono").html();
  var descuento= $("#descuento_bono").html();
  var imagen= $("#img_qr").attr("src");
  var codigo= $("#codigo").html();
  window.plugins.socialsharing.share('Hola, como estas?\r\nOhi! descárgate esta aplicación Buffet Express y almorza hoy por $ '+precio+', podes armar tu plato como queras…\r\nEs muy fácil entra a la app y en el menú dale click a comparte y gana, escanea el código QR que te llego con este mensaje o ingresa el siguiente código:\r\n\r\n'+codigo+'\r\n\r\nEste te dara un bono de $ '+descuento+'.',null,imagen, 'http://buffetexpress.co/');
}
function scanear(){
   cordova.plugins.barcodeScanner.scan(
      function (result) {
        var datos= localStorage.getItem("cuenta");
        var sponsor= result.text;
        var invited=0;
          if(datos!=null){
            var data= JSON.parse(datos);
            if(data.id!="")invited= data.id;
          }
          if(sponsor!=""&&invited!="")ajaxrest.setQR(sponsor,invited,0);
      },
      function (error) {
          console.log("problemas procesando scanner");
      }
      );
}
function registerBono(){
   var bono= $("#bono").val();
   if(bono!=""){
      var invited=0;
      var datos= localStorage.getItem("cuenta");
      if(datos!=null){
            var data= JSON.parse(datos);
            if(data.id!="")invited= data.id;
      }
      var sponsor=bono;
      ajaxrest.setQR(sponsor,invited,1);
   }
}
function registrarUser(){
   var cellPhone= $("#cellPhone").val();
   $("#password").val(cellPhone);
   $("#password2").val(cellPhone);
   localStorage.setItem("regQR","true");
   var check= ajaxrest.checkSMS();
   localStorage.setItem("sms","0");
   CreateTimer("time", "120");
   $(".time").show();
   setTimeout(function(){
    if(localStorage.getItem("sms")=="0"){
      alert("No se recibio el mensaje SMS de verificación.\nComprueba el número de celular ingresado y vuelve intentarlo");
      $("#code").val('');
      $(".register").show();
      $(".sms").hide();
      $(".time").hide();
      $("#time").html("0");
    }
   }, 120000);
   smsplugin.startReception(function success(result){
     var res=result.split(",");
     if(res[1]!=""){
      $("#code").val(res[1]);
      localStorage.setItem("sms","1");
      ajaxrest.setAccount('add',82);
    }
  },function failure(error){
    $("#code").val('');
  });
}
function registrarSMS(){
  var code= $("#code").val();
  if(code!=""){
    ajaxrest.getConfirmSMS();
  }else{
    alert("Código requerido");
    return true;
  }
}
function validarCuenta(){
  var datos= localStorage.getItem("cuenta");
  var data= JSON.parse(datos);
  $("#email").val(data.email);
  $("#name").val(data.names);
  $("#cellPhone").val($("#celular").val());
   localStorage.setItem("regQR","true");
   var check= ajaxrest.checkSMS();
   localStorage.setItem("sms","0");
   CreateTimer("time", "120");
   $(".time").show();
   setTimeout(function(){
    if(localStorage.getItem("sms")=="0"){
      alert("No se recibio el mensaje SMS de verificación.\nComprueba el número de celular ingresado y vuelve intentarlo");
      $("#code").val('');
      $(".validar").show();
      $(".sms").hide();
      $(".time").hide();
      $("#time").html("0");
    }
   }, 120000);
   smsplugin.startReception(function success(result){
     var res=result.split(",");
     if(res[1]!=""){
      $("#code").val(res[1]);
      localStorage.setItem("sms","1");
      var dat= localStorage.cuenta;
      var data= JSON.parse(dat);
      var res = dat.replace('validate":"0', 'validate":"1');
      localStorage.setItem("cuenta",res);
      ajaxrest.updateInfo(data.email);
      location.reload();
    }
  },function failure(error){
    $("#code").val('');
  });
}

function getListBono(id){
  if(id!=null){
    ajaxrest.getListBonos(id);
  }
}

function addShop(action){
  var num=$(".numero").html();
  if(action=="mas"){
    num++;
  }
  if(action=="menos"){
   if(num>0)num--;
 }
 localStorage.setItem("num",num);
 $(".numero").html(num);
 return false;
}
$.urlParam = function(name){
  var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
  if (results==null){
   return null;
 }
 else{
   return results[1] || 0;
 }
}


text:
package com.amazonaws.services.sagemaker.model;

import java.io.Serializable;
import javax.annotation.Generated;

import com.amazonaws.AmazonWebServiceRequest;

/**
 *
 * @see AWS API Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class GetModelPackageGroupPolicyRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {

    /**
     *

     * The name of the model group for which to get the resource policy.
     *

     */
    private String modelPackageGroupName;

    /**
     *

     * The name of the model group for which to get the resource policy.
     *

     *
     * @param modelPackageGroupName
     *        The name of the model group for which to get the resource policy.
     */

    public void setModelPackageGroupName(String modelPackageGroupName) {
        this.modelPackageGroupName = modelPackageGroupName;
    }

    /**
     *

     * The name of the model group for which to get the resource policy.
     *

     *
     * @return The name of the model group for which to get the resource policy.
     */

    public String getModelPackageGroupName() {
        return this.modelPackageGroupName;
    }

    /**
     *

     * The name of the model group for which to get the resource policy.
     *

     *
     * @param modelPackageGroupName
     *        The name of the model group for which to get the resource policy.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public GetModelPackageGroupPolicyRequest withModelPackageGroupName(String modelPackageGroupName) {
        setModelPackageGroupName(modelPackageGroupName);
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getModelPackageGroupName() != null)
            sb.append("ModelPackageGroupName: ").append(getModelPackageGroupName());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof GetModelPackageGroupPolicyRequest == false)
            return false;
        GetModelPackageGroupPolicyRequest other = (GetModelPackageGroupPolicyRequest) obj;
        if (other.getModelPackageGroupName() == null ^ this.getModelPackageGroupName() == null)
            return false;
        if (other.getModelPackageGroupName() != null && other.getModelPackageGroupName().equals(this.getModelPackageGroupName()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getModelPackageGroupName() == null) ? 0 : getModelPackageGroupName().hashCode());
        return hashCode;
    }

    @Override
    public GetModelPackageGroupPolicyRequest clone() {
        return (GetModelPackageGroupPolicyRequest) super.clone();
    }

}


text:
Copyright 2012 Rackspace

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.
--]]

local path = require('path')
local async = require('async')
local utils = require('utils')
local timer = require('timer')
local string = require('string')

local Scheduler = require('/schedule').Scheduler
local BaseCheck = require('/check/base').BaseCheck
local NullCheck = require('/check/null').NullCheck
local misc = require('/util/misc')

local exports = {}

local function make_check(...)
  local args = unpack({...})
  local check_path = path.join(TEST_DIR, string.format("%s.chk", args.check_path or args.id))
  local period = args.period or 1
  local state = args.state or 'OK'
  return BaseCheck:new('test', {["id"]=id, ["state"]=state, ["period"]=period, ["path"]=check_path})
end

exports['test_scheduler_scans'] = function(test, asserts)
  local checks = {
    make_check{id='ch0001'},
    make_check{id='ch0002'},
    make_check{id='ch0003'},
    make_check{id='ch0004'},
  }

  local scheduler = Scheduler:new(checks)

  async.waterfall({
    function(callback)
      scheduler:start()
      local timeout = timer.setTimeout(5000, function()
        -- they all should have run.
        asserts.ok(scheduler._runCount > 0)
        callback()
      end)
    end
  }, function(err)
    scheduler:stop()
    asserts.ok(err == nil)
    test.done()
  end)
end

exports['test_scheduler_adds'] = function(test, asserts)
  local scheduler
  local checks = {
    make_check{id='ch0001'}
  }
  local new_checks = {
    make_check{id='ch0001'},
    make_check{id='ch0002'}
  }

  async.waterfall({
    function(callback)
      scheduler = Scheduler:new(checks)
      scheduler:start()
      process.nextTick(callback)
    end,
    function(callback)
      local count = 0
      callback = misc.fireOnce(callback)
      scheduler:rebuild(new_checks)
      scheduler:on('check.completed', function()
        count = count + 1
        if count == 3 then
          callback()
        end
      end)
    end
  }, function(err)
    asserts.equals(scheduler:numChecks(), 2)
    scheduler:stop()
    asserts.ok(err == nil)
    test.done()
  end)
end

exports['test_scheduler_timeout'] = function(test, asserts)
  local scheduler
  local checks
  local done = misc.fireOnce(function()
    scheduler:stop()
    test.done()
  end)

  checks = {
    NullCheck:new({id='ch0001', state='OK', period=3}),
  }

  checks[1]:on('timeout', done)
  scheduler = Scheduler:new(checks)
  scheduler:start()

end

return exports


text:
[![Build Status](https://drone.io/github.com/flexiant/concerto/status.png)][cli_build] [![GoDoc](https://godoc.org/github.com/flexiant/concerto?status.png)](https://godoc.org/github.com/flexiant/concerto)

Flexiant Concerto's integration with Kubernetes allows you to deploy and maintain Kubernetes clusters using the Flexiant Concerto UI and CLI interface.

This guide concerns how to run the Kubernetes Guestbook example using Flexiant Concerto UI; for an introduction of Kubernetes in Flexiant Concerto see [Getting Started with Kubernetes](Getting started with Kubernetes.md).

It is also recommended to follow [Kubernetes Guestbook example](Kubernetes Guestbook example in Flexiant Concerto.md) before running the Spark example.

# Table of Contents

- [Setup](#setup)
  - [Pre-requisites](#pre-requisites)
  - [Creating the Kubernetes cluster](#creating-the-kubernetes-cluster)
  - [Deploying the Spark example](#deploying-the-spark-example)
  - [Launch Spark works](#launch-spark-works)
- [Contact](#contact)

# Setup

## Pre-requisites

Before setting up the Kubernetes Spark example, we will need:

 - A Flexiant Concerto account.
 - Cloud credentials for those providers you'd like to deploy the example on.
 - Enable Beta features for your Flexiant Concerto account.
 - (Optional) A domain to customize the example's URL.

Please, refer to [Getting Started with Kubernetes](Getting started with Kubernetes.md).

## Creating the Kubernetes cluster

1. Create the kubernetes cluster
2. Add a master node of at least 1GB RAM
3. Add several slave nodes of at least 2GB RAM.

For screen samples, see follow [Kubernetes Guestbook example](Kubernetes Guestbook example in Flexiant Concerto.md#creating-the-kubernetes-cluster)

## Deploying the Spark example

Once your cluster is running, create the replication controllers and services that will run and expose the Spark application.

1. Download Spark example files.

Access the [Kubernetes Spark Example](https://github.com/kubernetes/kubernetes/tree/v1.0.7/examples/spark) and download all json files.

(Please, note that we are refering to a fixed example version, and not to the master branch's version.)

2. Upload Spark files following the example's instructions.
  1. Upload the spark master pod.
  2. Upload the spark master service.
  3. Upload the spark workers controller and wait for the pods to be running.

   If the pods remain pending, you might want to use bigger machines in your cluster, or reduce the number of spark worker nodes.

## Launch Spark works

Follow [Kubernetes Spark Example](https://github.com/kubernetes/kubernetes/tree/v1.0.7/examples/spark) guide to execute work loads. If a worker hangs, try adding nodes with higher memory.

# Contact
If you want to have further information about Flexiant Concerto, you can contact us at <contact@flexiant.com>.

[cli_build]: https://drone.io/github.com/flexiant/concerto/latest
[cli_linux]: https://drone.io/github.com/flexiant/concerto/files/concerto.x64.linux
[cli_darwin]: https://drone.io/github.com/flexiant/concerto/files/concerto.x64.darwin
[cli_windows]: https://drone.io/github.com/flexiant/concerto/files/concerto.x64.windows.exe


text:
package repo

import (
	"code.gitea.io/gitea/models"
	"code.gitea.io/gitea/modules/context"

	api "code.gitea.io/sdk/gitea"
)

// GetRelease get a single release of a repository
func GetRelease(ctx *context.APIContext) {
	// swagger:operation GET /repos/{owner}/{repo}/releases/{id} repository repoGetRelease
	// ---
	// summary: Get a release
	// produces:
	// - application/json
	// parameters:
	// - name: owner
	//   in: path
	//   description: owner of the repo
	//   type: string
	//   required: true
	// - name: repo
	//   in: path
	//   description: name of the repo
	//   type: string
	//   required: true
	// - name: id
	//   in: path
	//   description: id of the release to get
	//   type: integer
	//   format: int64
	//   required: true
	// responses:
	//   "200":
	//     "$ref": "#/responses/Release"
	id := ctx.ParamsInt64(":id")
	release, err := models.GetReleaseByID(id)
	if err != nil {
		ctx.Error(500, "GetReleaseByID", err)
		return
	}
	if release.RepoID != ctx.Repo.Repository.ID {
		ctx.Status(404)
		return
	}
	if err := release.LoadAttributes(); err != nil {
		ctx.Error(500, "LoadAttributes", err)
		return
	}
	ctx.JSON(200, release.APIFormat())
}

// ListReleases list a repository's releases
func ListReleases(ctx *context.APIContext) {
	// swagger:operation GET /repos/{owner}/{repo}/releases repository repoListReleases
	// ---
	// summary: List a repo's releases
	// produces:
	// - application/json
	// parameters:
	// - name: owner
	//   in: path
	//   description: owner of the repo
	//   type: string
	//   required: true
	// - name: repo
	//   in: path
	//   description: name of the repo
	//   type: string
	//   required: true
	// responses:
	//   "200":
	//     "$ref": "#/responses/ReleaseList"
	releases, err := models.GetReleasesByRepoID(ctx.Repo.Repository.ID, models.FindReleasesOptions{
		IncludeDrafts: ctx.Repo.AccessMode >= models.AccessModeWrite,
		IncludeTags:   false,
	}, 1, 2147483647)
	if err != nil {
		ctx.Error(500, "GetReleasesByRepoID", err)
		return
	}
	rels := make([]*api.Release, len(releases))
	for i, release := range releases {
		if err := release.LoadAttributes(); err != nil {
			ctx.Error(500, "LoadAttributes", err)
			return
		}
		rels[i] = release.APIFormat()
	}
	ctx.JSON(200, rels)
}

// CreateRelease create a release
func CreateRelease(ctx *context.APIContext, form api.CreateReleaseOption) {
	// swagger:operation POST /repos/{owner}/{repo}/releases repository repoCreateRelease
	// ---
	// summary: Create a release
	// consumes:
	// - application/json
	// produces:
	// - application/json
	// parameters:
	// - name: owner
	//   in: path
	//   description: owner of the repo
	//   type: string
	//   required: true
	// - name: repo
	//   in: path
	//   description: name of the repo
	//   type: string
	//   required: true
	// - name: body
	//   in: body
	//   schema:
	//     "$ref": "#/definitions/CreateReleaseOption"
	// responses:
	//   "201":
	//     "$ref": "#/responses/Release"
	rel, err := models.GetRelease(ctx.Repo.Repository.ID, form.TagName)
	if err != nil {
		if !models.IsErrReleaseNotExist(err) {
			ctx.ServerError("GetRelease", err)
			return
		}
		rel = &models.Release{
			RepoID:       ctx.Repo.Repository.ID,
			PublisherID:  ctx.User.ID,
			Publisher:    ctx.User,
			TagName:      form.TagName,
			Target:       form.Target,
			Title:        form.Title,
			Note:         form.Note,
			IsDraft:      form.IsDraft,
			IsPrerelease: form.IsPrerelease,
			IsTag:        false,
			Repo:         ctx.Repo.Repository,
		}
		if err := models.CreateRelease(ctx.Repo.GitRepo, rel, nil); err != nil {
			if models.IsErrReleaseAlreadyExist(err) {
				ctx.Status(409)
			} else {
				ctx.Error(500, "CreateRelease", err)
			}
			return
		}
	} else {
		if !rel.IsTag {
			ctx.Status(409)
			return
		}

		rel.Title = form.Title
		rel.Note = form.Note
		rel.IsDraft = form.IsDraft
		rel.IsPrerelease = form.IsPrerelease
		rel.PublisherID = ctx.User.ID
		rel.IsTag = false
		rel.Repo = ctx.Repo.Repository
		rel.Publisher = ctx.User

		if err = models.UpdateRelease(ctx.User, ctx.Repo.GitRepo, rel, nil); err != nil {
			ctx.ServerError("UpdateRelease", err)
			return
		}
	}
	ctx.JSON(201, rel.APIFormat())
}

// EditRelease edit a release
func EditRelease(ctx *context.APIContext, form api.EditReleaseOption) {
	// swagger:operation PATCH /repos/{owner}/{repo}/releases/{id} repository repoEditRelease
	// ---
	// summary: Update a release
	// consumes:
	// - application/json
	// produces:
	// - application/json
	// parameters:
	// - name: owner
	//   in: path
	//   description: owner of the repo
	//   type: string
	//   required: true
	// - name: repo
	//   in: path
	//   description: name of the repo
	//   type: string
	//   required: true
	// - name: id
	//   in: path
	//   description: id of the release to edit
	//   type: integer
	//   format: int64
	//   required: true
	// - name: body
	//   in: body
	//   schema:
	//     "$ref": "#/definitions/EditReleaseOption"
	// responses:
	//   "200":
	//     "$ref": "#/responses/Release"
	id := ctx.ParamsInt64(":id")
	rel, err := models.GetReleaseByID(id)
	if err != nil && !models.IsErrReleaseNotExist(err) {
		ctx.Error(500, "GetReleaseByID", err)
		return
	}
	if err != nil && models.IsErrReleaseNotExist(err) ||
		rel.IsTag || rel.RepoID != ctx.Repo.Repository.ID {
		ctx.Status(404)
		return
	}

	if len(form.TagName) > 0 {
		rel.TagName = form.TagName
	}
	if len(form.Target) > 0 {
		rel.Target = form.Target
	}
	if len(form.Title) > 0 {
		rel.Title = form.Title
	}
	if len(form.Note) > 0 {
		rel.Note = form.Note
	}
	if form.IsDraft != nil {
		rel.IsDraft = *form.IsDraft
	}
	if form.IsPrerelease != nil {
		rel.IsPrerelease = *form.IsPrerelease
	}
	if err := models.UpdateRelease(ctx.User, ctx.Repo.GitRepo, rel, nil); err != nil {
		ctx.Error(500, "UpdateRelease", err)
		return
	}

	rel, err = models.GetReleaseByID(id)
	if err != nil {
		ctx.Error(500, "GetReleaseByID", err)
		return
	}
	if err := rel.LoadAttributes(); err != nil {
		ctx.Error(500, "LoadAttributes", err)
		return
	}
	ctx.JSON(200, rel.APIFormat())
}

// DeleteRelease delete a release from a repository
func DeleteRelease(ctx *context.APIContext) {
	// swagger:operation DELETE /repos/{owner}/{repo}/releases/{id} repository repoDeleteRelease
	// ---
	// summary: Delete a release
	// parameters:
	// - name: owner
	//   in: path
	//   description: owner of the repo
	//   type: string
	//   required: true
	// - name: repo
	//   in: path
	//   description: name of the repo
	//   type: string
	//   required: true
	// - name: id
	//   in: path
	//   description: id of the release to delete
	//   type: integer
	//   format: int64
	//   required: true
	// responses:
	//   "204":
	//     "$ref": "#/responses/empty"
	id := ctx.ParamsInt64(":id")
	rel, err := models.GetReleaseByID(id)
	if err != nil && !models.IsErrReleaseNotExist(err) {
		ctx.Error(500, "GetReleaseByID", err)
		return
	}
	if err != nil && models.IsErrReleaseNotExist(err) ||
		rel.IsTag || rel.RepoID != ctx.Repo.Repository.ID {
		ctx.Status(404)
		return
	}
	if err := models.DeleteReleaseByID(id, ctx.User, false); err != nil {
		ctx.Error(500, "DeleteReleaseByID", err)
		return
	}
	ctx.Status(204)
}


text:
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// This file is a part of the 'esoco-gwt' project.
// Copyright 2018 Elmar Sonnenschein, esoco GmbH, Flensburg, Germany
//
// 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 de.esoco.gwt.client.ui;

import de.esoco.data.element.DataElement;
import de.esoco.data.element.DataElementList;

import de.esoco.ewt.build.ContainerBuilder;
import de.esoco.ewt.component.Component;
import de.esoco.ewt.component.Container;
import de.esoco.ewt.style.StyleData;

import de.esoco.lib.property.LayoutType;

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

import static de.esoco.lib.property.LayoutProperties.LAYOUT;
import static de.esoco.lib.property.StateProperties.STRUCTURE_CHANGED;
import static de.esoco.lib.property.StyleProperties.STYLE;

/********************************************************************
 * A data element user interface that manages a {@link DataElementList} data
 * element in a child panel manager.
 *
 * @author eso
 */
public class DataElementListUI extends DataElementUI<DataElementList>
{
	//~ Instance fields --------------------------------------------------------

	private DataElementPanelManager aListPanelManager;

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

	/***************************************
	 * {@inheritDoc}
	 */
	@Override
	public void clearError()
	{
		super.clearError();

		aListPanelManager.clearErrors();
	}

	/***************************************
	 * {@inheritDoc}
	 */
	@Override
	public void collectInput(List<DataElement<?>> rModifiedElements)
	{
		aListPanelManager.collectInput(rModifiedElements);
	}

	/***************************************
	 * Overridden to return the base type from the panel manager instead.
	 *
	 * @see DataElementUI#getBaseStyle()
	 */
	@Override
	public StyleData getBaseStyle()
	{
		return aListPanelManager.getBaseStyle();
	}

	/***************************************
	 * Returns the {@link DataElementTablePanelManager} that is used for the
	 * display of the {@link DataElementList} of this instance.
	 *
	 * @return The panel manager or NULL for none
	 */
	public final DataElementPanelManager getPanelManager()
	{
		return aListPanelManager;
	}

	/***************************************
	 * Updates the child panel manager with the current style and properties and
	 * the data element UIs of all children.
	 *
	 * @see DataElementUI#update()
	 */
	@Override
	public void update()
	{
		updateStyle();
		aListPanelManager.updateUI();
	}

	/***************************************
	 * {@inheritDoc}
	 */
	@Override
	public void updateDataElement(DataElement<?> rNewElement, boolean bUpdateUI)
	{
		if (rNewElement.hasFlag(STRUCTURE_CHANGED))
		{
			// always use FALSE to not update UI before data element is updated;
			// UI update will be done in the update() method
			super.updateDataElement(rNewElement, false);

			if (aListPanelManager != null)
			{
				aListPanelManager.update((DataElementList) rNewElement, false);
			}

			if (bUpdateUI)
			{
				update();
			}
		}
		else
		{
			DataElementList rDataElementList = getDataElement();
			String		    sOldStyle		 =
				rDataElementList.getProperty(STYLE, null);

			rDataElementList.clearProperties();
			rDataElementList.setProperties(rNewElement, true);

			boolean bStyleChanged =
				!Objects.equals(sOldStyle,
								rDataElementList.getProperty(STYLE, null));

			aListPanelManager.updateFromProperties(bStyleChanged);

			updateStyle();
		}
	}

	/***************************************
	 * Overridden to create a child {@link DataElementTablePanelManager} for the
	 * data element list.
	 *
	 * @see DataElementUI#buildDataElementUI(ContainerBuilder, StyleData)
	 */
	@Override
	protected Component buildDataElementUI(
		ContainerBuilder<?> rBuilder,
		StyleData			rStyle)
	{
		DataElementList rDataElementList = getDataElement();
		Container	    rListPanel		 = null;

		LayoutType eDisplayMode =
			rDataElementList.getProperty(LAYOUT, LayoutType.TABLE);

		aListPanelManager =
			DataElementPanelManager.newInstance(getParent(), rDataElementList);

		aListPanelManager.buildIn(rBuilder, rStyle);
		rListPanel = aListPanelManager.getPanel();

		if (eDisplayMode == LayoutType.TABLE)
		{
			// DataElementPanelManager performs event handling for other cases
			setupInteractionHandling(rListPanel, false);
		}

		return rListPanel;
	}

	/***************************************
	 * @see DataElementUI#enableInteraction(boolean)
	 */
	@Override
	protected void enableInteraction(boolean bEnable)
	{
		aListPanelManager.enableInteraction(bEnable);
	}

	/***************************************
	 * Implemented to close an open child view.
	 *
	 * @see DataElementUI#dispose()
	 */
	@Override
	void dispose()
	{
		aListPanelManager.dispose();

		super.dispose();
	}

	/***************************************
	 * Updates the style of the panel.
	 */
	private void updateStyle()
	{
		DataElementList rDataElementList = getDataElement();
		String		    sAddStyle		 = aListPanelManager.getStyleName();

		StyleData rNewStyle =
			applyElementStyle(rDataElementList,
							  PanelManager.addStyles(getBaseStyle(),
													 sAddStyle));

		applyStyle();
		aListPanelManager.getPanel().applyStyle(rNewStyle);
	}
}


text:
<?php
namespace app\install;

use Yii;
use yii\base\Model;

class InstallForm extends Model
{
    public $root_password;
    public $root_email = '';
    public $root_login = '';

    public function rules()
    {
        return [
            [['root_password', 'root_email', 'root_login'], 'required'],
            ['root_password', 'string', 'min' => 6],
            [['root_email'], 'email'],
            [['root_password', 'root_email', 'root_login'], 'trim'],
        ];
    }

    public function attributeLabels()
    {
        return [
            'root_password' => Yii::t('app', 'Root password'),
            'root_email' => Yii::t('app', 'Root email'),
            'root_login' => Yii::t('app', 'Root login')
        ];
    }
}


text:
<resources>
    <!-- Example customization of dimensions originally defined in res/values/dimens.xml
         (such as screen margins) for screens with more than 820dp of available width. This
         would include 7" and 10" devices in landscape (~960dp and ~1280dp respectively). -->
    <dimen name="navigation_drawer_width">320dp</dimen>

    <dimen name="standard_margin_small">8dp</dimen>
    <dimen name="standard_padding_small">8dp</dimen>
    <dimen name="standard_padding_large">16dp</dimen>
    <dimen name="image_padding">4dp</dimen>
</resources>


text:
package com.balancedpayments.android;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.telephony.TelephonyManager;
import org.apache.http.conn.util.InetAddressUtils;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * Utility methods
 *
 * @author Ben Mills
 */
public class Utilities {

   protected static Map<String, String> capabilities(Context context) {

      TelephonyManager manager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
      String device = android.os.Build.MANUFACTURER;
      if (device == null || device.equals("unknown")) {
         device = "Simulator";
      }
      String model = android.os.Build.MODEL;
      String systemVersion = android.os.Build.VERSION.RELEASE;
      String carrier = manager.getNetworkOperatorName();
      String ip;
      String macAddress = "";
      if (carrier == null || carrier.equals("") || carrier.equals("Android")) {
         carrier = "Wi-Fi";
         ip = "";
         macAddress = Utilities.getMACAddress("eth0");
      }
      else
      {
         ip = Utilities.getIPAddress(true);
         macAddress = Utilities.getMACAddress("wlan0");
      }

      HashMap<String, String> capabilities = new HashMap<String, String>();

      capabilities.put("capabilities_system_timezone", getTimeZoneOffset());
      capabilities.put("capabilities_user_agent", userAgentString());
      capabilities.put("capabilities_ip_address", ip);
      capabilities.put("capabilities_mac_address", macAddress);
      capabilities.put("capabilities_device_model", model);
      capabilities.put("capabilities_system_version", systemVersion);
      capabilities.put("capabilities_device_name", device);
      capabilities.put("capabilities_carrier", carrier);
      capabilities.put("capabilities_language", getLocale());

      return capabilities;
   }

   /**
    * Assemble and return the user agent string.
    *
    * @return user agent as string
    */
   protected static String userAgentString() {
      return "balanced-android/" + Balanced.VERSION;
   }

   /**
    * Get the current time zone offset.
    *
    * @return time zone offset as string
    */
   protected static String getTimeZoneOffset() {
      Calendar mCalendar = new GregorianCalendar();
      TimeZone mTimeZone = mCalendar.getTimeZone();
      int mGMTOffset = mTimeZone.getOffset(mCalendar.getTimeInMillis());
      return Long.toString(TimeUnit.HOURS.convert(mGMTOffset, TimeUnit.MILLISECONDS));
   }

   /**
    * Returns MAC address of the given interface name.
    *
    * @param interfaceName eth0, wlan0 or NULL=use first interface
    * @return mac address or empty string
    */
   protected static String getMACAddress(String interfaceName) {
      try {
         List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
         for (NetworkInterface intf : interfaces) {
            if (interfaceName != null) {
               if (!intf.getName().equalsIgnoreCase(interfaceName)) {
                  continue;
               }
            }
            byte[] mac = intf.getHardwareAddress();
            if (mac == null) { return ""; }
            StringBuilder buf = new StringBuilder();
            for (int idx = 0; idx < mac.length; idx++) {
               buf.append(String.format("%02X:", mac[idx]));
            }
            if (buf.length() > 0) {
               buf.deleteCharAt(buf.length() - 1);
            }
            return buf.toString();
         }
      }
      catch (Exception ex) {} // ignore exceptions

      return "";
   }

   /**
    * Get IP address from first non-localhost interface
    *
    * @param useIPv4 true=return ipv4 address, false=return ipv6 address
    * @return address or empty string
    */
   protected static String getIPAddress(boolean useIPv4)
   {
      try {
         List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
         for (NetworkInterface intf : interfaces) {
            List<InetAddress> addrs = Collections.list(intf.getInetAddresses());
            for (InetAddress addr : addrs) {
               if (!addr.isLoopbackAddress()) {
                  String sAddr = addr.getHostAddress().toUpperCase();
                  boolean isIPv4 = InetAddressUtils.isIPv4Address(sAddr);
                  if (useIPv4) {
                     if (isIPv4) {
                        return sAddr;
                     }
                  }
                  else {
                     if (!isIPv4) {
                        int delim = sAddr.indexOf('%'); // drop ip6 port suffix
                        return delim < 0 ? sAddr : sAddr.substring(0, delim);
                     }
                  }
               }
            }
         }
      }
      catch (Exception ex) {} // ignore exceptions

      return "";
   }

   protected static String getLocale() {
      String locale = Locale.getDefault().getLanguage() + "-" + Locale.getDefault().getCountry();

      return locale;
   }

   private String getSoftwareVersion(Context context) {
      PackageInfo pi;
      try {
         pi = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
         return pi.versionName;
      } catch (final PackageManager.NameNotFoundException e) {
         return "na";
      }
   }
}


text:
a.nav-link,
a.standalone-link {
  color: var(--nav-link-foreground-color, var(--color-foreground-primary));
  text-decoration: none;
}
a.nav-link:visited,
a.standalone-link:visited {
  color: var(--nav-link-foreground-color, var(--color-foreground-primary));
}
a.nav-link:hover,
a.standalone-link:hover {
  color: var(--nav-link-foreground-color-hover, var(--color-foreground-primary));
  text-decoration: underline;
}
button.fake-link {
  background-color: transparent;
  border: 0;
  color: var(--fake-link-foreground-color, var(--color-foreground-primary));
  font-family: inherit;
  font-size: inherit;
  padding: 0;
  text-decoration: underline;
}
button.fake-link[disabled] {
  color: var(--fake-link-foreground-disabled-color, var(--color-foreground-disabled));
}


text:
from django.db import models
from django.contrib.auth.models import User

class Order(models.Model):
    """Order request."""
    order_id = models.CharField(max_length=20)
    currency = models.CharField(blank=True, max_length=5)
    amount = models.IntegerField(blank=True, null=True)
    payment_method = models.CharField(blank=True, null=True, max_length=20)
    signature = models.CharField(blank=True, null=True, max_length=40)
    date_added = models.DateTimeField(auto_now_add=True)

    def __unicode__(self):
        return "%s" % self.order_id

    def is_payed(self):
        if self.status == 9:
            return True
        else:
            return False

class OrderStatus(models.Model):
    """Order status."""
    order = models.ForeignKey(Order)
    amount = models.DecimalField(blank=True, null=True, decimal_places=2, max_digits=10)
    currency = models.CharField(blank=True, max_length=5)
    payment_method = models.CharField(blank=True, null=True, max_length=30)
    acceptance = models.CharField(blank=True, null=True, max_length=15)
    status = models.IntegerField(blank=True, null=True)
    card_number = models.CharField(blank=True, null=True, max_length=30)
    pay_id = models.CharField(blank=True, null=True, max_length=10)
    error = models.IntegerField(blank=True, null=True)
    brand = models.CharField(blank=True, null=True, max_length=30)
    signature = models.CharField(blank=True, null=True, max_length=40)
    date_added = models.DateTimeField(auto_now_add=True)

    def __unicode__(self):
        return "%s, status: %s" % (self.order, self.status)


text:
import {
  Span,
  SpanAttributes,
  SpanStatusCode,
  Tracer,
} from '@opentelemetry/api';
import { spanRequestSymbol } from './constants';

import type { PluginFastifyReply } from './internal-types';

/**
 * Starts Span
 * @param reply - reply function
 * @param tracer - tracer
 * @param spanName - span name
 * @param spanAttributes - span attributes
 */
export function startSpan(
  reply: PluginFastifyReply,
  tracer: Tracer,
  spanName: string,
  spanAttributes: SpanAttributes = {}
) {
  const span = tracer.startSpan(spanName, { attributes: spanAttributes });

  const spans: Span[] = reply[spanRequestSymbol] || [];
  spans.push(span);

  Object.defineProperty(reply, spanRequestSymbol, {
    enumerable: false,
    configurable: true,
    value: spans,
  });

  return span;
}

/**
 * Ends span
 * @param reply - reply function
 * @param err - error
 */
export function endSpan(reply: PluginFastifyReply, err?: any) {
  const spans = reply[spanRequestSymbol] || [];
  // there is no active span, or it has already ended
  if (!spans.length) {
    return;
  }
  spans.forEach(span => {
    if (err) {
      span.setStatus({
        code: SpanStatusCode.ERROR,
        message: err.message,
      });
      span.recordException(err);
    }
    span.end();
  });
  delete reply[spanRequestSymbol];
}

// @TODO after approve add this to instrumentation package and replace usage
// when it will be released

/**
 * This function handles the missing case from instrumentation package when
 * execute can either return a promise or void. And using async is not an
 * option as it is producing unwanted side effects.
 * @param execute - function to be executed
 * @param onFinish - function called when function executed
 * @param preventThrowingError - prevent to throw error when execute
 * function fails
 */
export function safeExecuteInTheMiddleMaybePromise<T>(
  execute: () => Promise<T>,
  onFinish: (e: unknown, result?: T) => void,
  preventThrowingError?: boolean
): Promise<T>;
export function safeExecuteInTheMiddleMaybePromise<T>(
  execute: () => T,
  onFinish: (e: unknown, result?: T) => void,
  preventThrowingError?: boolean
): T;
export function safeExecuteInTheMiddleMaybePromise<T>(
  execute: () => T | Promise<T>,
  onFinish: (e: unknown, result?: T) => void,
  preventThrowingError?: boolean
): T | Promise<T> | undefined {
  let error: unknown;
  let result: T | Promise<T> | undefined = undefined;
  try {
    result = execute();

    if (isPromise(result)) {
      result.then(
        res => onFinish(undefined, res),
        err => onFinish(err)
      );
    }
  } catch (e) {
    error = e;
  } finally {
    if (!isPromise(result)) {
      onFinish(error, result);
      if (error && !preventThrowingError) {
        // eslint-disable-next-line no-unsafe-finally
        throw error;
      }
    }
    // eslint-disable-next-line no-unsafe-finally
    return result;
  }
}

function isPromise<T>(val: T | Promise<T>): val is Promise<T> {
  return (
    (typeof val === 'object' &&
      val &&
      typeof Object.getOwnPropertyDescriptor(val, 'then')?.value ===
        'function') ||
    false
  );
}


text:
package org.jabref.logic.util.io;

import java.nio.file.Path;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;

public class FileHistory {

    private static final int HISTORY_SIZE = 8;

    private final LinkedList<Path> history;

    public FileHistory(List<Path> files) {
        history = new LinkedList<>(Objects.requireNonNull(files));
    }

    public int size() {
        return history.size();
    }

    public boolean isEmpty() {
        return history.isEmpty();
    }

    /**
     * Adds the file to the top of the list. If it already is in the list, it is merely moved to the top.
     */
    public void newFile(Path file) {
        removeItem(file);
        history.addFirst(file);
        while (size() > HISTORY_SIZE) {
            history.removeLast();
        }
    }

    public Path getFileAt(int index) {
        return history.get(index);
    }

    public void removeItem(Path file) {
        history.remove(file);
    }

    public List<Path> getHistory() {
        return Collections.unmodifiableList(history);
    }
}


text:
var Embedo = require('./embedo');
var Plugins = require('./plugins');

module.exports = Plugins;
export default Embedo;


text:
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The SFC licenses this file
// to you 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.

import { Fn } from '@seleniumhq/side-commons'
import { CommandShape } from '@seleniumhq/side-model'
import { WebDriverExecutor } from '..'
import { interpolateScript } from '../preprocessors'
import { CommandNodeOptions } from '../types'
import Variables from '../variables'
import { WebDriverExecutorCondEvalResult } from '../webdriver'
import { ControlFlowCommandChecks } from './commands'

export interface CommandExecutorOptions {
  executorOverride?: Fn
}

export interface CommandExecutionResult {
  next?: Fn
  skipped?: boolean
  value?: any
}

export class CommandNode {
  constructor(
    command: CommandShape,
    { emitControlFlowChange }: CommandNodeOptions = {}
  ) {
    this.command = command
    this.next = undefined
    this.left = undefined
    this.right = undefined
    this.index = 0
    this.level = 0
    this.timesVisited = 0
    this.emitControlFlowChange = emitControlFlowChange
      ? emitControlFlowChange
      : () => {}
  }
  command: CommandShape
  emitControlFlowChange: Fn
  next?: CommandNode
  transientError?: string
  left?: CommandNode
  right?: CommandNode
  index: number
  level: number
  timesVisited: number

  /* I'm not sure what this does yet, so I'm putting it on a shelf atm
  isExtCommand(executor: CommandNode): boolean {
    return !!(
      typeof executor.isExtCommand === 'function' &&
      executor.isExtCommand(this.command.command)
    )
  }
  */

  isControlFlow(): boolean {
    return !!(this.left || this.right)
  }

  isTerminal(): boolean {
    return (
      ControlFlowCommandChecks.isTerminal(this.command) ||
      this.command.command === ''
    )
  }

  shouldSkip(): boolean {
    return Boolean(this.command.skip || this.command.command.startsWith('//'))
  }

  async execute(
    commandExecutor: WebDriverExecutor,
    args?: CommandExecutorOptions
  ) {
    if (this._isRetryLimit()) {
      throw new Error(
        'Max retry limit exceeded. To override it, specify a new limit in the value input field.'
      )
    }
    if (this.shouldSkip()) {
      return this._executionResult({ skipped: true })
    }
    await commandExecutor.beforeCommand(this.command)
    const result = await this._executeCommand(commandExecutor, args)
    await commandExecutor.afterCommand(this.command)
    return this._executionResult(result)
  }

  async _executeCommand(
    commandExecutor: WebDriverExecutor,
    { executorOverride }: CommandExecutorOptions = {}
  ) {
    if (executorOverride) {
      return await executorOverride(this.command.target, this.command.value)
    } else if (this.isControlFlow()) {
      return this._evaluate(commandExecutor)
    } else if (this.isTerminal()) {
      return
    } else {
      const customCommand = commandExecutor.customCommands[this.command.command]
      if (customCommand) {
        return this.retryCommand(
          async () =>
            await customCommand.execute(this.command, commandExecutor),
          Date.now() + commandExecutor.implicitWait
        )
      }
      return this._executeCoreCommand(
        commandExecutor,
        Date.now() + commandExecutor.implicitWait
      )
    }
  }

  async pauseTimeout(timeout?: number): Promise<void> {
    return new Promise((resolve) => setTimeout(resolve, timeout))
  }

  async retryCommand(
    execute: () => Promise<unknown>,
    timeout: number
  ): Promise<unknown> {
    const timeLimit = timeout - Date.now()
    const expirationTimer = setTimeout(() => {
      throw new Error('Operation timed out!')
    }, timeLimit)
    try {
      const result = await execute()
      clearTimeout(expirationTimer)
      return result
    } catch (e) {
      this.handleTransientError(e, timeout)
      clearTimeout(expirationTimer)
      await this.pauseTimeout()
      return this.retryCommand(execute, timeout)
    }
  }

  async _executeCoreCommand(
    commandExecutor: WebDriverExecutor,
    timeout: number
  ): Promise<unknown> {
    const { command } = this
    const { target, value } = command
    return await this.retryCommand(
      () =>
        // @ts-expect-error webdriver is too kludged by here
        commandExecutor[commandExecutor.name(this.command.command)](
          target,
          value,
          command
        ),
      timeout
    )
  }

  _executionResult(result: CommandExecutionResult = {}) {
    this._incrementTimesVisited()
    return {
      next: this.isControlFlow() ? result.next : this.next,
      skipped: result.skipped,
    }
  }

  handleTransientError(e: unknown, timeout: number) {
    const { command, target, value } = this.command
    const thisCommand = `${command}-${target}-${value}`
    const thisErrorMessage = e instanceof Error ? e.message : ''
    const thisTransientError = `${thisCommand}-${thisErrorMessage}`
    const lastTransientError = this.transientError
    const isNewErrorMessage = lastTransientError !== thisTransientError
    const notRetrying = Date.now() > timeout
    if (isNewErrorMessage) {
      this.transientError = thisTransientError
      console.warn(
        'Unexpected error occured during command:',
        thisCommand,
        notRetrying ? '' : 'retrying...'
      )
      if (thisErrorMessage) {
        console.error(thisErrorMessage)
      }
    }

    if (notRetrying) {
      console.error('Command failure:', thisCommand)
      throw e
    }
  }

  evaluateForEach(variables: Variables): boolean | string {
    let collection = variables.get(
      interpolateScript(this.command.target as string, variables).script
    )
    if (!collection) return 'Invalid variable provided.'
    variables.set(
      interpolateScript(this.command.value as string, variables).script,
      collection[this.timesVisited]
    )
    const result = this.timesVisited < collection.length
    if (result)
      this.emitControlFlowChange({
        commandId: this.command.id,
        type: CommandType.LOOP,
        index: this.timesVisited,
        iterator: collection[this.timesVisited],
        collection,
      })
    // Reset timesVisited if loop ends, needed to support forEach recursion.
    // It's set to -1 since the incrementer will pick it up. Setting it to
    // 0 when called on a subsequent interation.
    else this.timesVisited = -1
    return result
  }

  _evaluate(commandExecutor: WebDriverExecutor) {
    let expression = interpolateScript(
      this.command.target as string,
      commandExecutor.variables
    )
    if (ControlFlowCommandChecks.isTimes(this.command)) {
      const number = Math.floor(+expression)
      if (isNaN(number)) {
        return Promise.reject(new Error('Invalid number provided as a target.'))
      }
      return this._evaluationResult({ value: this.timesVisited < number })
    } else if (ControlFlowCommandChecks.isForEach(this.command)) {
      const result = this.evaluateForEach(commandExecutor.variables)
      if (!result) {
        this.emitControlFlowChange({
          commandId: this.command.id,
          type: CommandType.LOOP,
          end: true,
        })
      }
      return this._evaluationResult({
        value: Boolean(result),
      })
    }
    return commandExecutor.evaluateConditional(expression).then((result) => {
      return this._evaluationResult(result)
    })
  }

  _evaluationResult(result: WebDriverExecutorCondEvalResult) {
    if (result.value) {
      return {
        next: this.right,
      }
    } else {
      return {
        next: this.left,
      }
    }
  }

  _incrementTimesVisited() {
    if (ControlFlowCommandChecks.isLoop(this.command)) this.timesVisited++
  }

  _isRetryLimit() {
    if (ControlFlowCommandChecks.isLoop(this.command)) {
      let limit = 1000
      let value = Math.floor(+(this.command.value as string))
      if (this.command.value && !isNaN(value)) {
        limit = value
      }
      return this.timesVisited >= limit
    }
    return false
  }
}

export const CommandType = {
  LOOP: 'loop',
  CONDITIONAL: 'conditional',
} as const


text:
	Vote object
----------------------------------------------]]

local VOTE = {}
VOTE.__index = VOTE

function VOTE:New( ply, value )
	local obj = setmetatable( {}, self )

	obj.player = ply
	obj.value = value or 1

	return obj
end

function VOTE:IsValid()
	return IsValid(self.player)
end

function VOTE:GetPlayer()
	return self.player
end

function VOTE:GetValue()
	return self.value
end

MediaPlayer.VOTE = VOTE

--[[--------------------------------------------
	Vote Manager
----------------------------------------------]]

local VoteManager = {}
VoteManager.__index = VoteManager

--
-- Initialize the media player object.
--
-- @param mp Media player object.
--
function VoteManager:New( mp )
	local obj = setmetatable({}, self)
	obj._mp = mp
	obj._votes = {}
	return obj
end

---
-- Clears all votes.
--
function VoteManager:Clear()
	self._votes = {}
end

function VoteManager:ClearVotesForMedia( media )
	self._votes[media:UniqueID()] = nil
end

---
-- Add vote for a player and media
--
-- @param media	Media object.
-- @param ply	Player.
-- @param value	Vote value.
--
function VoteManager:AddVote( media, ply, value )
	if not IsValid(ply) then return end

	local uid = media:UniqueID()

	local votes

	if self._votes[uid] then
		votes = self._votes[uid]
	else
		votes = {
			media = media,
			count = 0
		}
		self._votes[uid] = votes
	end

	local vote = self:GetVoteByPlayer(media, ply)

	-- Update vote if player has already voted
	if vote then
		vote.value = value
	else
		vote = VOTE:New(ply, value)
		table.insert( votes, vote )
	end

	-- player is retracting their vote
	if value == 0 then
		for k, v in ipairs(votes) do
			if v:GetPlayer() == ply then
				table.remove( votes, k )
				break
			end
		end
	end

	-- recalculate vote count
	self:GetVoteCountForMedia( media, true )
end

---
-- Remove the player's vote for a media item.
--
-- @param media	Media object.
-- @param ply	Player.
--
function VoteManager:RemoveVote( media, ply )
	self:AddVote( media, ply, 0 )
end

---
-- Get whether the player has already voted for the media.
--
-- @param media	Media object.
-- @param ply	Player.
-- @return Whether the player has voted for the media.
--
function VoteManager:HasVoted( media, ply )
	local uid = media:UniqueID()

	local votes = self._votes[uid]
	if not votes then return false end

	for k, vote in ipairs(votes) do
		if vote:GetPlayer() == ply then
			return true
		end
	end

	return false
end

---
-- Get the vote count for the given media.
--
-- @param media	Media object or UID.
-- @return Vote count for media.
--
function VoteManager:GetVoteCountForMedia( media, forceCalc )
	local uid = isstring(media) and media or media:UniqueID()

	local votes = self._votes[uid]
	if not votes then return 0 end

	if not votes.count or forceCalc then
		local count = 0

		for k, vote in ipairs(votes) do
			count = count + vote:GetValue()
		end

		votes.count = count
	end

	return votes.count
end

function VoteManager:GetVoteByPlayer( media, ply )
	local uid = media:UniqueID()

	local votes = self._votes[uid]
	if not votes then return nil end

	for _, vote in ipairs(votes) do
		if vote:GetPlayer() == ply then
			return vote
		end
	end

	return nil
end

---
-- Get the top voted media unique ID. VoteManager:Invalidate() should be called
-- prior to this in case any players may have disconnected.
--
-- @param removeMedia	Remove the media from the vote manager.
-- @return Top voted media UID.
--
function VoteManager:GetTopVote( removeMedia )
	local media, topVotes = nil, nil

	for uid, _ in pairs(self._votes) do
		local votes = self:GetVoteCountForMedia( uid )

		if not topVotes or votes > topVotes then
			media = self._votes[uid].media
			topVotes = votes
		end
	end

	if removeMedia and media then
		self._votes[media:UniqueID()] = nil
	end

	return media, topVotes
end

---
-- Iterate through all votes and determine if they're still valid. This should
-- called prior to getting the top vote.
--
-- @return Whether any votes were invalid and removed.
--
function VoteManager:Invalidate()
	local changed = false

	for uid, votes in pairs(self._votes) do
		local numVotes = 0

		for k, vote in ipairs(votes) do
			-- check for valid player in case they may have disconnected
			if not (IsValid(vote) and self._mp:HasListener(vote:GetPlayer())) then
				table.remove( votes, k )
				changed = true
			else
				numVotes = numVotes + 1
			end
		end

		if numVotes == 0 then
			self._votes[uid] = nil
		end
	end

	return changed
end

MediaPlayer.VoteManager = VoteManager


text:
namespace elsa {
	namespace compiler {

		template<typename TExpression>
		struct ExpressionPair
		{
			TExpression* expression;
			Expression* parent;
		};

		class NestedExpressionHelper
		{
		public:
			template<typename TExpression>
			static std::vector<ExpressionPair<TExpression>> get_nested_expressions(Expression* exp)
			{
				auto expressions = std::vector<ExpressionPair<TExpression>>();
				get_nested_expressions(exp, expressions, exp);
				return expressions;
			}

			template<typename TExpression>
			static void get_nested_expressions(Expression* exp, std::vector<ExpressionPair<TExpression>>& expressions, Expression* parent)
			{
				auto target_ext = dynamic_cast<TExpression*>(exp);
				if (target_ext != nullptr)
				{
					auto pair = ExpressionPair<TExpression>();
					pair.expression = target_ext;
					pair.parent = parent;

					expressions.push_back(pair);
				}

				if (auto vde = dynamic_cast<VariableDeclarationExpression*>(exp))
				{
					get_nested_expressions(vde->get_expression(), expressions, vde);
				}
				else if (auto conde_exp = dynamic_cast<ConditionalExpression*>(exp))
				{
					for (const auto& ie : conde_exp->get_if_body())
					{
						get_nested_expressions(ie.get(), expressions, conde_exp);
					}

					for (const auto& ee : conde_exp->get_else_body())
					{
						get_nested_expressions(ee.get(), expressions, conde_exp);
					}
				}
				else if (auto loop_exp = dynamic_cast<LoopExpression*>(exp))
				{
					for (const auto& be : loop_exp->get_body())
					{
						get_nested_expressions(be.get(), expressions, loop_exp);
					}
				}
				else if (auto ret_exp = dynamic_cast<ReturnExpression*>(exp))
				{
					get_nested_expressions(ret_exp->get_expression(), expressions, ret_exp);
				}
				else if (auto fde = dynamic_cast<FuncDeclarationExpression*>(exp))
				{
					for (const auto& body_exp : fde->get_body())
					{
						get_nested_expressions(body_exp.get(), expressions, fde);
					}

					for (const auto& arg_exp : fde->get_args())
					{
						get_nested_expressions(arg_exp.get(), expressions, fde);
					}
				}
				else if (auto fc_exp = dynamic_cast<FuncCallExpression*>(exp))
				{
					for (const auto& arg : fc_exp->get_args())
					{
						get_nested_expressions(arg.get(), expressions, fc_exp);
					}
				}
				else if (auto bo_exp = dynamic_cast<BinaryOperatorExpression*>(exp))
				{
					get_nested_expressions(bo_exp->get_left(), expressions, bo_exp);
					get_nested_expressions(bo_exp->get_right(), expressions, bo_exp);
				}
			}
		};

	}
}


text:
build :
	$(MAKE) -C elasticsearch build
	$(MAKE) -C elasticsearch-marvel build
	$(MAKE) -C kibana build

clean :
	docker-compose rm

docker-compose : build
	docker-compose up


text:
import java.util.*;
import java.util.Random;

class NaturalSelection {
    Network[] networks;
    public static final float MUTATION_CHANCE = 0.05f;
    public static final int MUTATION_FORCE = 20;

    NaturalSelection (Network[] networks) {
        this.networks = networks;
    }

    //performs natural selection by only allowing the 50% most fit to continue
    //to the next generation. the original population is restored through
    //breeding. Genes will be split and possibly mutated to create the new children
    public Network[] newGeneration () {
        //get the top 50%, rounded up
        Network[] mostFit = getMostFit();
        //next, create a new generation through crossing genes and mutations
        Network[] nextGen = createNewNetworks(mostFit, networks.length);

        return nextGen;
    }

    private Network[] getMostFit () {
        //sort the network array by the greatest fitness value
        sort();

        //now only take the top 50%. round up if the number is odd
        int finalLength = (int) Math.ceil(networks.length / 2.0f);
        Network[] newNetworks = new Network[finalLength];
        for (int index = 0; index < finalLength; index++) {
            newNetworks[index] = networks[index];
        }

        return newNetworks;
    }

    //makes more networks based on two parents and mutations. networkCount is how many
    //should exist by the end of this function
    private Network[] createNewNetworks (Network[] mostFit, int networkTotal) {
        //keep making new networks until networkTotal is reached
        Network[] newGen = new Network[0];

        while (newGen.length < networkTotal) {
            //use probability based on their fitness scores to choose random parents
            float fitnessTotal = 0;
            float[] probabilities = new float[mostFit.length];
            for (int i = 0; i < mostFit.length; i++) {
                probabilities[i] = mostFit[i].getFitness();
                fitnessTotal += mostFit[i].getFitness();
            }
            //if fitnessTotal is 0, everyone failed. give everyone equal probability to reproduce
            if (fitnessTotal == 0) {
                for (int i = 0; i < mostFit.length; i++) {
                    mostFit[i].setFitness(1);
                    probabilities[i] = 1;
                    fitnessTotal += 1;
                }
            }
            //normalize all the values so they are in percentages
            for (int i = 0; i < mostFit.length; i++) {
                probabilities[i] /= fitnessTotal;
            }
            //pick two parents based on this probability distribution given to each network
            //get two random parents together
            int firstParentIndex = pickIndex(probabilities);
            int secondParentIndex = pickIndex(probabilities);

            //let parents allow to be the same in the case where one parent gets all the points and has
            //100% chance to be picked; that will always be picked anyway

            Gene firstParentGene = new Gene(mostFit[firstParentIndex]);
            Gene secondParentGene = new Gene(mostFit[secondParentIndex]);
            Gene[] children = firstParentGene.breed(secondParentGene);

            Network offspring1 = children[0].toNetwork();
            Network offspring2 = children[1].toNetwork();

            int finalLength = newGen.length + 2;
            if (finalLength > networkTotal) {
                finalLength = networkTotal;
            }

            Network[] newGenAddTwo = new Network[finalLength];
            for (int index = 0; index < newGen.length; index++) {
                newGenAddTwo[index] = newGen[index];
            }
            //add the two new offspring
            if (newGen.length < networkTotal)
                newGenAddTwo[newGen.length] = offspring1;
            if (newGen.length + 1 < networkTotal)
                newGenAddTwo[newGen.length + 1] = offspring2;
            newGen = newGenAddTwo; //newGen has two more offspring on it
        }
        return newGen;
    }

    public int pickIndex (float[] probabilities) {
        float prob = (float) Math.random();
        float cumulativeProbability = 0.0f;
        for (int i = 0; i < probabilities.length; i++) {
            cumulativeProbability += probabilities[i];
            if (prob <= cumulativeProbability) {
                return i;
            }
        }
        return probabilities.length - 1; //if the for loop went all the way through
        //(theoretically impossible) then just return the last index
    }

    //sort the network array, largest to smallest
    private void sort () {
        Arrays.sort(networks, new Comparator<Network>() {
            public int compare(Network n1, Network n2) {
                return Float.compare(n2.getFitness(), n1.getFitness());
            }
        });
    }

}


text:
#include "SiconosConfig.h"
#ifdef WITH_SERIALIZATION
#include "SiconosFull.hpp"

#include "RegisterSimulation.hpp"

#include <boost/numeric/bindings/ublas/matrix.hpp>
#include <boost/numeric/bindings/ublas/vector.hpp>
#include <boost/numeric/bindings/ublas/vector_sparse.hpp>
#include <boost/numeric/bindings/ublas/matrix_sparse.hpp>

#include <boost/archive/binary_iarchive.hpp>

void RegisterSimulationIbin(std::ifstream& ifs, SP::Simulation& sim)
{
  boost::archive::binary_iarchive ar(ifs);
  siconos_io_register_Numerics(ar);
  siconos_io_register_Kernel(ar);
  siconos_io_register_Mechanics(ar);
  siconos_io_register_Control(ar);
  ar >> NVP(sim);
}
#endif


text:
class CommentController < ApplicationController
  skip_filter :require_admin, :only => [:create]

  def user_may_add_comment?(challenge)
    current_user.is_admin? || challenge.supervisor.id == current_user.id
  end

  def redirect_path
      if current_user.is_admin?
          admin_review_path(@comment.challenge.id)
      else
          supervisor_review_path(@comment.challenge.id)
      end
  end

  def create
    @comment = Comment.new(:comment => params[:comment][:comment])
    @comment.user = current_user
    @comment.challenge = Challenge.find(params[:comment][:challenge_id])

    raise RoleException::SupervisorLevelRequired.new('Supervisor level is required') unless user_may_add_comment?(@comment.challenge)

    if !@comment.save
      notice = @comment.errors.full_messages.to_sentence
      puts @comment.errors.full_messages

      redirect_to redirect_path(), :alert => notice
    else
      redirect_to redirect_path()
    end

  end

end


text:
This tutorial is follow-up of the previous one where we learn how to write our first hip program, in which we compute Matrix Transpose. In this tutorial, we'll explain how to use the hipEvent to get the performance score for memory transfer and kernel execution time.

## Introduction:

Memory transfer and kernel execution are the most important parameter in parallel computing (specially HPC and machine learning). Memory bottlenecks is the main problem why we are not able to get the highest performance, therefore obtaining the memory transfer timing and kernel execution timing plays key role in application optimization.

## Requirement:
For hardware requirement and software installation [Installation](https://github.com/ROCm-Developer-Tools/HIP/blob/master/INSTALL.md)

## prerequiste knowledge:

Programmers familiar with CUDA, OpenCL will be able to quickly learn and start coding with the HIP API. In case you are not, don't worry. You choose to start with the best one. We'll be explaining everything assuming you are completely new to gpgpu programming.

## Simple Matrix Transpose

We will be using the Simple Matrix Transpose application from the previous tutorial and modify it to learn how to get the performance score for memory transfer and kernel execution time.

## hipEvent_t

We'll learn how to use the event management functionality of HIP runtime api. In the same sourcecode, we used for MatrixTranspose we will declare the following events as follows:

```
   hipEvent_t start, stop;
```

We'll create the event with the help of following code:

```
   hipEventCreate(&start);
   hipEventCreate(&stop);
```

We'll use the "eventMs" variable to store the time taken value:
`  float eventMs = 1.0f;`

## Time taken measurement by using hipEvents:

We'll start the timer by calling:
`  hipEventRecord(start, NULL);`
in this, the first parameter is the hipEvent_t, will will mark the start of the time from which the measurement has to be performed, while the second parameter has to be of the type hipStream_t. In current situation, we have passed NULL (the default stream). We will learn about the `hipStream_t` in more detail latter.

Now, we'll have the operation for which we need to compute the time taken. For the case of memory transfer, we'll place the `hipMemcpy`:
`  hipMemcpy(gpuMatrix, Matrix, NUM*sizeof(float), hipMemcpyHostToDevice);`

and for kernel execution time we'll use `hipKernelLaunch`:
```
hipLaunchKernelGGL(matrixTranspose,
                   dim3(WIDTH/THREADS_PER_BLOCK_X, HEIGHT/THREADS_PER_BLOCK_Y),
                   dim3(THREADS_PER_BLOCK_X, THREADS_PER_BLOCK_Y),
                   0, 0,
                   gpuTransposeMatrix , gpuMatrix, WIDTH ,HEIGHT);
```

Now to mark the end of the eventRecord, we will again use the hipEventRecord by passing the stop event:
`  hipEventRecord(stop, NULL);`

Will synchronize the event with the help of:
`  hipEventSynchronize(stop);`

In order to calculate the time taken by measuring the difference of occurance marked by the start and stop event, we'll use:
`  hipEventElapsedTime(&eventMs, start, stop);`
Here the first parameter will store the time taken value, second parameter is the starting marker for the event while the third one is marking the end.

We can print the value of time take comfortably since eventMs is float variable.

## How to build and run:
Use the make command and execute it using ./exe
Use hipcc to build the application, which is using hcc on AMD and nvcc on nvidia.

## More Info:
- [HIP FAQ](https://github.com/ROCm-Developer-Tools/HIP/blob/master/docs/markdown/hip_faq.md)
- [HIP Kernel Language](https://github.com/ROCm-Developer-Tools/HIP/blob/master/docs/markdown/hip_kernel_language.md)
- [HIP Runtime API (Doxygen)](http://rocm-developer-tools.github.io/HIP)
- [HIP Porting Guide](https://github.com/ROCm-Developer-Tools/HIP/blob/master/docs/markdown/hip_porting_guide.md)
- [HIP Terminology](https://github.com/ROCm-Developer-Tools/HIP/blob/master/docs/markdown/hip_terms.md) (including Rosetta Stone of GPU computing terms across CUDA/HIP/HC/AMP/OpenL)
- [HIPIFY](https://github.com/ROCm-Developer-Tools/HIPIFY/blob/master/README.md)
- [Developer/CONTRIBUTING Info](https://github.com/ROCm-Developer-Tools/HIP/blob/master/CONTRIBUTING.md)
- [Release Notes](https://github.com/ROCm-Developer-Tools/HIP/blob/master/RELEASE.md)


text:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;

public class QuickSlot : NetworkBehaviour
{
    public KeyCode[] Slots;

    public void Update()
    {
        if (!isLocalPlayer)
            return;
        if (!InputManager.Active)
            return;
        if (PlayerInventory.inv.Inventory.isActiveAndEnabled)
            return;
        if (Player.Local != null)
            if (Player.Local.Building.InBuildMode)
                return;

        for (int i = 0; i < Slots.Length; i++)
        {
            if (Input.GetKeyDown(Slots[i]))
            {
                QuickSelect(i + 1);
            }
        }
    }

    /// <summary>
    /// Selects the item for the local player. Note that the number is from 0 to 3.
    /// </summary>
    /// <param name="number"></param>
    public void QuickSelect(int number)
    {
        if (!isLocalPlayer)
            return;

        foreach (InventoryItemData i in PlayerInventory.inv.Inventory.Contents)
        {
            if (i.Data == null)
                continue;
            if (i.Data.ContainsKey("Quick Slot") && i.Data.Get<int>("Quick Slot") == number)
            {
                Item.Option_Equip(i, i.Prefab);
                break;
            }
        }
    }
}


text:
//
//  NSView+BFUtilities.h
//
//  Created by Heiko Dreyer on 04/27/12.
//  Copyright (c) 2012 boxedfolder.com. All rights reserved.
//

#import <Cocoa/Cocoa.h>

@interface NSView (BFUtilities)

///---------------------------------------------------------------------------------------
/// @name Flattening View Hierarchy
///---------------------------------------------------------------------------------------

/**
 *  Flatten self + subviews, return proper NSImage.
 */
- (NSImage *)flattenWithSubviews;

@end