text:
'use strict';

// Header Component: load-bar
Vue.component('load-bar', {
    template: '<transition name="fade">

</transition>',
    props: {
        'progress': {
            type: Number,
            default: 0
        }
    },
    computed: {
        show_load_bar: function() {
            return (this.progress > 0 && this.progress < 100);
        },
        style_object: function() {
            return {
                width: this.progress + '%'
            }
        },
        class_object: function() {
            return {
                'is-loading': this.show_load_bar
            }
        }
    }
});

// Header Component: Introduce
Vue.component('toolkit-intro', {
    template: '
\

Train Query Helper
\

Distributed under the MIT License.
Implemented in Python. Written by ShadowMan(Wang).
\

\
                    Online: {{ online_count }}\
                    Active: {{ active_count }}\

\

',
    props: [ 'online_count', 'active_count' ],
    computed: {
        online_style: function() {
            return {
                color: this.online_count < 10 ? 'green' : 'red'
            }
        },
        active_style: function() {
            return {
                color: this.active_count < 5 ? 'green' : 'red'
            }
        }
    }
});

// Header Component
Vue.component('train-query-header', {
    template: '' +
                  '<load-bar :progress="progress"></load-bar>' +
                  '<toolkit-intro :online_count="online_count" :active_count="active_count"></toolkit-intro>' +
              '',
    props: [ 'progress', 'online_count', 'active_count' ]
});

// Body Component: input-group
Vue.component('input-group', {
    template: '
' +
                  '{{ label }}' +
                  '<input v-if="type == \'text\'" :class="inputClass" type="text" :style="input_style" :name="name" v-model="input_value" @change="send_input_value">' +
                  '<input v-if="type == \'date\'" :class="inputClass" type="date" :style="input_style" :name="name" v-model="input_value" @change="send_input_value">' +
              '
',
    props: [ 'label', 'name', 'label-class', 'input-class', 'type' ],
    data: function() {
        return {
            input_value: '',
            input_status: 'default'
        }
    },
    computed: {
        input_style: function() {
            if (!this.input_value.length) {
                this.input_status = 'default';
                return { borderColor: null };
            }

            switch (this.input_status) {
                case 'default': break;
                case 'error': return { borderColor: '#F00' }; break;
                case 'success': return { borderColor: '#0F0' }; break;
                case 'waiting': return { borderColor: '#FF0' }; break;
            }
        }
    },
    methods: {
        send_input_value: function() {
            this.$emit('receive_input_data', {
                name: this.name,
                value: this.input_value
            })
        }
    }
});

Vue.component('train-query-parameter', {
    template: '
<form>' +
                  '<input-group type="text" label="FROM" name="from_station" ref="from_station" label-class="input-group-label" input-class="input-group-input" @receive_input_data="parse_input_data"></input-group>' +
                  '<input-group type="text" label="TO" name="to_station" ref="to_station" label-class="input-group-label" input-class="input-group-input" @receive_input_data="parse_input_data"></input-group>' +
                  '<input-group type="date" label="DATE" name="train_date" ref="train_date" label-class="input-group-label" input-class="input-group-input" @receive_input_data="parse_input_data"></input-group>' +
                  '<button class="train-query-submit widget-btn widget-btn-default" :class="button_style" :disabled="is_disable" @click.stop.prevent="query_train">Start</button>' +
              '</form>
',
    props: [ 'from-station', 'to-station', 'train-date' ],
    computed: {
        button_style: function() {
            var button_style_name = null;
            if (this.fromStation && this.toStation && this.trainDate) {
                button_style_name = 'default';
            } else {
                button_style_name = 'disabled';
            }

            return 'widget-btn-' + button_style_name;
        },
        is_disable: function() {
            return this.button_style == 'widget-btn-disabled';
        }
    },
    methods: {
        parse_input_data: function(data) {
            // is station data
            if (data.name === 'from_station' || data.name === 'to_station') {
                // the value is empty, notice parent-component, break
                if (!data.value.length) {
                    this.$emit('receive_input_true_data', data.name, '');
                    return;
                }
                // send request, check station exists
                this.$root.socket.emit('request.train.station', { station_name: data.value, key: data.name });

                // Vue instance reference
                var _self = this;
                // socket.io event
                this.$root.socket.on('response.train.station', function(response) {
                    // input-group component reference
                    var sub_component = (response.key === 'from_station') ? _self.$refs.from_station : _self.$refs.to_station;
                    // the station is exists
                    if (response.status === true) {
                        // update sub-component status
                        sub_component.input_status = 'success';
                        // emit parent-component event
                        this.$emit('receive_input_true_data', response.key, response.station_code);
                        // change progress
                        this.$root.event_bus.$emit('change-progress', 10, true);
                        // reset error
                        this.$root.event_bus.$emit('reset-error', response.key);
                    // station non-exists
                    } else {
                        // update sub-component status
                        sub_component.input_status = 'error';
                        // change progress
                        this.$root.event_bus.$emit('change-progress', -10, true);
                        // empty station code
                        this.$emit('receive_input_true_data', response.key, '');
                        // show error message
                        this.$root.event_bus.$emit('error-occurs', response.key, response.message, 'warning');
                    }
                }.bind(this));
            // is date data
            } else if (data.name === 'train_date') {
                var sub_component = this.$refs.train_date;
                var select_date = new Date(data.value.replace(/-/g, '/'));
                var current_date = new Date();

                var select_date_timestamp = select_date.getTime() / 1000;
                var current_date_timestamp = current_date.getTime() / 1000;

                if ((current_date_timestamp - select_date_timestamp < 86400)
                    || (select_date_timestamp > current_date_timestamp)) {
                    // change input status
                    sub_component.input_status = 'success';
                    // update train data
                    this.$emit('receive_input_true_data', 'train_date', data.value);
                    // change progress
                    this.$root.event_bus.$emit('change-progress', 10, true);
                } else {
                    // update train date to empty
                    this.$emit('receive_input_true_data', data.name, '');
                    // update input status
                    sub_component.input_status = 'error';
                    // change progress
                    this.$root.event_bus.$emit('change-progress', -10, true);
                }
            }
        },
        query_train: function() {
            if (this.fromStation && this.toStation && this.trainDate) {
                // change progress
                this.$root.event_bus.$emit('change-progress', 3, true);
                // change progress
                this.$root.event_bus.$emit('trigger-query-animation');
                // reset response
                this.$root.event_bus.$emit('reset-response');
                // WebSocket send request
                this.$root.socket.emit('request.train.list', {
                    from: this.fromStation,
                    to: this.toStation,
                    date: this.trainDate,
                    ts: (new Date()).getTime()
                });
            } else {
                alert('Hey Guy, too young, too simple, sometimes native')
            }
        }
    }
});

Vue.component('error-info', {
    template: '<transition name="fade">

{{ error }}

</transition>',
    props: ['error', 'level'],
    computed: {
        'error_class': function() {
            return 'error-level-' + (this.level ? this.level : 'default');
        }
    }
});

Vue.component('query-progress-animation', {
    template: '<transition name="query-animation">

</transition>',
    props: ['show']
});

Vue.component('train-list', {
    // here hidden train code list
    //

    template: '<transition name="fade">\

\

Total {{ count }} {{ train_word }}
\

\

{{ train_code }}
\

\

\
               </transition>',
    props: {
        count: {
            required: true,
            type: Number
        },
        list: {
            required: true,
            type: Array
        }
    },
    computed: {
        train_word: function() {
            return 'Train' + (this.count == 1 ? '' : 's');
        }
    }
});

