text:
<?xml version="1.0" encoding="utf-8"?>

<!--
  ~ Copyright (C) 2015 Actor LLC. <https://actor.im>
  -->

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ScrollView
        android:id="@+id/scrollContainer"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fillViewport="true">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <FrameLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content">

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="vertical">

                    <FrameLayout
                        android:layout_width="fill_parent"
                        android:layout_height="248dp"
                        android:orientation="horizontal">

                        <ImageView
                            android:id="@+id/avatar_bgrnd"
                            android:layout_width="match_parent"
                            android:layout_height="match_parent"
                            android:scaleType="centerCrop" />

                        <im.actor.sdk.view.avatar.CoverAvatarView
                            android:id="@+id/avatar"
                            android:layout_width="match_parent"
                            android:layout_height="match_parent" />

                        <LinearLayout
                            android:layout_width="match_parent"
                            android:layout_height="64dp"
                            android:layout_gravity="bottom"
                            android:gravity="center_vertical|left"
                            android:orientation="vertical"
                            android:paddingLeft="72dp"
                            android:paddingRight="24dp">

                            <TextView
                                android:id="@+id/name"
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:layout_marginTop="-2dp"
                                android:ellipsize="end"
                                android:includeFontPadding="false"
                                android:lines="1"
                                android:singleLine="true"
                                android:textSize="26sp" />

                        </LinearLayout>

                    </FrameLayout>

                    <FrameLayout
                        android:id="@+id/before_nick_container"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content" />

                    <LinearLayout
                        android:id="@+id/nickContainer"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:orientation="vertical">

                    </LinearLayout>

                    <FrameLayout
                        android:id="@+id/about"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:background="@drawable/selector"
                        android:clickable="true">

                        <LinearLayout
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:orientation="horizontal">

                            <ImageView
                                android:id="@+id/recordIcon"
                                android:layout_width="24dp"
                                android:layout_height="24dp"
                                android:layout_marginBottom="24dp"
                                android:layout_marginLeft="16dp"
                                android:layout_marginRight="32dp"
                                android:layout_marginTop="16dp" />

                            <LinearLayout
                                android:layout_width="match_parent"
                                android:layout_height="wrap_content"
                                android:layout_gravity="center_vertical"
                                android:gravity="center_vertical"
                                android:orientation="vertical">

                                <TextView
                                    android:id="@+id/value"
                                    android:layout_width="match_parent"
                                    android:layout_height="wrap_content"
                                    android:textSize="18sp"
                                    android:paddingRight="20dp" />

                                <TextView
                                    android:id="@+id/title"
                                    android:layout_width="match_parent"
                                    android:layout_height="wrap_content"
                                    android:textSize="16sp"
                                    android:layout_marginBottom="10dp"
                                    android:paddingRight="20dp" />
                            </LinearLayout>
                        </LinearLayout>

                        <View
                            android:id="@+id/divider"
                            android:layout_width="match_parent"
                            android:layout_height="@dimen/div_size"
                            android:layout_gravity="bottom"
                            android:layout_marginLeft="72dp"
                            android:background="@android:color/holo_red_dark" />
                    </FrameLayout>

                    <LinearLayout
                        android:id="@+id/phoneContainer"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:orientation="vertical">

                    </LinearLayout>

                    <FrameLayout
                        android:id="@+id/after_phone_container"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content" />

                    <FrameLayout
                        android:id="@+id/wallpaperDivider"
                        android:layout_width="match_parent"
                        android:layout_height="16dp">

                        <View
                            android:layout_width="match_parent"
                            android:layout_height="4dp"
                            android:layout_gravity="top"
                            android:background="@drawable/card_shadow_bottom" />

                        <View
                            android:layout_width="match_parent"
                            android:layout_height="1dp"
                            android:layout_gravity="bottom"
                            android:background="@drawable/card_shadow_top" />
                    </FrameLayout>

                    <TextView
                        android:id="@+id/settings_wallpaper_title"
                        android:layout_width="match_parent"
                        android:layout_height="48dp"
                        android:gravity="center_vertical|left"
                        android:paddingLeft="72dp"
                        android:text="@string/wallpaper"
                        android:textSize="16sp" />

                    <HorizontalScrollView
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:requiresFadingEdge="none"
                        android:scrollbars="none">

                        <LinearLayout
                            android:id="@+id/background_container"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:orientation="horizontal">

                            <View
                                android:layout_width="72dp"
                                android:layout_height="90dp"
                                android:background="@android:color/transparent" />

                        </LinearLayout>
                    </HorizontalScrollView>

                    <FrameLayout
                        android:id="@+id/after_phone_divider"
                        android:layout_width="match_parent"
                        android:layout_height="16dp">

                        <View
                            android:layout_width="match_parent"
                            android:layout_height="4dp"
                            android:layout_gravity="top"
                            android:background="@drawable/card_shadow_bottom" />

                        <View
                            android:layout_width="match_parent"
                            android:layout_height="1dp"
                            android:layout_gravity="bottom"
                            android:background="@drawable/card_shadow_top" />
                    </FrameLayout>

                    <LinearLayout
                        android:id="@+id/before_settings_container"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:orientation="vertical" />

                    <TextView
                        android:id="@+id/settings_header_text"
                        android:layout_width="match_parent"
                        android:layout_height="48dp"
                        android:gravity="center_vertical|left"
                        android:paddingLeft="72dp"
                        android:text="@string/settings_header"
                        android:textSize="16sp" />

                    <FrameLayout
                        android:id="@+id/settings_top_container"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content" />

                    <LinearLayout
                        android:id="@+id/notifications"
                        android:layout_width="match_parent"
                        android:layout_height="48dp"
                        android:background="@drawable/selector"
                        android:clickable="true">

                        <im.actor.sdk.view.TintImageView
                            android:id="@+id/settings_notification_icon"
                            android:layout_width="24dp"
                            android:layout_height="match_parent"
                            android:layout_marginLeft="16dp"
                            android:layout_marginRight="32dp"
                            app:src="@drawable/ic_notifications_white_18dp" />

                        <TextView
                            android:id="@+id/settings_notifications_title"
                            android:layout_width="match_parent"
                            android:layout_height="match_parent"
                            android:gravity="left|center_vertical"
                            android:text="@string/settings_notifications"
                            android:textSize="16sp" />
                    </LinearLayout>

                    <View
                        android:id="@+id/divider1"
                        android:layout_width="match_parent"
                        android:layout_height="@dimen/div_size"
                        android:layout_marginLeft="72dp"
                        android:layout_marginRight="16dp" />

                    <LinearLayout
                        android:id="@+id/chatSettings"
                        android:layout_width="match_parent"
                        android:layout_height="48dp"
                        android:background="@drawable/selector"
                        android:clickable="true">

                        <im.actor.sdk.view.TintImageView
                            android:id="@+id/settings_chat_icon"
                            android:layout_width="24dp"
                            android:layout_height="match_parent"
                            android:layout_marginLeft="16dp"
                            android:layout_marginRight="32dp"
                            app:src="@drawable/ic_chat_white_18dp" />

                        <TextView
                            android:id="@+id/settings_chat_title"
                            android:layout_width="match_parent"
                            android:layout_height="match_parent"
                            android:gravity="left|center_vertical"
                            android:text="@string/settings_chat"
                            android:textSize="16sp" />
                    </LinearLayout>

                    <View
                        android:id="@+id/divider2"
                        android:layout_width="match_parent"
                        android:layout_height="@dimen/div_size"
                        android:layout_marginLeft="72dp"
                        android:layout_marginRight="16dp" />

                    <LinearLayout
                        android:id="@+id/encryption"
                        android:layout_width="match_parent"
                        android:layout_height="48dp"
                        android:background="@drawable/selector"
                        android:clickable="true">

                        <im.actor.sdk.view.TintImageView
                            android:id="@+id/settings_security_icon"
                            android:layout_width="24dp"
                            android:layout_height="match_parent"
                            android:layout_marginLeft="16dp"
                            android:layout_marginRight="32dp"
                            app:src="@drawable/ic_security_white_18dp" />

                        <TextView
                            android:id="@+id/settings_security_title"
                            android:layout_width="match_parent"
                            android:layout_height="match_parent"
                            android:gravity="left|center_vertical"
                            android:text="@string/settings_security"
                            android:textSize="16sp" />
                    </LinearLayout>

                    <View
                        android:id="@+id/divider7"
                        android:layout_width="match_parent"
                        android:layout_height="@dimen/div_size"
                        android:layout_marginLeft="72dp"
                        android:layout_marginRight="16dp" />

                    <LinearLayout
                        android:id="@+id/blockedList"
                        android:layout_width="match_parent"
                        android:layout_height="48dp"
                        android:background="@drawable/selector"
                        android:clickable="true">

                        <im.actor.sdk.view.TintImageView
                            android:id="@+id/settings_blocked_icon"
                            android:layout_width="24dp"
                            android:layout_height="match_parent"
                            android:layout_marginLeft="16dp"
                            android:layout_marginRight="32dp"
                            app:src="@drawable/ic_block_white_18dp" />

                        <TextView
                            android:id="@+id/settings_blocked_title"
                            android:layout_width="match_parent"
                            android:layout_height="match_parent"
                            android:gravity="left|center_vertical"
                            android:text="@string/settings_blocked_list"
                            android:textSize="16sp" />
                    </LinearLayout>

                    <View
                        android:id="@+id/divider3"
                        android:layout_width="match_parent"
                        android:layout_height="@dimen/div_size"
                        android:layout_marginLeft="72dp"
                        android:layout_marginRight="16dp" />

                    <LinearLayout
                        android:id="@+id/askQuestion"
                        android:layout_width="match_parent"
                        android:layout_height="48dp"
                        android:background="@drawable/selector"
                        android:clickable="true">

                        <im.actor.sdk.view.TintImageView
                            android:id="@+id/settings_ask_icon"
                            android:layout_width="24dp"
                            android:layout_height="match_parent"
                            android:layout_marginLeft="16dp"
                            android:layout_marginRight="32dp"
                            app:src="@drawable/ic_help_white_18dp" />

                        <TextView
                            android:id="@+id/settings_ask_title"
                            android:layout_width="match_parent"
                            android:layout_height="match_parent"
                            android:gravity="left|center_vertical"
                            android:text="@string/settings_ask"
                            android:textSize="16sp" />
                    </LinearLayout>

                    <View
                        android:id="@+id/divider5"
                        android:layout_width="match_parent"
                        android:layout_height="@dimen/div_size"
                        android:layout_marginLeft="72dp"
                        android:layout_marginRight="16dp" />

                    <LinearLayout
                        android:id="@+id/twitter"
                        android:layout_width="match_parent"
                        android:layout_height="48dp"
                        android:background="@drawable/selector"
                        android:clickable="true">

                        <im.actor.sdk.view.TintImageView
                            android:id="@+id/settings_twitter_icon"
                            android:layout_width="24dp"
                            android:layout_height="match_parent"
                            android:layout_marginLeft="16dp"
                            android:layout_marginRight="32dp"
                            app:src="@drawable/ic_twitterlogo_18dp" />

                        <TextView
                            android:id="@+id/settings_twitter"
                            android:layout_width="match_parent"
                            android:layout_height="match_parent"
                            android:gravity="left|center_vertical"
                            android:text="@string/settings_twitter"
                            android:textSize="16sp" />
                    </LinearLayout>

                    <View
                        android:id="@+id/divider6"
                        android:layout_width="match_parent"
                        android:layout_height="@dimen/div_size"
                        android:layout_marginLeft="72dp"
                        android:layout_marginRight="16dp" />

                    <LinearLayout
                        android:id="@+id/home_page"
                        android:layout_width="match_parent"
                        android:layout_height="48dp"
                        android:background="@drawable/selector"
                        android:clickable="true">

                        <im.actor.sdk.view.TintImageView
                            android:id="@+id/settings_home_page_icon"
                            android:layout_width="24dp"
                            android:layout_height="match_parent"
                            android:layout_marginLeft="16dp"
                            android:layout_marginRight="32dp"
                            app:src="@drawable/ic_home_page_18dp" />

                        <TextView
                            android:id="@+id/settings_home_page"
                            android:layout_width="match_parent"
                            android:layout_height="match_parent"
                            android:gravity="left|center_vertical"
                            android:text="@string/settings_home_page"
                            android:textSize="16sp" />
                    </LinearLayout>

                    <View
                        android:id="@+id/divider4"
                        android:layout_width="match_parent"
                        android:layout_height="@dimen/div_size"
                        android:layout_marginLeft="72dp"
                        android:layout_marginRight="16dp"
                        android:visibility="gone" />

                    <LinearLayout
                        android:id="@+id/helpSettings"
                        android:layout_width="match_parent"
                        android:layout_height="48dp"
                        android:background="@drawable/selector"
                        android:clickable="true"
                        android:visibility="gone">

                        <im.actor.sdk.view.TintImageView
                            android:id="@+id/settings_help_icon"
                            android:layout_width="24dp"
                            android:layout_height="match_parent"
                            android:layout_marginLeft="16dp"
                            android:layout_marginRight="32dp"
                            app:src="@drawable/ic_help_white_18dp" />

                        <TextView
                            android:id="@+id/settings_help_title"
                            android:layout_width="match_parent"
                            android:layout_height="match_parent"
                            android:gravity="left|center_vertical"
                            android:text="@string/settings_help"
                            android:textSize="16sp" />
                    </LinearLayout>

                    <FrameLayout
                        android:id="@+id/settings_bottom_container"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content" />

                </LinearLayout>

                <com.getbase.floatingactionbutton.FloatingActionButton
                    android:id="@+id/profileAction"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="right|top"
                    android:layout_marginRight="6dp"
                    android:layout_marginTop="214dp"
                    android:visibility="gone"
                    app:fab_icon="@drawable/ic_share_white_24dp" />

            </FrameLayout>

            <FrameLayout
                android:id="@+id/bottom_divider"
                android:layout_width="match_parent"
                android:layout_height="16dp"
                android:layout_weight="1">

                <View
                    android:layout_width="match_parent"
                    android:layout_height="4dp"
                    android:layout_gravity="top"
                    android:background="@drawable/card_shadow_bottom" />

            </FrameLayout>

            <LinearLayout
                android:id="@+id/after_settings_container"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical" />

        </LinearLayout>
    </ScrollView>

    <View
        android:layout_width="match_parent"
        android:layout_height="56dp"
        android:layout_gravity="top"
        android:background="@drawable/profile_avatar_top_shadow" />
