text:
/*global jQuery,QUnit,window*/
/*jslint vars:true nomen:true*/
(function ($) {
    'use strict';

    QUnit.module('jquery.waitFor');

    QUnit.asyncTest('found while waiting', function () {
        // when
        var dfd = $('#target').waitFor();
        window.setTimeout(function () {
            $('#qunit-fixture').html('
apples
');
        }, 10);

        // then
        dfd.done(function ($elem) {
            QUnit.equal($elem.text(), 'apples', '$elem.text()');
            QUnit.start();
        });
        dfd.fail(function () { QUnit.ok(false, 'unexpected fail'); });
    });

    QUnit.asyncTest('found immediately', function () {
        // when
        $('#qunit-fixture').html('
oranges
');
        var dfd = $('#target').waitFor();

        // then
        dfd.done(function ($elem) {
            QUnit.equal($elem.text(), 'oranges', '$elem.text()');
            QUnit.start();
        });
        dfd.fail(function () { QUnit.ok(false, 'unexpected fail'); });
    });

    QUnit.asyncTest('timeout before found', function () {
        // when
        var dfd = $('#target').waitFor();
        window.setTimeout(function () {
            $('#qunit-fixture').html('
bananas
');
        }, 200);

        // then
        dfd.done(function () { QUnit.ok(false, 'unexpected done'); });
        dfd.fail(function () {
            QUnit.ok(true, 'fail');

            // Note: prevent disturbing the next test by waiting until the bananas #target have been inserted
            window.setTimeout(function () {
                QUnit.start();
            }, 200);
        });
    });

    QUnit.asyncTest('custom timeout', function () {
        // when
        var dfd = $('#target').waitFor({timeout: 300});
        window.setTimeout(function () {
            $('#qunit-fixture').html('
grapes
');
        }, 200);

        // then
        dfd.done(function ($elem) {
            QUnit.equal($elem.text(), 'grapes', '$elem.text()');
            QUnit.start();
        });
        dfd.fail(function () { QUnit.ok(false, 'unexpected fail'); });
    });

    QUnit.asyncTest('custom pause', function () {
        // when
        var dfd = $('#target').waitFor({timeout: 50, pause: 250});
        window.setTimeout(function () {
            $('#qunit-fixture').html('
grapes
');
        }, 200);

        // then
        dfd.done(function ($elem) {
            QUnit.equal($elem.text(), 'grapes', '$elem.text()');
            QUnit.start();
        });
        dfd.fail(function () { QUnit.ok(false, 'unexpected fail'); });
    });

    QUnit.asyncTest('pipeline', function () {
        // given
        window.setTimeout(function () {
            $('#qunit-fixture').html('
apples
');
        }, 30);

        // when
        $('#target1').waitFor().then(function ($target1) {
            // then
            QUnit.equal($target1.text(), 'apples', '$target1.text()');

            // and given
            window.setTimeout(function () {
                $('#qunit-fixture').html('
oranges
');
            }, 30);

            // and when
            return $('#target2').waitFor();
        }).then(function ($target2) {
            // and then
            QUnit.equal($target2.text(), 'oranges', '$target2.text()');
        }).done(function () {
            QUnit.start();
        }).fail(function (msg) {
            QUnit.ok(false, msg);
            QUnit.start();
        });
    });

    QUnit.asyncTest('pipeline-fails-late', function () {
        // given
        window.setTimeout(function () {
            $('#qunit-fixture').html('
apples
');
        }, 30);

        // when
        $('#target1').waitFor().then(function ($target1) {
            // then
            QUnit.equal($target1.text(), 'apples', '$target1.text()');

            // and given
            window.setTimeout(function () {
                $('#qunit-fixture').html('
oranges
');
            }, 30);

            // and when
            return $('#target2-not-found').waitFor();
        }).then(function () {
            QUnit.ok(false, '#target2-not-found found');
        }).done(function () {
            QUnit.ok(false, 'should never be called');
            QUnit.start();
        }).fail(function (msg) {

            // and then
            QUnit.equal(msg, 'Timed out waiting for: "#target2-not-found"', 'msg');
            QUnit.start();
        });
    });

    QUnit.asyncTest('pipeline-fails-early', function () {
        // given
        window.setTimeout(function () {
            $('#qunit-fixture').html('
apples
');
        }, 30);

        // when
        $('#target1-not-found').waitFor().then(function () {
            QUnit.ok(false, '#target1-not-found found');
        }).then(function () {
            QUnit.ok(false, 'should never be called');
        }).done(function () {
            QUnit.ok(false, 'should never be called');
            QUnit.start();
        }).fail(function (msg) {

            // and then
            QUnit.equal(msg, 'Timed out waiting for: "#target1-not-found"', 'msg');
            QUnit.start();
        });
    });

}(jQuery));


text:
class AddQueuedAtToDocumentAnalysis < ActiveRecord::Migration[5.2]
  def change
    add_column :document_analyses, :queued_at, :datetime
  end
end

redpajama_set_name: RedPajamaGithub


text:
``` diff
 namespace Microsoft.AspNetCore.Builder.Extensions {
     public class MapOptions {
+        public bool PreserveMatchedPathSegment { get; set; }
     }
 }
```


text:
package teetime.stage.basic;

import teetime.framework.AbstractConsumerStage;
import teetime.framework.OutputPort;

/**
 *
 * @author Christian Wulf
 *
 * @param <I>
 *            the type of the input port
 * @param <O>
 *            the type of the output port
 *
 * @since 2.0
 */
public abstract class AbstractTransformation<I, O> extends AbstractConsumerStage<I> implements ITransformation<I, O> {

	protected final OutputPort<O> outputPort = createOutputPort();

	protected AbstractTransformation() {
		super();
	}

	@Override
	public final OutputPort<O> getOutputPort() {
		return outputPort;
	}

}


text:
<title>Namegen</title>
<link rel="stylesheet" type="text/css" href="namegen.css"></link>

				<button type="button" onclick="handleButtonClick('male')">Male</button>
				<button type="button" onclick="handleButtonClick('female')">Female</button>

You may also try:

Esports Team Names

Markov-Chain English Names

English Fantasy Names

German Fantasy Names

Tech Project Names

Excuses

Book Titles

Code Names


text:
    <md-button class="md-primary" ui-sref="kct.saveManager.mods" flex="initial" layout-align="left center">
      <ng-md-icon icon="chevron_left"></ng-md-icon>
      kct.layout.saveManager.mods.details.return
    </md-button>

  <md-card layout="column" layout-padding="">

kct.layout.saveManager.mods.details.edition.header

    <md-divider></md-divider>

      <form ng-submit="modDetailsCtrl.editMod()" flex flex-sm="100" name="modDetailsCtrl.modForm">
        <md-input-container smart-field>
          kct.layout.common.fields.title
          <input id="modTitle" required name="modTitle" type="text" ng-model="modDetailsCtrl.mod.title" />
        </md-input-container>
        <md-input-container>
          kct.layout.common.fields.desc
          <textarea ng-model="modDetailsCtrl.mod.desc" id="modDesc" rows="5"></textarea>
        </md-input-container>
        <md-input-container layout="row" layout-md="column" layout-sm="column">
          <md-button class="md-raised md-primary" flex flex-md="100" flex-sm="100">kct.layout.saveManager.mods.details.edition.buttons.edit</md-button>

          <md-button ng-click="modDetailsCtrl.deleteMod()" class="md-raised md-warn" type="button" flex flex-md="100" flex-sm="100">kct.layout.saveManager.mods.details.edition.buttons.delete</md-button>
        </md-input-container>
      </form>

kct.layout.saveManager.mods.details.edition.versions.header

            <md-button class="md-raised" ui-sref="kct.saveManager.mod.versions(({modId : modDetailsCtrl.mod.$id}))" flex>
              kct.layout.saveManager.mods.details.edition.versions.manage
            </md-button>

        <md-data-table-container>

                {{modVersion.$id | replaceChars:'_':'.'}}
                {{modVersion.depsLength}}

        </md-data-table-container>

  </md-card>


text:
package org.apache.ofbiz.product.config;

@SuppressWarnings("serial")
public class ProductConfigWrapperException extends Exception {

    /** Creates a new instance of ProductConfigWrapperException */
    public ProductConfigWrapperException(String message) {
        super(message);
    }

}


text:
package priv.jesse.cloudnote.dao;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

import priv.jesse.cloudnote.entity.Note;

public interface NoteDAO extends Serializable {
	List<Map<String, Object>> findNoteByNotebookId(String notebookId);

	Note findNoteById(String id);

	void updateNote(Note note);

	void saveNote(Note note);

	void removeNote(Note note);
}


text:
module XBattBar.Backend (getCharge, getPower, Power(..)) where

data Power = AC | Battery
            deriving (Show)

-- | retrieves battery charge
getCharge :: IO Double
getCharge = getChargeLinux

-- | retrieves power status
getPower :: IO Power
getPower  = getPowerLinux

-- | get charge from ACPI on linux
getChargeLinux :: IO Double
getChargeLinux = do
    let path = "/sys/bus/acpi/drivers/battery/PNP0C0A:00/power_supply/BAT0/"
    fullS <- readFile $ path++"energy_full"
    nowS <- readFile $ path++"energy_now"
    let f = read fullS
    let n = read nowS
    return (n / f)

-- | get power state from ACPI on linux
getPowerLinux :: IO Power
getPowerLinux = do
    let path = "/sys/bus/acpi/drivers/ac/ACPI0003:00/power_supply/AC/online"
    s <- readFile path
    return $ case (read s) of
                0 -> Battery
                1 -> AC


text:
/*eslint-env browser */
/*global describe, beforeEach, it, expect*/ // test runner globals

var u = require('../test-utils');
var triggerKey = u.triggerKey;

var hotkey, app, events;

describe('mounting', function() {

    beforeEach(function() {
        events = [];
        hotkey = require('../').activate();
        app = render();
    });

    describe("not mounted", function() {
        it('should not respond to hotkeys', function() {
            triggerKey(document);
            triggerKey(document);
            expect(events.length).toBe(0);
        });
    });

    describe("mounted", function() {
        beforeEach(function() {
            app.setState({mount: true});
        });
        it('should respond to hotkeys', function() {
            triggerKey(document);
            triggerKey(document);
            expect(events.length).toBe(2);
        });
    });

});

var React = require('react');
var ReactDOM = require('react-dom');
var div = document.createElement("div");
document.body.appendChild(div);
function render() {
    var App = React.createClass({
        getInitialState: function() {
            return { mount: false };
        },
        render: function() {
            if (this.state.mount) {
                return React.createElement(Component);
            } else {
                return null;
            }
        }
    });
    var Component = React.createClass({
        mixins: [hotkey.Mixin('hotkey')],
        hotkey: function(e) {
            events.push(e);
        },
        render: function() {
            return React.DOM.div({}, "div");
        }
    });
    ReactDOM.unmountComponentAtNode(div);
    return ReactDOM.render(React.createElement(App), div);
}


text:
#region Namespaces
using System;
using System.Windows.Forms;
using System.Reflection;
#endregion // Namespaces

namespace ADNPlugin.Revit.StringSearch
{
  partial class AboutBox : Form
  {
    public AboutBox()
    {
      InitializeComponent();

      // Initialize the AboutBox to display the product
      // information from the assembly information.
      // Change assembly information settings for your
      // application through either Project > Properties
      // > Application > Assembly Information or
      // by editing AssemblyInfo.cs.

      Text = "About " + AssemblyTitle;
      labelProductName.Text = AssemblyProduct;
      labelVersion.Text = "Version " + AssemblyVersion;
      labelCopyright.Text = AssemblyCopyright;
      labelCompanyName.Text = AssemblyCompany;
      textBoxDescription.Text = AssemblyDescription;
    }

    #region Assembly attribute accessors
    /// <summary>
    /// Shortcut to retrieve executing assembly
    /// </summary>
    static public Assembly ExecutingAssembly
    {
      get
      {
        return Assembly.GetExecutingAssembly();
      }
    }

    static object GetFirstCustomAttribute( Type t )
    {
      Assembly a = ExecutingAssembly;

      object[] attributes
        = a.GetCustomAttributes( t, false );

      return ( 0 < attributes.Length )
        ? attributes[0]
        : null;
    }

    static public string AssemblyTitle
    {
      get
      {
        // Get all Title attributes on this assembly
        //object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes( typeof( AssemblyTitleAttribute ), false );
        //object[] attributes = GetCustomAttributes( typeof( AssemblyTitleAttribute ) );
        object a = GetFirstCustomAttribute( typeof( AssemblyTitleAttribute ) );
        // If there is at least one Title attribute
        if( null != a )
        {
          // Select the first one
          AssemblyTitleAttribute titleAttribute = (AssemblyTitleAttribute) a;
          // If it is not an empty string, return it
          if( titleAttribute.Title != "" )
            return titleAttribute.Title;
        }
        // If there was no Title attribute, or if the Title attribute was the empty string, return the .exe name
        return System.IO.Path.GetFileNameWithoutExtension( ExecutingAssembly.CodeBase );
      }
    }

    static public string AssemblyVersion
    {
      get
      {
        return ExecutingAssembly.GetName().Version.ToString();
      }
    }

    static public string AssemblyDescription
    {
      get
      {
        // Get all Description attributes on this assembly
        //object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes( typeof( AssemblyDescriptionAttribute ), false );
        //object[] attributes = GetCustomAttributes( typeof( AssemblyDescriptionAttribute ) );
        object a = GetFirstCustomAttribute( typeof( AssemblyDescriptionAttribute ) );
        // If there aren't any Description attributes, return an empty string
        //if( attributes.Length == 0 )
        //  return "";
        // If there is a Description attribute, return its value
        //return ( (AssemblyDescriptionAttribute) attributes[0] ).Description;
        return (null == a)
          ? string.Empty
          : ( (AssemblyDescriptionAttribute) a ).Description;
      }
    }

    static public string AssemblyProduct
    {
      get
      {
        // Get all Product attributes on this assembly
        //object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes( typeof( AssemblyProductAttribute ), false );
        //object[] attributes = GetCustomAttributes( typeof( AssemblyProductAttribute ) );
        object a = GetFirstCustomAttribute( typeof( AssemblyProductAttribute ) );
        // If there aren't any Product attributes, return an empty string
        //if( attributes.Length == 0 )
        //  return "";
        // If there is a Product attribute, return its value
        //return ( (AssemblyProductAttribute) attributes[0] ).Product;
        return ( null == a )
          ? string.Empty
          : ( ( AssemblyProductAttribute ) a ).Product;
      }
    }

    static public string AssemblyCopyright
    {
      get
      {
        // Get all Copyright attributes on this assembly
        //object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes( typeof( AssemblyCopyrightAttribute ), false );
        //object[] attributes = GetCustomAttributes( typeof( AssemblyCopyrightAttribute ) );
        object a = GetFirstCustomAttribute( typeof( AssemblyCopyrightAttribute ) );
        // If there aren't any Copyright attributes, return an empty string
        //if( attributes.Length == 0 )
        //  return "";
        // If there is a Copyright attribute, return its value
        //return ( (AssemblyCopyrightAttribute) attributes[0] ).Copyright;
        return ( null == a )
          ? string.Empty
          : ( ( AssemblyCopyrightAttribute ) a ).Copyright;
      }
    }

    static public string AssemblyCompany
    {
      get
      {
        // Get all Company attributes on this assembly
        //object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes( typeof( AssemblyCompanyAttribute ), false );
        //object[] attributes = GetCustomAttributes( typeof( AssemblyCompanyAttribute ) );
        object a = GetFirstCustomAttribute( typeof( AssemblyCompanyAttribute ) );
        // If there aren't any Company attributes, return an empty string
        //if( attributes.Length == 0 )
        //  return "";
        // If there is a Company attribute, return its value
        //return ( (AssemblyCompanyAttribute) attributes[0] ).Company;
        return ( null == a )
          ? string.Empty
          : ( ( AssemblyCompanyAttribute ) a ).Company;
      }
    }
    #endregion // Assembly attribute accessors
  }
}


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

	<body bgcolor="white">
		Contains helper classes for animations.
	</body>
</html>


text:
import sys
import re, time, json, codecs, urllib, urllib2, codecs
import mechanize
import cookielib
from multiprocessing import Pool
from lxml import etree
import urlparse
import pymongo

# first fast check id is in our db
# genrate two txt, one for id not our db, one for rating list

db = pymongo.Connection().server
cdb = pymongo.Connection().scrapy

class browser(object):
    br = mechanize.Browser()
    cj = cookielib.LWPCookieJar()

    def __init__(self):
        self.br.set_cookiejar(self.cj)
        self.br.set_handle_equiv(True)
        self.br.set_handle_gzip(True)
        self.br.set_handle_redirect(True)
        self.br.set_handle_referer(True)
        self.br.set_handle_robots(False)
        #self.br.set_debug_http(True)
        self.br.addheaders = [('User-agent',
                               'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.1.11) Gecko/20100701 Firefox/3.5.11')]

def dumps(title, data):
    with codecs.open('%s.json' % title, 'wb', 'utf-8') as f:
        json.dump(data, f)

    with codecs.open('%s.txt' % title, 'wb', 'utf-8') as f:
        f.write('\n'.join(data))

if __name__ == '__main__':
    if not sys.argv[1:]:
        print "Usage: python douban_rating.py http://movie.douban.com/doulist/240962/\n"
        sys.exit(0)

    start = str(sys.argv[1])
    ids = list()
    while start:
        page = browser.br.open(start).read()
        tree = etree.fromstring(page, etree.HTMLParser())

        ids += [urlparse.urlparse(i).path.split('/')[-2] for i in tree.xpath("//*[@class='doulist_item']/td/a/@href")]

        try:
            start = tree.xpath("//*[@class='next']/link/@href")[0]
        except IndexError:
            start = None

    dids = []
    titles = []
    fetchs = []
    # ids = list(set(ids))
    for i in ids:
        try: # already exist in our db
            title = db.server.find({'douban.id': i}, {'title': 1})[0]['title']
            dids.append(i)
            titles.append(title)
        except IndexError:
            try:
                atemplate = u"http://api.douban.com/v2/movie/subject/%s"
                vtemplate = u"http://movie.douban.com/subject/%s/"
                js = json.loads(urllib2.urlopen(atemplate % i, timeout=30).read())
                title = js['title']

                titles.append(title)

                desc = " / ".join([title] + js['aka'] + js['genres'] + js['countries'] + [js['year']])
                desc += js['summary']

                todb = {'source': [vtemplate % i], 'title': i, 'desc': desc, 'resource': [], 'track': 'scrapy',
                        'level': 999}

                fetchs.append(todb)
            except:
                pass

    for i in fetchs:
        cdb.scrapy.insert(i)

    dumps('ranking', titles)
    # dumps('fetch', fetchs)
    dumps('dids', dids)


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ProjectModuleManager">
    <modules>
      <module fileurl="file://$PROJECT_DIR$/.idea/modules/telephone.iml" filepath="$PROJECT_DIR$/.idea/modules/telephone.iml" />
      <module fileurl="file://$PROJECT_DIR$/.idea/modules/telephone-build.iml" filepath="$PROJECT_DIR$/.idea/modules/telephone-build.iml" />
    </modules>
  </component>
</project>


text:
<!DOCTYPE html>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">

	<title>Rum Rum is…writing</title>

	<link href="../stylesheets/index-stylesheet.css" media="screen, projection" rel="stylesheet" type="text/css">

Rum2 is…

writing,

building,

communicating,

and (social) networking...

Blocs, Procs, and Lambdas

---Week 6

Blocs, Procs, and Lambdas are closures - a closure is a function or reference to a function together with a referencing environment—a table storing a reference to each of the non-local variables (also called free variables or upvalues) of that function.[1] A closure—unlike a plain function pointer—enables a function to access those non-local variables even when invoked outside its immediate lexical scope.  In essence, a closure is a ways of grouping code we want to run.

The differences between Blocs and Procs are:

Procs are objects, blocks are not.

At most one block can appear in an argument list.  In contrast, you can pass multiple procs to methods.

Although both Procs and Lambdas are both Proc objects, there are many differences, such as:

Lambdas check the number of arguments, while procs do not.

Lambdas and procs treat the 'return' keyword differently.

+More about me?


text:
First of all, thanks for contributing!

In the effort of keeping the development experience consistent between `integrations-extras`
and `integrations-core`, the contribution guidelines are the same for both the
projects and are outlined in [this document][0].

[0]: https://github.com/DataDog/integrations-core/blob/master/CONTRIBUTING.md


text:
package org.sagebionetworks.evaluation.dbo;

import static org.junit.jupiter.api.Assertions.assertEquals;

import java.util.Date;

import org.junit.jupiter.api.Test;
import org.sagebionetworks.evaluation.model.Evaluation;
import org.sagebionetworks.evaluation.model.EvaluationStatus;
import org.sagebionetworks.evaluation.model.SubmissionQuota;

public class EvaluationDBOUtilTest {

    @Test
    public void testDtoToDbo() {
    	Evaluation evalDTO = new Evaluation();
    	Evaluation evalDTOclone = new Evaluation();
    	EvaluationDBO evalDBO = new EvaluationDBO();
    	EvaluationDBO evalDBOclone = new EvaluationDBO();

    	evalDTO.setContentSource("syn123");
    	evalDTO.setCreatedOn(new Date());
    	evalDTO.setDescription("description");
    	evalDTO.setEtag("eTag");
    	evalDTO.setId("123");
    	evalDTO.setName("name");
    	evalDTO.setOwnerId("456");
    	evalDTO.setStatus(EvaluationStatus.OPEN);
    	SubmissionQuota quota = new SubmissionQuota();
    	quota.setSubmissionLimit(10L);
    	Date firstRoundStart = new Date();
    	quota.setFirstRoundStart(firstRoundStart);
    	quota.setNumberOfRounds(100L);
    	quota.setRoundDurationMillis(60000L);
    	evalDTO.setQuota(quota);
    	evalDTO.setSubmissionInstructionsMessage("some instructions");
    	evalDTO.setSubmissionReceiptMessage("some receipt");

    	// method under test
    	EvaluationDBOUtil.copyDtoToDbo(evalDTO, evalDBO);
    	// method under test
    	EvaluationDBOUtil.copyDboToDto(evalDBO, evalDTOclone);
    	// method under test
    	EvaluationDBOUtil.copyDtoToDbo(evalDTOclone, evalDBOclone);

    	assertEquals(evalDTO, evalDTOclone);
    	assertEquals(evalDBO, evalDBOclone);

    	assertEquals(firstRoundStart.getTime(), evalDBO.getStartTimestamp());
    	assertEquals(firstRoundStart.getTime()+60000L*100L, evalDBO.getEndTimestamp());

    }
}


text:
from flask import Blueprint
from flask import render_template
from flask import request
from flask import session
from flask import url_for
from werkzeug.utils import redirect

from src.models.alerts.alert import Alert
from src.models.items.item import Item
import src.models.users.decorators as user_decorators

__author__ = 'glgs'

alert_blueprint = Blueprint('alerts', __name__)

@alert_blueprint.route('edit/<string:alert_id>', methods=['GET', 'POST'])
@user_decorators.requires_login
def edit_alert(alert_id):
    alert = Alert.find_by_id(alert_id)
    if request.method == 'POST':
        alert.price_limit = float(request.form['price_limit'])
        alert.update_to_db()

        return redirect(url_for('users.user_alerts'))

    return render_template('alerts/edit_alert.html', alert=alert)

@alert_blueprint.route('/new', methods=['GET', 'POST'])
@user_decorators.requires_login
def create_alert():
    if request.method == 'POST':
        name = request.form['name']
        url = request.form['url']
        price_limit = float(request.form['price_limit'])

        item = Item(name, url)
        item.save_to_db()

        alert = Alert(session['email'], price_limit, item._id)
        alert.load_item_price()

    return render_template('alerts/create_alert.html')

@alert_blueprint.route('/deactivate/<string:alert_id>')
@user_decorators.requires_login
def deactivate_alert(alert_id):
    alert = Alert.find_by_id(alert_id)
    alert.deactivate()
    return redirect(url_for('users.user_alerts'))

@alert_blueprint.route('/activate/<string:alert_id>')
@user_decorators.requires_login
def activate_alert(alert_id):
    alert = Alert.find_by_id(alert_id)
    alert.activate()
    return redirect(url_for('users.user_alerts'))

@alert_blueprint.route('/delete/<string:alert_id>')
@user_decorators.requires_login
def remove_alert(alert_id):
    alert = Alert.find_by_id(alert_id)
    alert.item.remove_from_db()
    alert.remove_from_db()
    return redirect(url_for('users.user_alerts'))

@alert_blueprint.route('/<string:alert_id>')
@user_decorators.requires_login
def get_alert_page(alert_id):
    alert = Alert.find_by_id(alert_id)
    return render_template('alerts/alert.html', alert=alert)

@alert_blueprint.route('/check_alert_price/<string:alert_id>')
@user_decorators.requires_login
def check_alert_price(alert_id):
    alert = Alert.find_by_id(alert_id)
    alert.load_item_price()
    return redirect(url_for('.get_alert_page', alert_id=alert._id))


text:
/*
 * This software is distributed under BSD 3-clause license (see LICENSE file).
 *
 * Authors: Dawei Chen, Viktor Gal, Soeren Sonnenburg, Heiko Strathmann,
 *          Sergey Lisitsyn
 */

#include <shogun/base/init.h>
#include <shogun/base/Parameter.h>
#include <shogun/io/SerializableAsciiFile.h>
#include <shogun/features/DenseFeatures.h>
#ifdef _WIN32
#include <io.h>
#include <fcntl.h>
#else
#include <unistd.h>
#endif

using namespace shogun;

void print_message(FILE* target, const char* str)
{
	fprintf(target, "%s", str);
}

class CTestClass : public CSGObject
{
public:
	CTestClass() {}
	CTestClass(float64_t number, float64_t vec_start, int32_t features_start)
	{
		m_number=number;
		m_vec=SGVector<float64_t>(10);
		SGVector<float64_t>::range_fill_vector(m_vec.vector, m_vec.vlen, vec_start);

		m_mat=SGMatrix<float64_t>(3,3);
		SGVector<float64_t>::range_fill_vector(m_mat.matrix, m_mat.num_cols*m_mat.num_rows,
				vec_start);

		SGMatrix<int32_t> data=SGMatrix<int32_t>(3, 2);
		SGVector<int32_t>::range_fill_vector(data.matrix, data.num_rows*data.num_cols,
				features_start);
		m_features=new CDenseFeatures<int32_t>(data);
		SG_REF(m_features);

		m_parameters->add(&m_number, "number", "Test variable");
		m_parameters->add(&m_mat, "mat", "Test variable");
		m_parameters->add(&m_vec, "vec", "Test variable");
		m_parameters->add((CSGObject**)&m_features, "features", "Test variable");
	}

	virtual ~CTestClass()
	{
		SG_UNREF(m_features);
	}

	void print()
	{
		SG_PRINT("m_number=%f\n", m_number);
		SGVector<float64_t>::display_vector(m_vec.vector, m_vec.vlen, "m_vec");
		SGVector<float64_t>::display_vector(m_mat.matrix, m_mat.num_cols*m_mat.num_rows,
				"m_mat");

		SGMatrix<int32_t> features=m_features->get_feature_matrix();
		SGMatrix<int32_t>::display_matrix(features.matrix, features.num_rows,
				features.num_cols, "m_features");
	}

	inline virtual const char* get_name() const { return "TestClass"; }

public:
	float64_t m_number;
	SGVector<float64_t> m_vec;
	SGMatrix<float64_t> m_mat;
	CDenseFeatures<int32_t>* m_features;
};

void test_test_class_serial()
{
	char filename_tmp[] = "serialization_test.XXXXXX";
#ifdef _WIN32
	int err = _mktemp_s(filename_tmp, strlen(filename_tmp) + 1);
	ASSERT(err == 0);
#else
	int fd = mkstemp(filename_tmp);
	ASSERT(fd != -1);
	int retval = close(fd);
	ASSERT(retval != -1);
#endif
	char* filename = filename_tmp;

	CTestClass* to_save=new CTestClass(10, 0, 0);
	CTestClass* to_load=new CTestClass(20, 10, 66);

	SG_SPRINT("original instance 1:\n");
	to_save->print();
	SG_SPRINT("original instance 2:\n");
	to_load->print();

	CSerializableAsciiFile* file;

	file=new CSerializableAsciiFile(filename, 'w');
	to_save->save_serializable(file);
	file->close();
	SG_UNREF(file);

	file=new CSerializableAsciiFile(filename, 'r');
	to_load->load_serializable(file);
	file->close();
	SG_UNREF(file);

	SG_SPRINT("deserialized instance 1 into instance 2: (should be equal to "
			"first instance)\n");
	to_load->print();

	/* assert that variable is equal */
	ASSERT(to_load->m_number==to_save->m_number);

	/* assert that vector is equal */
	for (index_t i=0; i<to_load->m_vec.vlen; ++i)
	{
		ASSERT(to_load->m_vec[i]==to_save->m_vec[i]);
	}

	/* assert that matrix is equal */
	for (index_t i=0; i<to_load->m_mat.num_cols*to_load->m_mat.num_rows; ++i)
	{
		ASSERT(to_load->m_mat[i]==to_save->m_mat[i]);
	}

	/* assert that features object is equal */
	SGMatrix<int32_t> features_loaded=to_load->m_features->get_feature_matrix();
	SGMatrix<int32_t> features_saved=to_save->m_features->get_feature_matrix();
	for (index_t i=0; i<features_loaded.num_rows*features_loaded.num_cols; ++i)
	{
		ASSERT(features_loaded[i]==features_saved[i]);
	}

	SG_UNREF(to_save);
	SG_UNREF(to_load);
	unlink(filename);
}

int main(int argc, char **argv)
{
	init_shogun(&print_message, &print_message, &print_message);

	test_test_class_serial();

	exit_shogun();

	return 0;
}


text:
import pandas as pd

from bokeh.plotting import figure, show, output_file
from bokeh.sampledata import periodic_table

elements = periodic_table.elements
elements = elements[elements["atomic number"] <= 82]
elements = elements[~pd.isnull(elements["melting point"])]
mass = [float(x.strip("[]")) for x in elements["atomic mass"]]
elements["atomic mass"] = mass

palette = list(reversed([
    "#67001f","#b2182b","#d6604d","#f4a582","#fddbc7","#f7f7f7","#d1e5f0","#92c5de","#4393c3","#2166ac","#053061"
]))

melting_points = elements["melting point"]
low = min(melting_points)
high= max(melting_points)
melting_point_inds = [int(10*(x-low)/(high-low)) for x in melting_points] #gives items in colors a value from 0-10
meltingpointcolors = [palette[i] for i in melting_point_inds]

output_file("elements.html", title="elements.py example")

TOOLS = "pan,wheel_zoom,box_zoom,reset,resize,save"

p = figure(tools=TOOLS, toolbar_location="left", logo="grey", plot_width=1200)
p.title = "Density vs Atomic Weight of Elements (colored by melting point)"
p.background_fill= "#cccccc"

p.circle(elements["atomic mass"], elements["density"], size=12,
       color=meltingpointcolors, line_color="black", fill_alpha=0.8)

p.text(elements["atomic mass"], elements["density"]+0.3,
    text=elements["symbol"],text_color="#333333",
    text_align="center", text_font_size="10pt")

p.xaxis.axis_label="atomic weight (amu)"
p.yaxis.axis_label="density (g/cm^3)"
p.grid.grid_line_color="white"

show(p)


text:
<?php

declare(strict_types=1);

namespace Soluble\Jasper\Proxy\Export;

use Soluble\Japha\Bridge\Adapter as BridgeAdapter;
use Soluble\Japha\Interfaces\JavaObject;
use Soluble\Jasper\Proxy\Engine\DefaultJasperReportsContext;
use Soluble\Jasper\Proxy\RemoteJavaObjectProxyInterface;

class SimplePdfExporterConfiguration implements RemoteJavaObjectProxyInterface
{
    /**
     * @var BridgeAdapter
     */
    private $ba;

    /**
     * @var JavaObject Java('net.sf.jasperreports.export.SimplePdfExporterConfiguration')
     */
    private $config;

    /**
     * Create a local context, if no parentContext is given, assume the DefaultJasperReportsContext.
     *
     * @param BridgeAdapter $bridgeAdapter
     */
    public function __construct(BridgeAdapter $bridgeAdapter)
    {
        $this->ba     = $bridgeAdapter;
        $this->config = $this->ba->java(
            'net.sf.jasperreports.export.SimplePdfExporterConfiguration'
        );
    }

    public function setCompressed(bool $compressed): void
    {
        $this->config->setCompressed($compressed);
    }

    public function setEncrypted(bool $encrypted): void
    {
        $this->config->setEncrypted($encrypted);
    }

    public function set128BitKey(bool $use128BitKey): void
    {
        $this->config->set128BitKey($use128BitKey);
    }

    public function setOwnerPassword(string $password): void
    {
        $this->config->setOwnerPassword($password);
    }

    public function setUserPassword(string $password): void
    {
        $this->config->setUserPassword($password);
    }

    public function setMetadataAuthor(string $author): void
    {
        $this->config->setMetadataAuthor($author);
    }

    public function setMetadataCreator(string $creator): void
    {
        $this->config->setMetadataCreator($creator);
    }

    public function setMetadataKeywords(string $keywords): void
    {
        $this->config->setMetadataKeywords($keywords);
    }

    public function setMetadataSubject(string $subject): void
    {
        $this->config->setMetadataSubject($subject);
    }

    public function setMetadataTitle(string $title): void
    {
        $this->config->setMetadataTitle($title);
    }

    public function setPdfVersion(string $version): void
    {
        $this->config->setPdfVersion($version);
    }

    /**
     * @return JavaObject Java('net.sf.jasperreports.export.SimplePdfExporterConfiguration')
     */
    public function getJavaProxiedObject(): JavaObject
    {
        return $this->config;
    }
}


text:
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

from subprocess import call
import numpy as np
import os
import nibabel as nib
import pdb
import dipy.core.geometry as geom

import math

# Function takes as input simDir, codeDir, matlabDir and set of eddy pulse features - saves -new_pulse to codeDir
def generateEddyPulse(simDir,codeDir,matlabDir,bS, eS):
    str="addEddy({}, {}, {}, {}, {}, {}, {}, {}, {}, {});exit".format(bS[0],bS[1],bS[2],bS[3],eS[0],eS[1],eS[2],eS[3],eS[4],eS[5])
    call([matlabDir,  "-nodisplay", "-nojvm", "-nosplash","-r",str])

# Function takes as input sim dir, codedir and set of eddy pulse features including bvec, so the eddy currents
# generated are a function of the applied bvec- saves -new_pulse to code dir
def generateEddyPulseFromBvec(simDir,codeDir,matlabDir,bS, ep, tau, bval,bvec):
  from subprocess import call
  str="addEddyAccordingToBvec({}, {}, {}, {}, {}, {}, {}, {}, {}, {});exit".format(bS[0],bS[1],bS[2],bS[3],ep, tau, bval, bvec[0], bvec[1], bvec[2])
  #print str
  call([matlabDir,  "-nodisplay", "-nojvm", "-nosplash","-r",str])

def generateEddyPulseFromBvecFlat(simDir,codeDir,matlabDir,bS, ep, tau, bval,bvec):
  from subprocess import call
  str="addEddyAccordingToBvecFlat({}, {}, {}, {}, {}, {}, {}, {}, {}, {});exit".format(bS[0],bS[1],bS[2],bS[3],ep, tau, bval, bvec[0], bvec[1], bvec[2])
  #print str
  call([matlabDir,  "-nodisplay", "-nojvm", "-nosplash","-r",str])

# Function that takes a segmented image, tensor image and a bval, bvec - attenuates the segmented image and returns
def attenuateImage(image,tensor,bval, bvec):

    #Rewrite bvectors into convenient form for multiplication with tensor
    bvecLong = np.array([0.0] * 6)
    bvecLong[0] = bvec[0] ** 2
    bvecLong[1] = bvec[0] * bvec[1] * 2
    bvecLong[2] = bvec[1] ** 2
    bvecLong[3] = bvec[0] * bvec[2] * 2
    bvecLong[4] = bvec[1] * bvec[2] * 2
    bvecLong[5] = bvec[2] ** 2

    #pdb.set_trace()
    attenuationMap = tensor * bvecLong
    attenuationMap=np.sum(attenuationMap, axis = 3)
    attenuationMap=np.exp(-(bval* (10 ** -6) * attenuationMap * (10 **6)))
   # img = attenuationMap[:,:,35]
   # implot=plt.imshow(img.squeeze())
   # plt.colorbar()
    #plt.show()
    attenuationMap = np.array([np.tile(attenuationMap, (1,1)) for i in range(3)])
    attenuationMap = np.transpose(attenuationMap,[1,2,3,0])
    attenuatedImage =  attenuationMap * image
    return attenuatedImage, attenuationMap

def attenuateImageSphericalHarmonics (image, B, coefficients,bval, bvalStandard):
  dataSize = coefficients.shape
  attenuationMap = np.zeros((dataSize[0],dataSize[1],dataSize[2]))
  for i in range(0,dataSize[0]):
    for j in range(0,dataSize[1]):
      for k in range(0,dataSize[2]):
        coeff = coefficients[i,j,k,:]
        attenuationMap[i,j,k] = np.dot(B,coeff)

  attenuationMap = np.array([np.tile(attenuationMap, (1,1)) for i in range(3)])
  attenuationMap = np.transpose(attenuationMap,[1,2,3,0])

  #Get rid of any negative values
  attenuationMap[attenuationMap < 0] = 0
  #Correct for b-value not being exactly 1000/2000 using mono-exponential assumption:
  if abs(bval-bvalStandard) > 50:
    attenuationMap=np.log(attenuationMap) * (bval/bvalStandard)
    attenuationMap=np.exp(attenuationMap)

  attenuatedImage =  attenuationMap * image
  return attenuatedImage

def saveImage(simDir,saveImageDir,fileName):
  call(["mv", simDir + "/image_abs.nii.gz", os.path.join(saveImageDir,fileName)])

#Load in segmented brain used for possum
def loadSegData(seg_path):
  segmentedBrain = nib.load(seg_path)
  segmentedBrainData = segmentedBrain.get_data()
  return segmentedBrain, segmentedBrainData

#Load in tensor data
def loadTensorData(templateDir,templateName):
  tensorBrain = nib.load(os.path.join(templateDir,templateName))
  tensorBrainData = tensorBrain.get_data()
  return tensorBrainData

def makeRotMatrix(motionParams, simDirClusterDirection):
  #Make three rotation matrices
  call(["makerot", "-t", str(motionParams[4]), "-a", "1,0,0", "--cov="+simDirClusterDirection+ "/brain.nii.gz", "-o", "rotx.mat"])
  call(["makerot", "-t", str(motionParams[5]), "-a", "0,1,0", "--cov="+simDirClusterDirection+ "/brain.nii.gz", "-o", "roty.mat"])
  call(["makerot", "-t", str(motionParams[6]), "-a", "0,0,1", "--cov="+simDirClusterDirection+ "/brain.nii.gz", "-o", "rotz.mat"])
  #Concatenate
  call(["convert_xfm", "-omat", "rotxy.mat","-concat", "roty.mat", "rotx.mat"])
  call(["convert_xfm", "-omat", "rotxyz.mat","-concat", "rotz.mat", "rotxy.mat"])

  #Add translations
  rot = np.loadtxt('rotxyz.mat')
  rot[0,3] += motionParams[1]
  rot[1,3] += motionParams[2]
  rot[2,3] += motionParams[3]
  np.savetxt('trans.mat', rot )
  #Tidy up
  call(["rm","rotx.mat","roty.mat","rotz.mat","rotxy.mat","rotxyz.mat",])

def rotateBvecs(bvec, rotationAngles):
  #Rotates the bvecs before the attentuation is sampled, based on motion parameters, so that rotations adjust the diffusion contrast. Code rotates the brain around x, y then z sucessively, so this code rotates the bvec around z, y then x.
  rotMat = geom.euler_matrix(math.radians(rotationAngles[2]), math.radians(rotationAngles[1]), math.radians(rotationAngles[0]), 'szyx')
  bvecRot = np.dot(rotMat[0:3,0:3],bvec)
  return bvecRot

def read_pulse(fname):
    #Implementation of the read_pulse.m shipped with FSL. This is stripped down and assumes little-endian storage.
    fid = open(fname,"rb")
    testval= np.fromfile(fid, dtype=np.uint32,count = 1)
    dummy=np.fromfile(fid, dtype=np.uint32,count = 1)
    nrows=np.fromfile(fid, dtype=np.uint32,count = 1)
    ncols=np.fromfile(fid, dtype=np.uint32,count = 1)
    nrows= int(nrows)
    ncols= int(ncols)

    time=np.fromfile(fid, dtype=np.float64,count = nrows)
    mvals = np.fromfile(fid, dtype=np.float32, count = nrows*(ncols-1))
    mvals = np.reshape(mvals,(nrows, ncols-1),order='F')
    m = np.zeros((nrows,ncols))
    m[:,0] = time
    m[:,1:] = mvals

    fid.close()
    return m

def write_pulse(fname,mat):
    time = mat[:,0]
    mvals = mat[:,1:]

    fidin = open(fname,"w")
    magicnumber=42+1
    dummy=0
    [nrows,ncols]=mat.shape
    header = np.array([magicnumber,dummy,nrows,ncols])
    header.astype(np.uint32).tofile(fidin)
    time.astype(np.float64).tofile(fidin)
    mvals = np.reshape(mvals,[len(mvals)*7],order='F')
    mvals.astype(np.float32).tofile(fidin)
    fidin.close()

def addEddyAccordingToBvec(pulse,pulseinfo,tint,delta,Delta,Gdiff,ep,tau,bval,bvec):
    #Quick hack to ensure eddy currents scale with b-value
    Gdiff=Gdiff * bval / 2000

    #Extract time
    time=pulse[:,0].T
    numSlices=int(pulseinfo[12])
    TRslice=pulseinfo[3]
    RFtime=time[7]
    #Adjust RF time for spin-echo pulse sequences
    if pulseinfo[0]==3:
      RFtime=time[14]

    Eddyx=np.zeros((4,len(pulse)))
    Eddyy=np.zeros((4,len(pulse)))
    Eddyz=np.zeros((4,len(pulse)))

    for i in range(numSlices):
        t = np.zeros(4)
        t[0]=tint + TRslice * i
        t[1]=tint + delta + TRslice * i
        t[2]=tint + Delta + TRslice * i
        t[3]=tint + delta + Delta + TRslice * i
        RF=RFtime + TRslice * i
        #sliceEnd allows the eddy current to be cut off at the end of the slice acquistion, preventing the slice-wise buildup of ECs. This allows me to shorten TRslice to a realistic value in the simulations whilst not needing to model slice-by-slice buildup for now.
        sliceEnd = TRslice * ( i + 1)

        #Remember the signs need to change
        for j in range(4):
            logical = (time > t[j]) * (time > RF) * (time < sliceEnd)
            addx=(ep * Gdiff * bvec[0] * (np.exp(- (time - t[j]) / tau))) * logical
            addy=(ep * Gdiff * bvec[1] * (np.exp(- (time - t[j]) / tau))) * logical
            addz=(ep * Gdiff * bvec[2] * (np.exp(- (time - t[j]) / tau))) * logical
            addx[np.isnan(addx)]=0
            addy[np.isnan(addy)]=0
            addz[np.isnan(addz)]=0
            if j == 1 or j == 2:
                addx=addx * - 1
                addy=addy * - 1
                addz=addz * - 1
            Eddyx[j,:]=Eddyx[j,:] + addx
            Eddyy[j,:]=Eddyy[j,:] + addy
            Eddyz[j,:]=Eddyz[j,:] + addz
    new_pulse=pulse
    new_pulse[:,5]=pulse[:,5] + np.sum(Eddyx,0).T
    new_pulse[:,6]=pulse[:,6] + np.sum(Eddyy,0).T
    new_pulse[:,7]=pulse[:,7] + np.sum(Eddyz,0).T
    return new_pulse

def makeFolder(directory):
  if not os.path.exists(directory):
    os.makedirs(directory)

def interleavePulse(pulse, numSlices, interleaveFactor):
  [nrows,ncols]=pulse.shape
  pulseInterleaved = np.zeros((nrows,ncols))
  pulseInterleaved[:,0] = pulse[:,0]
  counter = 0
  entriesPerSlice = int(nrows/numSlices)
  for i in range(interleaveFactor):
    for j in range(i,numSlices,interleaveFactor):
      startIndexOld = counter* entriesPerSlice
      endIndexOld = (counter + 1) * entriesPerSlice -1
      startIndex = j* entriesPerSlice
      endIndex = (j + 1) * entriesPerSlice -1
      pulseInterleaved[startIndexOld:endIndexOld,1:] = pulse[startIndex:endIndex,1:]
      counter = counter + 1
  return pulseInterleaved

def get_motion_level(directory,translation_threshold=2.5,rotation_threshold=2.5):
  '''Roughly classify the amount of motion per slice for calculating likelihood of signal dropouts - 1 = severe motion, 2 = moderate motion'''
  motion_path = os.path.join(directory,'motion')
  motion = np.loadtxt(motion_path)
  max_motion = np.max(motion[:,1:],axis=0)
  min_motion = np.min(motion[:,1:],axis=0)
  diff_motion = np.abs(max_motion-min_motion)
  diff_motion[:3] = diff_motion[:3]*1000
  diff_motion[3:] = np.rad2deg(diff_motion[3:])

  if np.any( diff_motion[:3] > translation_threshold):
      return 1
  elif np.any(diff_motion[3:] > rotation_threshold):
      return 1
  elif np.any( diff_motion[:3] > 1):
      return 2
  elif np.any(diff_motion[3:] > 1):
      return 2
  else:
      return 0

def add_signal_dropout(signal,motion_level,num_slices,num_voxels_per_slice):
  if motion_level ==0:
    if np.random.random() < 0: #Add dropout  volumes with no motion
      for i in range(num_slices):
        if np.random.random() < 0.4:
          dropout_factor = np.random.random()
          signal[:,num_voxels_per_slice*i:num_voxels_per_slice*(i+1)] = signal[:,num_voxels_per_slice*i:num_voxels_per_slice*(i+1)] * dropout_factor

  if motion_level == 1:
    if np.random.random() < 0.3: #Add dropout to 30% of volumes with severe motion
     for i in range(num_slices):
       if np.random.random() < 0.4:
         dropout_factor = np.random.random()
         signal[:,num_voxels_per_slice*i:num_voxels_per_slice*(i+1)] = signal[:,num_voxels_per_slice*i:num_voxels_per_slice*(i+1)] * dropout_factor

  elif motion_level == 2: #Don't add dropout to volumes with moderate motion atm
    for i in range(num_slices):
      if np.random.random() < 0.0: #Dont add to examples with mild motion
        dropout_factor = np.random.random()
        signal[:,num_voxels_per_slice*i:num_voxels_per_slice*(i+1)] = signal[:,num_voxels_per_slice*i:num_voxels_per_slice*(i+1)] * dropout_factor
  return signal


text:
import sys
import os
from collections import OrderedDict

def main():
    outfile = sys.argv[1]
    if os.path.exists(outfile):
        print "output file %s exists. quitting" % outfile
        sys.exit(1)

    else:
        print "output file %s" % outfile

    infiles = sys.argv[2:]

    for infile in infiles:
        if not os.path.exists(infile):
            print "input file %s does not exists" % infile
            sys.exit(1)

    data = OrderedDict()
    for infile in infiles:
        print "reading %s" % infile
        with open(infile, 'r') as fhd:
            for line in fhd:
                line = line.strip()
                if len(line) == 0:
                    continue
                if line[0] == ">":
                    name = line
                    print "reading %s seq %s" % (infile, name),
                    if name not in data:
                        data[name] = ""
                        print " *"
                    else:
                        print
                else:
                    data[name] += line

    with open(outfile, 'w') as fhd:
        for name in data:
            line = data[name]
            print "saving %s (%d)" % (name, len(line))
            fhd.write(name + "\n")
            for seq in split_by_n(line, 80):
                fhd.write(seq + "\n")

def split_by_n( seq, n ):
    """
    A generator to divide a sequence into chunks of n units.
    http://stackoverflow.com/questions/9475241/split-python-string-every-nth-character
    """
    while seq:
        yield seq[:n]
        seq = seq[n:]

if __name__ == '__main__':
    main()


text:
package com.dubture.twig.core.parser.ast.node;

import java.util.List;

import org.eclipse.dltk.ast.ASTVisitor;
import org.eclipse.dltk.ast.expressions.Expression;

/**
 *
 * Anything in the form: foo(..)
 *
 * @author Robert Gruendler <r.gruendler@gmail.com>
 *
 */
public class TwigCallExpression extends Expression {
	protected final List<Expression> arguments;
	protected final String name;

	public TwigCallExpression(int startIndex, int stopIndex, String name, List<Expression> arguments) {
		super(startIndex, stopIndex);
		this.name = name;
		this.arguments = arguments;
	}

	@Override
	public void traverse(ASTVisitor visitor) throws Exception {
		if (visitor.visit(this)) {

			if (arguments != null) {
				for (Expression exp : arguments) {

					if (exp != null) {
						exp.traverse(visitor);
					}
				}
			}
			visitor.endvisit(this);
		}
	}

	@Override
	public int getKind() {
		return ASTNodeKinds.CALL_EXPRESSION;
	}

	public List<Expression> getArguments() {
		return arguments;
	}

	@SuppressWarnings("rawtypes")
	@Override
	public List getChilds() {
		return arguments;
	}

	public String getName() {
		return name;
	}
}


text:
/*
Ui.HBox.extend('Storage.FileViewer', {
	uploader: undefined,
	file: undefined,
	updateNeeded: false,
	viewer: undefined,
	tools: undefined,
	contentBox: undefined,
	playing: false,
	contentViewer: undefined,

	constructor: function(config) {
		this.addEvents('toolschange', 'end');

		this.tools = [];

		this.contentBox = new Ui.LBox();
		this.append(this.contentBox, true);

		if('uploader' in config) {
			this.uploader = config.uploader;
			delete(config.uploader);
		}
		else if('file' in config) {
			this.update(config.file);
			delete(config.file);
		}
	},

	getSetupPopup: function() {
		var popup = new Ui.MenuPopup();
		var vbox = new Ui.VBox({ spacing: 10 });
		popup.setContent(vbox);

		for(var i = 0; i < this.tools.length; i++) {
			vbox.append(this.tools[i]);
		}

		var button = new Ui.Button({ text: 'Propriétés', icon: 'edit' });
		this.connect(button, 'press', function() {
			var dialog = new KJing.ResourcePropertiesDialog({ resource: this.file });
			dialog.open();
			popup.close();
		});
		vbox.append(button);
		return popup;
	},

	update: function(file) {
//		console.log(this+'.update('+file.id+')');
		if((this.file === undefined) || this.updateNeeded || (this.file.rev != file.rev)) {
			this.file = file;
			this.updateNeeded = false;
			if(this.getIsLoaded())
				this.buildContent();
		}
	},

	removeContent: function() {
		this.contentBox.setContent();
	},

	buildContent: function() {

		if(this.uploader !== undefined)
			this.contentBox.setContent(new Storage.UploaderViewer({ uploader: this.uploader, fileViewer: this }));
		else {
//			console.log('buildContent file: '+this.file.getId()+', mime: '+this.file.getData().mimetype);
//			console.log(this.file.getData());

			this.tools = [];
			this.supportProperties = true;

			if(this.file.getMimetype().indexOf('application/x-kjing-state') == 0)
				this.contentViewer = new Storage.StateFileViewer({ file: this.file, fileViewer: this });
			else if(this.file.getMimetype() == 'image/gif')
				this.contentViewer = new Storage.GifImageFileViewer({file: this.file, fileViewer: this });
			else if(this.file.getMimetype().indexOf('image/') == 0)
				this.contentViewer = new Storage.ImageFileViewer({ file: this.file, fileViewer: this });
			else if(this.file.getMimetype() == 'text/uri-list')
				this.contentViewer = new Storage.SiteFileViewer({ file: this.file, fileViewer: this });
//			else if(this.file.getMimetype() == 'application/x-webnapperon2-rss-item')
//				this.contentViewer = new Storage.RssItemFileViewer({ file: this.file, fileViewer: this });
			else if((!navigator.isIE7 && !navigator.isIE8) && (this.file.getMimetype().indexOf('video/') == 0))
				this.contentViewer = new Storage.VideoFileViewer({ file: this.file, fileViewer: this });
			else if((!navigator.isIE7 && !navigator.isIE8) && (this.file.getMimetype().indexOf('audio/') == 0))
				this.contentViewer = new Storage.AudioFileViewer({ file: this.file, fileViewer: this });
			else if((this.file.getMimetype().indexOf('text/plain') == 0) && (this.file.getData().size < 50000))
				this.contentViewer = new Storage.TextFileViewer({ file: this.file, fileViewer: this });
			else if(this.file.getMimetype().indexOf('application/pdf') === 0)
				this.contentViewer = new Storage.PdfFileViewer({ file: this.file, fileViewer: this });
			else if('pdf' in this.file.getData())
				this.contentViewer = new Storage.PdfFileViewer({ file: KJing.File.create(this.file.getData().pdf), fileViewer: this });
			else
				this.contentViewer = new Storage.GenericFileViewer({ file: this.file, fileViewer: this });

			this.contentBox.setContent(this.contentViewer);
			if(this.playing)
				this.play();
		}
	},

	getFile: function() {
		return this.file;
	},

	getUploader: function() {
		return this.uploader;
	},

	getTools: function() {
		return this.tools;
	},

	appendTool: function(tool) {
		this.tools.push(tool);
		this.fireEvent('toolschange', this, this.tools);
	},

	play: function() {
		if(this.contentViewer === undefined) {
			this.playing = true;
		}
		else {
			if('play' in this.contentViewer) {
				this.connect(this.contentViewer, 'end', this.onPlayEnd);
				this.contentViewer.play();
			}
			else {
				var duration = 5;
				if('duration' in this.file.meta)
					duration = parseFloat(this.file.meta.duration);
				new Core.DelayedTask({ scope: this, delay: duration, callback: this.onPlayEnd });
			}
		}
	},

	current: function() {
//		console.log('FileViewer current storage: '+this.storage+', file: '+this.file.id);
		if((this.contentBox.getChildren().length > 0) && ('current' in this.contentBox.getChildren()[0]))
			this.contentBox.getChildren()[0].current();
	},

	uncurrent: function() {
//		console.log('FileViewer uncurrent storage: '+this.storage+', file: '+this.file.id);
		if((this.contentBox.getChildren().length > 0) && ('uncurrent' in this.contentBox.getChildren()[0]))
			this.contentBox.getChildren()[0].uncurrent();
	},

	onPlayEnd: function() {
		this.playing = false;
		this.fireEvent('end', this);
	},

	deleteFile: function() {
		if(this.file !== undefined) {
			this.file.suppress();
			var request = new Core.HttpRequest({ method: 'DELETE', url: '/cloud/storage/'+this.storage+'/'+this.file.id });
			request.send();
		}
		else if(this.uploader != undefined)
			this.uploader.abort();
	},

	onFileChange: function() {
		if((this.contentViewer === undefined) || !('supportUpdate' in this.contentViewer) || !this.contentViewer.supportUpdate())
			this.buildContent();
	}

}, {
	onLoad: function() {
		Storage.FileViewer.base.onLoad.apply(this, arguments);
		this.connect(this.file, 'change', this.onFileChange);
		if(this.file.getIsReady())
			this.onFileChange();
		this.file.monitor();
	},

	onUnload: function() {
		Storage.FileViewer.base.onUnload.apply(this, arguments);
		this.disconnect(this.file, 'change', this.onFileChange);
		this.removeContent();
		this.file.unmonitor();
	}
});

Ui.LBox.extend('Storage.UploaderViewer', {
	uploader: undefined,
	progressbar: undefined,
	label: undefined,
	fileViewer: undefined,

	constructor: function(config) {
		this.uploader = config.uploader;
		delete(config.uploader);
		this.fileViewer = config.fileViewer;
		delete(config.fileViewer);

		var vbox = new Ui.VBox({ verticalAlign: 'center', horizontalAlign: 'center' });
		this.setContent(vbox);

		vbox.append(new Ui.Icon({ icon: 'uploadfile', fill: '#3f3f3f', width: 256, height: 256, horizontalAlign: 'center' }));

		this.progressbar = new Ui.ProgressBar({ width: 120, height: 10 });
		vbox.append(this.progressbar);

		if(this.uploader.getFile().getFileName() != undefined)
			vbox.append(new Ui.CompactLabel({ width: 256, maxLine: 3, textAlign: 'center', text: this.uploader.getFile().getFileName() }));

		this.connect(this.uploader, 'progress', this.onUploaderProgress);
	},

	onUploaderProgress: function(uploader, loaded, total) {
		this.progressbar.setValue(loaded/total);
	}
});

Ui.LBox.extend('Storage.DirectoryFileViewer', {
	storage: undefined,
	file: undefined,
	image: undefined,
	values: undefined,
	quality: false,
	fileViewer: undefined,
	transBox: undefined,
	playing: false,
	directoryChildren: undefined,
	position: undefined,

	constructor: function(config) {
		this.addEvents('end');

		this.storage = config.storage;
		delete(config.storage);
		this.file = config.file;
		delete(config.file);

		this.fileViewer = config.fileViewer;
		delete(config.fileViewer);

		this.transBox = new Ui.TransitionBox();
		this.setContent(this.transBox);

		var request = new Core.HttpRequest({ url: '/cloud/storage/'+this.storage+'/'+this.file.id+'?depth=1' });
		this.connect(request, 'done', function() {
			var json = request.getResponseJSON();
			this.directoryChildren = json.children;

			if(this.directoryChildren.length === 0) {
				if(this.playing)
					this.fireEvent('end', this);
			}
			else {
				this.position = 0;
				var fileViewer = new Storage.FileViewer({ storage: this.storage, file: json.children[this.position] });
				this.connect(fileViewer, 'end', this.onFileEnd);
				this.transBox.replaceContent(fileViewer);
				if(this.playing)
					fileViewer.play();
			}
		});
		request.send();
	},

	play: function() {
		this.playing = true;
		if((this.directoryChildren !== undefined) && (this.directoryChildren.length === 0))
			this.fireEvent('end', this);
		else if(this.transBox.getCurrent() !== undefined)
			this.transBox.getCurrent().play();
	},

	onFileEnd: function() {
		this.disconnect(this.transBox.getCurrent(), 'end', this.onFileEnd);
		this.position++;
		if(this.position >= this.directoryChildren.length)
			this.fireEvent('end', this);
		else {
			var fileViewer = new Storage.FileViewer({ storage: this.storage, file: this.directoryChildren[this.position] });
			this.connect(fileViewer, 'end', this.onFileEnd);
			this.transBox.replaceContent(fileViewer);
			fileViewer.play();
		}
	}
});

Ui.ScrollingArea.extend('Storage.ImageFileViewer', {
	file: undefined,
	image: undefined,
	values: undefined,
	quality: false,
	fileViewer: undefined,
	transformable: undefined,
	userInteraction: true,

	constructor: function(config) {

		this.file = config.file;
		delete(config.file);

		this.fileViewer = config.fileViewer;
		delete(config.fileViewer);

		this.setMaxScale(4);

		this.image = new KJing.ScaledImage2();
//		if((this.file.getMimetype() === 'image/png') ||
//		   (this.file.getMimetype() === 'image/jpeg') ||
//		   (this.file.getMimetype() === 'image/gif'))
//			this.image.setSrc(this.file.getDownloadUrl());
//		else
		if(this.file.getPreviewHighUrl() !== undefined)
			this.image.setSrc(this.file.getPreviewHighUrl());
		this.setContent(this.image);
	}
});

Ui.LBox.extend('Storage.GifImageFileViewer', {
	file: undefined,
	image: undefined,
	values: undefined,
	fileViewer: undefined,

	constructor: function(config) {
		this.file = config.file;
		delete(config.file);
		this.fileViewer = config.fileViewer;
		delete(config.fileViewer);
		this.image = new KJing.ScaledImage2();
		this.image.setSrc(this.file.getDownloadUrl());
		this.setContent(this.image);
	}
});

Ui.LBox.extend('Storage.SiteFileViewer', {
	storage: undefined,
	file: undefined,
	text: undefined,
	fileViewer: undefined,
	linkButton: undefined,

	constructor: function(config) {
		this.file = config.file;
		delete(config.file);
		this.fileViewer = config.fileViewer;
		delete(config.fileViewer);

		var request = new Core.HttpRequest({ method: 'GET', url: this.file.getDownloadUrl() });
		this.connect(request, 'done', this.onContentLoaded);
		request.send();

		var vbox = new Ui.VBox({ verticalAlign: 'center', horizontalAlign: 'center', spacing: 10 });
		this.setContent(vbox);

		var lbox = new Ui.LBox({ verticalAlign: 'bottom', horizontalAlign: 'center' });
		vbox.append(lbox);
		var image = new Ui.Image({ width: 128 });
		if(this.file.getPreviewUrl() !== undefined)
			image.setSrc(this.file.getPreviewUrl());
		lbox.append(image);
		this.connect(image, 'error', function() {
			lbox.setContent(new Ui.Icon({ icon: 'earth', verticalAlign: 'bottom', horizontalAlign: 'center', width: 128 }));
		});

		this.text = new Ui.Text({ textAlign: 'center', text: this.file.getName(), fontSize: 20 });
		vbox.append(this.text);

		this.linkButton = new Ui.LinkButton({ text: 'Ouvrir le site', horizontalAlign: 'center' });
		this.linkButton.disable();
		vbox.append(this.linkButton);
	},

	onContentLoaded: function(request) {
		//console.log('iframe: '+this.file.meta.iframe);

		// embed in a iframe
//		if((this.file.meta !== undefined) && (this.file.meta.iframe === 'true')) {
//			var iframe = new Ui.IFrame({ src: request.getResponseText() });
//			this.setContent(iframe);
//		}
//		else {
			this.linkButton.setSrc(request.getResponseText());
			this.linkButton.enable();
//		}
	}
});

Ui.LBox.extend('Storage.AudioFileViewer', {
	file: undefined,
	fileViewer: undefined,
	player: undefined,
	playing: false,

	constructor: function(config) {
		console.log('new Storage.AudioFileViewer');

		this.addEvents('end');

		this.file = config.file;
		delete(config.file);
		this.fileViewer = config.fileViewer;
		delete(config.fileViewer);
	},

	uncurrent: function() {
		if(this.player !== undefined)
			this.player.pause();
	},

	play: function() {
		this.playing = true;
		var support = !navigator.iOs && !navigator.Android;
		if((this.player !== undefined) && (support))
			this.player.play();
	},

	onMediaEnd: function() {
		this.fireEvent('end', this);
	},

	onFileChange: function() {
		console.log(this+'.onFileChange');
		console.log(this.file.getData());
		// no MP3 audio, sorry
		if(this.file.getData().audioMp3 === undefined) {
			this.setContent(new Ui.Text({ text: 'Impossible d\'écouter ce fichier son', verticalAlign: 'center', textAlign: 'center' }));
		}
		else {
			var audioMp3 = KJing.File.create(this.file.getData().audioMp3);
			if(audioMp3.getMimetype() === 'application/x-cache-progress') {
				var vbox = new Ui.VBox({ verticalAlign: 'center', spacing: 10 });
				vbox.append(new Ui.Loading({ width: 50, height: 50, horizontalAlign: 'center' }));
				vbox.append(new Ui.Text({ text: 'Encodage en cours... Veuillez patienter', textAlign: 'center' }));
			}
			// rock an roll
			else if(audioMp3.getMimetype() === 'audio/mpeg') {
				this.player = new KJing.AudioPlayer({ src: audioMp3.getDownloadUrl(), text: this.file.getName() });
				this.connect(this.player, 'end', this.onMediaEnd);
				this.setContent(this.player);
				if(this.playing)
					this.play();
			}
			// sorry no MP3
			else
				this.setContent(new Ui.Text({ text: 'Impossible d\'écouter ce fichier son', verticalAlign: 'center', textAlign: 'center' }));
		}
	}

}, {
	onVisible: function() {
		if(this.player === undefined) {
			this.connect(this.file, 'change', this.onFileChange);
			this.onFileChange();
		}
	},

	onHidden: function() {
		this.disconnect(this.file, 'change', this.onFileChange);
		if(this.player !== undefined)
			this.player.pause();
	}
});

Ui.Pressable.extend('Storage.VideoFileViewer', {
	file: undefined,
	fileViewer: undefined,
	player: undefined,
	playing: false,

	constructor: function(config) {
		this.addEvents('end');

		this.file = config.file;
		delete(config.file);
		this.fileViewer = config.fileViewer;
		delete(config.fileViewer);

		this.setLock(true);
		this.connect(this, 'press', this.onVideoPress);
	},

	onVideoEnd: function(player) {
		this.playing = false;
		this.fireEvent('end', this);
	},

	onVideoStateChange: function(player) {
		this.setLock(this.player.getIsControlsVisible());
	},

	onVideoPress: function() {
		if((this.player !== undefined) && (this.player.getState() == 'playing'))
			this.player.pause();
	},

	uncurrent: function() {
		if(this.player !== undefined)
			this.player.pause();
	},

	play: function() {
		this.playing = true;
		var support = !navigator.iOs && !navigator.Android;
		if((this.player !== undefined) && (support))
			this.player.play();
	},

	onFileChange: function() {
		// no MP4 video, sorry
		if(this.file.getData().videoMp4 === undefined) {
			this.setContent(new Ui.Text({ text: 'Impossible de lire ce fichier vidéo', verticalAlign: 'center', textAlign: 'center' }));
		}
		else {
			var videoMp4 = KJing.File.create(this.file.getData().videoMp4);
			if(videoMp4.getMimetype() === 'application/x-cache-progress') {
				var vbox = new Ui.VBox({ verticalAlign: 'center', spacing: 10 });
				vbox.append(new Ui.Loading({ width: 50, height: 50, horizontalAlign: 'center' }));
				vbox.append(new Ui.Text({ text: 'Encodage en cours... Veuillez patienter', textAlign: 'center' }));
			}
			// rock an roll
			else if(videoMp4.getMimetype() === 'video/mp4') {
				this.player = new KJing.VideoPlayer({ src: videoMp4.getDownloadUrl(), poster: this.file.getPreviewHighUrl() });
				this.connect(this.player, 'statechange', this.onVideoStateChange);
				this.connect(this.player, 'end', this.onVideoEnd);
				this.setContent(this.player);
				if(this.playing)
					this.play();
			}
			// sorry no MP4
			else
				this.setContent(new Ui.Text({ text: 'Impossible de lire ce fichier vidéo', verticalAlign: 'center', textAlign: 'center' }));
		}
	}
}, {
	onVisible: function() {
		if(this.player === undefined) {
			this.connect(this.file, 'change', this.onFileChange);
			this.onFileChange();
		}
	},

	onHidden: function() {
		this.disconnect(this.file, 'change', this.onFileChange);
		if(this.player !== undefined)
			this.player.pause();
	}
});

Ui.LBox.extend('Storage.TextFileViewer', {
	file: undefined,
	fileViewer: undefined,
	text: undefined,

	constructor: function(config) {
		this.storage = config.storage;
		delete(config.storage);
		this.file = config.file;
		delete(config.file);
		this.fileViewer = config.fileViewer;
		delete(config.fileViewer);

		var scalebox = new Ui.ScaleBox({ fixedWidth: 800, fixedHeight: 600 });
		this.setContent(scalebox);

		scalebox.append(new Ui.Rectangle({ fill: 'black' }));

		this.text = new Ui.Text({ margin: 20, style: { "Ui.Text": { fontSize: 40, color: 'white' } } });
		scalebox.append(this.text);

		var request = new Core.HttpRequest({ method: 'GET', url: this.file.getDownloadUrl() });
		this.connect(request, 'done', this.onTextLoaded);
		request.send();

		var button = new Ui.Button({ text: 'Edit', icon: 'edit' });
		this.connect(button, 'press', function() {
			var dialog = new Storage.TextEditor({ file: this.file });
			dialog.open();
			// find MenuPopup
			var popup = undefined;
			var current = button.getParent();
			while((popup === undefined) && (current !== undefined)) {
				if(Ui.Popup.hasInstance(current))
					popup = current;
				current = current.getParent();
			}
			if(popup !== undefined)
				popup.close();
		});
		this.fileViewer.appendTool(button);
	},

	onTextLoaded: function(req) {
		this.text.setText(req.getResponseText());
	}
});

Ui.CanvasElement.extend('Storage.PageBackgroundGraphic', {}, {
	updateCanvas: function(ctx) {
		var width = this.getLayoutWidth();
		var height = this.getLayoutHeight();
		// shadow
		ctx.roundRectFilledShadow(5, 5, width-10, height-10, 2, 2, 2, 2, false, 2, new Ui.Color({ r:0, g: 0, b: 0, a: 0.5}));
		// white bg
		ctx.fillStyle = '#ffffff';
		ctx.fillRect(7, 7, width-14, height-14);
	}
});

Ui.LBox.extend('Storage.RssItemFileViewer', {
	storage: undefined,
	file: undefined,
	fileViewer: undefined,
	title: undefined,
	content: undefined,

	constructor: function(config) {
		this.storage = config.storage;
		delete(config.storage);
		this.file = config.file;
		delete(config.file);
		this.fileViewer = config.fileViewer;
		delete(config.fileViewer);

		var scroll = new Ui.ScrollingArea({ scrollHorizontal: false, scrollVertical: true });
		this.setContent(scroll);

		var lbox = new Ui.LBox();
		lbox.append(new Storage.PageBackgroundGraphic());
		scroll.setContent(lbox);

		var vbox = new Ui.VBox({ margin: 20, spacing: 10 });
		lbox.append(vbox);

		this.title = new Ui.Text({ text: this.file.name, fontWeight: 'bold', fontSize: 24, marginTop: 20 });
		vbox.append(this.title);

		this.content = new Ui.Html();
		this.connect(this.content, 'link', this.onContentLink);
		vbox.append(this.content);

		var request = new Core.HttpRequest({ method: 'GET', url: '/cloud/storage/'+this.storage+'/'+this.file.id+'/content?rev='+this.file.rev });
		this.connect(request, 'done', this.onTextLoaded);
		request.send();
	},

	onTextLoaded: function(req) {
		var html = '
';
		html += (new Date(this.file.meta.pubDate)).toLocaleString()+'  ';
		if(this.file.meta.link != undefined)
			html += 'article complet
';
		html += '
';
		html += req.getResponseText();
		html += '
';
		this.content.setHtml(html);
	},

	onContentLink: function(html, url) {
		window.open(url, '_blank');
	}
});

Ui.CanvasElement.extend('Storage.PdfPageGraphic', {
	src: undefined,
	image: undefined,
	ratio: 1,

	constructor: function(config) {
		this.src = config.src;
		delete(config.src);
		this.ratio = config.ratio;
		delete(config.ratio);

		this.image = new Ui.Image({ src: this.src });
		this.connect(this.image, 'ready', this.onImageReady);
		this.appendChild(this.image);
	},

	onImageReady: function() {
		this.invalidateDraw();
	}
}, {
	measureCore: function(width, height) {
		return { width: width, height: ((width-14)/this.ratio)+14 };
	},

	updateCanvas: function(ctx) {
		var width = this.getLayoutWidth();
		var height = this.getLayoutHeight();
		// shadow
		ctx.roundRectFilledShadow(5, 5, width-10, height-10, 2, 2, 2, 2, false, 2, new Ui.Color({ r:0, g: 0, b: 0, a: 0.5}));
		// white bg
		ctx.fillStyle = '#ffffff';
		ctx.fillRect(7, 7, width-14, height-14);
		// image
		if(this.image.getIsReady())
			ctx.drawImage(this.image.getDrawing(), 0, 0, this.image.getNaturalWidth(), this.image.getNaturalHeight(), 7, 7, width-14, height-14);
	}
});

Ui.ScrollingArea.extend('Storage.PdfPage', {
	file: undefined,

	constructor: function(config) {
		this.file = config.file;
		delete(config.file);

		this.setMaxScale(4);
		this.setContent(new KJing.ScaledImage2({ src: this.file.getDownloadUrl() }));
	}
});

Ui.CarouselableLoader.extend('Storage.PdfPagesLoader', {
	file: undefined,
	pages: undefined,

	constructor: function(config) {
		this.file = config.file;
		delete(config.file);

		console.log(this.file);

		this.pages = this.file.getData().pdfPages.cacheChildren;
	}
}, {
	getMin: function() {
		return 0;
	},

	getMax: function() {
		return this.pages.length - 1;
	},

	getElementAt: function(position) {
		return new Storage.PdfPage({ file: KJing.File.create(this.pages[position]) });
	}
});

Ui.LBox.extend('Storage.PdfFileViewer', {
	file: undefined,
	fileViewer: undefined,
	data: undefined,
	isCurrent: false,
	carousel: undefined,
	loader: undefined,
	checkTask: undefined,
	request: undefined,
	position: 0,

	constructor: function(config) {
		this.file = config.file;
		delete(config.file);
		this.fileViewer = config.fileViewer;
		delete(config.fileViewer);

		this.onPagesReady();
	},

	onPagesReady: function() {
		this.loader = new Storage.PdfPagesLoader({ file: this.file });
		this.carousel = new Ui.Carousel3({ loader: this.loader });
		this.setContent(this.carousel);
	}
});

Ui.LBox.extend('Storage.GenericFileViewer', {
	file: undefined,
	text: undefined,
	fileViewer: undefined,

	constructor: function(config) {
		this.file = config.file;
		delete(config.file);
		this.fileViewer = config.fileViewer;
		delete(config.fileViewer);

		var vbox = new Ui.VBox({ verticalAlign: 'center', horizontalAlign: 'center', spacing: 10 });
		this.setContent(vbox);

		vbox.append(new Ui.Icon({ icon: 'file', width: 128, height: 128, horizontalAlign: 'center' }));

		this.text = new Ui.Text({ textAlign: 'center', text: this.file.getName(), fontSize: 20 });
		vbox.append(this.text);

		var downloadButton = new Ui.DownloadButton({ text: 'Télécharger', horizontalAlign: 'center' });
		downloadButton.setSrc(this.file.getDownloadUrl(true));
		vbox.append(downloadButton);
	}
});
*/


text:
BUILDS=$1

. ./env.sh

set -e

if [ "$SSH_PUBLIC_KEY_FILE" != "" ] && [ ! -f "$SSH_PUBLIC_KEY_FILE" ];
    then
    echo "The SSH public key ($SSH_PUBLIC_KEY_FILE) wasn't provided"
    exit 1
fi

if [ "$BUILD_FILE" != "" ] && [ ! -f "$BUILD_FILE" ]
    then
    echo "The build file ($BUILD_FILE) file couldn't be found"
    exit 1
fi

if [ "$BUILDS" == "" ];
    then
    echo "Please specify a builder from $BUILD_FILE: "
    packer inspect $BUILD_FILE -machine-readable|grep template-builder|cut -d',' -f4
    exit 1
fi

echo Building: $BOX_NAME
echo Builders: $BUILDS
echo Build file: $BUILD_FILE

if [ $(VBoxManage list vms|grep "$BOX_NAME"|wc -l) == 1 ]
    then
    echo "VirtualBox has a registered VM named $BOX_NAME - please remove this before continuing."
    exit 1
fi

packer validate -var 'vm_name'="$BOX_NAME" -only=$BUILDS $BUILD_FILE

packer build \
    -only=$BUILDS \
    -var ssh_public_key_file=$SSH_PUBLIC_KEY_FILE \
    -var vm_name=$BOX_NAME \
    $BUILD_FILE


text:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="org.hibernate.test.fileimport">
    <class name="Dog" table="dog">
        <id name="id"/>
        <many-to-one name="master" column="master_fk"/>
    </class>
</hibernate-mapping>


text:
namespace base {

namespace internal {

namespace {
#if !defined(OS_NACL)
const struct sched_param kRealTimePrio = {8};
#endif
}  // namespace

const ThreadPriorityToNiceValuePair kThreadPriorityToNiceValueMap[4] = {
    {ThreadPriority::BACKGROUND, 10},
    {ThreadPriority::NORMAL, 0},
    {ThreadPriority::DISPLAY, -6},
    {ThreadPriority::REALTIME_AUDIO, -10},
};

bool SetCurrentThreadPriorityForPlatform(ThreadPriority priority) {
#if !defined(OS_NACL)
  return priority == ThreadPriority::REALTIME_AUDIO &&
         pthread_setschedparam(pthread_self(), SCHED_RR, &kRealTimePrio) == 0;
#else
  return false;
#endif
}

bool GetCurrentThreadPriorityForPlatform(ThreadPriority* priority) {
#if !defined(OS_NACL)
  int maybe_sched_rr = 0;
  struct sched_param maybe_realtime_prio = {0};
  if (pthread_getschedparam(pthread_self(), &maybe_sched_rr,
                            &maybe_realtime_prio) == 0 &&
      maybe_sched_rr == SCHED_RR &&
      maybe_realtime_prio.sched_priority == kRealTimePrio.sched_priority) {
    *priority = ThreadPriority::REALTIME_AUDIO;
    return true;
  }
#endif
  return false;
}

}  // namespace internal

// static
void PlatformThread::SetName(const std::string& name) {
  ThreadIdNameManager::GetInstance()->SetName(CurrentId(), name);
  tracked_objects::ThreadData::InitializeThreadContext(name);

#if !defined(OS_NACL)
  // On FreeBSD we can get the thread names to show up in the debugger by
  // setting the process name for the LWP.  We don't want to do this for the
  // main thread because that would rename the process, causing tools like
  // killall to stop working.
  if (PlatformThread::CurrentId() == getpid())
    return;
  setproctitle("%s", name.c_str());
#endif  //  !defined(OS_NACL)
}

void InitThreading() {}

void TerminateOnThread() {}

size_t GetDefaultThreadStackSize(const pthread_attr_t& attributes) {
#if !defined(THREAD_SANITIZER)
  return 0;
#else
  // ThreadSanitizer bloats the stack heavily. Evidence has been that the
  // default stack size isn't enough for some browser tests.
  return 2 * (1 << 23);  // 2 times 8192K (the default stack size on Linux).
#endif
}

}  // namespace base


text:
package at.diamonddogs.service.processor;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import at.diamonddogs.data.adapter.ReplyAdapter;
import at.diamonddogs.data.dataobjects.CacheInformation;
import at.diamonddogs.data.dataobjects.Reply;
import at.diamonddogs.data.dataobjects.Request;
import at.diamonddogs.data.dataobjects.WebReply;
import at.diamonddogs.data.dataobjects.WebRequest;
import at.diamonddogs.util.CacheManager;
import at.diamonddogs.util.CacheManager.CachedObject;
import at.diamonddogs.util.Utils;

// @formatter:off
/**
 * Abstract class required to process data from services. For performance and
 * complexity reasons it is deprecated to save the state of a processing
 * operation, since the processor can be called from multiple threads at once.
 *
 * Message Format (Error and Success):
 *
 * android-http 1.0
 * 1) m.what - _MUST_ be the processorID
 * 2) m.arg1 - _MUST_ be either {@link ServiceProcessor#RETURN_MESSAGE_FAIL} or {@link ServiceProcessor#RETURN_MESSAGE_OK}
 * 3) The {@link Request} must be provided using {@link ServiceProcessor#BUNDLE_EXTRA_MESSAGE_REQUEST} as bundle key
 * 4) A {@link Throwable} should be provided using {@link ServiceProcessor#BUNDLE_EXTRA_MESSAGE_THROWABLE} as {@link Bundle} key, IF {@link Message#arg1} == {@link ServiceProcessor#RETURN_MESSAGE_FAIL}
 *
 * android-http 1.0+
 * 5) The {@link Reply} must be provided using {@link ServiceProcessor#BUNDLE_EXTRA_MESSAGE_REPLY} as bundle key UNLESS the object was obtained from cache
 * 6) The http status code must be provided using {@link ServiceProcessor#BUNDLE_EXTRA_MESSAGE_HTTPSTATUSCODE} as {@link Bundle} key UNLESS the object was obtained from cache OR if an error prevents access to the http status code
 * 7) Payload, which is defined as the result of the {@link WebRequest}, processed by a {@link ServiceProcessor} must be saved in m.obj
 * 8) The {@link ServiceProcessor#BUNDLE_EXTRA_MESSAGE_FROMCACHE} must be used to indicate if the Object was obtained from the cache or the {@link WebRequest}, {@link Boolean} flag!
 *
 * @param <OUTPUT>
 *            the type out output {@link Object} the subclass will produce.
 */
// @formatter:on
public abstract class ServiceProcessor<OUTPUT> {

	private static final Logger LOGGER = LoggerFactory.getLogger(ServiceProcessor.class.getSimpleName());

	/**
	 * Constant that indicates failure
	 */
	public static final int RETURN_MESSAGE_FAIL = 0;

	/**
	 * Constant that indicated success
	 */
	public static final int RETURN_MESSAGE_OK = 1;

	/**
	 * {@link Bundle} key for {@link Throwable}s caused during processing
	 */
	public static final String BUNDLE_EXTRA_MESSAGE_THROWABLE = "BUNDLE_EXTRA_MESSAGE_THROWABLE";

	/**
	 * {@link Bundle} key for the {@link Request} that was processed
	 */
	public static final String BUNDLE_EXTRA_MESSAGE_REQUEST = "BUNDLE_EXTRA_MESSAGE_REQUEST";

	/**
	 * {@link Bundle} key for the {@link Reply} that was processed
	 */
	public static final String BUNDLE_EXTRA_MESSAGE_REPLY = "BUNDLE_EXTRA_MESSAGE_REPLY";

	/**
	 * {@link Bundle} key for the HTTP status code returned by the operation
	 */
	public static final String BUNDLE_EXTRA_MESSAGE_HTTPSTATUSCODE = "BUNDLE_EXTRA_MESSAGE_HTTPSTATUSCODE";

	/**
	 * {@link Bundle} key that indicates if the result of a {@link WebRequest}
	 * was taken from the cache
	 */
	public static final String BUNDLE_EXTRA_MESSAGE_FROMCACHE = "BUNDLE_EXTRA_MESSAGE_FROMCACHE";

	/**
	 * Called when a {@link Reply} is ready for processing
	 *
	 * @param c
	 *            a {@link Context}
	 * @param r
	 *            a {@link ReplyAdapter} containing {@link Request} and
	 *            {@link Reply}
	 * @param handler
	 *            the {@link Handler} instance that posts the result of the
	 *            {@link Request} to the UI thread
	 */
	public abstract void processWebReply(Context c, ReplyAdapter r, Handler handler);

	/**
	 * Called if there is a {@link CachedObject} available for the
	 * {@link Request} that is being processed
	 *
	 * @param cachedObject
	 *            the {@link CachedObject} related to the {@link Request}
	 * @param handler
	 *            the {@link Handler} instance that posts the result of the
	 *            {@link Request} to the UI thread
	 * @param request
	 *            the {@link Request} that is being processed
	 */
	public abstract void processCachedObject(CachedObject cachedObject, Handler handler, Request request);

	/**
	 * Called if there is a {@link CachedObject} available for the
	 * {@link Request} that is being processed, defaults to the old
	 * implementation.
	 *
	 * @param cachedObject
	 *            the {@link CachedObject} related to the {@link Request}
	 * @param handler
	 *            the {@link Handler} instance that posts the result of the
	 *            {@link Request} to the UI thread
	 * @param request
	 *            the {@link Request} that is being processed
	 * @param context
	 *            the {@link Context} that is used
	 */
	public void processCachedObject(CachedObject cachedObject, Handler handler, Request request, Context context) {
		processCachedObject(cachedObject, handler, request);
	}

	/**
	 * Returns the ID of the processor
	 *
	 * @return the id of the processor
	 */
	public abstract int getProcessorID();

	/**
	 * @deprecated don't use, only for backwards compatibility
	 */
	@Deprecated
	protected void cacheObjectToFile(Context context, WebRequest request, byte[] data) {
		cacheObjectToFile(context, request, data, false);
	}

	/**
	 * Writes {@link WebRequest} specific data to the cache. Ignores
	 * {@link WebRequest} whose {@link WebRequest#getCacheTime()} is
	 * {@link CacheInformation#CACHE_NO}. This method disables
	 * {@link CacheInformation}s offline caching feature.
	 *
	 * @param context
	 *            a {@link Context}
	 * @param r
	 *            a {@link ReplyAdapter}
	 * @see CacheInformation#useOfflineCache
	 */
	protected void cacheObjectToFile(Context context, ReplyAdapter r) {
		cacheObjectToFile(context, (WebRequest) r.getRequest(), ((WebReply) r.getReply()).getData(), false);
	}

	/**
	 * Writes {@link WebRequest} specific data to the cache. Ignores
	 * {@link WebRequest} whose {@link WebRequest#getCacheTime()} is
	 * {@link CacheInformation#CACHE_NO}
	 *
	 * @param context
	 *            a {@link Context}
	 * @param r
	 *            a {@link ReplyAdapter}
	 * @param useOfflineCache
	 *            controls {@link CacheInformation}s useOfflineCache parameter
	 *
	 * @see CacheInformation#useOfflineCache
	 */
	protected void cacheObjectToFile(Context context, ReplyAdapter r, boolean useOfflineCache) {
		cacheObjectToFile(context, (WebRequest) r.getRequest(), ((WebReply) r.getReply()).getData(), useOfflineCache);
	}

	/**
	 * Writes {@link WebRequest} specific data to the cache. Ignores
	 * {@link WebRequest} whose {@link WebRequest#getCacheTime()} is
	 * {@link CacheInformation#CACHE_NO}
	 *
	 * @param context
	 *            a {@link Context}
	 * @param request
	 *            the {@link WebRequest} whose data will be saved to the cache
	 * @param data
	 *            the actual data
	 * @param useOfflineCache
	 *            controls {@link CacheInformation}s useOfflineCache parameter
	 *
	 * @see CacheInformation#useOfflineCache
	 */
	protected void cacheObjectToFile(Context context, WebRequest request, byte[] data, boolean useOfflineCache) {
		String filename = Utils.getMD5Hash(request.getUrl().toString());
		BufferedOutputStream bos = null;
		try {
			if (filename != null && data != null) {
				if (request.getCacheTime() != CacheInformation.CACHE_NO) {
					File path = Utils.getCacheDir(context);
					FileOutputStream fos = new FileOutputStream(new File(path, filename));
					bos = new BufferedOutputStream(fos);
					bos.write(data);

					CacheInformation ci = createCachingInformation(request.getCacheTime(), path.toString(), filename, useOfflineCache);

					CacheManager cm = CacheManager.getInstance();
					cm.addToCache(context, ci);
				}
			}
		} catch (Throwable th) {
		} finally {
			if (bos != null) {
				try {
					bos.close();
				} catch (IOException e) {
					bos = null;
				}
			}
		}
	}

	private CacheInformation createCachingInformation(long chacheTime, String filePath, String fileName, boolean useOfflineCache) {
		CacheInformation c = new CacheInformation();
		c.setCacheTime(chacheTime);
		c.setCreationTimeStamp(System.currentTimeMillis());
		c.setFileName(fileName);
		c.setFilePath(filePath);
		c.setUseOfflineCache(useOfflineCache);
		return c;
	}

	/**
	 * Use this method to create a return {@link Message} if the result of the
	 * {@link WebRequest} was obtained from the web rather than the cache
	 *
	 * @param replyAdapter
	 *            the {@link ReplyAdapter} that was passed to
	 *            {@link ServiceProcessor#processWebReply(Context, ReplyAdapter, Handler)}
	 * @param payload
	 *            the processed data
	 * @return a {@link Message} object containing all required return data
	 */
	protected Message createReturnMessage(ReplyAdapter replyAdapter, OUTPUT payload) {
		Message m = Message.obtain();
		m.what = getProcessorID();
		m.arg1 = ServiceProcessor.RETURN_MESSAGE_OK;
		m.obj = payload;
		Bundle dataBundle = new Bundle();
		dataBundle.putSerializable(BUNDLE_EXTRA_MESSAGE_REPLY, (WebReply) replyAdapter.getReply());
		dataBundle.putSerializable(BUNDLE_EXTRA_MESSAGE_REQUEST, (WebRequest) replyAdapter.getRequest());
		dataBundle.putInt(BUNDLE_EXTRA_MESSAGE_HTTPSTATUSCODE, ((WebReply) replyAdapter.getReply()).getHttpStatusCode());
		dataBundle.putSerializable(BUNDLE_EXTRA_MESSAGE_FROMCACHE, false);
		m.setData(dataBundle);
		return m;
	}

	/**
	 * Use this method to create a return {@link Message} if the result of the
	 * {@link WebRequest} was obtained from the cache rather than the web
	 *
	 * @param webRequest
	 *            the {@link WebRequest} that is the root of this reply
	 * @param payload
	 *            the processed data
	 * @return a {@link Message} object containing all required return data
	 */
	protected Message createReturnMessage(WebRequest webRequest, OUTPUT payload) {
		Message m = Message.obtain();
		m.what = getProcessorID();
		m.arg1 = ServiceProcessor.RETURN_MESSAGE_OK;
		m.obj = payload;
		Bundle dataBundle = new Bundle();
		dataBundle.putSerializable(BUNDLE_EXTRA_MESSAGE_REQUEST, webRequest);
		dataBundle.putSerializable(BUNDLE_EXTRA_MESSAGE_FROMCACHE, true);
		m.setData(dataBundle);
		return m;
	}

	/**
	 * Creates a default error message for a {@link WebRequest}
	 *
	 * @param tr
	 *            the {@link Throwable} related to the error
	 * @param replyAdapter
	 *            the instance of {@link ReplyAdapter} that was the result of
	 *            the {@link WebRequest}
	 * @return an error {@link Message} object
	 */
	public Message createErrorMessage(Throwable tr, ReplyAdapter replyAdapter) {
		Message m = Message.obtain();
		m.what = getProcessorID();
		m.arg1 = RETURN_MESSAGE_FAIL;
		Bundle b = new Bundle(1);
		b.putSerializable(BUNDLE_EXTRA_MESSAGE_THROWABLE, tr == null ? new Throwable("Unknown Error") : tr);
		b.putSerializable(BUNDLE_EXTRA_MESSAGE_REQUEST, (WebRequest) replyAdapter.getRequest());
		b.putSerializable(BUNDLE_EXTRA_MESSAGE_REPLY, (WebReply) replyAdapter.getReply());
		b.putSerializable(BUNDLE_EXTRA_MESSAGE_FROMCACHE, false);
		if (replyAdapter.getReply() != null) {
			b.putInt(BUNDLE_EXTRA_MESSAGE_HTTPSTATUSCODE, ((WebReply) replyAdapter.getReply()).getHttpStatusCode());
		}
		m.setData(b);
		return m;
	}

	/**
	 * Creates a default error message for a {@link WebRequest}. Creates and
	 * provides a new {@link Throwable}.
	 *
	 * @param replyAdapter
	 *            the instance of {@link ReplyAdapter} that was the result of
	 *            the {@link WebRequest}
	 * @return an error {@link Message} object
	 */
	public Message createErrorMessage(ReplyAdapter replyAdapter) {
		Message m = Message.obtain();
		m.what = getProcessorID();
		m.arg1 = RETURN_MESSAGE_FAIL;
		Bundle b = new Bundle(1);
		b.putSerializable(BUNDLE_EXTRA_MESSAGE_THROWABLE, replyAdapter.getThrowable() == null ? new Throwable("Unknown error")
			: replyAdapter.getThrowable());
		b.putSerializable(BUNDLE_EXTRA_MESSAGE_REQUEST, (WebRequest) replyAdapter.getRequest());
		b.putSerializable(BUNDLE_EXTRA_MESSAGE_REPLY, (WebReply) replyAdapter.getReply());
		b.putSerializable(BUNDLE_EXTRA_MESSAGE_FROMCACHE, false);
		if (replyAdapter.getReply() != null) {
			b.putInt(BUNDLE_EXTRA_MESSAGE_HTTPSTATUSCODE, ((WebReply) replyAdapter.getReply()).getHttpStatusCode());
		}
		m.setData(b);
		return m;
	}

	/**
	 * Creates a default error message for a {@link WebRequest}. Use this method
	 * when dealing with errors caused by cache retrieval.
	 *
	 * @param tr
	 *            a {@link Throwable} explaining the error
	 * @param webRequest
	 *            the {@link WebRequest} that caused the error to appear
	 * @return a {@link Message} {@link Object}
	 */
	public Message createErrorMessage(Throwable tr, WebRequest webRequest) {
		Message m = Message.obtain();
		m.what = getProcessorID();
		m.arg1 = RETURN_MESSAGE_FAIL;
		Bundle b = new Bundle(1);
		b.putSerializable(BUNDLE_EXTRA_MESSAGE_THROWABLE, tr);
		b.putSerializable(BUNDLE_EXTRA_MESSAGE_REQUEST, webRequest);
		b.putSerializable(BUNDLE_EXTRA_MESSAGE_FROMCACHE, true);
		m.setData(b);
		return m;
	}

	/**
	 * Creates a default error message for a {@link WebRequest}. Creates and
	 * provides a new {@link Throwable}. Use this method when dealing with
	 * errors caused by cache retrieval.
	 *
	 * @param webRequest
	 *            the {@link WebRequest} that caused the error to appear
	 * @return a {@link Message} {@link Object}
	 */
	public Message createErrorMessage(WebRequest webRequest) {
		Message m = Message.obtain();
		m.what = getProcessorID();
		m.arg1 = RETURN_MESSAGE_FAIL;
		Bundle b = new Bundle(1);
		b.putSerializable(BUNDLE_EXTRA_MESSAGE_THROWABLE, new Throwable("Unknown error"));
		b.putSerializable(BUNDLE_EXTRA_MESSAGE_REQUEST, webRequest);
		b.putSerializable(BUNDLE_EXTRA_MESSAGE_FROMCACHE, true);
		m.setData(b);
		return m;
	}

	protected boolean getBoolean(String s) {
		if (isStringEmpty(s)) {
			return false;
		}
		try {
			return Boolean.parseBoolean(s);
		} catch (Throwable tr) {
			LOGGER.warn("Could not parse: ", tr);
			return false;
		}
	}

	protected byte getByte(String s) {
		if (isStringEmpty(s)) {
			return 0;
		}
		try {
			return Byte.parseByte(s);
		} catch (Throwable tr) {
			LOGGER.warn("Could not parse: ", tr);
			return 0;
		}
	}

	protected short getShort(String s) {
		if (isStringEmpty(s)) {
			return 0;
		}
		try {
			return Short.parseShort(s);
		} catch (Throwable tr) {
			LOGGER.warn("Could not parse: ", tr);
			return 0;
		}
	}

	protected char getChar(String s) {
		if (isStringEmpty(s) || s.length() != 1) {
			return '\0';
		}
		try {
			return s.charAt(0);
		} catch (Throwable tr) {
			LOGGER.warn("Could not parse: ", tr);
			return '\0';
		}
	}

	protected int getInt(String s) {
		if (isStringEmpty(s)) {
			return 0;
		}
		try {
			return Integer.parseInt(s);
		} catch (Throwable tr) {
			LOGGER.warn("Could not parse: ", tr);
			return 0;
		}
	}

	protected long getLong(String s) {
		if (isStringEmpty(s)) {
			return 0;
		}
		try {
			return Long.parseLong(s);
		} catch (Throwable tr) {
			LOGGER.warn("Could not parse: ", tr);
			return 0;
		}
	}

	protected float getFloat(String s) {
		if (isStringEmpty(s)) {
			return 0.0f;
		}
		try {
			return Float.parseFloat(s);
		} catch (Throwable tr) {
			LOGGER.warn("Could not parse: ", tr);
			return 0.0f;
		}
	}

	protected double getDouble(String s) {
		if (isStringEmpty(s)) {
			return 0.0d;
		}
		try {
			return Double.parseDouble(s);
		} catch (Throwable tr) {
			LOGGER.warn("Could not parse: ", tr);
			return 0.0d;
		}
	}

	protected <T extends Enum<T>> T getEnum(String s, Class<T> cls) {
		try {
			if (s.equals("")) {
				return null;
			}
			return Enum.valueOf(cls, s);
		} catch (Throwable tr) {
			LOGGER.warn("Could not parse: ", tr);
			return null;
		}
	}

	protected Date getDate(String s, String format) {
		try {
			SimpleDateFormat formatter = new SimpleDateFormat(format);
			return formatter.parse(s);
		} catch (Throwable tr) {
			LOGGER.warn("Could not parse: ", tr);
			return null;
		}
	}

	protected Date getDate(String s, DateFormat formatter) {
		try {
			return formatter.parse(s);
		} catch (Throwable tr) {
			LOGGER.warn("Could not parse: ", tr);
			return null;
		}
	}

	protected boolean isStringEmpty(String string) {
		return string == null || string.length() == 0;
	}
}


text:
/*
Accounts.onCreateUser(function(options, user){
    var newEmail = user.emails[0].address;
    console.log(newEmail);
    var emailAlreadyExist = Meteor.users.find({"emails.address": newEmail}, {limit: 1}).count() > 0;
    console.log(emailAlreadyExist + ' exitence');
    if(emailAlreadyExist === true) {
        throw new Meteor.Error(403, "email already registered");
    }
    else {
        profile = options.profile;
        profile.nameOfArray = [];
        user.profile = profile;
        return user;
    }
});
*/