Vue.component('train-profile', {
    template: '
\
                   {{ profile.train_code }}	\
                   {{ profile.start_station[0] }}	\
                   {{ profile.end_station[0] }}	\
                   {{ profile.start_time }}	\
                   {{ profile.arrive_time }}	\
                   {{ profile.total_time }}	\
                   <button class="widget-btn widget-btn-default" :class="{ \'widget-btn-disabled\': profile.available }" :disabled="profile.available" title="Already available and does not need to query">Check</button>	\
                   {{ profile.train_status }}	\

',
    props: [ 'profile', 'status_tag' ]
});

Vue.component('train-query-result', {
    template: '
<transition-group name="down-fade" tag="table" class="train-query-result-container">\
                      <train-profile v-if="trains.length" :profile="train_title" key="train_table_title" :status_tag="\'text\'"></train-profile>\
                      <train-profile v-for="train in trains" :profile="train" :key="train.train_code" :status_tag="\'button\'"></train-profile>\
               </transition-group>
',
    data: function() {
        return {
            train_title: {
                train_code: 'Train Code',
                start_station: [ 'Start Station' ],
                end_station: [ 'End Station' ],
                start_time: 'Start Time',
                arrive_time: 'Arrive Time',
                total_time: 'Total Time',
                train_status: 'Status'
            }
        }
    },
    props: ['trains']
});

Vue.component('train-query-contents', {
    template: '
\
                   <train-query-parameter :from-station="from_station" :to-station="to_station" :train-date="train_date" @receive_input_true_data="receive_true_data"></train-query-parameter>\
                   <error-info :error="error_message" :level="error_level"></error-info>\
                   <query-progress-animation :show="show_progress"></query-progress-animation>\
                   <train-list :count="response_train_count" :list="response_train_list"></train-list>\
                   <train-query-result :trains="response_train_profile"></train-query-result>\

',
    data: function() {
        return {
            from_station: '',
            to_station: '',
            train_date: '',
            error_message: '',
            error_level: '',
            show_progress: false,
            error_trigger: null,
            response_train_count: 0,
            response_train_list: [],
            response_train_profile: []
        }
    },
    methods: {
        receive_true_data: function(name, true_data) {
            switch (name) {
                case 'from_station': this.from_station = true_data; break;
                case 'to_station': this.to_station = true_data; break;
                case 'train_date': this.train_date = true_data; break;
            }

            if (this.from_station && this.to_station && this.train_date) {
                this.$emit('package_query_parameter', this.from_station, this.to_station, this.train_date);
            }
        }
    },
    created: function() {
        // receive train count
        this.$root.socket.on('response.train.count', function(message) {
            this.response_train_count = message.count;
        }.bind(this));
        // receive train list
        this.$root.socket.on('response.train.list', function(message) {
            this.response_train_list = message.list;
        }.bind(this));
        // receive train progress
        this.$root.socket.on('response.train.query.progress', function(message) {
            if (message.status === false) {
                // reset progress
                this.$root.event_bus.$emit('change-progress', 0);
                // trigger error
                this.$root.event_bus.$emit('error-occurs', 'socket', message.message);
            }
            if (message.progress === 100) {
                if (this.response_train_profile.length == 0) {
                    this.$root.event_bus.$emit('error-occurs', 'socket', 'Empty Trains')
                }

                // If increase to 100, then the element is gone directly
                this.$root.event_bus.$emit('change-progress', 99.999);
                // after increase to 100
                setTimeout(function() {
                    this.$root.event_bus.$emit('change-progress', 100);
                }.bind(this), 1000);
            } else if (message.progress == 0) {
                this.$root.event_bus.$emit('change-progress', 2, true);
            }
        }.bind(this));
        // receive each train profile
        this.$root.socket.on('response.train.profile', function(message) {
            this.response_train_profile.push(message)
        }.bind(this));
        // receive error message
        this.$root.event_bus.$on('error-occurs', function(trigger, error, error_level) {
            this.error_trigger = trigger;
            this.error_message = error;
        }.bind(this));
        // reset error
        this.$root.event_bus.$on('reset-error', function(trigger) {
            if (trigger && trigger === this.error_trigger) {
                this.error_message = '';
                this.error_level = '';
                this.error_trigger = '';
            }
        }.bind(this));
        // start query animation
        this.$root.event_bus.$on('trigger-query-animation', function() {
            this.show_progress = !this.show_progress;
        }.bind(this));
        // reset response
        this.$root.event_bus.$on('reset-response', function() {
            this.response_train_profile = [];
            this.response_train_count = 0;
            this.response_train_list = [];
        }.bind(this));
    }
});

Vue.component('train-query-footer', {
    template: ''
});


text:
using Gem.Gui.Input;
using Gem.Infrastructure.Input;

namespace Gem.Gui.Aggregation
{
    /// <summary>
    /// Factory for returning scripts that are used by ScriptAggregator to aggregate the controls
    /// </summary>
    public static class Script
    {
        public static ScriptAggregator<KeyboardInput> ForKeyboard(KeyboardInputKeys keyboardKeys)
        {
            return new ScriptAggregator<KeyboardInput>(InputManager.Keyboard,
                                                             //never disable
                                                             input => false,
                                                             input => input.IsKeyPressed(keyboardKeys.Next),
                                                             input => input.IsKeyPressed(keyboardKeys.Previous),
                                                             input => input.IsKeyClicked(keyboardKeys.Trigger),
                                                             InputManager.KeyRepetition);
        }