</FrameLayout>


text:
'use strict';

const path = require('path');
const express = require('express');
const onExit = require('signal-exit');
const Promise = require('bluebird');
const bodyParser = require('body-parser');
const {INTERNAL_SERVER_ERROR, OK} = require('http-codes');

const App = require('./app');
const {MAX_REQUEST_SIZE, KEEP_ALIVE_TIMEOUT, HEADERS_TIMEOUT} = require('./constants/server');
const {initializeCustomGui, runCustomGuiAction} = require('../server-utils');
const {logger} = require('../common-utils');
const initPluginsRoutes = require('./routes/plugins');

exports.start = async ({paths, hermione, guiApi, configs}) => {
    const {options, pluginConfig} = configs;
    const app = App.create(paths, hermione, configs);
    const server = express();

    server.use(bodyParser.json({limit: MAX_REQUEST_SIZE}));

    await guiApi.initServer(server);

    // allow plugins to precede default server routes
    server.use(initPluginsRoutes(express.Router(), pluginConfig));

    server.use(express.static(path.join(__dirname, '../static'), {index: 'gui.html'}));
    server.use(express.static(path.join(process.cwd(), pluginConfig.path)));

    server.get('/', (req, res) => res.sendFile(path.join(__dirname, '../static', 'gui.html')));

    server.get('/events', (req, res) => {
        res.writeHead(OK, {'Content-Type': 'text/event-stream'});

        app.addClient(res);
    });

    server.set('json replacer', (key, val) => {
        return typeof val === 'function' ? val.toString() : val;
    });

    server.get('/init', async (req, res) => {
        try {
            await initializeCustomGui(hermione, pluginConfig);
        } catch (e) {
            app.data.customGuiError = {
                response: {
                    status: INTERNAL_SERVER_ERROR,
                    data: `Error while trying to initialize custom GUI: ${e.message}`
                }
            };
        }

        res.json(app.data);
    });

    server.post('/run', (req, res) => {
        try {
            // do not wait for completion so that response does not hang and browser does not restart it by timeout
            app.run(req.body);
            res.sendStatus(OK);
        } catch (e) {
            res.status(INTERNAL_SERVER_ERROR).send(`Error while trying to run tests: ${e.message}`);
        }
    });

    server.post('/run-custom-gui-action', async ({body: payload}, res) => {
        try {
            await runCustomGuiAction(hermione, pluginConfig, payload);
            res.sendStatus(OK);
        } catch (e) {
            res.status(INTERNAL_SERVER_ERROR).send(`Error while running custom gui action: ${e.message}`);
        }
    });

    server.post('/get-update-reference-data', (req, res) => {
        try {
            const data = app.getTestsDataToUpdateRefs(req.body);
            res.json(data);
        } catch (error) {
            res.status(INTERNAL_SERVER_ERROR).send({error: error.message});
        }
    });

    server.post('/update-reference', (req, res) => {
        app.updateReferenceImage(req.body)
            .then((updatedTests) => res.json(updatedTests))
            .catch(({message}) => res.status(INTERNAL_SERVER_ERROR).send({error: message}));
    });

    server.post('/get-find-equal-diffs-data', (req, res) => {
        try {
            const data = app.getImageDataToFindEqualDiffs(req.body);
            res.json(data);
        } catch (error) {
            res.status(INTERNAL_SERVER_ERROR).send({error: error.message});
        }
    });

    server.post('/find-equal-diffs', async (req, res) => {
        try {
            const result = await app.findEqualDiffs(req.body);
            res.json(result);
        } catch ({message}) {
            res.status(INTERNAL_SERVER_ERROR).send({error: message});
        }
    });

    onExit(() => {
        app.finalize();
        logger.log('server shutting down');
    });

    server.post('/stop', (req, res) => {
        try {
            // pass 0 to prevent terminating hermione process
            hermione.halt('Tests were stopped by the user', 0);
            res.sendStatus(OK);
        } catch (e) {
            res.status(INTERNAL_SERVER_ERROR).send(`Error while stopping tests: ${e.message}`);
        }
    });

    await app.initialize();

    const {port, hostname} = options;
    await Promise.fromCallback((callback) => {
        const httpServer = server.listen(port, hostname, callback);
        httpServer.keepAliveTimeout = KEEP_ALIVE_TIMEOUT;
        httpServer.headersTimeout = HEADERS_TIMEOUT;
    });

    const data = {url: `http://${hostname}:${port}`};

    await guiApi.serverReady(data);

    return data;
};