        public static ScriptAggregator<GamePadInput> ForGamePad(GamePadInputButtons gamepadButtons)
        {
            return new ScriptAggregator<GamePadInput>(InputManager.GamePad,
                                                             input => !input.IsConnected,
                                                             input => input.IsButtonPressed(gamepadButtons.Next),
                                                             input => input.IsButtonPressed(gamepadButtons.Previous),
                                                             input => input.IsButtonClicked(gamepadButtons.Trigger),
                                                             InputManager.KeyRepetition);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

defined('MBQ_IN_IT') or exit;

MbqMain::$oClk->includeClass('MbqBaseActLogoutUser');

/**
 * logout_user action
 *
 * @since  2012-8-27
 * @author Wu ZeTao <578014287@qq.com>
 */
Class MbqActLogoutUser extends MbqBaseActLogoutUser {

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

    /**
     * action implement
     */
    public function actionImplement() {
        parent::actionImplement();
    }

}

?>


text:
import logging
import rmqid
import time

ROUTING_KEY = 'benchmark_get'
ITERATIONS = 100000

logging.basicConfig(level=logging.INFO)

with open('lorem.txt') as handle:
    BODY = handle.read()

logging.info('Starting benchmark')
with rmqid.Connection() as connection:
    with connection.channel() as channel:
        queue = rmqid.Queue(channel, ROUTING_KEY,
                            auto_delete=True, exclusive=True)
        queue.declare()
        logging.info('Queue declared, publishing %i messages', ITERATIONS)
        for iteration in range(0, ITERATIONS):
            message = rmqid.Message(channel, BODY[:2048],
                                    {'content_type': 'text/plain',
                                     'delivery_mode': 1})
            message.publish('', ROUTING_KEY)

        received = 0
        start_time = time.time()
        while received < ITERATIONS:
            message = queue.get(acknowledge=False)
            #message.ack()
            received += 1

total_time = time.time() - start_time
velocity = float(ITERATIONS / total_time)
logging.info('Get %.2f messages/sec in %.2f seconds', velocity, total_time)


text:
package datasafer.backup.dao;

import java.math.BigInteger;
import java.security.SecureRandom;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import datasafer.backup.model.Autorizacao;
import datasafer.backup.model.Usuario;

@Repository
public class AutorizacaoDao {

	@PersistenceContext
	private EntityManager manager;

	private static final SecureRandom randomGenerator = new SecureRandom();

	@Transactional
	public Autorizacao obtemAutorizacao(String ip,
										String token_autorizacao) {
		List<Autorizacao> resultadosToken = manager	.createQuery(
																"SELECT a FROM Autorizacao a "
																		+ "WHERE a.token = :token_autorizacao "
																		+ "AND a.ip = :ip_autorizacao ",
																Autorizacao.class)
													.setParameter("token_autorizacao", token_autorizacao)
													.setParameter("ip_autorizacao", ip)
													.getResultList();

		Autorizacao autorizacao = resultadosToken.isEmpty()	? null
															: resultadosToken.get(0);

		if (autorizacao != null) {
			autorizacao.setUltimoAcesso(Timestamp.from(LocalDateTime.now()
																	.toInstant(ZoneOffset.UTC)));
		}

		return autorizacao;
	}

	@Transactional
	public Autorizacao emiteAutorizacao(Usuario usuario,
										String ip) {

		usuario = manager.find(Usuario.class, usuario.getId());

		manager	.createQuery("DELETE "
				+ "FROM Autorizacao a "
				+ "WHERE a.ip = :ip_autorizacao "
				+ "AND a.usuario.id = :id_usuario ")
				.setParameter("ip_autorizacao", ip)
				.setParameter("id_usuario", usuario.getId())
				.executeUpdate();

		String novo_token = null;
		do {
			novo_token = new BigInteger(635, randomGenerator).toString(32);
		} while (this.obtemAutorizacao(ip, novo_token) != null);

		Autorizacao autorizacao = new Autorizacao();
		autorizacao.setToken(novo_token);
		autorizacao.setIp(ip);
		autorizacao.setEmissao(Timestamp.from(LocalDateTime	.now()
															.toInstant(ZoneOffset.UTC)));

		usuario	.getAutorizacoes()
				.add(autorizacao);
		autorizacao.setUsuario(usuario);

		manager.persist(autorizacao);

		return autorizacao;
	}

	@Transactional
	public void revogaAutorizacoes(Usuario usuario) {

		manager	.createQuery("DELETE "
				+ "FROM Autorizacao a "
				+ "WHERE a.usuario.id = :id_usuario ")
				.setParameter("id_usuario", usuario.getId())
				.executeUpdate();

	}

	@Transactional
	public void revogaToken(Autorizacao autorizacao) {

		manager	.createQuery("DELETE "
				+ "FROM Autorizacao a "
				+ "WHERE a.token = :token_autorizacao ")
				.setParameter("token_autorizacao", autorizacao.getToken())
				.executeUpdate();

	}

	@Transactional
	public void limpaAutorizacoes(Integer dias) {

		manager	.createQuery("DELETE "
				+ "FROM Autorizacao a "
				+ "WHERE a.ultimoAcesso IS NOT NULL "
				+ "AND a.ultimoAcesso < :data ")
				.setParameter("data", Timestamp.from(LocalDateTime	.now().minusDays(dias)
																	.toInstant(ZoneOffset.UTC)))
				.executeUpdate();
	}

	public Usuario login(Usuario usuario) {
		List<Usuario> results = manager	.createQuery(
													"SELECT usuario FROM Usuario usuario "
															+ "WHERE usuario.login = :login_usuario "
															+ "AND usuario.senha = :senha_usuario ",
													Usuario.class)
										.setParameter("login_usuario", usuario.getLogin())
										.setParameter("senha_usuario", usuario.getSenha())
										.getResultList();

		return results.isEmpty()	? null
									: results.get(0);
	}
}


text:
#ifndef __GWEN_OPENGL3_CORE_RENDERER_H
#define __GWEN_OPENGL3_CORE_RENDERER_H

#include "Gwen/Gwen.h"
#include "Gwen/BaseRender.h"
#include "GLPrimitiveRenderer.h"
#include "../OpenGLWindow/OpenGLInclude.h"

struct sth_stash;
#include "fontstash.h"
#include "Gwen/Texture.h"

#include "TwFonts.h"
static float extraSpacing = 0.;  //6f;
#include <assert.h>
#include <math.h>

template <class T>
inline void MyClamp(T& a, const T& lb, const T& ub)
{
	if (a < lb)
	{
		a = lb;
	}
	else if (ub < a)
	{
		a = ub;
	}
}

static GLuint BindFont(const CTexFont* _Font)
{
	GLuint TexID = 0;
	glGenTextures(1, &TexID);
	glBindTexture(GL_TEXTURE_2D, TexID);
	glPixelStorei(GL_UNPACK_SWAP_BYTES, GL_FALSE);
	glPixelStorei(GL_UNPACK_LSB_FIRST, GL_FALSE);
	glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
	glPixelStorei(GL_UNPACK_SKIP_ROWS, 0);
	glPixelStorei(GL_UNPACK_SKIP_PIXELS, 0);
	glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
	glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, _Font->m_TexWidth, _Font->m_TexHeight, 0, GL_RED, GL_UNSIGNED_BYTE, _Font->m_TexBytes);
	glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
	glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
	glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
	glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
	glBindTexture(GL_TEXTURE_2D, 0);

	return TexID;
}

struct MyTextureLoader
{
	virtual ~MyTextureLoader()
	{
	}
	virtual void LoadTexture(Gwen::Texture* pTexture) = 0;
	virtual void FreeTexture(Gwen::Texture* pTexture) = 0;
};

class GwenOpenGL3CoreRenderer : public Gwen::Renderer::Base
{
	GLPrimitiveRenderer* m_primitiveRenderer;
	float m_currentColor[4];
	float m_yOffset;
	sth_stash* m_font;
	float m_screenWidth;
	float m_screenHeight;
	float m_fontScaling;
	float m_retinaScale;
	bool m_useTrueTypeFont;
	const CTexFont* m_currentFont;

	GLuint m_fontTextureId;
	MyTextureLoader* m_textureLoader;

public:
	GwenOpenGL3CoreRenderer(GLPrimitiveRenderer* primRender, sth_stash* font, float screenWidth, float screenHeight, float retinaScale, MyTextureLoader* loader = 0)
		: m_primitiveRenderer(primRender),
		  m_font(font),
		  m_screenWidth(screenWidth),
		  m_screenHeight(screenHeight),
		  m_retinaScale(retinaScale),
		  m_useTrueTypeFont(false),
		  m_textureLoader(loader)
	{
		///only enable true type fonts on Macbook Retina, it looks gorgeous
		if (retinaScale == 2.0f)
		{
			m_useTrueTypeFont = true;
		}
		m_currentColor[0] = 1;
		m_currentColor[1] = 1;
		m_currentColor[2] = 1;
		m_currentColor[3] = 1;

		m_fontScaling = 16.f * m_retinaScale;

		TwGenerateDefaultFonts();

		m_currentFont = g_DefaultNormalFont;
		//m_currentFont = g_DefaultNormalFontAA;

		//m_currentFont = g_DefaultLargeFont;
		m_fontTextureId = BindFont(m_currentFont);
	}

	virtual ~GwenOpenGL3CoreRenderer()
	{
		TwDeleteDefaultFonts();
	}
	virtual void Resize(int width, int height)
	{
		m_screenWidth = width;
		m_screenHeight = height;
	}

	virtual void Begin()
	{
		m_yOffset = 0;
		glEnable(GL_BLEND);
		assert(glGetError() == GL_NO_ERROR);

		glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

		assert(glGetError() == GL_NO_ERROR);

		assert(glGetError() == GL_NO_ERROR);

		glDisable(GL_DEPTH_TEST);
		assert(glGetError() == GL_NO_ERROR);
		//glColor4ub(255,0,0,255);

		glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

		//	saveOpenGLState(width,height);//m_glutScreenWidth,m_glutScreenHeight);

		assert(glGetError() == GL_NO_ERROR);

		glDisable(GL_CULL_FACE);

		glDisable(GL_DEPTH_TEST);
		assert(glGetError() == GL_NO_ERROR);

		glEnable(GL_BLEND);

		assert(glGetError() == GL_NO_ERROR);
	}
	virtual void End()
	{
		glDisable(GL_BLEND);
	}

	virtual void StartClip()
	{
		if (m_useTrueTypeFont)
			sth_flush_draw(m_font);
		Gwen::Rect rect = ClipRegion();

		// OpenGL's coords are from the bottom left
		// so we need to translate them here.
		{
			GLint view[4];
			glGetIntegerv(GL_VIEWPORT, &view[0]);
			rect.y = view[3] / m_retinaScale - (rect.y + rect.h);
		}

		glScissor(m_retinaScale * rect.x * Scale(), m_retinaScale * rect.y * Scale(), m_retinaScale * rect.w * Scale(), m_retinaScale * rect.h * Scale());
		glEnable(GL_SCISSOR_TEST);
		//glDisable( GL_SCISSOR_TEST );
	};

	virtual void EndClip()
	{
		if (m_useTrueTypeFont)
			sth_flush_draw(m_font);
		glDisable(GL_SCISSOR_TEST);
	};

	virtual void SetDrawColor(Gwen::Color color)
	{
		m_currentColor[0] = color.r / 256.f;
		m_currentColor[1] = color.g / 256.f;
		m_currentColor[2] = color.b / 256.f;
		m_currentColor[3] = color.a / 256.f;
	}
	virtual void DrawFilledRect(Gwen::Rect rect)
	{
		//		BT_PROFILE("GWEN_DrawFilledRect");
		Translate(rect);

		m_primitiveRenderer->drawRect(rect.x, rect.y + m_yOffset,
									  rect.x + rect.w, rect.y + rect.h + m_yOffset, m_currentColor);

		//		m_primitiveRenderer->drawTexturedRect2a(rect.x, rect.y+m_yOffset,
		//		rect.x+rect.w, rect.y+rect.h+m_yOffset, m_currentColor,0,0,1,1);
		//		m_yOffset+=rect.h+10;
	}

	void RenderText(Gwen::Font* pFont, Gwen::Point rasterPos, const Gwen::UnicodeString& text)
	{
		//		BT_PROFILE("GWEN_RenderText");

		Gwen::String str = Gwen::Utility::UnicodeToString(text);
		const char* unicodeText = (const char*)str.c_str();

		Gwen::Rect r;
		r.x = rasterPos.x;
		r.y = rasterPos.y;
		r.w = 0;
		r.h = 0;

		//
		//printf("str = %s\n",unicodeText);
		//int xpos=0;
		//int ypos=0;
		float dx;

		int measureOnly = 0;

		if (m_useTrueTypeFont)
		{
			float yoffset = 0.f;
			if (m_retinaScale == 2.0f)
			{
				yoffset = -12;
			}
			Translate(r);
			sth_draw_text(m_font,
						  1, m_fontScaling,
						  r.x, r.y + yoffset,
						  unicodeText, &dx, m_screenWidth, m_screenHeight, measureOnly, m_retinaScale);
		}
		else
		{
			//float width = 0.f;
			int pos = 0;
			//float color[]={0.2f,0.2,0.2f,1.f};

			glBindTexture(GL_TEXTURE_2D, m_fontTextureId);
			float width = r.x;

			while (unicodeText[pos])
			{
				int c = unicodeText[pos];
				r.h = m_currentFont->m_CharHeight;
				r.w = m_currentFont->m_CharWidth[c] + extraSpacing;
				Gwen::Rect rect = r;
				Translate(rect);

				m_primitiveRenderer->drawTexturedRect2(rect.x, rect.y + m_yOffset, rect.x + rect.w, rect.y + rect.h + m_yOffset, m_currentColor, m_currentFont->m_CharU0[c], m_currentFont->m_CharV0[c], m_currentFont->m_CharU1[c], m_currentFont->m_CharV1[c]);

				width += r.w;
				r.x = width;
				pos++;
			}
			{
				m_primitiveRenderer->drawTexturedRect3D2Text(false);
			}
			glBindTexture(GL_TEXTURE_2D, 0);
		}
	}
	Gwen::Point MeasureText(Gwen::Font* pFont, const Gwen::UnicodeString& text)
	{
		//		BT_PROFILE("GWEN_MeasureText");
		Gwen::String str = Gwen::Utility::UnicodeToString(text);
		const char* unicodeText = (const char*)str.c_str();

		// printf("str = %s\n",unicodeText);
		int xpos = 0;
		int ypos = 0;

		int measureOnly = 1;
		float dx = 0;
		if (m_useTrueTypeFont)
		{
			sth_draw_text(m_font,
						  1, m_fontScaling,
						  xpos, ypos,
						  unicodeText, &dx, m_screenWidth, m_screenHeight, measureOnly);

			Gwen::Point pt;

			if (m_retinaScale == 2.0f)
			{
				pt.x = dx * Scale() / 2.f;
				pt.y = m_fontScaling / 2 * Scale() + 1;
			}
			else
			{
				pt.x = dx * Scale();
				pt.y = m_fontScaling * Scale() + 1;
			}
			return pt;
		}
		else
		{
			float width = 0.f;
			int pos = 0;
			while (unicodeText[pos])
			{
				width += m_currentFont->m_CharWidth[(int)unicodeText[pos]] + extraSpacing;
				pos++;
			}
			Gwen::Point pt;
			int fontHeight = m_currentFont->m_CharHeight;

			pt.x = width * Scale();
			pt.y = (fontHeight + 2) * Scale();

			return pt;
		}

		return Gwen::Renderer::Base::MeasureText(pFont, text);
	}

	virtual void LoadTexture(Gwen::Texture* pTexture)
	{
		if (m_textureLoader)
			m_textureLoader->LoadTexture(pTexture);
	}
	virtual void FreeTexture(Gwen::Texture* pTexture)
	{
		if (m_textureLoader)
			m_textureLoader->FreeTexture(pTexture);
	}