redpajama_set_name: RedPajamaGithub


text:
using System;

namespace TestNumbers
{
    public class TestNumbers
    {
        public static void Main()
        {
            var firstNum = int.Parse(Console.ReadLine());
            var secondNum = int.Parse(Console.ReadLine());
            var stopNum = int.Parse(Console.ReadLine());

            var sum = 0.0;
            var count = 0;

            bool isStopNum = false;

            for (int i = firstNum; i > 0; i--)
            {
                for (int j = 1; j <= secondNum; j++)
                {
                    count++;

                    sum += 3 * i * j;

                    if (sum >= stopNum)
                    {
                        isStopNum = true;
                        break;
                    }
                }

                if (isStopNum)
                {
                    Console.WriteLine($"{count} combinations");
                    Console.WriteLine($"Sum: {sum} >= {stopNum}");
                    break;
                }
            }

            if (sum < stopNum)
            {
                Console.WriteLine($"{count} combinations");
                Console.WriteLine($"Sum: {sum}");
            }
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Reflection;
using NServiceBus;

public static class EndpointConfigurationExtensions
{
    public static void SetTypesToScan(this EndpointConfiguration configuration, IEnumerable<Type> typesToScan)
    {
        var methodInfo = typeof(EndpointConfiguration).GetMethod("TypesToScanInternal", BindingFlags.NonPublic | BindingFlags.Instance);
        if (methodInfo == null)
        {
            throw new Exception("Could not find 'TypesToScanInternal' field.");
        }
        methodInfo.Invoke(configuration, new object[]
        {
            typesToScan
        });
    }
}


text:
'use strict';

/**
 * The template server resource
 *
 * @author Giannis Georgalis <jgeorgal@meme.hokudai.ac.jp>
 */
ww3Services.factory('Template', ['$resource', function($resource) {
	return $resource('/api/dev/webbles/:id', { id: '@id' });
}]);

/**
 * The template loader pattern that can be used for multiple instantiations/requests
 *
 * @author Giannis Georgalis <jgeorgal@meme.hokudai.ac.jp>
 */
ww3Services.factory('TemplatesLoader', ['Template', '$q', 'gettext', function(Template, $q, gettext) {
	return function() {

		var delay = $q.defer();

		Template.query(
			function(templates) {
				delay.resolve(templates);
			},
			function() {
				delay.reject(gettext("Unable to retrieve templates"));
			});
		return delay.promise;
	};
}]);

/**
 * The template service for creating and modifying templates BUT ALSO
 * for retrieving and editing individual files within templates
 *
 * @author Giannis Georgalis <jgeorgal@meme.hokudai.ac.jp>
 */
ww3Services.factory('templateService', ['$q', '$upload', '$http', function($q, $upload, $http) {
	return {

		query: function(q) {
			return $http.get('/api/dev/templates?q=' + encodeURIComponent(q));
		},
		queryById: function(id) {
			return $http.get('/api/dev/templates?qid=' + encodeURIComponent(id));
		},

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

		create: function(files, templateData) {

			return $upload.upload({
				url: '/api/dev/webbles',
				method: 'POST',
				data: templateData,
				file: files
			});
		},

		copy: function(defid) {
			return $http.post('/api/dev/webbles/' + encodeURIComponent(defid));
		},

		update: function(id, files, templateData) {

			return $upload.upload({
				url: '/api/dev/webbles/' + id + '/files',
				method: 'PUT',
				data: templateData,
				file: files
			});
			// .progress(function(evt) {}
			// .success(function(data, status, headers, config) {}
			// .error(function(data, status, headers, config) {}
		},

		clearFiles: function(id) {
			return $http.delete('/api/dev/webbles/' + id + '/files');
		},

		getFiles: function(id) {
			return $http.get('/api/dev/webbles/' + id + '/files');
		},

		publish: function(id) {
			return $http.put('/api/dev/webbles/' + id + '/publish')
		},

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

		getBoilerplate: function(file) {
			return $http.get('/data/WebbleDevPack_Unpacked/' + file);
		},

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

		toUrl: function(id, file) {
			return '/devwebbles/' + id + '/0/' + encodeURIComponent(file);
		},

		getFile: function(id, file) {
			return $http.get('/api/dev/webbles/' + id + '/files/' + encodeURIComponent(file));
		},
		updateFile: function(id, file, content) {
			return $http.put('/api/dev/webbles/' + id + '/files/' + encodeURIComponent(file), { content: content });
		},
		deleteFile: function(id, file) {
			return $http.delete('/api/dev/webbles/' + id + '/files/' + encodeURIComponent(file));
		}
	};
}]);


text:
package org.ovirt.engine.core.common.businessentities;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;

@XmlAccessorType(XmlAccessType.NONE)
@XmlType(name = "OperationMode")
public enum OperationMode {
    FullVirtualized,
    ParaVirtualized;

    public int getValue() {
        return this.ordinal();
    }

    public static OperationMode forValue(int value) {
        return values()[value];
    }
}


text:
require 'ostruct'
require 'representable/json'

module Storify
  module Data
    class Link < OpenStruct

    end

    module LinkRepresentable
      include Representable::JSON

      property :rest_api_url
      property :oembed_url
      property :thumbnail
      property :description
      property :title
    end
  end
end


text:
export default Ember.Route.extend({

  setupController: function(controller, model) {
    this._super(controller,model);
    var title = model.get('name');
    this.controllerFor('header').set('title', title);
  },

	model: function(params) {
    return this.modelFor('routine');
	}
});


text:
namespace {

class DestinationURLEqualsURL {
 public:
  explicit DestinationURLEqualsURL(const GURL& url) : url_(url) {}
  bool operator()(const AutocompleteMatch& match) const {
    return match.destination_url == url_;
  }
 private:
  const GURL url_;
};

// Like URLPrefix::BestURLPrefix() except also handles the prefix of
// "www.".  This is needed because sometimes the string we're matching
// against here (which comes from |fill_into_edit|) can start with
// "www." without having a protocol at the beginning.  Because "www."
// is not on the default prefix list, we test for it explicitly here
// and use that match if the default list didn't have a match or the
// default list's match was shorter than it could've been.
const URLPrefix* BestURLPrefixWithWWWCase(
    const base::string16& text,
    const base::string16& prefix_suffix) {
  CR_DEFINE_STATIC_LOCAL(URLPrefix, www_prefix,
                         (base::ASCIIToUTF16("www."), 1));
  const URLPrefix* best_prefix = URLPrefix::BestURLPrefix(text, prefix_suffix);
  if ((best_prefix == NULL) ||
      (best_prefix->num_components < www_prefix.num_components)) {
    if (URLPrefix::PrefixMatch(www_prefix, text, prefix_suffix))
      best_prefix = &www_prefix;
  }
  return best_prefix;
}

}  // namespace

ShortcutsProvider::ShortcutsProvider(AutocompleteProviderListener* listener,
                                     Profile* profile)
    : AutocompleteProvider(listener, profile,
          AutocompleteProvider::TYPE_SHORTCUTS),
      languages_(profile_->GetPrefs()->GetString(prefs::kAcceptLanguages)),
      initialized_(false) {
  scoped_refptr<history::ShortcutsBackend> backend =
      ShortcutsBackendFactory::GetForProfile(profile_);
  if (backend.get()) {
    backend->AddObserver(this);
    if (backend->initialized())
      initialized_ = true;
  }
}

void ShortcutsProvider::Start(const AutocompleteInput& input,
                              bool minimal_changes) {
  matches_.clear();

  if ((input.type() == AutocompleteInput::INVALID) ||
      (input.type() == AutocompleteInput::FORCED_QUERY))
    return;

  if (input.text().empty())
    return;

  if (!initialized_)
    return;

  base::TimeTicks start_time = base::TimeTicks::Now();
  GetMatches(input);
  if (input.text().length() < 6) {
    base::TimeTicks end_time = base::TimeTicks::Now();
    std::string name = "ShortcutsProvider.QueryIndexTime." +
        base::IntToString(input.text().size());
    base::HistogramBase* counter = base::Histogram::FactoryGet(
        name, 1, 1000, 50, base::Histogram::kUmaTargetedHistogramFlag);
    counter->Add(static_cast<int>((end_time - start_time).InMilliseconds()));
  }
  UpdateStarredStateOfMatches();
}

void ShortcutsProvider::DeleteMatch(const AutocompleteMatch& match) {
  // Copy the URL since DeleteMatchesWithURLs() will invalidate |match|.
  GURL url(match.destination_url);

  // When a user deletes a match, he probably means for the URL to disappear out
  // of history entirely. So nuke all shortcuts that map to this URL.
  scoped_refptr<history::ShortcutsBackend> backend =
      ShortcutsBackendFactory::GetForProfileIfExists(profile_);
  if (backend)  // Can be NULL in Incognito.
    backend->DeleteShortcutsWithUrl(url);
  matches_.erase(std::remove_if(matches_.begin(), matches_.end(),
                                DestinationURLEqualsURL(url)),
                 matches_.end());
  // NOTE: |match| is now dead!
  listener_->OnProviderUpdate(true);

  // Delete the match from the history DB. This will eventually result in a
  // second call to DeleteShortcutsWithURLs(), which is harmless.
  HistoryService* const history_service =
      HistoryServiceFactory::GetForProfile(profile_, Profile::EXPLICIT_ACCESS);

  DCHECK(history_service && url.is_valid());
  history_service->DeleteURL(url);
}

ShortcutsProvider::~ShortcutsProvider() {
  scoped_refptr<history::ShortcutsBackend> backend =
      ShortcutsBackendFactory::GetForProfileIfExists(profile_);
  if (backend.get())
    backend->RemoveObserver(this);
}

void ShortcutsProvider::OnShortcutsLoaded() {
  initialized_ = true;
}

void ShortcutsProvider::GetMatches(const AutocompleteInput& input) {
  scoped_refptr<history::ShortcutsBackend> backend =
      ShortcutsBackendFactory::GetForProfileIfExists(profile_);
  if (!backend.get())
    return;
  // Get the URLs from the shortcuts database with keys that partially or
  // completely match the search term.
  base::string16 term_string(base::i18n::ToLower(input.text()));
  DCHECK(!term_string.empty());

  base::string16 fixed_up_term_string(term_string);
  AutocompleteInput fixed_up_input(input);
  if (FixupUserInput(&fixed_up_input))
    fixed_up_term_string = fixed_up_input.text();

  int max_relevance;
  if (!OmniboxFieldTrial::ShortcutsScoringMaxRelevance(
      input.current_page_classification(), &max_relevance))
    max_relevance = AutocompleteResult::kLowestDefaultScore - 1;

  for (history::ShortcutsBackend::ShortcutMap::const_iterator it =
           FindFirstMatch(term_string, backend.get());
       it != backend->shortcuts_map().end() &&
           StartsWith(it->first, term_string, true); ++it) {
    // Don't return shortcuts with zero relevance.
    int relevance = CalculateScore(term_string, it->second, max_relevance);
    if (relevance) {
      matches_.push_back(ShortcutToACMatch(
          it->second, relevance, term_string, fixed_up_term_string,
          input.prevent_inline_autocomplete()));
      matches_.back().ComputeStrippedDestinationURL(profile_);
    }
  }
  // Remove duplicates.
  std::sort(matches_.begin(), matches_.end(),
            &AutocompleteMatch::DestinationSortFunc);
  matches_.erase(std::unique(matches_.begin(), matches_.end(),
                             &AutocompleteMatch::DestinationsEqual),
                 matches_.end());
  // Find best matches.
  std::partial_sort(matches_.begin(),
      matches_.begin() +
          std::min(AutocompleteProvider::kMaxMatches, matches_.size()),
      matches_.end(), &AutocompleteMatch::MoreRelevant);
  if (matches_.size() > AutocompleteProvider::kMaxMatches) {
    matches_.erase(matches_.begin() + AutocompleteProvider::kMaxMatches,
                   matches_.end());
  }
  // Reset relevance scores to guarantee no match is given a score that may
  // allow it to become the highest ranked match (i.e., the default match)
  // unless either it is a legal default match (i.e., inlineable) or the
  // omnibox will reorder matches as necessary to correct the problem.  In
  // the process of resetting scores, guarantee that all scores are decreasing
  // (but do not assign any scores below 1).
  if (!OmniboxFieldTrial::ReorderForLegalDefaultMatch(
          input.current_page_classification()) &&
      (matches_.empty() || !matches_.front().allowed_to_be_default_match)) {
    max_relevance = std::min(max_relevance,
                             AutocompleteResult::kLowestDefaultScore - 1);
  }
  for (ACMatches::iterator it = matches_.begin(); it != matches_.end(); ++it) {
    max_relevance = std::min(max_relevance, it->relevance);
    it->relevance = max_relevance;
    if (max_relevance > 1)
      --max_relevance;
  }
}

AutocompleteMatch ShortcutsProvider::ShortcutToACMatch(
    const history::ShortcutsBackend::Shortcut& shortcut,
    int relevance,
    const base::string16& term_string,
    const base::string16& fixed_up_term_string,
    const bool prevent_inline_autocomplete) {
  DCHECK(!term_string.empty());
  AutocompleteMatch match(shortcut.match_core.ToMatch());
  match.provider = this;
  match.relevance = relevance;
  match.deletable = true;
  DCHECK(match.destination_url.is_valid());
  match.RecordAdditionalInfo("number of hits", shortcut.number_of_hits);
  match.RecordAdditionalInfo("last access time", shortcut.last_access_time);
  match.RecordAdditionalInfo("original input text",
                             base::UTF16ToUTF8(shortcut.text));

  // Set |inline_autocompletion| and |allowed_to_be_default_match| if possible.
  // If the match is a search query this is easy: simply check whether the
  // user text is a prefix of the query.  If the match is a navigation, we
  // assume the fill_into_edit looks something like a URL, so we use
  // BestURLPrefix() to try and strip off any prefixes that the user might
  // not think would change the meaning, but would otherwise prevent inline
  // autocompletion.  This allows, for example, the input of "foo.c" to
  // autocomplete to "foo.com" for a fill_into_edit of "http://foo.com".
  if (AutocompleteMatch::IsSearchType(match.type)) {
    if (StartsWith(match.fill_into_edit, term_string, false)) {
      match.inline_autocompletion =
          match.fill_into_edit.substr(term_string.length());
      match.allowed_to_be_default_match =
          !prevent_inline_autocomplete || match.inline_autocompletion.empty();
    }
  } else {
    const URLPrefix* best_prefix =
        BestURLPrefixWithWWWCase(match.fill_into_edit, term_string);
    const base::string16* matching_string = &term_string;
    // If we failed to find a best_prefix initially, try again using a
    // fixed-up version of the user input.  This is especially useful to
    // get about: URLs to inline against chrome:// shortcuts.  (about:
    // URLs are fixed up to the chrome:// scheme.)
    if ((best_prefix == NULL) && !fixed_up_term_string.empty() &&
        (fixed_up_term_string != term_string)) {
        best_prefix = BestURLPrefixWithWWWCase(
            match.fill_into_edit, fixed_up_term_string);
        matching_string = &fixed_up_term_string;
    }
    if (best_prefix != NULL) {
      match.inline_autocompletion = match.fill_into_edit.substr(
          best_prefix->prefix.length() + matching_string->length());
      match.allowed_to_be_default_match =
          !prevent_inline_autocomplete || match.inline_autocompletion.empty();
    }
  }

  // Try to mark pieces of the contents and description as matches if they
  // appear in |term_string|.
  WordMap terms_map(CreateWordMapForString(term_string));
  if (!terms_map.empty()) {
    match.contents_class = ClassifyAllMatchesInString(term_string, terms_map,
        match.contents, match.contents_class);
    match.description_class = ClassifyAllMatchesInString(term_string, terms_map,
        match.description, match.description_class);
  }
  return match;
}

// static
ShortcutsProvider::WordMap ShortcutsProvider::CreateWordMapForString(
    const base::string16& text) {
  // First, convert |text| to a vector of the unique words in it.
  WordMap word_map;
  base::i18n::BreakIterator word_iter(text,
                                      base::i18n::BreakIterator::BREAK_WORD);
  if (!word_iter.Init())
    return word_map;
  std::vector<base::string16> words;
  while (word_iter.Advance()) {
    if (word_iter.IsWord())
      words.push_back(word_iter.GetString());
  }
  if (words.empty())
    return word_map;
  std::sort(words.begin(), words.end());
  words.erase(std::unique(words.begin(), words.end()), words.end());

  // Now create a map from (first character) to (words beginning with that
  // character).  We insert in reverse lexicographical order and rely on the
  // multimap preserving insertion order for values with the same key.  (This
  // is mandated in C++11, and part of that decision was based on a survey of
  // existing implementations that found that it was already true everywhere.)
  std::reverse(words.begin(), words.end());
  for (std::vector<base::string16>::const_iterator i(words.begin());
       i != words.end(); ++i)
    word_map.insert(std::make_pair((*i)[0], *i));
  return word_map;
}

// static
ACMatchClassifications ShortcutsProvider::ClassifyAllMatchesInString(
    const base::string16& find_text,
    const WordMap& find_words,
    const base::string16& text,
    const ACMatchClassifications& original_class) {
  DCHECK(!find_text.empty());
  DCHECK(!find_words.empty());

  // The code below assumes |text| is nonempty and therefore the resulting
  // classification vector should always be nonempty as well.  Returning early
  // if |text| is empty assures we'll return the (correct) empty vector rather
  // than a vector with a single (0, NONE) match.
  if (text.empty())
    return original_class;

  // First check whether |text| begins with |find_text| and mark that whole
  // section as a match if so.
  base::string16 text_lowercase(base::i18n::ToLower(text));
  ACMatchClassifications match_class;
  size_t last_position = 0;
  if (StartsWith(text_lowercase, find_text, true)) {
    match_class.push_back(
        ACMatchClassification(0, ACMatchClassification::MATCH));
    last_position = find_text.length();
    // If |text_lowercase| is actually equal to |find_text|, we don't need to
    // (and in fact shouldn't) put a trailing NONE classification after the end
    // of the string.
    if (last_position < text_lowercase.length()) {
      match_class.push_back(
          ACMatchClassification(last_position, ACMatchClassification::NONE));
    }
  } else {
    // |match_class| should start at position 0.  If the first matching word is
    // found at position 0, this will be popped from the vector further down.
    match_class.push_back(
        ACMatchClassification(0, ACMatchClassification::NONE));
  }

  // Now, starting with |last_position|, check each character in
  // |text_lowercase| to see if we have words starting with that character in
  // |find_words|.  If so, check each of them to see if they match the portion
  // of |text_lowercase| beginning with |last_position|.  Accept the first
  // matching word found (which should be the longest possible match at this
  // location, given the construction of |find_words|) and add a MATCH region to
  // |match_class|, moving |last_position| to be after the matching word.  If we
  // found no matching words, move to the next character and repeat.
  while (last_position < text_lowercase.length()) {
    std::pair<WordMap::const_iterator, WordMap::const_iterator> range(
        find_words.equal_range(text_lowercase[last_position]));
    size_t next_character = last_position + 1;
    for (WordMap::const_iterator i(range.first); i != range.second; ++i) {
      const base::string16& word = i->second;
      size_t word_end = last_position + word.length();
      if ((word_end <= text_lowercase.length()) &&
          !text_lowercase.compare(last_position, word.length(), word)) {
        // Collapse adjacent ranges into one.
        if (match_class.back().offset == last_position)
          match_class.pop_back();

        AutocompleteMatch::AddLastClassificationIfNecessary(&match_class,
            last_position, ACMatchClassification::MATCH);
        if (word_end < text_lowercase.length()) {
          match_class.push_back(
              ACMatchClassification(word_end, ACMatchClassification::NONE));
        }
        last_position = word_end;
        break;
      }
    }
    last_position = std::max(last_position, next_character);
  }

  return AutocompleteMatch::MergeClassifications(original_class, match_class);
}

history::ShortcutsBackend::ShortcutMap::const_iterator
    ShortcutsProvider::FindFirstMatch(const base::string16& keyword,
                                      history::ShortcutsBackend* backend) {
  DCHECK(backend);
  history::ShortcutsBackend::ShortcutMap::const_iterator it =
      backend->shortcuts_map().lower_bound(keyword);
  // Lower bound not necessarily matches the keyword, check for item pointed by
  // the lower bound iterator to at least start with keyword.
  return ((it == backend->shortcuts_map().end()) ||
    StartsWith(it->first, keyword, true)) ? it :
    backend->shortcuts_map().end();
}

int ShortcutsProvider::CalculateScore(
    const base::string16& terms,
    const history::ShortcutsBackend::Shortcut& shortcut,
    int max_relevance) {
  DCHECK(!terms.empty());
  DCHECK_LE(terms.length(), shortcut.text.length());

  // The initial score is based on how much of the shortcut the user has typed.
  // Using the square root of the typed fraction boosts the base score rapidly
  // as characters are typed, compared with simply using the typed fraction
  // directly. This makes sense since the first characters typed are much more
  // important for determining how likely it is a user wants a particular
  // shortcut than are the remaining continued characters.
  double base_score = max_relevance *
      sqrt(static_cast<double>(terms.length()) / shortcut.text.length());

  // Then we decay this by half each week.
  const double kLn2 = 0.6931471805599453;
  base::TimeDelta time_passed = base::Time::Now() - shortcut.last_access_time;
  // Clamp to 0 in case time jumps backwards (e.g. due to DST).
  double decay_exponent = std::max(0.0, kLn2 * static_cast<double>(
      time_passed.InMicroseconds()) / base::Time::kMicrosecondsPerWeek);

  // We modulate the decay factor based on how many times the shortcut has been
  // used. Newly created shortcuts decay at full speed; otherwise, decaying by
  // half takes |n| times as much time, where n increases by
  // (1.0 / each 5 additional hits), up to a maximum of 5x as long.
  const double kMaxDecaySpeedDivisor = 5.0;
  const double kNumUsesPerDecaySpeedDivisorIncrement = 5.0;
  double decay_divisor = std::min(kMaxDecaySpeedDivisor,
      (shortcut.number_of_hits + kNumUsesPerDecaySpeedDivisorIncrement - 1) /
      kNumUsesPerDecaySpeedDivisorIncrement);

  return static_cast<int>((base_score / exp(decay_exponent / decay_divisor)) +
      0.5);
}


text:
madmath-cpp
==============

C++ code repository.


text:
FROM ruby:2.5.1

WORKDIR /app
ADD Gemfile /app/Gemfile
ADD Gemfile.lock /app/Gemfile.lock
RUN bundle install --system

ADD . /app
RUN bundle install --system

EXPOSE 4567

# If you do not have a bin/web wrapper file, create one or update this command
RUN chmod a+x bin/web
CMD ["bin/web"]


text:
<html><body>
<!--StartFragment-->XXX<!--EndFragment-->
</body>
</html>


text:
using System;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using M120_LB2_FS17.Classes;
using M120_LB2_FS17.Classes.Backend;
using M120_LB2_FS17.Classes.EventArgs;

namespace M120_LB2_FS17.Xaml.Windows
{
    /// <summary>
    /// Interaction logic for CreateReservationWindow.xaml
    /// </summary>
    public partial class CreateReservationWindow
    {
        public event EventHandler<Button> SaveButtonClicked;

        public CreateReservationWindow()
        {
            InitializeComponent();
        }

        public CreateReservationWindow(int column, int row)
        {
            InitializeComponent();
            CheckRadioButton(column, row);
        }

        public void ReservationForm_OnSaveButtonClicked(object sender, ReservationEventArgs e)
        {
            if (!IsValidForm(e.Reservation.Seat))
            {
                return;
            }
            AppendReservation(e.Reservation);
            SaveButtonClicked?.Invoke(this, null);
            MainWindowSwitcher.Instance.SetSuccessMessage("Erfolgreich reserviert");
            Close();
        }

        private void AppendReservation(Reservation reservation)
        {
            Library.AppendReservation(reservation);
        }

        private bool IsValidForm(Seat seat)
        {
            var valid = true;
            var reservation = Library.GetReservation(Publics.CurrentlySelectedMovie, Publics.CurrentlySelectedDateTime, seat);
            if (null != reservation)
            {
                MessageBox.Show("Platz bereits besetzt");
                valid = false;
            }

            return valid;
        }

        private void CheckRadioButton(int column, int row)
        {
            var grid =
                CreateReservationWindowReservationForm.ReservationFormSeatPicker.SeatPickerContentControl.Content as
                    Grid;
            var seatRadioButtons = grid.Children.OfType<SeatRadioButton>();
            var seatRadioButton = seatRadioButtons.FirstOrDefault(s => s.Seat.Column == column && s.Seat.Row == row);
            seatRadioButton.IsChecked = true;
        }

    }
}


text:
"use strict";
var Patient = (function () {
    function Patient() {
    }
    // constructor(public productId: number,
    //     public productName: string,
    //     public productCode: string,
    //     public releaseDate: string,
    //     public price: number,
    //     public description: string,
    //     public starRating: number,
    //     public imageUrl: string) {
    // }
    Patient.prototype.calculateDiscount = function (percent) {
        return this.price - (this.price * percent / 100);
    };
    return Patient;
}());
exports.Patient = Patient;
//# sourceMappingURL=patient.model.js.map


text:
'use strict';

var argv = require('yargs').argv;
var config = require('./config');
var azure = require('azure-api')({ verbose: true });
var Q = require('q');
var E = require('linq');
var assert = require('chai').assert;

//
// Generate the full name for a VM.
//
var genFullVmName = function (vm, vmBaseName) {

	assert.isObject(vm);
	assert.isString(vmBaseName);

	if (vm.fullName) {
		return vm.fullName;
	}

	if (vmBaseName) {
		return vmBaseName + vm.name;
	}

	if (vm.name) {
		return vm.name;
	}

	throw new Error("VM has no name!");
}

//
// Provision a collection of VMs.
//
var provisionVms = function (vms, networkName, vmBaseName) {

	assert.isArray(vms);
	assert.isString(networkName);
	assert.isString(vmBaseName);

	var provisionVmPromises = E.from(vms)
		.select(function (vm) {
			return azure.provisionVM({
					name: genFullVmName(vm, vmBaseName),
					networkName: networkName,
					imageName: vm.imageName,
					user: vm.user,
					pass: vm.pass,
					staticIp: vm.ip,
					endpoints: vm.endpoints,
					provisionScript: vm.provisionScript,
					provisioningTemplateView: vm,
				});
		})
		.toArray()

	return Q.all(provisionVmPromises);
};

//
// Provision an entire network and VMs.
//
var provisionNetwork = function (network) {

	assert.isObject(network);

	console.log('Creating network ' + network.name + ' in location ' + network.location);

	return azure.createNetwork(network.name, network.location)
		.then(function () {
			return provisionVms(network.vms, network.name, network.vmBaseName);
		});
};

//
// Provision a collection of networks.
//
var provisionNetworks = function (networks) {
	assert.isArray(networks);

	return E.from(networks)
		.select(function (network) {
			return provisionNetwork(network);
		})
		.toArray();
};

Q.all(provisionNetworks(config.networks))
	.then(function () {
		console.log('Provisioning complete');
	})
	.catch(function (err) {
		console.error('An error occurred during provisioning:');
		console.error(err.stack);
	});


text:
package gmc_hdfs.replicationsimulator;

import gmc_hdfs.distribution.StdRandom;
import hdfs.replicationsimulator.Main;
import hdfs.replicationsimulator.Node;
import hdfs.replicationsimulator.SimTrace;
import hdfs.replicationsimulator.Simulator;
import java.util.LinkedList;
import java.util.Queue;

/**
 * workload class is component whose generate workload.
 * It is a component which simulates the work load. Work load is a set
 * of requests which are sent by the users to the system for accessing the
 * data and processing them.
 *
 * @author AliMori
 * @since GMC_HDFSSim Toolkit 1.0
 */
public class Workload implements Runnable {

    /**
     * With executing this method, the workload is implemented to the system
     * and it continues until the simulation is finished. The type and features
     * of the workload should be written inside the function. In fact anything
     * that is in this function will be executed. It is recommended that you
     * should write functions for the work load and call the function inside
     * the run function.
     *
     * Two important methods for creating the work load are written before in
     * this class which will be introduced in the following.
     */
    @Override
    public void run() {
        Simulator.addTrace(new SimTrace("Started Workload Generator . . ."));

        flashCrowedWorkload();

        //slashdotWorkload();
    }

    /**
     * This method creates flash crowd workload. This work load is based on
     * the default topology of data centers that is written in this simulator.
     * You can customize it according to your needs.
     */
    /////////////////////////////// FASHCROWED WORKLOAD
    void flashCrowedWorkload() {

        long requestId = 0;
        int period = (int) Main.getSimulationDuration() / 2;
        int requestTime = 0;
        User user;
        int dataitemId;
        long start = System.currentTimeMillis();

        long initialTime = 0;

        Queue<Integer> dataitems = new LinkedList<>();
        while (dataitems.size() < 727000) {
            int dataitemID = (int) StdRandom.boundedPareto(0.1, 1, Simulator.getNumberofdataitems()
                    * Simulator.getDatacentersTopology().size());
            dataitems.add(dataitemID);
        }

        while (Node.now() <= start + period) {

            requestTime += StdRandom.poisson(10);
            user = Simulator.getDatacentersTopology().getDatacenters().get((int) StdRandom.boundedPareto(1.5,
                    0, 10)).getAllUsers().getUsers().get(StdRandom.uniform(0, Simulator.getNumberOfUsers()));
//            dataitemId = (int) StdRandom.boundedPareto(1, 1, Simulator.getNumberofdataitems()
//                    * Simulator.getDatacentersTopology().size());
            dataitemId = dataitems.poll();

            Request request = user.readDataitem(requestId++, dataitemId, (long) requestTime);

            try {
                Thread.sleep(request.getTime() - initialTime);
                initialTime = request.getTime();
            } catch (InterruptedException ex) {
                ex.printStackTrace();
                System.out.println("Request " + request.getRequestType() + " from User #" + request.getUser()
                        .getDatacenterId() + "_" + request.getUser().getId() + " for Dataitem #"
                        + request.getDataitemID() + " is inetrrupted . . .");
            }

//            System.out.println("" + request.getTime() + " : Reqest #" + request.getId() + " : User #"
//                    + request.getUser().getDatacenterId()
//                    + "_" + request.getUser().getId() + " for Dataitem #" + request.getDataitemID());
            Simulator.addToRequestsList(request);
        }

        while (Node.now() <= start + (2 * period)) {

            requestTime += StdRandom.poisson(10);
            user = Simulator.getDatacentersTopology().getDatacenters().get(inversRegions(
                    (int) StdRandom.boundedPareto(1.5, 0, 10))).
                    getAllUsers().getUsers().get(StdRandom.uniform(0, Simulator.getNumberOfUsers()));
//            dataitemId = (int) StdRandom.boundedPareto(0.7, 1, Simulator.getNumberofdataitems()
//                    * Simulator.getDatacentersTopology().size());
            dataitemId = dataitems.poll();
            Request request = user.readDataitem(requestId++, dataitemId, (long) requestTime);

            try {
                Thread.sleep(request.getTime() - initialTime);
                initialTime = request.getTime();
            } catch (InterruptedException ex) {
                ex.printStackTrace();
                System.out.println("Request " + request.getRequestType() + " from User #" + request.getUser()
                        .getDatacenterId() + "_" + request.getUser().getId() + " for Dataitem #"
                        + request.getDataitemID() + " is inetrrupted . . .");
            }

//            System.out.println("" + request.getTime() + " : Reqest #" + request.getId() + " : User #"
//                    + request.getUser().getDatacenterId()
//                    + "_" + request.getUser().getId() + " for Dataitem #" + request.getDataitemID());
            Simulator.addToRequestsList(request);
        }
    }

    /**
     * This method creates slashdot workload. This work load is based on
     * the default topology of data centers that is written in this simulator.
     * You can customize it according to your needs.
     */
    ////////////////////////////// FLASHDOT WORKLOAD
    void slashdotWorkload() {

        long requestId = 0;
        int period = (int) Main.getSimulationDuration() / 3;
        int requestTime = 0;
        User user;
        int dataitemId;
        long start = System.currentTimeMillis();

        long initialTime = 0;

        Queue<Integer> dataitems = new LinkedList<>();
        while (dataitems.size() < 300000) {
            int dataitemID = (int) StdRandom.boundedPareto(0.3, 1, Simulator.getNumberofdataitems()
                    * Simulator.getDatacentersTopology().size());
            dataitems.add(dataitemID);
        }

        while (Node.now() <= start + period) {

            requestTime += StdRandom.poisson(400);
            user = Simulator.getDatacentersTopology().getDatacenters().get(StdRandom.uniform(0, 10)).
                    getAllUsers().getUsers().get(StdRandom.uniform(0, Simulator.getNumberOfUsers()));
//            dataitemId = (int) StdRandom.boundedPareto(1.161, 1, Simulator.getNumberofdataitems()
//                    * Simulator.getDatacentersTopology().size());

            dataitemId = dataitems.poll();

            Request request = user.readDataitem(requestId++, dataitemId, (long) requestTime);

            try {
                Thread.sleep(request.getTime() - initialTime);
                initialTime = request.getTime();
            } catch (InterruptedException ex) {
                ex.printStackTrace();
                System.out.println("Request " + request.getRequestType() + " from User #" + request.getUser()
                        .getDatacenterId() + "_" + request.getUser().getId() + " for Dataitem #"
                        + request.getDataitemID() + " is inetrrupted . . .");
            }

//            System.out.println("" + request.getTime() + " : Reqest #" + request.getId() + " : User #"
//                    + request.getUser().getDatacenterId()
//                    + "_" + request.getUser().getId() + " for Dataitem #" + request.getDataitemID());
            Simulator.addToRequestsList(request);
        }

        while (Node.now() <= start + (2 * period)) {

            requestTime += StdRandom.poisson(10);
            user = Simulator.getDatacentersTopology().getDatacenters().get(StdRandom.uniform(0, 10)).
                    getAllUsers().getUsers().get(StdRandom.uniform(0, Simulator.getNumberOfUsers()));
//            dataitemId = (int) StdRandom.boundedPareto(1.161, 1, Simulator.getNumberofdataitems()
//                    * Simulator.getDatacentersTopology().size());

            dataitemId = dataitems.poll();
            Request request = user.readDataitem(requestId++, dataitemId, (long) requestTime);

            try {
                Thread.sleep(request.getTime() - initialTime);
                initialTime = request.getTime();
            } catch (InterruptedException ex) {
                ex.printStackTrace();
                System.out.println("Request " + request.getRequestType() + " from User #" + request.getUser()
                        .getDatacenterId() + "_" + request.getUser().getId() + " for Dataitem #"
                        + request.getDataitemID() + " is inetrrupted . . .");
            }

//            System.out.println("" + request.getTime() + " : Reqest #" + request.getId() + " : User #"
//                    + request.getUser().getDatacenterId()
//                    + "_" + request.getUser().getId() + " for Dataitem #" + request.getDataitemID());
            Simulator.addToRequestsList(request);
        }

        while (Node.now() <= start + (3 * period)) {

            requestTime += StdRandom.poisson(400);
            user = Simulator.getDatacentersTopology().getDatacenters().get(StdRandom.uniform(0, 10)).
                    getAllUsers().getUsers().get(StdRandom.uniform(0, Simulator.getNumberOfUsers()));
//            dataitemId = (int) StdRandom.boundedPareto(1.161, 1, Simulator.getNumberofdataitems()
//                    * Simulator.getDatacentersTopology().size());

            dataitemId = dataitems.poll();
            Request request = user.readDataitem(requestId++, dataitemId, (long) requestTime);

            try {
                Thread.sleep(request.getTime() - initialTime);
                initialTime = request.getTime();
            } catch (InterruptedException ex) {
                ex.printStackTrace();
                System.out.println("Request " + request.getRequestType() + " from User #" + request.getUser()
                        .getDatacenterId() + "_" + request.getUser().getId() + " for Dataitem #"
                        + request.getDataitemID() + " is inetrrupted . . .");
            }

//            System.out.println("" + request.getTime() + " : Reqest #" + request.getId() + " : User #"
//                    + request.getUser().getDatacenterId()
//                    + "_" + request.getUser().getId() + " for Dataitem #" + request.getDataitemID());
            Simulator.addToRequestsList(request);
        }
    }
    ///////////////////////////////////////

    /**
     * This method is used in flashCrowdedWorkload method for changing the
     * geographical regions in the traffic change.
     * @param region id of region
     * @return regions far from current regions
     */
    // it is using for change geoghraphical regions to other sides
    int inversRegions(int region) {
        int answer = 0;
        switch (region) {
            case 0: {
                answer = 9;
                break;
            }
            case 1: {
                answer = 8;
                break;
            }
            case 2: {
                answer = 7;
                break;
            }
            case 3: {
                answer = 6;
                break;
            }
            case 4: {
                answer = 5;
                break;
            }
            case 5: {
                answer = 4;
                break;
            }
            case 6: {
                answer = 3;
                break;
            }
            case 7: {
                answer = 2;
                break;
            }
            case 8: {
                answer = 1;
                break;
            }
            case 9: {
                answer = 0;
                break;
            }
        }
        return answer;
    }

}

//        List<Request> requests = Simulator.getWorkloadSimulation();
//        for (Request request : requests) {
//            try {
//                Thread.sleep(request.getTime() - initialTime);
//                initialTime = request.getTime();
//            } catch (InterruptedException ex) {
//                ex.printStackTrace();
//                System.out.println("Request " + request.getRequestType() + " from User #" + request.getUser()
//                        .getDatacenterId() + "_" + request.getUser().getId() + " for Dataitem #"
//                        + request.getDataitemID() + " is inetrrupted . . .");
//            }
//
//            System.out.println("" + request.getTime() + " : Reqest #" + request.getId() + " : User #"
//                    + request.getUser().getDatacenterId()
//                    + "_" + request.getUser().getId() + " for Dataitem #" + request.getDataitemID());
//
//            Simulator.addToRequestsList(request);
//        }


text:
package org.spongepowered.common.mixin.core.block.properties;

import net.minecraft.block.properties.PropertyHelper;
import org.spongepowered.api.block.trait.BlockTrait;
import org.spongepowered.api.util.Functional;
import org.spongepowered.asm.mixin.Implements;
import org.spongepowered.asm.mixin.Interface;
import org.spongepowered.asm.mixin.Intrinsic;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.common.interfaces.block.IMixinPropertyHolder;

import java.util.function.Predicate;

@Mixin(value = PropertyHelper.class)
@Implements(@Interface(iface = BlockTrait.class, prefix = "trait$"))
public abstract class MixinPropertyHelper<T extends Comparable<T>> implements BlockTrait<T>, IMixinPropertyHolder {

    protected String propertyName;
    protected String idString;

    @Shadow private String name;
    @Shadow public abstract Class<T> shadow$getValueClass();

    @Override
    public String getId() {
        return this.idString;
    }

    @Override
    public String getName() {
        return this.name;
    }

    @Intrinsic
    public Class<T> trait$getValueClass() {
        return this.shadow$getValueClass();
    }

    @Override
    public Predicate<T> getPredicate() {
        return Functional.predicateIn(getPossibleValues());
    }

    @Override
    public void setId(String id) {
        this.idString = id;
    }
}


text:
package com.alse.paideia;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.speech.tts.TextToSpeech;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.View;
import android.widget.TextView;

import com.alse.paideia.Classifier.Recognition;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;

import static java.lang.System.*;

public class RecognitionScoreView extends View {
  private static final float TEXT_SIZE_DIP = 30;
  private static final float TEXT_SIZE_DIP_FACTOR = (float)0.5;
  private List<Recognition> results;
  private List<Recognition> prevResults;
  private List<HashMap<List<Recognition>, Long>> cached_results = new ArrayList<>();
  private final Paint fgPaint;

  public RecognitionScoreView(final Context context, final AttributeSet set) {
    super(context, set);

    float textSizePx =
        TypedValue.applyDimension(
            TypedValue.COMPLEX_UNIT_DIP, TEXT_SIZE_DIP, getResources().getDisplayMetrics());
    fgPaint = new Paint();
    fgPaint.setColor(MainActivity.baseTextColor);
    fgPaint.setTextSize(textSizePx);
  }

  public void setResults(final List<Recognition> results) {
    this.results = results;
    postInvalidate();
  }

  public void filterCached(){
    for (Iterator<HashMap<List<Recognition>, Long>> iterator = cached_results.iterator(); iterator.hasNext();) {
        HashMap<List<Recognition>, Long> h = iterator.next();
        if (currentTimeMillis() / 1000 - h.get(h.keySet().iterator().next()) > 10){
          iterator.remove();
        }
    }
  }

  public List<String> getTopResults(){
    HashMap<String, Float> classes = new HashMap<>();
    for(HashMap<List<Recognition>, Long> h: cached_results){
      for(Recognition r : h.keySet().iterator().next()){
        if (classes.containsKey(r.getTitle()))
          classes.put(r.getTitle(), classes.get(r.getTitle()) > r.getConfidence() ? classes.get(r.getTitle()): r.getConfidence());
        else
          classes.put(r.getTitle(), r.getConfidence());
      }
    }
    Set<Map.Entry<String, Float>> set = classes.entrySet();
    List<Map.Entry<String, Float>> list = new ArrayList<>(
            set);
    Collections.sort(list, new Comparator<Map.Entry<String, Float>>() {
      public int compare(Map.Entry<String, Float> o1,
                         Map.Entry<String, Float> o2) {
        return o2.getValue().compareTo(o1.getValue());
      }
    });
    List<String> result = new ArrayList<>();
    for(int i=0; i<(list.size() > 5? 5:list.size()); i++){
      result.add(list.get(i).getKey());
    }
    return result;
  }
  @Override
  public void onDraw(final Canvas canvas) {

    float max_confidence = -1;
    float min_confidence = 1;

    if (results != null && results.size() > 0) {
      for (final Recognition recog : results) {
        max_confidence = max_confidence > recog.getConfidence() ? max_confidence : recog.getConfidence();
        min_confidence = min_confidence < recog.getConfidence() ? min_confidence : recog.getConfidence();
      }

      final int x = 100;
      int y = 0;

      fgPaint.setTextSize(TEXT_SIZE_DIP);
      for (final Recognition recog : results) {
//        fgPaint.setTextSize(recog.getConfidence()*TEXT_SIZE_DIP + TEXT_SIZE_DIP_FACTOR/recog.getConfidence());
        if (y == 0)
          y = (int) (fgPaint.getTextSize() * 1.5f);
        String text = recog.getTitle() + ": " + recog.getConfidence();
        canvas.drawText(text, x, y, fgPaint);
        y += fgPaint.getTextSize();
      }
      if (cached_results != null && cached_results.size() > 0) {
        if (!prevResults.get(0).getTitle().equals(results.get(0).getTitle())){
          MainActivity.speak(results.get(0).getTitle());
        }
      }

      if (results != null && results.size() > 0) {
        HashMap<List<Recognition>, Long> cache = new HashMap<List<Recognition>, Long>();
        cache.put(results, currentTimeMillis() / 1000);
        cached_results.add(cache);
      }
      prevResults = results;
    }
  }
}


text:
package models.slick.systemmanage

import models.systemmanage.GlobalParam

import scala.slick.lifted.Tag
import com.typesafe.slick.driver.oracle.OracleDriver.simple._

/**
 * Created by hooxin on 15-2-12.
 */
class GlobalParamTable(tag: Tag) extends Table[GlobalParam](tag, "t_globalpar") {
  def id = column[String]("globalparcode", O.PrimaryKey)

  def globalparname = column[String]("globalparname")

  def globalparvalue = column[String]("globalparvalue")

  def * = (
    id,
    globalparname,
    globalparvalue
    ) <>(GlobalParam.tupled, GlobalParam.unapply)
}


text:
@implementation CBCBrew

#pragma mark - NSObject

- (NSString *)debugDescription
{
    return @"Mmmm, that's a tasty brew.";
}

@end


text:
/*global NB$:true NB:true $:true*/

define(function(require) {
  var Conf            = require('conf');
  var Dom             = require('dom');
  var Models          = require('models');
  var Pers            = require('pers');
  var Handlebars 	= require('handlebars');
  var concierge       = require('concierge');

  if ('NB$' in window) {
    var $ = NB$;
  }

  Pers.init = function () {
    //get data:
    var payload_objects = { types: ['settings'] };
    Pers.call('getObjects', payload_objects, function(payload){
      $(".nb-widget-body").append(require("hbs!templates_dir/your_settings")({
        firstname: payload.settings.user.firstname, lastname: payload.settings.user.lastname}));
      Pers.createStore(payload);
    });
    $.concierge.addComponents({});
  };

  Pers.createStore = function (payload) {
    Pers.store = new Models.Store();
    Pers.store.create(payload.settings, {
      ds:     { pFieldName: 'ds' },
      us:     { pFieldName: 'us' },
      sl:     { pFieldName: 'sl' },
    });
    Pers.settings_menu();
  };

  Pers.validateNewPassword = function (event) {
    var savebutton =  $('#save_button');
    var passwd1 = $('#new_password1')[0].value;
    var passwd2 = $('#new_password2')[0].value;

    if (passwd1.indexOf('/') !== -1 || passwd2.indexOf('/') !== -1) {
      savebutton.attr('disabled', 'disabled');
      $('#newpassword_msg').text("Your password can't contain the following character(s): /");
      return;
    }

    if (passwd1 === '' || passwd2 === '') {
      savebutton.attr('disabled', 'disabled');
      $('#newpassword_msg').text('');
      return;
    }

    if (passwd1 === passwd2) {
      savebutton.removeAttr('disabled');
      $('#newpassword_msg').text('Passwords match');
    } else {
      savebutton.attr('disabled', 'disabled');
      $('#newpassword_msg').html("Passwords don't match...");
    }
  };

  Pers.validateFirstName = function (event) {
    var savebutton =  $('#save_button');
    var firstname = $('#firstname')[0].value;
    if(firstname.trim()) {
      savebutton.removeAttr('disabled');
      $('#firstname_msg').text("");
    }
    else {
      savebutton.attr('disabled', 'disabled');
      $('#firstname_msg').text("Firstname is required");
    }
    return;
  };

  Pers.validateLastName = function (event) {
    // Currently, no validation is required for the last name
  };

  Pers.on_setting_change = function (event) {
    var t = event.currentTarget;
    var id_item = t.getAttribute('id_item');
    Pers.newSettings[id_item] = t.options[t.selectedIndex].value;
  };

  Pers.settings_menu = function () {
    Pers.newSettings = {};
    $('select.settings_selector').each(function () {
      var m = Pers.store;
      var elt = $(this);
      elt.empty();

      var id_item = this.getAttribute('id_item');
      id_item = m.get('ds', { name: id_item }).first().id;
      var labels = m.get('sl', { setting_id: id_item }).items;
      var set_value =  m.o.ds[id_item].value;
      var us = m.get('us', { setting_id: id_item }).first();
      if (us !== null) {
        set_value =  us.value;
      }

      var default_str, l;
      for (var v in labels) {
        l = labels[v];
        default_str = (set_value === l.value) ? ' selected="true" ' : '';
        elt.append('<option ' + default_str + ' value="' + l.value + '">' + l.label + '</option>');
      }

    });

    var f_cleanup = function (do_save) {
      if (do_save) {
        var passwd = $('#new_password1')[0].value;
        if (passwd !== '') {
          Pers.newSettings['__PASSWD__'] = passwd;
          $('#newpassword_msg').hide();
          $('#new_password1')[0].value = '';
          $('#new_password2')[0].value = '';
        }
        Pers.newSettings["firstname"] = $("#firstname")[0].value.trim();
        Pers.newSettings["lastname"] = $("#lastname")[0].value.trim();

        Pers.call('save_settings', Pers.newSettings, function (payload) {
          //update new settings
          Pers.store.add('us', payload.settings.us);
          // Reload the page to update Conf.userinfo if the user's name gets changed and also to
          // ensure the name displayed at the top of the page is correct.
          window.location.reload();
        });
      }
    };

    $('#cancel_button').click(function () {
      f_cleanup(false);
      window.location.href = "/";
    });

    $('#save_button').click(function () {f_cleanup(true);});

    var u = Conf.userinfo;
    $('#your_firstname').text(u.firstname);
    $('#your_lastname').text(u.lastname);
    $('#your_email').text(u.email);
  };

});


text:
"""

"""

import ast
import functools
import types
import inspect

from .decompile     import to_ast
from .compile       import from_ast, ast_to_source
from .optimizations import BasicOptimization

__all__ = \
        [ "optimize"
        , "get_source"
        ]

def transform(value, transformers, file=None):
    """

    :param value:
    :param transformers:
    :return:
    """

    result = value

    if transformers:
        node = to_ast(value, file=file)
        if node:
            for transformer in transformers:
                node = transformer.visit(node)
                node = ast.fix_missing_locations(node)
            result = from_ast(node, value)

    return result

def optimize\
    ( optimizations: (BasicOptimization, type, list, tuple) = None
    , level: (float, int) = None
    , classes: tuple = None
    , file: str = None
    , value = None
    ):

    """

    :param optimizations:
    :param level:
    :param classes:
    :param value:
    :return:
    """

    if optimizations and not value and isinstance(optimizations, types.FunctionType):
        optimizations, value = value, optimizations

    if optimizations:
        if not isinstance(optimizations, (list, tuple)):
            optimizations = (optimizations, )
    else:
        optimizations = (opt for _, opt in BasicOptimization.optimizations.items())

    optimizations = (op if isinstance(op, classes or (BasicOptimization, )) else op() for op in optimizations)

    if level:
        optimizations = (op for op in optimizations if op.level <= level)

    if value:
        result = transform(value, optimizations, file=file)
    else:
        result = functools.partial(transform, transformers=optimizations, file=file)

    return result

def get_source\
    ( value
    , optimized: bool = False
    , optimizations: (BasicOptimization, type, list, tuple) = None
    , level: (float, int) = None
    , classes: tuple = None
    , iter_count: int = 10
    ):

    """

    """

    if not value:
        return ""

    if optimized:
        try:
            file = inspect.getfile(value)
        except TypeError:
            file = None
        for i in range(iter_count):
            value = optimize\
                    ( optimizations = optimizations
                    , level         = level
                    , classes       = classes
                    , file          = file
                    , value         = value
                    )

    if isinstance(value, str):
        result = value
    else:
        tree   = to_ast(value)
        result = ast_to_source(tree)

    return result


text:
@interface HZPushViewController : UIViewController

@end


text:
package mobi.hsz.idea.latex.actions.editor;

import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.text.StringUtil;
import mobi.hsz.idea.latex.LatexBundle;
import mobi.hsz.idea.latex.actions.editor.base.DialogEditorAction;
import mobi.hsz.idea.latex.ui.ImageEditorActionDialog;
import mobi.hsz.idea.latex.util.Icons;
import org.jetbrains.annotations.NotNull;

/**
 * Editor action - insert image.
 *
 * @author Jakub Chrzanowski <jakub@hsz.mobi>
 * @since 0.3
 */
public class ImageAction extends DialogEditorAction<ImageEditorActionDialog> {

    /** Builds a new instance of {@link ImageAction}. */
    public ImageAction() {
        super(Type.IMAGE, LatexBundle.message("editor.image"), Icons.Editor.IMAGE);
    }

    @NotNull
    @Override
    protected ImageEditorActionDialog getDialog(@NotNull Project project) {
        return new ImageEditorActionDialog(project);
    }

    @NotNull
    @Override
    protected String getContent(@NotNull ImageEditorActionDialog dialog) {
        StringBuilder sb = new StringBuilder();
        String path = dialog.getPath();
        String caption = dialog.getCaption();
        String label = dialog.getLabel();

        sb.append("\\begin{figure}\n");
        sb.append("\\centering\n");
        sb.append("\\includegraphics");
        sb.append(String.format("{%s}\n", path));

        if (!StringUtil.isEmpty(caption)) {
            sb.append(String.format("\\caption{%s}\n", caption));
        }
        if (!StringUtil.isEmpty(label)) {
            sb.append(String.format("\\label{%s}\n", label));
        }

        sb.append("\\end{figure}");

        return sb.toString();
    }

}


text:
"use strict";

var collectPidFiles = require('./collect-pid-files');

module.exports = function findPids(task, grunt) {
  if (task.filesSrc != null && task.filesSrc.length > 0) {
    return collectPidFiles(task.filesSrc, grunt);
  }
  else if (task.options.pid != null) {
    return handlePidOption(task.options.pid, grunt);
  }
  else {
    return [];
  }
};

function handlePidOption(pidSpecified, grunt) {
  if (typeof pidSpecified === 'string') {
    return handlePidOptionAsString(pidSpecified, grunt);
  }
  else if (typeof pidSpecified === 'function') {
    return [ pidSpecified() ];
  }
  else if (!isNaN(pidSpecified)) {
    return [ pidSpecified ];
  }
}

function handlePidOptionAsString(pidSpecified, grunt) {
  var pid = parseInt(pidSpecified, 10);

  if (isNaN(pid)) {
    return collectPidFiles([ pidSpecified ], grunt);
  }
  else {
    return [ pid ];
  }
}