	virtual void DrawTexturedRect(Gwen::Texture* pTexture, Gwen::Rect rect, float u1 = 0.0f, float v1 = 0.0f, float u2 = 1.0f, float v2 = 1.0f)
	{
		//		BT_PROFILE("DrawTexturedRect");
		Translate(rect);

		//float eraseColor[4] = {0,0,0,0};
		//m_primitiveRenderer->drawRect(rect.x, rect.y+m_yOffset, rect.x+rect.w, rect.y+rect.h+m_yOffset, eraseColor);

		GLint texHandle = (GLint)pTexture->m_intData;
		//if (!texHandle)
		//	return;

		glActiveTexture(GL_TEXTURE0);
		glBindTexture(GL_TEXTURE_2D, texHandle);
		//		glDisable(GL_DEPTH_TEST);

		assert(glGetError() == GL_NO_ERROR);

		/*	bool useFiltering = true;
	if (useFiltering)
	{
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	} else
	{
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
	}
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
*/

		//glEnable(GL_TEXTURE_2D);

		//	glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_NONE );
		static float add = 0.0;
		//add+=1./512.;//0.01;
		float color[4] = {1, 1, 1, 1};

		m_primitiveRenderer->drawTexturedRect(rect.x, rect.y + m_yOffset, rect.x + rect.w, rect.y + rect.h + m_yOffset, color, 0 + add, 0, 1 + add, 1, true);

		assert(glGetError() == GL_NO_ERROR);
	}
};
#endif  //__GWEN_OPENGL3_CORE_RENDERER_H


text:
---
layout: post
title: "Chrome extensions for quick site redesigns"
category: posts
---

There's this thing I hate about the modern web which is that sites are rarely
one giant html file filled with goodies. You can't just "run a site" locally.
You need an `npm` or a `gulp` step or a `docker` if you're lucky. And probably
a local server, but not the one you have installed. Which, I mean,
makes sense, because modern web sites are big and powerful and have complicated
front-ends and _do_ more things than a giant html file would. But
it also kind of sucks because the build ceremonial sacrifices can be a bit overwhelming.
Maybe you just want to see what the links would look like if they didn't have
underlines. Maybe you want to change the fonts. Maybe you're never even
going to ship these changes, you just want to get a feel for them.

Boy, have I got an idea for you: Chrome extensions. Hear me out. A Chrome extension
is a bit of code that runs on a specific page (or set of pages). It can be anything
you want. In particular, it can be a CSS stylesheet.

Then, re-theming a site is just a matter of installing this Chrome extension. If
you want to share it with people, you can just zip it up and send it around.
It's obviously not production ready, but it's amaaaaazing for prototyping.

I made a [glitch](https://glitch.com/edit/#!/chrome-css-extension) project
that gets you started with writing a Chrome extension that injects a CSS stylesheet.
There's only one thing you need to know: this stylesheet is a _User Agent_
stylesheet, which means it has the lowest specificity. So some of its styles
won't get applied unless you slap some `!important`s on it (or have extra
specific selectors). Or, if you have an ID, you can do my favourite CSS hack ever
that I learnt from [Surma](https://twitter.com/dassurma) and will take to the grave:

```css
#foo#foo {
  /* this is a really winner #foo selector */
  color: red;
}
```

<hr>

That's it! If you want to see an example of such an extension in the wild, I made [picasso](https://github.com/notwaldorf/picasso),
which is just a pretty Google Calendar theme. Originally it was just a local
extension I kept on my machine, but eventually I published it because I
realized other people may want to give their calendar a bubble bath. Anyway, happy retheming!


text:
using static STULib.Types.Generic.Common;

namespace STULib.Types.Dump {
    [STU(0x78D39627)]
    public class STU_78D39627 : STULib.Types.STUConfigVar {
    }
}


text:
from __future__ import division

import wx
import os

from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg
from matplotlib.figure import Figure
import numpy as n

from wanglib.pylab_extensions.density import density_plot

class MainWindow(wx.Frame):

    def __init__(self, parent, title, filename=None):
        wx.Frame.__init__(self, parent, title=title, size=(500,400))

        self.panel = ImagePanel(self)

        #self.CreateStatusBar()

        filemenu = wx.Menu()

        menuAbout = filemenu.Append(wx.ID_ABOUT, "&About", " Info plz")
        #filemenu.AppendSeparator()
        menuExit = filemenu.Append(wx.ID_EXIT, "E&xit", " Stop program")
        menuOpen = filemenu.Append(wx.ID_OPEN, "&Open", " open a file")

        menuBar = wx.MenuBar()
        menuBar.Append(filemenu, "&File")
        self.SetMenuBar(menuBar)

        self.Bind(wx.EVT_MENU, self.OnAbout, menuAbout)
        self.Bind(wx.EVT_MENU, self.OnExit, menuExit)
        self.Bind(wx.EVT_MENU, self.OnOpen, menuOpen)

        if filename is not None:
            self.open('', filename)

        #self.Show(True)

    def OnAbout(self, e):
        dlg = wx.MessageDialog(self, "small text editior",
                'about this prog', wx.OK)
        dlg.ShowModal()
        dlg.Destroy()

    def OnExit(self, e):
        self.Close(True)

    def OnOpen(self, e):
        self.dirname = ''
        dlg = wx.FileDialog(self,
                message="Choose a file",
                defaultDir=self.dirname,
                defaultFile='',
                wildcard="NPZ files (*.npz)|*.npz",
                style=wx.FD_OPEN)
        if dlg.ShowModal() == wx.ID_OK:
            self.filename = dlg.GetFilename()
            self.dirname = dlg.GetDirectory()
            self.open(self.dirname, self.filename)
        dlg.Destroy()

    def open(self, dirname, filename):
        self.panel.open(dirname, filename)
        self.SetTitle(filename)

from .imaging import (show_image, add_hist_to_cbar,
                      add_nice_sizebar, add_marker)

class ImagePanel(wx.Panel):

    def __init__(self, parent, size=(4096, 4096)):
        """
        Create a new image panel with an (initially) blank image.

        Set size of the blank image with 'size'
        """

        wx.Panel.__init__(self, parent)

        vector = n.ndarray((2,2))
        vector[:] = n.nan

        fig = Figure()
        self.ax = fig.add_subplot(111)
        #self.im = self.ax.imshow(vector)
        self.im = density_plot(vector,
                               n.array((0,size[0]/2)),
                               n.array((0,size[1]/2)),
                               ax=self.ax)

        self.cbar = fig.colorbar(self.im, aspect=8)
        self.ax.invert_xaxis()

        # whether the vertical scale is locked
        self.scale_locked = False

        self.canvas = FigureCanvasWxAgg(self, -1, fig)
        self.canvas.draw()

        def relimcolor(state):
            im = self.im
            if not state.mousedown.inaxes == state.mouseup.inaxes:
                # drag was not contained in one axes
                return
            elif state.mousedown.inaxes is None:
                # drag was totally outside axes
                return
            if state.mousedown.inaxes == self.cbar.ax:
                # if we are in the colorbar
                scaling = state.mouseup.ydata/state.mousedown.ydata
                if scaling == 1:
                    # restore zoom
                    im.autoscale()
                    self.scale_locked = False
                elif scaling > 1:
                    # adjust vmax
                    vmin, vmax = im.get_clim()
                    im.set_clim(vmax = vmin + (vmax - vmin)/scaling)
                    self.scale_locked = True
                elif scaling < 1:
                    # adjust vmin
                    vmin, vmax = im.get_clim()
                    im.set_clim(vmin = vmax - (vmax - vmin)*scaling)
                    self.scale_locked = True
                self.canvas.draw()

        self.ds = DragState(relimcolor)
        self.canvas.mpl_connect('button_press_event', self.ds.recv)
        self.canvas.mpl_connect('button_release_event', self.ds.recv)

        self.box = wx.StaticBox(self, label="Image")
        self.sizer = wx.StaticBoxSizer(self.box, orient=wx.VERTICAL)
        self.sizer.Add(self.canvas, 1, wx.EXPAND)

        self.checkbox = wx.CheckBox(self, label="Sizebar")
        self.Bind(wx.EVT_CHECKBOX, self.add_or_remove_sizebar)
        self.bar_spinbox = wx.SpinCtrlDouble(self, value='1')
        self.cal_spinbox = wx.SpinCtrlDouble(self, value='.083', inc=.001)
        self.Bind(wx.EVT_SPINCTRLDOUBLE, self.update_sizebar)

        self.subsizer = wx.BoxSizer(wx.HORIZONTAL)
        self.subsizer.Add(self.checkbox, 0, wx.EXPAND)
        self.subsizer.Add(self.bar_spinbox, 1, wx.EXPAND)
        self.subsizer.Add(wx.StaticText(self, label='um, cal:'),
                0, wx.ALIGN_CENTER)
        self.subsizer.Add(self.cal_spinbox, 1, wx.EXPAND)
        self.subsizer.Add(wx.StaticText(self, label='um/bit'),
                0, wx.ALIGN_CENTER)
        self.sizer.Add(self.subsizer, 0, wx.EXPAND)

        self.SetSizer(self.sizer)
        self.SetAutoLayout(1)
        self.sizer.Fit(self)

    def open(self, dirname, filename):
        with n.load(os.path.join(dirname, filename)) as npz:
            self.update_image(npz['image'], npz['X'], npz['Y'])

    def update_sizebar(self, event):
        if self.checkbox.IsChecked():
            self.sb.remove()
            self.add_or_remove_sizebar(None)

    def add_or_remove_sizebar(self, event):
        if self.checkbox.IsChecked():
            bar = self.bar_spinbox.GetValue()
            cal = self.cal_spinbox.GetValue()
            self.sb = add_nice_sizebar(self.ax, cal=cal, bar=bar)
        else:
            self.sb.remove()
        self.canvas.draw()

    def update_image(self, image, x, y):
        """ load a new image."""
        #self.ax.clear()
        for prev_im in self.ax.images:
            prev_im.remove()  # remove any previous images/colorbars
        self.cbar.ax.clear()  # would be cool to have a control for this
        clim = self.im.get_clim() if self.scale_locked else None
        self.im = show_image(image, x, y,
                             ax=self.ax,
                             cax=self.cbar.ax,
                             mirror=True,
                             clim=clim,
                             hist=True)
        self.canvas.draw()

    def update_data(self, newdata):
        """ The image contents have changed, but not the bounds. """
        self.im.set_data(newdata)
        if not self.scale_locked:
            self.im.autoscale()
        self.im.changed()
        self.canvas.draw()

class Marker(object):
    """ A circle marking a point on the image """

    def __init__(self, ax, xloc, yloc, **kwargs):
        self.line = add_marker(xloc, yloc, ax=ax, **kwargs)

    def set_x(self, xloc):
        self.line.set_xdata((xloc,))

    def set_y(self, yloc):
        self.line.set_ydata((yloc,))

    def set_pos(self, xloc, yloc):
        self.line.set_data((xloc,), (yloc,))

    def draw(self):
        self.line.axes.figure.canvas.draw()

class DragState(object):
    """
    handles click-drag selection of an area in matplotlib

    """

    def __init__(self, callback):
        self.recording = False
        self.callback = callback

    def recv(self, event):
        if not self.recording and event.name == 'button_press_event':
            self.mousedown = event
            self.recording = True
        elif self.recording and event.name == 'button_release_event':
            self.mouseup = event
            self.recording = False
            self.callback(self)

if __name__ == "__main__":
    import sys

    # support wildcard character on windows
    import glob
    if '*' in sys.argv[-1]:
         sys.argv[-1:] = glob.glob(sys.argv[-1])

    # open a window for each command line arg
    files_to_open = sys.argv[1:]

    if not files_to_open:
        # or open a single, blank window
        files_to_open.append(None)

    app = wx.App(False)
    for fn in files_to_open:
        frame = MainWindow(None, 'Confocal Image Viewer', filename=fn)
        frame.Show(True)
    app.MainLoop()


text:
<?php

namespace mpf\widgets;

/**
 * Description of Exception
 *
 * @author mirel
 */
class Exception extends \Exception {
    const CODE_MISSING_CONFIG = 20;
    //put your code here
    public $widget;

    public $columnName;

    public function __construct($message, $code, $previous, $widget = null, $extra = null) {
        if ($extra && self::CODE_MISSING_CONFIG == $code)
            $this->columnName = $extra;
        $this->widget = $widget;
        parent::__construct($message, $code, $previous);
    }
}


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

using AutoMapper;
using Microsoft.Azure.Commands.Network.Models;
using Microsoft.Azure.Commands.ResourceManager.Common.Tags;
using Microsoft.Azure.Management.Network;
using System;
using System.Collections.Generic;
using System.Management.Automation;
using MNM = Microsoft.Azure.Management.Network.Models;

namespace Microsoft.Azure.Commands.Network
{
    [Cmdlet(VerbsCommon.Set, "AzureRmVirtualNetworkGateway"), OutputType(typeof(PSVirtualNetworkGateway))]
    public class SetAzureVirtualNetworkGatewayCommand : VirtualNetworkGatewayBaseCmdlet
    {
        [Parameter(
            Mandatory = true,
            ValueFromPipeline = true,
            HelpMessage = "The virtual network gateway object to base modifications off of. This can be retrieved using Get-AzureRmVirtualNetworkGateway")]
        public PSVirtualNetworkGateway VirtualNetworkGateway { get; set; }

        [Parameter(
            Mandatory = false,
            ValueFromPipelineByPropertyName = true,
            HelpMessage = "The virtual network gateway's SKU")]
        [ValidateSet(
        MNM.VirtualNetworkGatewaySkuTier.Basic,
        MNM.VirtualNetworkGatewaySkuTier.Standard,
        MNM.VirtualNetworkGatewaySkuTier.HighPerformance,
        IgnoreCase = true)]
        public string GatewaySku { get; set; }

        [Parameter(
             Mandatory = false,
             ValueFromPipelineByPropertyName = true,
            HelpMessage = "The default site to use for force tunneling. If a default site is specified, all internet traffic from the gateway's vnet is routed to that site.")]
        public PSLocalNetworkGateway GatewayDefaultSite { get; set; }

        [Parameter(
            Mandatory = false,
            ValueFromPipelineByPropertyName = true,
            HelpMessage = "The address space to allocate VPN client IP addresses from. This should not overlap with virtual network or on-premise ranges.")]
        [ValidateNotNullOrEmpty]
        public List<string> VpnClientAddressPool { get; set; }

        [Parameter(
            Mandatory = false,
            ValueFromPipelineByPropertyName = true,
            HelpMessage = "A list of VPN client root certificates to use for VPN client authentication. Connecting VPN clients must present certificates generated from one of these root certificates.")]
        public List<PSVpnClientRootCertificate> VpnClientRootCertificates { get; set; }

        [Parameter(
            Mandatory = false,
            ValueFromPipelineByPropertyName = true,
            HelpMessage = "A list of revoked VPN client certificates. A VPN client presenting a certificate that matches one of these will be told to go away.")]
        public List<PSVpnClientRevokedCertificate> VpnClientRevokedCertificates { get; set; }

        [Parameter(
            Mandatory = false,
            ValueFromPipelineByPropertyName = true,
            HelpMessage = "The virtual network gateway's ASN, used to set up BGP sessions inside IPsec tunnels")]
        public uint Asn { get; set; }

        [Parameter(
            Mandatory = false,
            ValueFromPipelineByPropertyName = true,
            HelpMessage = "The weight added to routes learned over BGP from this virtual network gateway")]
        public int PeerWeight { get; set; }

        [Parameter(
            Mandatory = false,
            ValueFromPipelineByPropertyName = true,
            HelpMessage = "ActiveActive feature flag")]
        public bool ActiveActive { get; set; }

        public override void Execute()
        {
            base.Execute();

            if (!this.IsVirtualNetworkGatewayPresent(this.VirtualNetworkGateway.ResourceGroupName, this.VirtualNetworkGateway.Name))
            {
                throw new ArgumentException(Microsoft.Azure.Commands.Network.Properties.Resources.ResourceNotFound);
            }

            this.VirtualNetworkGateway.ActiveActive = this.ActiveActive;

            if (this.VirtualNetworkGateway.ActiveActive)
            {
                bool activeActiveSkuCriteria = !string.IsNullOrEmpty(this.GatewaySku) ? !this.GatewaySku.Equals(MNM.VirtualNetworkGatewaySkuTier.HighPerformance) : !this.VirtualNetworkGateway.Sku.Tier.Equals(MNM.VirtualNetworkGatewaySkuTier.HighPerformance);

                if(activeActiveSkuCriteria)
                {
                    throw new ArgumentException("Virtual Network Gateway Sku should be " + MNM.VirtualNetworkGatewaySkuTier.HighPerformance + " when Active-Active feature flag is set to True.");
                }
            }

            if (!string.IsNullOrEmpty(GatewaySku))
            {
                this.VirtualNetworkGateway.Sku = new PSVirtualNetworkGatewaySku();
                this.VirtualNetworkGateway.Sku.Tier = this.GatewaySku;
                this.VirtualNetworkGateway.Sku.Name = this.GatewaySku;
            }

            if (this.VirtualNetworkGateway.ActiveActive && !this.VirtualNetworkGateway.VpnType.Equals(MNM.VpnType.RouteBased))
            {
                throw new ArgumentException("Virtual Network Gateway VpnType should be " + MNM.VpnType.RouteBased + " when Active-Active feature flag is set to True.");
            }

            if (this.VirtualNetworkGateway.ActiveActive && this.VirtualNetworkGateway.IpConfigurations.Count != 2)
            {
                throw new ArgumentException("Virtual Network Gateway should have 2 Gateway IpConfigurations specified when Active-Active feature flag is True.");
            }

            if (!this.VirtualNetworkGateway.ActiveActive && this.VirtualNetworkGateway.IpConfigurations.Count == 2)
            {
                throw new ArgumentException("Virtual Network Gateway should have Active-Active feature flag set to True as there are 2 Gateway IpConfigurations specified. OR there should be only one Gateway IpConfiguration specified.");
            }

            if (this.GatewayDefaultSite != null)
            {
                this.VirtualNetworkGateway.GatewayDefaultSite = new PSResourceId();
                this.VirtualNetworkGateway.GatewayDefaultSite.Id = this.GatewayDefaultSite.Id;
            }

            if ((this.VpnClientAddressPool != null || this.VpnClientRootCertificates != null || this.VpnClientRevokedCertificates != null) && this.VirtualNetworkGateway.VpnClientConfiguration == null)
            {
                this.VirtualNetworkGateway.VpnClientConfiguration = new PSVpnClientConfiguration();
            }

            if (this.VpnClientAddressPool != null)
            {
                this.VirtualNetworkGateway.VpnClientConfiguration.VpnClientAddressPool = new PSAddressSpace();
                this.VirtualNetworkGateway.VpnClientConfiguration.VpnClientAddressPool.AddressPrefixes = this.VpnClientAddressPool;
            }

            if (this.VpnClientRootCertificates != null)
            {
                this.VirtualNetworkGateway.VpnClientConfiguration.VpnClientRootCertificates = this.VpnClientRootCertificates;
            }

            if (this.VpnClientRevokedCertificates != null)
            {
                this.VirtualNetworkGateway.VpnClientConfiguration.VpnClientRevokedCertificates = this.VpnClientRevokedCertificates;
            }

            if ((this.Asn > 0 || this.PeerWeight > 0) && this.VirtualNetworkGateway.BgpSettings == null)
            {
                this.VirtualNetworkGateway.BgpSettings = new PSBgpSettings();
                this.VirtualNetworkGateway.BgpSettings.BgpPeeringAddress = null; // The gateway's BGP peering address (private IP address assigned within the vnet) can't be changed
            }

            if (this.Asn > 0)
            {
                this.VirtualNetworkGateway.BgpSettings.Asn = this.Asn;
            }

            if (this.PeerWeight > 0)
            {
                this.VirtualNetworkGateway.BgpSettings.PeerWeight = this.PeerWeight;
            }
            else if (this.PeerWeight < 0)
            {
                throw new ArgumentException("PeerWeight must be a positive integer");
            }

            // Map to the sdk object
            MNM.VirtualNetworkGateway sdkVirtualNetworkGateway = Mapper.Map<MNM.VirtualNetworkGateway>(this.VirtualNetworkGateway);
            sdkVirtualNetworkGateway.Tags = TagsConversionHelper.CreateTagDictionary(this.VirtualNetworkGateway.Tag, validate: true);

            this.VirtualNetworkGatewayClient.CreateOrUpdate(this.VirtualNetworkGateway.ResourceGroupName, this.VirtualNetworkGateway.Name, sdkVirtualNetworkGateway);

            var getVirtualNetworkGateway = this.GetVirtualNetworkGateway(this.VirtualNetworkGateway.ResourceGroupName, this.VirtualNetworkGateway.Name);

            WriteObject(getVirtualNetworkGateway);
        }
    }
}


text:
package design.patterns.responsibility;

import java.util.Set;

public class FileLogger extends Logger {
	public FileLogger(Set<LogLevel> logLevels) {
		super(logLevels);
	}

	@Override
	protected void logMessage(String message) {
		System.out.println("[*] Logging to FILE: " + message);
	}

}


text:
// Return attributes and values of a node in a convenient way:
/* example:
    <ExampleElement attr1="15" attr2>
    {   attr1: {
            hasValue: true,
            value: 15
        },
        attr2: {
            hasValue: false
        }
Inclusion of hasValue is in case an eslint rule cares about boolean values
explicitely assigned to attribute vs the attribute being used as a flag
*/
class NodeAttributes {
  constructor(ASTnode) {
    this.attributes = {}
    ASTnode.attributes.forEach((attribute) => {
      if (!attribute.type || attribute.type !== 'JSXAttribute') {
        return
      }
      this.attributes[attribute.name.name] = {
        hasValue: !!attribute.value,
      }
      if (attribute.value) {
        if (attribute.value.value) {
          this.attributes[attribute.name.name].value = attribute.value.value
        } else if (attribute.value.expression) {
          this.attributes[attribute.name.name].value =
            typeof attribute.value.expression.value !== 'undefined'
              ? attribute.value.expression.value
              : attribute.value.expression.properties
        }
      }
    })
  }
  hasAny() {
    return !!Object.keys(this.attributes).length
  }
  has(attrName) {
    return !!this.attributes[attrName]
  }
  hasValue(attrName) {
    return !!this.attributes[attrName].hasValue
  }
  value(attrName) {
    if (!this.attributes[attrName]) {
      return true
    }

    return this.attributes[attrName].value
  }
}

module.exports = NodeAttributes


text:
package org.basex.query.func.array;

import static org.basex.query.QueryError.*;

import org.basex.query.*;
import org.basex.query.value.array.Array;
import org.basex.query.value.item.*;
import org.basex.util.*;

/**
 * Function implementation.
 *
 * @author BaseX Team 2005-15, BSD License
 * @author Christian Gruen
 */
public final class ArrayTail extends ArrayFn {
  @Override
  public Item item(final QueryContext qc, final InputInfo ii) throws QueryException {
    final Array array = toArray(exprs[0], qc);
    if(array.isEmptyArray()) throw ARRAYEMPTY.get(info);
    return array.tail();
  }
}


text:
code: true
type: page
title: setAutoRefresh
description: Kuzzle:setAutoRefresh
---

# setAutoRefresh

The `autoRefresh` flag, when set to true, will make Kuzzle perform a
[`refresh`](https://www.elastic.co/guide/en/elasticsearch/reference/5.4/docs-refresh.html) request
immediately after each write request, causing documents to be immediately visible in a search.

Given an index, the `setAutoRefresh` function updates its `autoRefresh` status.

:::warning
A refresh operation comes with some performance costs.

While forcing the autoRefresh can be convenient on a development or test environmnent, we recommend that you avoid
using it in production or at least carefully monitor its implications before using it.
:::

---

## setAutoRefresh([index], autoRefresh, [options], [callback])

| Argument      | Type        | Description                                                                                |
| ------------- | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |
| `index`       | string      | _Optional_ The index to set the `autoRefresh` for. If not set, defaults to [kuzzle.defaultIndex](/sdk/android/3/core-classes/kuzzle#properties). |
| `autoRefresh` | boolean     | The value to set for the `autoRefresh` setting.                                                                                |
| `options`     | JSON object | Optional parameters                                                                                |
| `callback`    | function    | _Optional_ Callback handling the response                                                                                |

---

## Options

| Option     | Type    | Description                       | Default |
| ---------- | ------- | --------------------------------- | ------- |
| `queuable` | boolean | Make this request queuable or not | `true`  |

---

## Return Value

Returns the `Kuzzle` SDK object to allow chaining.

---

## Callback Response

Returns a boolean with the new `autoRefresh` status.

## Usage

<<< ./snippets/set-auto-refresh-1.java


text:
lager_backends (v0.1.0)
Custom backends for lager:
* lager_backend_email
* lager_backend_rabbitmq

lager_backends is released under the terms of the [MIT](http://en.wikipedia.org/wiki/MIT_License) license

copyright 2012-2014 Kivra

## tl;dr
### Example app.config:
```erlang
{lager, [{ handlers
         , [ { lager_backend_email
             , [warning, "machine@foo", "alarms@foo"] }
           , { lager_backend_rabbitmq
             , [ info
               , [{"mq1@foo", 5672}, {"mq2@foo", 5672}]
               , "username"
               , "password"
               , "exchange"
               , "routing key"
               ]}
            ]}
        ]}.
```


text:
package org.locationtech.geomesa.filter.function

import java.util.Date

import org.geotools.data.Base64
import org.junit.runner.RunWith
import org.locationtech.geomesa.features.ScalaSimpleFeature
import org.locationtech.geomesa.utils.bin.BinaryOutputEncoder
import org.locationtech.geomesa.utils.bin.BinaryOutputEncoder.EncodedValues
import org.locationtech.geomesa.utils.geotools.SimpleFeatureTypes
import org.specs2.mutable.Specification
import org.specs2.runner.JUnitRunner

@RunWith(classOf[JUnitRunner])
class Convert2ViewerFunctionTest extends Specification {

  import org.locationtech.geomesa.filter.ff

  "Convert2ViewerFunction" should {
    "convert inputs" in {
      import scala.collection.JavaConversions._
      val sft = SimpleFeatureTypes.createType("foo", "foo:String,dtg:Date,*geom:Point:srid=4326")
      val sf = ScalaSimpleFeature.create(sft, "", "foo", "2017-01-01T00:00:00.000Z", "POINT (45 50)")
      val fn = new Convert2ViewerFunction()
      fn.setParameters(List(ff.property("foo"), ff.property("geom"), ff.property("dtg")))
      val result = Base64.decode(fn.evaluate(sf))
      result must haveLength(24)
      BinaryOutputEncoder.decode(result) mustEqual
          EncodedValues(
            BinaryOutputEncoder.convertToTrack("foo"),
            50f, 45f,
            BinaryOutputEncoder.convertToDate(sf.getAttribute("dtg").asInstanceOf[Date]),
            BinaryOutputEncoder.convertToLabel("foo"))
    }

  }
}


text:
"""Utility for ROCm backend"""
import subprocess
from os.path import join
from . import util
from ..api import register_func, convert

def rocm_link(in_file, out_file):
    """Link relocatable ELF object to shared ELF object using lld

    Parameters
    ----------
    in_file : str
        Input file name (relocatable ELF object file)

    out_file : str
        Output file name (shared ELF object file)
    """
    args = ["ld.lld", "-shared", in_file, "-o", out_file]
    proc = subprocess.Popen(
        args,
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT)
    (out, _) = proc.communicate()

    if proc.returncode != 0:
        msg = "Linking error using ld.lld:\n"
        msg += str(out)
        raise RuntimeError(msg)

@register_func("tvm_callback_rocm_link")
def callback_rocm_link(obj_bin):
    """Links object file generated from LLVM to HSA Code Object

    Parameters
    ----------
    obj_bin : bytearray
        The object file

    Return
    ------
    cobj_bin : bytearray
        The HSA Code Object
    """
    tmp_dir = util.tempdir()
    tmp_obj = tmp_dir.relpath("rocm_kernel.o")
    tmp_cobj = tmp_dir.relpath("rocm_kernel.co")
    with open(tmp_obj, "wb") as out_file:
        out_file.write(bytes(obj_bin))
    rocm_link(tmp_obj, tmp_cobj)
    cobj_bin = bytearray(open(tmp_cobj, "rb").read())
    return cobj_bin

@register_func("tvm_callback_rocm_bitcode_path")
def callback_rocm_bitcode_path(rocdl_dir="/opt/rocm/lib/"):
    """Utility function to find ROCm device library bitcodes

    Parameters
    ----------
    rocdl_dir : str
        The path to rocm library directory
        The default value is the standard location
    """
    # seems link order matters.
    bitcode_files = [
        "oclc_daz_opt_on.amdgcn.bc",
        "ocml.amdgcn.bc",
        "hc.amdgcn.bc",
        "irif.amdgcn.bc",
        "ockl.amdgcn.bc",
        "oclc_correctly_rounded_sqrt_off.amdgcn.bc",
        "oclc_correctly_rounded_sqrt_on.amdgcn.bc",
        "oclc_daz_opt_off.amdgcn.bc",
        "oclc_finite_only_off.amdgcn.bc",
        "oclc_finite_only_on.amdgcn.bc",
        "oclc_isa_version_803.amdgcn.bc",
        "oclc_isa_version_900.amdgcn.bc",
        "oclc_unsafe_math_off.amdgcn.bc",
        "oclc_unsafe_math_on.amdgcn.bc"
    ]
    return convert([join(rocdl_dir, bitcode) for bitcode in bitcode_files])


text:
package de.jbiblio.serstapa.restapi;

import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import de.jbiblio.serstapa.api.LoginService;

@Path("login")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public class LoginRestService implements LoginService {

	@POST
	@Produces(MediaType.TEXT_PLAIN)
	@Override
	public String login(@FormParam("userName") String userName,
			@FormParam("password") String password) {
		return "OK";
	}

}