text:
using System;
using System.Threading;
using System.Threading.Tasks;
using Lime.Protocol;
using Takenet.MessagingHub.Client.Listener;
using Takenet.MessagingHub.Client.Sender;
using Takenet.MessagingHub.Client.Extensions.Bucket;
using System.Linq;
using Lime.Messaging.Contents;

namespace Take.Blip.Animal
{
    public class PlainTextMessageReceiver : IMessageReceiver
    {
        private readonly IMessagingHubSender _sender;
        private readonly IBucketExtension _bucketExtension;

        public PlainTextMessageReceiver(IMessagingHubSender sender, IBucketExtension bucketExtension)
        {
            _sender = sender;
            _bucketExtension = bucketExtension;
        }

        public async Task ReceiveAsync(Message message, CancellationToken cancellationToken)
        {
            var fromIdentity = message.From.ToIdentity();

            // Gets the stored document for the identity
            var userSession = await _bucketExtension.GetAsync<JsonDocument>(
                fromIdentity,
                cancellationToken);

            var text = message.Content.ToString().ToLowerInvariant();

            // Creates the response
            var responseMessage = new Message()
            {
                Id = EnvelopeId.NewId(),
                To = message.From,
                Content = "Pong!!!"
            };

            // If there is a stored session
            if (userSession != null)
            {
                if (text == "ping")
                {
                    // Removes the session
                    await _bucketExtension.DeleteAsync(fromIdentity, cancellationToken);
                }
                else
                {
                    var state = userSession["state"].ToString();
                    switch (state)
                    {
                        case "cachorro":
                            responseMessage.Content = "Au Au Au!!!";
                            break;

                        case "gato":
                            responseMessage.Content = "Miau Miau Miau!!!";
                            break;

                        case "EscolherAnimal":
                            if (new[] { "cachorro", "gato" }.Contains(text))
                            {
                                // Sets the current state as the animal name
                                await _bucketExtension.SetAsync(
                                    fromIdentity,
                                    new JsonDocument
                                    {
                                        { "state", text }
                                    },
                                    cancellationToken: cancellationToken);

                                if (text == "cachorro")
                                {
                                    responseMessage.Content =
                                        new MediaLink
                                        {
                                            Title = "Cachorro",
                                            Text = "Agora sou um cachorro",
                                            Type = "image/jpeg",
                                            Uri = new Uri("http://tudosobrecachorros.com.br/wp-content/uploads/cachorro-independente-766x483.jpg"),
                                        };
                                }
                                else if (text == "gato")
                                {
                                    responseMessage.Content =
                                        new MediaLink
                                        {
                                            Title = "Gato",
                                            Text = "Agora sou um gato",
                                            Type = "image/jpeg",
                                            Uri = new Uri("http://www.gatosmania.com/Uploads/gatosmania.com/ImagensGrandes/linguagem-corporal-gatos.jpg"),
                                        };
                                }
                            }

                            break;
                    }

                }
            }
            else if (text == "animal")
            {
                await _bucketExtension.SetAsync(
                    fromIdentity,
                    new JsonDocument
                    {
                        { "state", "EscolherAnimal" }
                    },
                    cancellationToken: cancellationToken);

                responseMessage.Content =
                    new Select
                    {
                        Text = "Escolha uma opção",
                        Options = new[]
                        {
                            new SelectOption { Order = 1, Text = "Cachorro"},
                            new SelectOption { Order = 2, Text = "Gato"}
                        }
                    };
            }

            await _sender.SendMessageAsync(responseMessage, cancellationToken);
        }
    }
}


text:
require 'rcr'
require 'rcr/config'

module RCR::Logging
	ENABLED_BY_DEFAULT = RCR::Config.logging_enabled

	def self.log_line(source, args)
		puts "[#{source}] #{args.map(&:to_s).join}"
	end

	def self.included(klass)
		klass.instance_eval do
			define_method :logging_enabled? do
				if defined?(@enable_logging)
					@enable_logging
				else
					ENABLED_BY_DEFAULT
				end
			end

			define_method :log do |*args|
			  RCR::Logging.log_line(self.class, args) if logging_enabled?
			end

			define_method :warn do |*args|
				puts "[#{self.class}] WARN: #{args.map(&:to_s).join}"
			end

			define_method :with_logging do |&block|
				with_logging_set(true, &block)
			end

			define_method :without_logging do |&block|
				with_logging_set(false, &block)
			end

			define_method :with_logging_set do |value, &block|
				old_value = defined?(@enable_logging) ? @enable_logging : nil
				@enable_logging = value
				block.call
				@enable_logging = old_value
			end

			attr_accessor :enable_logging
		end

		class << klass
			define_method :logging_enabled? do
				if defined?(@enable_logging)
					@enable_logging
				else
					ENABLED_BY_DEFAULT
				end
			end

			define_method :log do |*args|
				RCR::Logging.log_line(self, args) if logging_enabled?
			end

			define_method :warn do |*args|
				puts "[#{self.class}] WARN: #{args.map(&:to_s).join}"
			end

			define_method :with_logging do |&block|
				with_logging_set(true, &block)
			end

			define_method :without_logging do |&block|
				with_logging_set(false, &block)
			end

			define_method :with_logging_set do |value, &block|
				old_value = defined?(@enable_logging) ? @enable_logging : nil
				@enable_logging = value
				result = block.call
				@enable_logging = old_value
				result
			end
		end
	end
end

redpajama_set_name: RedPajamaGithub


text:
gcc --std=c99 -I/usr/local/include -L/usr/local/lib -o pmess pmess.c -lmongoc
gcc -I/usr/local/include -L/usr/local/lib -o elmboxo elmboxo.c
gcc -I/usr/local/include -L/usr/local/lib -o ivox ivox.c


text:
Gtkmm in-car computer for rasperry pi

##DEPENDENCIES

Before this code can be compiled, there are a number of dependencies that must be installed:

Libraries required by Carputer:

	sudo apt-get install libmpg123-dev					# MP3 library

	sudo apt-get install libao-dev						# Sound driver library

	sudo apt-get install libconfig++-dev				# For reading config files

	sudo apt-get install libgtkmm-3.0-dev				# C++ wrapper around GTK (for user interface)

	sudo apt-get install libsqlite3-dev					# SQLite - For reading postcode database

GPSD must be compiled from source. Using apt-get will not install the library:

	wget http://download.savannah.gnu.org/releases/gpsd/gpsd-3.11.tar.gz

	tar -xzf gpsd-3.11.tar.gz

	cd gpsd-3.11

Install scons (required to build gpsd):

	sudo apt-get install scons

Install libraries required by gpsd:

	sudo apt-get install libncurses-dev

	sudo apt-get install python-dev

Build gpsd:

	scons

	scons check

	sudo scons udev-install

You also need to upgrade GCC to the latest version so that you can use the new C++ 11 standard:

	sudo apt-get install gcc-4.7 g++-4.7

	sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-4.6 60 --slave /usr/bin/g++ g++ /usr/bin/g++-4.6

	sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-4.7 40 --slave /usr/bin/g++ g++ /usr/bin/g++-4.7

Then run this command and select gcc-4.7.

	sudo update-alternatives --config gcc

You should then be able to compile the code just by typing:

	make

##ABOUT THE PROJECT

Quite a lot of this is custom code written to my tight specifications so everything has to be done in a certain way. It's not written to be highly configurable - I wrote it with myself and my own requirements in mind with no plans to make it a releasable project so you'll have to bear with me for those bits :)

The bulk of this code is a music player but it has some GPS functionality - a speedo and a postcode link to Navit.

The assets directory contains the graphics for the application. You can edit these - but if you move the buttons around you'll have to change the corresponding coordinates in the code files.

The file 'carputer.glade' is the UI of the application. it is loaded at runtime and is used to build the interface, along with the graphics. It's XML so you can edit it by hand or using the Glade editor ("sudo apt-get install glade", I think)

carputer.cfg contains the configuration:

musicpath - Path to the directory where the MP3s are (more on this later)

assetspath - Path to the directory containing carputer.glade and the graphics (I keep them in /etc/carputer)

postcodedb - This is for postcode lookup - a SQLite db containing a Postcode to Lat/Lng lookup table. It's 75Mb so I haven't included it. Let me know if you want it.

The GPIO pins are for the steering wheel controls. There are four buttons that control the application: Next, previous, navigate and mode. The pins for those are configured here.

The music directory has to be laid out in a specific way. You can't just point it to a directory of MP3s and expect it to work... it won't.

Each directory within the main music directory is treated as one album, named in the format "Artist - Album Name".
Any files in the music dir root are ignored.

Only MP3 files within the album directories are loaded. (It doesn't support any other format). No sub-directories are loaded. MP3s should be named starting with the track number so they are loaded in order; "01 Track name.mp3". The actual artist/track name displayed in the UI is taken from the ID3 tags.

There *must* also be a 160x160px PNG file called albumart.png in the album directory. I'm a bit anal about my album art.

Anything else in the album dir is ignored.

So for example if your root music dir is /media/PENDRIVE, your layout would look like this:

/media/PENDRIVE/Pink Floyd - Dark Side of the Moon/01 - Speak to Me.mp3

/media/PENDRIVE/Pink Floyd - Dark Side of the Moon/02 - Breathe.mp3

...

/media/PENDRIVE/Pink Floyd - Dark Side of the Moon/10 - Eclipse.mp3

/media/PENDRIVE/Pink Floyd - Dark Side of the Moon/albumart.png

/media/PENDRIVE/Michael Jackson - Thriller/01 - Wanna Be Startin Somethin.mp3

/media/PENDRIVE/Michael Jackson - Thriller/02 - Baby Be Mine.mp3

...

/media/PENDRIVE/Michael Jackson - Thriller/09 - The Lady In My Life.mp3

/media/PENDRIVE/Michael Jackson - Thriller/albumart.png

##CONSIDERATIONS

This is my first ever C++ application so bear that in mind. (I'm a C# developer by trade). There might be a whole load of bugs/memory leaks.

The link to Navit doesn't quite work yet - I think I need a delay between starting up Navit and passing it the DBUS signals.

The Postcode Lookup screen/functionality is useless if you're outside the UK. You could just bypass it by doing:

	system("navit");

when the speedo is clicked, rather than have it open the PostcodeWindow.

This code is designed to run on a 320x240 touch screen - it hides the mouse pointer. If you want to test the code *with* the pointer, comment out the line:

	get_window()->set_cursor(Gdk::Cursor::create(Gdk::BLANK_CURSOR));

in the .cpp files for each window (MainWindow.cpp, AlbumWindow.cpp, PostcodeWindow.cpp).

If you want a title bar, in the Glade file, set "decorated" to "True" for each window. (No need to recompile - the Glade file is loaded at runtime)


text:
/**
 * Class ObjectCoordinateInterpolator is especially useful for doing animations based on inconsistent and irregular
 * updates.
 * It can be used in network games where network lags would prevent smooth animation of game objects.
 *
 * API: see README.md
 *
 * @author Konstantin Raev (bestander@gmail.com)
 */

'use strict';
var TWEEN = require('tween.js');

/**
 * create animation smoother interpolator object
 * @param initialCoordinate starting position
 * @constructor
 */
function ObjectCoordinateInterpolator (initialCoordinate) {
  this._previosTweenTargetPosition = initialCoordinate;
  this._previosTweenFinishTime = Date.now();
  this._onCoordinateRequest = null;
}

module.exports = ObjectCoordinateInterpolator;

/**
 * update all interpolators
 */
ObjectCoordinateInterpolator.updateAll = function () {
  TWEEN.update();
};

/**
 * schedule next animation sequence
 * @param coordinate destination coordinate, starting position will be destination of previous point
 * @param delayFromNow in how many milliseconds after current moment the animation must finish
 */
ObjectCoordinateInterpolator.prototype.scheduleNext = function (coordinate, delayFromNow) {
  var startTime;
  var animationDuration;
  var tween;
  delayFromNow = delayFromNow > 0 ? delayFromNow : 0;

  startTime = Math.max(Date.now(), this._previosTweenFinishTime);
  animationDuration = Date.now() + delayFromNow - startTime;
  tween = new TWEEN.Tween(this._previosTweenTargetPosition).to(coordinate, animationDuration);
  tween.start(startTime);
  tween.onUpdate(this._onCoordinateRequest);
  this._previosTweenTargetPosition = coordinate;
  this._previosTweenFinishTime = Date.now() + animationDuration;

};

/**
 * register a callback that will be called every time ObjectCoordinateInterpolator.updateAll is executed
 * @param callback where 'this' scope is current coordinate
 */
ObjectCoordinateInterpolator.prototype.onCoordinateRequest = function (callback) {
  this._onCoordinateRequest = callback;
};


text:
module("baidu.fx.zoomIn");

// scale的一种调用,仅校验参数即可
test('test id', function() {
	stop();
	document.body.appendChild(document.getElementById('img_id'));
	$('#img_id').css('position', 'absolute').css('left', 0).css('top', 0).css('width', 100).css('height', 100);
//	$('img_div').css('position', 'absolute').css('left', 0).css('top', 0);
	setTimeout(function(){//等待图片加载
		var c = baidu.fx.zoomIn('img_id', {
			duration : 2000,
			interval : 50,
			onafterfinish : function() {
				ok(true, 'test id');
				equals(this.interval, 50, 'interval = ' + this.interval);
				equals(this.duration, 2000, 'duration = ' + this.duration);
				equals(this.dynamic, true, 'dynamic = ' + this.dynamic);
				equals(this.percent, 1, 'percent = ' + this.percent);
				equals(this.to, 1, 'default: this.to = ' + this.to);
				equals(this.from, 0.1, 'default: this.from = ' + this.from);
				equals(this.restoreAfterFinish, true,
						'default: this.restoreAfterFinish = '
								+ this.restoreAfterFinish);
				equals(this.transition(2), 4, 'default: this.transition(2) = '
						+ this.transition(2));
				$('#img_id').remove();
				setTimeout(QUnit.start, 200);
			}
		});
	}, 1000);
});


text:
package com.yl.core.component.net.view;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.TextView;

import com.yl.core.R;

/**
 * Created by zm on 2018/9/9.
 */

public class DialogUtil {

    public static DialogDismissListener createLoadingDialog(final Context context, DialogCancelListener dialogCancelListener, String tips) {
        if(context == null) {
            return null;
        }
        if(context instanceof Activity && ((Activity)context).isFinishing()) {
            return null;
        }
        final CustomLoadingDialog customLoadingDialog = new CustomLoadingDialog(context, tips);
        customLoadingDialog.setDialogCancelListener(dialogCancelListener);
        customLoadingDialog.setCanceledOnTouchOutside(false);
        customLoadingDialog.setCancelable(true);
        customLoadingDialog.show();
        return new DialogDismissListener() {
            @Override
            public void onDismiss() {
                if(context == null || (context instanceof Activity && ((Activity)context).isFinishing())) {
                    return;
                }
                customLoadingDialog.dismiss();
            }
        };
    }

    public static class CustomLoadingDialog extends AlertDialog {

        private Context context;
        private String tips;
        private DialogCancelListener dialogCancelListener;
        private AnimationDrawable animationDrawable;

        public CustomLoadingDialog(Context context) {
            super(context, R.style.TransparentDialogStyle);
            this.context = context;
        }

        public CustomLoadingDialog(Context context, String tips) {
            super(context, R.style.TransparentDialogStyle);
            this.context = context;
            this.tips = tips;
        }

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            View view = LayoutInflater.from(context).inflate(R.layout.dialog_loading_custom_layout, null);

            if (TextUtils.isEmpty(tips) == false) {
                TextView tvTips = (TextView) view.findViewById(R.id.dialog_loading_custom_tv_tips);
                tvTips.setVisibility(View.VISIBLE);
                tvTips.setText(tips);
            }

            Window dialogWindow = getWindow();
            dialogWindow.setContentView(view);
            this.setOnCancelListener(new OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    if(animationDrawable != null) {
                        animationDrawable.stop();
                    }
                    if (dialogCancelListener != null) {
                        dialogCancelListener.onCancel();
                    }
                }
            });
        }

        @Override
        public void onWindowFocusChanged(boolean hasFocus) {
            super.onWindowFocusChanged(hasFocus);
            if(animationDrawable != null) {
                animationDrawable.start();
            }
        }

        public DialogCancelListener getDialogCancelListener() {
            return dialogCancelListener;
        }

        public void setDialogCancelListener(DialogCancelListener dialogCancelListener) {
            this.dialogCancelListener = dialogCancelListener;
        }
    }

    public interface DialogDismissListener {
        void onDismiss();
    }

    public interface DialogCancelListener {
        void onCancel();
    }
}


text:
package debop4k.data.orm.mapping.associations.manytoone;

import debop4k.data.orm.mapping.AbstractMappingTest;
import debop4k.data.orm.mapping.associations.manytoone.models.Jug;
import debop4k.data.orm.mapping.associations.manytoone.models.JugMeter;
import org.assertj.core.api.Assertions;
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;

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

import static org.assertj.core.api.Assertions.assertThat;

@SpringBootTest(classes = {ManyToOneConfiguration.class})
public class ManyToOneTests extends AbstractMappingTest {

  @PersistenceContext EntityManager em;

  @Test
  public void checkMapping() {
    assertThat(em).isNotNull();
  }

  @Test
  public void unidirectionalManyToOne() {
    Jug jug = new Jug("JUG Summer Camp");
    JugMeter emmanuel = new JugMeter("Emmanuel Bernard");
    emmanuel.setMemberOf(jug);

    JugMeter jerome = new JugMeter("Jerome");
    jerome.setMemberOf(jug);

    em.persist(jug);
    em.persist(emmanuel);
    em.persist(jerome);
    em.flush();
    em.clear();

    JugMeter emmanuel2 = em.find(JugMeter.class, emmanuel.getId());
    assertThat(emmanuel2).isNotNull().isEqualTo(emmanuel);
    assertThat(emmanuel2.getMemberOf()).isNotNull().isEqualTo(jug);

    em.remove(emmanuel2);
    em.flush();
    em.clear();

    JugMeter jerome2 = em.find(JugMeter.class, jerome.getId());
    assertThat(jerome2).isNotNull().isEqualTo(jerome);
    assertThat(jerome2.getMemberOf()).isNotNull().isEqualTo(jug);

    Jug jug2 = jerome2.getMemberOf();
    // JugMeter 먼저 삭제해야 한다. Jug 먼저 삭제하면, JugMeter#memgerOf 가 null 로 설정되어 버린다.
    em.remove(jerome2);
    em.remove(jug2);
    em.flush();
    em.clear();

    Assertions.assertThat(em.find(Jug.class, jug.getId())).isNull();
  }
}


text:
@implementation DotView

- (instancetype)init
{
    self = [super init];
    if (self) {

    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {

    }
    return self;
}

- (instancetype)initWithCoder:(NSCoder *)coder
{
    self = [super initWithCoder:coder];
    if (self) {

    }
    return self;
}

- (void)initialization{
    self.backgroundColor = [UIColor clearColor];
    self.layer.cornerRadius = CGRectGetWidth(self.frame) * 0.5;
    self.layer.borderColor = [UIColor whiteColor].CGColor;
    self.layer.borderWidth = 2.0f;
}

- (void)changeActivityState:(BOOL)active{
    if (active) {
        self.backgroundColor = [UIColor whiteColor];
    }else{
        self.backgroundColor = [UIColor clearColor];
    }
}

@end


text:
title: Currency
keywords:
last_updated: September 29, 2016
tags:
summary: The currency input type
sidebar: excel_sidebar
permalink: Currency.html
folder: excel
---

## Description
Many functions require the input of a currency.  Currencies are used to link models and curves to products, this ensures that one can never use for example a USD curve to value a ZAR based cashflow.  For simple cases where you are not concerned about the risk of using the wrong curve you can use the special currency \"ANY\".

Currencies are entered into QuantSA functions simply as a three letter string of the currency code.  See below for the supported values.

## Available values

* **ANY** use this is you don't mind what currency you are dealing with.
* **ZAR**
* **USD**
* **EUR**


text:
//%2005////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2000, 2001, 2002 BMC Software; Hewlett-Packard Development
// Company, L.P.; IBM Corp.; The Open Group; Tivoli Systems.
// Copyright (c) 2003 BMC Software; Hewlett-Packard Development Company, L.P.;
// IBM Corp.; EMC Corporation, The Open Group.
// Copyright (c) 2004 BMC Software; Hewlett-Packard Development Company, L.P.;
// IBM Corp.; EMC Corporation; VERITAS Software Corporation; The Open Group.
// Copyright (c) 2005 Hewlett-Packard Development Company, L.P.; IBM Corp.;
// EMC Corporation; VERITAS Software Corporation; The Open Group.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// THE ABOVE COPYRIGHT NOTICE AND THIS PERMISSION NOTICE SHALL BE INCLUDED IN
// ALL COPIES OR SUBSTANTIAL PORTIONS OF THE SOFTWARE. THE SOFTWARE IS PROVIDED
// "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
// LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//==============================================================================
//
// Author: Mike Brasher (mbrasher@bmc.com)
//
// Modified By: Jenny Yu, Hewlett-Packard Company (jenny_yu@hp.com)
//              Carol Ann Krug Graves, Hewlett-Packard Company
//                (carolann_graves@hp.com)
//
//%/////////////////////////////////////////////////////////////////////////////

/*
	This program tests the CIM QualifierList functions.
*/

#include <cassert>
#include <Pegasus/Common/CIMQualifier.h>
#include <Pegasus/Common/CIMQualifierList.h>
#include <Pegasus/Common/CIMProperty.h>
#include <Pegasus/Common/DeclContext.h>

PEGASUS_USING_PEGASUS;
PEGASUS_USING_STD;

int main(int argc, char** argv)
{
    Boolean verbose = (getenv("PEGASUS_TEST_VERBOSE")) ? true : false;
    try
    {
	const String NAMESPACE = "/zzz";

	// Create and populate a declaration context:

	SimpleDeclContext context;

	context.addQualifierDecl(NAMESPACE, CIMQualifierDecl
            (CIMName ("abstract"),
	    false, CIMScope::CLASS, CIMFlavor::OVERRIDABLE));

	context.addQualifierDecl(NAMESPACE, CIMQualifierDecl
            (CIMName ("description"),
	    String(), CIMScope::CLASS, CIMFlavor::OVERRIDABLE));

	context.addQualifierDecl(NAMESPACE, CIMQualifierDecl(CIMName ("q1"),
	    false, CIMScope::CLASS, CIMFlavor::OVERRIDABLE +
            CIMFlavor::TOSUBCLASS));

	context.addQualifierDecl(NAMESPACE, CIMQualifierDecl(CIMName ("q2"),
	    false, CIMScope::CLASS, CIMFlavor::TOSUBCLASS));

	// ATTN: KS P1 29 Mar 2002 - Add Tests for Null Value

	// ATTN: KS P1 29 Mar 2002 - Add tests for array values in Qualifier.

	// Create qualifier list 1:

	CIMQualifierList qualifiers0;
	CIMQualifierList qualifiers1;

	qualifiers1
	    .add(CIMQualifier(CIMName ("Abstract"), true))
	    .add(CIMQualifier(CIMName ("Description"),
                String("CIMQualifier List 1")))
	    .add(CIMQualifier(CIMName ("q1"), false))
	    .add(CIMQualifier(CIMName ("q2"), false));

	// Run the find, get, etc tests.

	assert(qualifiers1.getCount() == 4);
	assert(qualifiers1.find(CIMName ("Abstract")) == 0);
	assert(qualifiers1.exists(CIMName ("Abstract")));
	assert(qualifiers1.isTrue(CIMName ("Abstract")));
	assert(qualifiers1.exists(CIMName ("q1")));
	assert(!qualifiers1.isTrue(CIMName ("q1")));
	assert(qualifiers1.exists(CIMName ("q2")));
	assert(!qualifiers1.isTrue(CIMName ("q2")));

	assert(qualifiers1.find(CIMName ("QualifierDoesNotExist")) ==
            PEG_NOT_FOUND);
	assert(!qualifiers1.exists(CIMName ("QualifierDoesNotExist")));

	qualifiers1.resolve(
	    &context, NAMESPACE, CIMScope::CLASS, false, qualifiers0, true);

	// Qualifiers after the resolve.  Should have resolved against the
	// declarations.
	assert(qualifiers1.getCount() == 4);
	assert(qualifiers1.find(CIMName ("Abstract")) == 0);
	assert(qualifiers1.exists(CIMName ("Abstract")));
	assert(qualifiers1.isTrue(CIMName ("Abstract")));
	assert(qualifiers1.exists(CIMName ("q1")));
	assert(!qualifiers1.isTrue(CIMName ("q1")));
	assert(qualifiers1.exists(CIMName ("q2")));
	assert(!qualifiers1.isTrue(CIMName ("q2")));

	assert(qualifiers1.find(CIMName ("QualifierDoesNotExist")) ==
            PEG_NOT_FOUND);
	assert(!qualifiers1.exists(CIMName ("QualifierDoesNotExist")));
	if(verbose)
	    qualifiers1.print();

	// Add test for double add of a name
	Boolean exceptionCaught = false;
	try
	{
	    qualifiers1.add(CIMQualifier(CIMName ("Abstract"), true));
	}
	catch (Exception& e)
	{
	    exceptionCaught = true;
	}
	assert(exceptionCaught);

	// Test some of the basics again after the double insertion problem
	assert(qualifiers1.getCount() == 4);
	assert(qualifiers1.find(CIMName ("Abstract")) == 0);
	assert(qualifiers1.exists(CIMName ("Abstract")));
	assert(qualifiers1.isTrue(CIMName ("Abstract")));

	// Create qualifier list 2: Will be resolved against qualifiers1

	CIMQualifierList qualifiers2;

	qualifiers2
	    .add(CIMQualifier(CIMName ("Description"),
                String("CIMQualifier List 1")))
	    .add(CIMQualifier(CIMName ("q1"), Boolean(true),
                CIMFlavor::OVERRIDABLE));

	if(verbose)
	    qualifiers2.print();

	assert(qualifiers2.getCount() == 2);
	assert(qualifiers2.exists(CIMName ("Description")));
	assert(qualifiers2.exists(CIMName ("q1")));
	assert(qualifiers2.isTrue(CIMName ("q1")));

	// Resolve the qualifiers against the previous list qualifiers1
	qualifiers2.resolve(
	    &context, NAMESPACE, CIMScope::CLASS, false, qualifiers1, true);

	if(verbose)
	    qualifiers2.print();

	// Post resolution
	assert(qualifiers2.getCount() == 4);
	assert(qualifiers2.exists(CIMName ("Description")));
	assert(qualifiers2.exists(CIMName ("abstract")));
	assert(qualifiers2.isTrue(CIMName ("abstract")));

	assert(qualifiers2.exists(CIMName ("q1")));
	assert(qualifiers2.isTrue(CIMName ("q1")));

	assert(qualifiers2.exists(CIMName ("q2")));
	// Should inherit the value from the superclass
	assert(!qualifiers2.isTrue(CIMName ("q2")));

    }
    catch (Exception& e)
    {
		cerr << "Exception: " << e.getMessage() << endl;
		exit(1);
    }

    cout << argv[0] << " +++++ passed all tests" << endl;

    return 0;
}


text:
using System;
using System.Net;
using System.Diagnostics;

namespace OpenQA.Selenium.Environment
{
    public class TestWebServer
    {
        private Process webserverProcess;

        private string standaloneTestJar = @"build\java\client\test\org\openqa\selenium\tests-standalone.jar";
        private string webserverClassName = "org.openqa.selenium.environment.webserver.Jetty7AppServer";
        private string projectRootPath;

        public TestWebServer(string projectRoot)
        {
            projectRootPath = projectRoot;
        }

        public void Start()
        {
            if (webserverProcess == null || webserverProcess.HasExited)
            {
                webserverProcess = new Process();
                webserverProcess.StartInfo.FileName = "java.exe";
                webserverProcess.StartInfo.Arguments = "-cp " + standaloneTestJar + " " + webserverClassName;
                webserverProcess.StartInfo.WorkingDirectory = projectRootPath;
                webserverProcess.Start();
                DateTime timeout = DateTime.Now.Add(TimeSpan.FromSeconds(30));
                bool isRunning = false;
                while (!isRunning && DateTime.Now < timeout)
                {
                    // Poll until the webserver is correctly serving pages.
                    HttpWebRequest request = WebRequest.Create(EnvironmentManager.Instance.UrlBuilder.LocalWhereIs("simpleTest.html")) as HttpWebRequest;
                    try
                    {
                        HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                        if (response.StatusCode == HttpStatusCode.OK)
                        {
                            isRunning = true;
                        }
                    }
                    catch (WebException)
                    {
                    }
                }

                if (!isRunning)
                {
                    throw new TimeoutException("Could not start the test web server in 15 seconds");
                }
            }
        }

        public void Stop()
        {
            HttpWebRequest request = WebRequest.Create(EnvironmentManager.Instance.UrlBuilder.LocalWhereIs("quitquitquit")) as HttpWebRequest;
            try
            {
                request.GetResponse();
            }
            catch (WebException)
            {
            }

            if (webserverProcess != null)
            {
                webserverProcess.WaitForExit(10000);
                if (!webserverProcess.HasExited)
                {
                    webserverProcess.Kill();
                }

                webserverProcess.Dispose();
                webserverProcess = null;
            }
        }
    }
}


text:
Manifest
********

The manifest file will list files which are not included in the build by
default.

*Note*: By default, ``distutils`` will include the following files in your
release package:

- ``README.txt``
- ``setup.py``
- The ``.py`` files needed by the multi-file modules listed in the
  packages parameter.
- The individual ``.py`` files listed in the ``py_modules`` parameter.

Syntax
======

Taking this sample
``sample/python/distutils/simple-booking-engine/MANIFEST.in`` file.

::

  include LICENSE
  recursive-include docs *.html *.css *.png *.gif

Sample from a Django project:

::

  include LICENSE
  include MANIFEST.in
  include README.rst
  recursive-include docs *
  recursive-include simple-booking-engine/templates *

Note:

- The first line is self-explanatory; include the ``LICENSE`` file from the
  project's root directory.
- The second line is a bit more complicated; the ``recursive-include``
  command takes a directory name and one or more filenames.  The filenames
  aren't limited to specific files; they can include wildcards.


text:
@php
    use Illuminate\Support\Str;

    foreach ($renderer->getErrorMessages($control->getKey()) as $message)
    {
        $name = str_replace('_', ' ', Str::snake($control->getKey()));
        $label = $control->getLabel() ? $control->getLabel() : $control->getPlaceholder();
        $message = str_replace($name, $label, $message);
        break;
    }
@endphp

@if(!empty($message))
    <small class="error">{{ $message }}</small>
@endif


text:
date: "2015-12-09"
title: "ES6, ES2015 : le protocole d'itération"
tags:
  - javascript
  - ES6
  - ES2015
  - iterators
authors:
  - ffesseler
---

Imaginez un concept si important que si vous l'enleviez du langage, il faudrait
en conséquence enlever le spread, le destructuring, les générateurs, le for…of
et bien d'autres. Ce concept, introduit dans l'ES6, est en fait un protocole :
le protocole d'itération.

Le principe est de définir une convention dans le langage, qui permet de
standardiser la façon dont des sources de données peuvent être traversées.

Première bonne nouvelle, ce protocole est assez simple à comprendre et se base
sur 2 "interfaces" (oui les guillemets c'est pour dire qu'on ne parle pas
d'interface au sens technique, puisqu'elles n'existent pas en JS).

La première interface, appelée **Iterator** permet à un objet de produire des
valeurs en séquence. Un objet est un Iterator lorsqu'il implémente une
function ``next()`` qui retourne un objet avec 2 propriétés :

* ``value``: la valeur courante lors de l'itération
* ``done`` : un booléen qui indique si on a atteint la fin de l'itération ou non

Les appels successifs à la méthode ``next()`` d'un Iterator permettent donc de
traverser et récupérer les valeurs d'un objet. Prenons l'exemple de l'Iterator
retourné par un Array qui contiendrait 2 valeurs ("a" et "b") :

```js
iteratorArray.next()
// -> Object {value: "a", done: false}
iteratorArray.next()
// -> Object {value: "b", done: false}
iteratorArray.next()
// -> Object {value: undefined, done: true}
```

Mais comment récupérer l'Iterator d'un objet vas-tu me dire ? (n'est-ce pas ?)
Ça tombe bien, c'est le rôle de la seconde interface, appelée **Iterable**. Un
objet est Iterable s'il implémente une méthode particulière qui va retourner
l'Iterator. Cette méthode particulière (appelée *@@iterator* dans la
spécification) doit être définie en utilisant le symbole ``[Symbol.iterator]``.
(Les symboles seront expliqués dans un prochain article, pas de panique).

En reprenant l'exemple précédent, voici comment récupérer l'Iterator d'un Array :

```js
const arr = ["a", "b"]
const iteratorArray = arr[Symbol.iterator]()
iteratorArray.next()
// -> Object {value: "a", done: false}
iteratorArray.next()
// -> Object {value: "b", done: false}
iteratorArray.next()
// -> Object {value: undefined, done: true}
```

L'exemple ci-dessus illustre donc l'implémentation du protocole par l'Array.
Il n'est pas très utile en soi, en voici donc un autre qui va permettre de
boucler sur les valeurs et les afficher :

```js
const arr = ["a", "b"]
var iterator = arr[Symbol.iterator]()

var result = iterator.next()
while (!result.done) {
  console.log(result.value)
  result = iterator.next()
}
// 'a'
// 'b'
```

De manière générale, quand un objet qui implémente le protocole d'itération est
traversé, sa méthode *@@iterator* est appelée (une seule fois donc) et l'Iterator
retourné est utilisé pour boucler sur ses valeurs.

# Consommateurs d'Iterable

La deuxième bonne nouvelle, c'est que plusieurs concepts du langage tirent avantage de ce protocole :

* Certaines syntaxes s'attendent à recevoir des Iterables

```js
const arr = ["a", "b"]

// La syntaxe à laquelle on pense immédiatement est la syntaxe « for .. of »
// qui permet de boucler sur les valeurs des Iterables.
for (val of arr) {
    console.log(val)
}

// Le spread qui permet d'insérer facilement des valeurs dans un Array
// utilise également des Iterable
['0', ...arr, '1'] // 0, a, b, 1

// yield nécessite également des Iterable
function* gen(){
  yield* arr
}
gen().next() // { value:"a", done:false }

// Le destructuring avec le pattern Array
const [x, y] = arr // x = 'a',  y = "b"
```

* Des API acceptent également des Iterables

```js
const arr = ["a", "b", "b"]

// Certains constructeurs acceptent des Iterable

// Set et Weakset
const set = new Set(arr)
set.has("b") // true
// Map et WeakMap
const map = new Map(arr.entries()) // Attention, le constructeur attend un ensemble [clé, valeur]
map.get(0) // 'a'

// Ou encore les API suivants :

Array.from(iterable) // transforme n'importe quel Iterable en Array.
Promise.all(iterableCollectionDePromises) // n'importe quel Iterable qui contient un ensemble de Promises
Promise.race(iterableCollectionDePromises) // idem
```

# Built-in Iterable

Troisième bonne nouvelle, plusieurs objets du langage implémentent déjà ce protocole :

```js
// évidemment les Array
const arr = ["l", "o", "l"]
for (v of arr) {
  console.log(v)
  // 'l'
  // 'o'
  // 'l'
}

// les String
const str = "lol"
for (v of str) {
  console.log(v)
  // 'l'
  // 'o'
  // 'l'
}

// les Map et Set (mais PAS WeakMap et WeakSet)
const map = new Map().set('l', 1).set('o', 2)
for (v of map) {
  console.log(v)
  // ["l", 1]
  // ["o", 2]
}
const set = new Set().add('l').add('o')
for (v of map) {
  console.log(v)
  // 'l'
  // 'o'
}

// Les TypedArray que vous utilisez tous les jours
const int16 = new Int16Array(2)
int16[0] = 42
for (v of int16) {
  console.log(v)
  // 42
  // 0
}

// Même l'objet spécial arguments (que vous
// ne devriez plus utiliser avec l'ES6) est un Iterable
function test() {
  for (v of arguments) {
    console.log(v)
    // 'l'
    // 'o'
    // 'l'
  }
}
test('l', 'o', 'l')

// Les NodeList retournés par l'API DOM également !
const matches = document.querySelectorAll('div')
for (m of matches) {
  console.log(m)
  // <div id="topSection">
  // <div id="brandLogo">
  // ...
}
```

Autre point : Array, TypedArray, Map, Set sont des Iterable mais définissent
aussi des méthodes qui retournent également des Iterable (ça va, vous suivez
toujours ?) :

- entries() retourne un ensemble des clés/valeurs
- keys() retourne les clés
- values() retourne les valeurs

```js
for (cleVals of arr.entries()) {
  console.log(cleVals)
  // [0, "l"]
  // [1, "o"]
  // [2, "l"]
}
```

Détail important, ``Object`` n'est pas Iterable mais il n'est pas impossible de
voir apparaitre dans l'ES7 les méthodes entries(), keys() et values() sur
Object (cf.
[la proposition spec](https://github.com/tc39/proposal-object-values-entries)).

# Conclusion

J'espère que cet article a bien illustré l'importance de ce protocole dans le
langage. Nous avons vu ci-dessus que de nombreux concepts du langage tirent
déjà avantage de ce protocole mais il est au moins aussi important de noter que
cela permet d'établir une convention sur laquelle des librairies externes peuvent
s'appuyer.

Elles peuvent le faire de 2 manières :

* en proposant des sources de données qui implémentent le protocole (ex:
liste chaînée)
* en tant que consommateur du protocole (ex: un algorithme de tri)

# Un dernier verre pour la route

Les articles suivants vous permettront d'aller encore plus loin dans le sujet. Vous y
apprendrez notamment qu'un iterator peut retourner en option 2 autres méthodes,
qu'un générateur est à la fois un Iterable et un Iterator, qu'un Iterable peut
être infini ou encore des exemples d'implémentations divers et variés :

* [Iterables and iterators in ECMAScript 6](http://www.2ality.com/2015/02/es6-iteration.html)
* [Iteration Protocols](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols)
* [ES6 in depth : iterators and the for of loop](https://hacks.mozilla.org/2015/04/es6-in-depth-iterators-and-the-for-of-loop/)
* [ES6 iterators in depth](https://ponyfoo.com/articles/es6-iterators-in-depth)

La pratique restant le meilleur moyen de se former, le site
[ES6 Katas](http://es6katas.org/) est très bien fait pour s'exercer.


text:
<?php

namespace Topxia\Api\SpecialResponse;

use Topxia\Common\ArrayToolkit;

class QiQiuYunV1OpenCourseResponse implements SpecialResponse
{
    public function filter($data)
    {
        if (isset($data['error'])) {
            return $data;
        }

        $resources = array();
        foreach ($data['resources'] as $openCourse) {
            $resources[] = array(
                'id'          => $openCourse['id'],
                'title'       => $openCourse['title'],
                'subtitle'    => $openCourse['subtitle'],
                'type'        => 'public_' . $openCourse['type'],
                'lessonNum'   => $openCourse['lessonNum'],
                'studentNum'  => $openCourse['studentNum'],
                'hitNum'      => $openCourse['hitNum'],
                'likeNum'     => $openCourse['likeNum'],
                'postNum'     => $openCourse['postNum'],
                'tags'        => ArrayToolkit::column($openCourse['tags'], 'name'),
                'category'    => isset($openCourse['category']['name']) ? $openCourse['category']['name'] : '',
                'about'       => $openCourse['about'],
                'picture'     => $openCourse['largePicture'],
                'createdTime' => $openCourse['createdTime'],
                'updatedTime' => $openCourse['updatedTime']
            );

        }
        $data['resources'] = $resources;
        return $data;
    }
}


text:
package galebv2

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"net/http/httptest"
	"strconv"
	"strings"
	"testing"

	"github.com/gorilla/mux"
	"github.com/tsuru/config"
	"github.com/tsuru/tsuru/db"
	"github.com/tsuru/tsuru/db/dbtest"
	galebClient "github.com/tsuru/tsuru/router/galebv2/client"
	"github.com/tsuru/tsuru/router/routertest"
	"gopkg.in/check.v1"
)

func Test(t *testing.T) {
	check.TestingT(t)
}

type fakeGalebServer struct {
	targets      map[string]interface{}
	virtualhosts map[string]interface{}
	rules        map[string]interface{}
	items        map[string]map[string]interface{}
	ruleVh       map[string][]string
	idCounter    int
	router       *mux.Router
}

func NewFakeGalebServer() (*fakeGalebServer, error) {
	server := &fakeGalebServer{
		targets:      make(map[string]interface{}),
		virtualhosts: make(map[string]interface{}),
		rules:        make(map[string]interface{}),
		ruleVh:       make(map[string][]string),
	}
	server.items = map[string]map[string]interface{}{
		"target":      server.targets,
		"virtualhost": server.virtualhosts,
		"rule":        server.rules,
	}
	r := mux.NewRouter()
	r.HandleFunc("/api/target", server.createTarget).Methods("POST")
	r.HandleFunc("/api/rule", server.createRule).Methods("POST")
	r.HandleFunc("/api/virtualhost", server.createVirtualhost).Methods("POST")
	r.HandleFunc("/api/{item}/{id}", server.findItem).Methods("GET")
	r.HandleFunc("/api/{item}/{id}", server.destroyItem).Methods("DELETE")
	r.HandleFunc("/api/{item}/search/findByName", server.findItemByNameHandler).Methods("GET")
	r.HandleFunc("/api/rule/{id}/parents", server.addRuleVirtualhost).Methods("PATCH")
	r.HandleFunc("/api/rule/{id}/parents", server.findVirtualhostByRule).Methods("GET")
	r.HandleFunc("/api/rule/{id}/parents/{vhid}", server.destroyRuleVirtualhost).Methods("DELETE")
	r.HandleFunc("/api/target/{id}/children", server.findTargetsByParent).Methods("GET")
	server.router = r
	return server, nil
}

func (s *fakeGalebServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	s.router.ServeHTTP(w, r)
}

func (s *fakeGalebServer) findItem(w http.ResponseWriter, r *http.Request) {
	id := mux.Vars(r)["id"]
	item := mux.Vars(r)["item"]
	obj, ok := s.items[item][id]
	if !ok {
		w.WriteHeader(http.StatusNotFound)
		return
	}
	json.NewEncoder(w).Encode(obj)
}

type searchRsp struct {
	Embedded map[string][]interface{} `json:"_embedded"`
}

func makeSearchRsp(itemName string, items ...interface{}) searchRsp {
	return searchRsp{Embedded: map[string][]interface{}{itemName: items}}
}

func (s *fakeGalebServer) findItemByNameHandler(w http.ResponseWriter, r *http.Request) {
	itemName := mux.Vars(r)["item"]
	wantedName := r.URL.Query().Get("name")
	ret := s.findItemByName(itemName, wantedName)
	json.NewEncoder(w).Encode(makeSearchRsp(itemName, ret...))
}

func (s *fakeGalebServer) findItemByName(itemName string, wantedName string) []interface{} {
	items := s.items[itemName]
	var ret []interface{}
	for i, item := range items {
		name := item.(interface {
			GetName() string
		}).GetName()
		if name == wantedName {
			ret = append(ret, items[i])
		}
	}
	return ret
}

func (s *fakeGalebServer) findTargetsByParent(w http.ResponseWriter, r *http.Request) {
	wantedId := mux.Vars(r)["id"]
	var ret []interface{}
	for i, item := range s.targets {
		target := item.(*galebClient.Target)
		if strings.HasSuffix(target.BackendPool, "/"+wantedId) {
			ret = append(ret, s.targets[i])
		}
	}
	json.NewEncoder(w).Encode(makeSearchRsp("target", ret...))
}

func (s *fakeGalebServer) destroyItem(w http.ResponseWriter, r *http.Request) {
	id := mux.Vars(r)["id"]
	item := mux.Vars(r)["item"]
	_, ok := s.items[item][id]
	if !ok {
		w.WriteHeader(http.StatusNotFound)
		return
	}
	delete(s.items[item], id)
	w.WriteHeader(http.StatusNoContent)
}

func (s *fakeGalebServer) createTarget(w http.ResponseWriter, r *http.Request) {
	var target galebClient.Target
	target.Status = "OK"
	json.NewDecoder(r.Body).Decode(&target)
	targetsWithName := s.findItemByName("target", target.Name)
	for _, item := range targetsWithName {
		otherTarget := item.(*galebClient.Target)
		if otherTarget.BackendPool == target.BackendPool {
			w.WriteHeader(http.StatusConflict)
			return
		}
	}
	s.idCounter++
	target.ID = s.idCounter
	target.Links.Self.Href = fmt.Sprintf("http://%s%s/%d", r.Host, r.URL.String(), target.ID)
	s.targets[strconv.Itoa(target.ID)] = &target
	w.Header().Set("Location", target.Links.Self.Href)
	w.WriteHeader(http.StatusCreated)
}

func (s *fakeGalebServer) createRule(w http.ResponseWriter, r *http.Request) {
	var rule galebClient.Rule
	rule.Status = "OK"
	json.NewDecoder(r.Body).Decode(&rule)
	s.idCounter++
	rule.ID = s.idCounter
	rule.Links.Self.Href = fmt.Sprintf("http://%s%s/%d", r.Host, r.URL.String(), rule.ID)
	s.rules[strconv.Itoa(rule.ID)] = &rule
	w.Header().Set("Location", rule.Links.Self.Href)
	w.WriteHeader(http.StatusCreated)
}

func (s *fakeGalebServer) addRuleVirtualhost(w http.ResponseWriter, r *http.Request) {
	id := mux.Vars(r)["id"]
	data, err := ioutil.ReadAll(r.Body)
	if err != nil {
		w.WriteHeader(http.StatusBadRequest)
		return
	}
	parts := strings.Split(string(data), "\n")
	if len(parts) == 0 || parts[0] == "" {
		w.WriteHeader(http.StatusBadRequest)
		return
	}
	vhId := parts[0][strings.LastIndex(parts[0], "/")+1:]
	baseRule := s.rules[id].(*galebClient.Rule)
	baseVirtualHost := s.virtualhosts[vhId].(*galebClient.VirtualHost)
	if baseRule == nil || baseVirtualHost == nil {
		w.WriteHeader(http.StatusNotFound)
		return
	}
	s.ruleVh[id] = append(s.ruleVh[id], vhId)
	w.WriteHeader(http.StatusNoContent)
}

func (s *fakeGalebServer) destroyRuleVirtualhost(w http.ResponseWriter, r *http.Request) {
	ruleId := mux.Vars(r)["id"]
	vhId := mux.Vars(r)["vhid"]
	idx := -1
	for i, currentVh := range s.ruleVh[ruleId] {
		if currentVh == vhId {
			idx = i
			break
		}
	}
	if idx == -1 {
		w.WriteHeader(http.StatusNotFound)
		return
	}
	s.ruleVh[ruleId] = append(s.ruleVh[ruleId][:idx], s.ruleVh[ruleId][idx+1:]...)
	if len(s.ruleVh[ruleId]) == 0 {
		delete(s.ruleVh, ruleId)
	}
	w.WriteHeader(http.StatusNoContent)
}

func (s *fakeGalebServer) findVirtualhostByRule(w http.ResponseWriter, r *http.Request) {
	ruleId := mux.Vars(r)["id"]
	var ret []interface{}
	for _, vhId := range s.ruleVh[ruleId] {
		ret = append(ret, s.virtualhosts[vhId])
	}
	json.NewEncoder(w).Encode(makeSearchRsp("virtualhost", ret...))
}

func (s *fakeGalebServer) createVirtualhost(w http.ResponseWriter, r *http.Request) {
	var virtualhost galebClient.VirtualHost
	virtualhost.Status = "OK"
	json.NewDecoder(r.Body).Decode(&virtualhost)
	if len(s.findItemByName("virtualhost", virtualhost.Name)) > 0 {
		w.WriteHeader(http.StatusConflict)
		return
	}
	s.idCounter++
	virtualhost.ID = s.idCounter
	virtualhost.Links.Self.Href = fmt.Sprintf("http://%s%s/%d", r.Host, r.URL.String(), virtualhost.ID)
	s.virtualhosts[strconv.Itoa(virtualhost.ID)] = &virtualhost
	w.Header().Set("Location", virtualhost.Links.Self.Href)
	w.WriteHeader(http.StatusCreated)
}

func init() {
	suite := &routertest.RouterSuite{
		SetUpSuiteFunc: func(c *check.C) {
			config.Set("routers:galeb:username", "myusername")
			config.Set("routers:galeb:password", "mypassword")
			config.Set("routers:galeb:domain", "galeb.com")
			config.Set("routers:galeb:type", "galeb")
			config.Set("database:url", "127.0.0.1:27017")
			config.Set("database:name", "router_galebv2_tests")
		},
	}
	var server *httptest.Server
	var fakeServer *fakeGalebServer
	suite.SetUpTestFunc = func(c *check.C) {
		var err error
		fakeServer, err = NewFakeGalebServer()
		c.Assert(err, check.IsNil)
		server = httptest.NewServer(fakeServer)
		config.Set("routers:galeb:api-url", server.URL+"/api")
		gRouter, err := createRouter("routers:galeb")
		c.Assert(err, check.IsNil)
		suite.Router = gRouter
		conn, err := db.Conn()
		c.Assert(err, check.IsNil)
		defer conn.Close()
		dbtest.ClearAllCollections(conn.Collection("router_galebv2_tests").Database)
	}
	suite.TearDownTestFunc = func(c *check.C) {
		server.Close()
		c.Check(fakeServer.targets, check.DeepEquals, map[string]interface{}{})
		c.Check(fakeServer.virtualhosts, check.DeepEquals, map[string]interface{}{})
		c.Check(fakeServer.rules, check.DeepEquals, map[string]interface{}{})
		c.Check(fakeServer.ruleVh, check.DeepEquals, map[string][]string{})
	}
	check.Suite(suite)
}


text:
package gex.newsml.g2;

import lombok.ToString;

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

/**
 * Flexible generic PCL-Type for controlled, uncontrolled values and arbitrary
 * values, with mandatory relationship
 *
 *

 * Java class for Flex2ExtPropType complex type.
 *
 *

 * The following schema fragment specifies the expected content contained within
 * this class.
 *
 *

 * <complexType name="Flex2ExtPropType">
 *   <complexContent>
 *     <extension base="{http://iptc.org/std/nar/2006-10-01/}Flex1ExtPropType">
 *       <attGroup ref="{http://iptc.org/std/nar/2006-10-01/}timeValidityAttributes"/>
 *       <attribute name="rel" type="{http://iptc.org/std/nar/2006-10-01/}QCodeType" />
 *       <attribute name="reluri" type="{http://iptc.org/std/nar/2006-10-01/}IRIType" />
 *       <anyAttribute processContents='lax' namespace='##other'/>
 *     </extension>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Flex2ExtPropType")
@ToString
public class Flex2ExtPropType extends Flex1ExtPropType {

	@XmlAttribute(name = "rel")
	protected String rel;
	@XmlAttribute(name = "reluri")
	protected String reluri;
	@XmlAttribute(name = "validfrom")
	protected String validfrom;
	@XmlAttribute(name = "validto")
	protected String validto;

	/**
	 * Gets the value of the rel property.
	 *
	 * @return possible object is {@link String }
	 *
	 */
	public String getRel() {
		return rel;
	}

	/**
	 * Sets the value of the rel property.
	 *
	 * @param value
	 *            allowed object is {@link String }
	 *
	 */
	public void setRel(String value) {
		this.rel = value;
	}

	/**
	 * Gets the value of the reluri property.
	 *
	 * @return possible object is {@link String }
	 *
	 */
	public String getReluri() {
		return reluri;
	}

	/**
	 * Sets the value of the reluri property.
	 *
	 * @param value
	 *            allowed object is {@link String }
	 *
	 */
	public void setReluri(String value) {
		this.reluri = value;
	}

	/**
	 * Gets the value of the validfrom property.
	 *
	 * @return possible object is {@link String }
	 *
	 */
	public String getValidfrom() {
		return validfrom;
	}

	/**
	 * Sets the value of the validfrom property.
	 *
	 * @param value
	 *            allowed object is {@link String }
	 *
	 */
	public void setValidfrom(String value) {
		this.validfrom = value;
	}

	/**
	 * Gets the value of the validto property.
	 *
	 * @return possible object is {@link String }
	 *
	 */
	public String getValidto() {
		return validto;
	}

	/**
	 * Sets the value of the validto property.
	 *
	 * @param value
	 *            allowed object is {@link String }
	 *
	 */
	public void setValidto(String value) {
		this.validto = value;
	}

}


text:
#pragma once

typedef struct {
  float x;
  float y;
  float w;
  float h;
} graphics_Quad;

void graphics_Quad_new(graphics_Quad *dst, float x, float y, float w, float h);
void graphics_Quad_newWithRef(graphics_Quad *dst, float x, float y, float w, float h, float rw, float rh);


text:
<!doctype html>

    <link href='http://fonts.googleapis.com/css?family=Share+Tech+Mono' rel='stylesheet' type='text/css'>
    <meta charset="utf-8">
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1, minimal-ui">
    <title>Justin Parker</title>

    <link rel="stylesheet" href="styles/vendor.css">

    <link rel="stylesheet" href="styles/main.css">

Justin Parker

Front End Engineer

315-497-7275

JustinParker@outlook.com

justinparker.us

GitHub:JustinRParker

LinkedIN


text:
Currently, there are 2 test suites:
* `test` executes several egison programs and checks if the results are expected.
* `test-cli` tests command line options.

## How to Run Tests

To run all tests, simply execute the following.
(We recommend _not_ to use `--fast` option, as some tests can take very long time without compiler optimizations.)
```
$ stack test
```

To run selected test suites, you can add `egison:[test suite name]`.
```
$ stack test egison:test
$ stack test egison:test-cli
```

For the `test` suite, you can use `--test-arguments` (or `--ta` for short) to specify which program to test.
```
$ stack test egison:test --test-arguments=--select-tests="test/syntax.egi"
$ stack test egison:test --ta=--select-tests="test/syntax.egi"
```


text:
An MQTT encoder and decoder,written in Golang.

This library was modified heavily from https://github.com/plucury/mqtt.go and
is API-incompatible with it.

Currently the library's API is unstable.


text:
import glob

import numpy as np

import instance_occlsegm_lib

import chainer_mask_rcnn as mrcnn

import contrib

def main():
    class_names = contrib.core.get_class_names()

    bboxes_, labels_, masks_ = None, None, None
    json_files = sorted(glob.glob('*.json'))
    for json_file in json_files:
        img, lbl_ins, lbl_cls = contrib.core.load_json_file(json_file)

        labels, bboxes, masks = mrcnn.utils.label2instance_boxes(
            lbl_ins, lbl_cls, return_masks=True)

        if bboxes_ is None:
            masks_inv = None
        else:
            masks_inv = []
            for i in range(len(bboxes)):
                mask = masks[i]
                label = labels[i]

                mask_inv = np.zeros_like(mask)
                for j in range(len(bboxes_)):
                    label_ = labels_[j]
                    mask_ = masks_[j]
                    if label_ == label:
                        continue
                    mask_inv = np.bitwise_or(
                        mask_inv,
                        np.bitwise_and(mask, mask_),  # invisible region
                    )
                masks_inv.append(mask_inv)

        captions = [class_names[l] for l in labels]
        viz1 = mrcnn.utils.draw_instance_bboxes(
            img, bboxes, labels, n_class=len(class_names),
            masks=masks, captions=captions)
        viz2 = mrcnn.utils.draw_instance_bboxes(
            img, bboxes, labels, n_class=len(class_names),
            masks=masks_inv, captions=captions)
        tile = instance_occlsegm_lib.image.tile([img, viz1, viz2])
        instance_occlsegm_lib.io.imshow(tile)
        key = instance_occlsegm_lib.io.waitkey()
        if key == ord('q'):
            break

        bboxes_, masks_, labels_ = bboxes, masks, labels

if __name__ == '__main__':
    main()


text:
import '../testSetup';

import express from 'express';
import mongoose from 'mongoose';

import _ from '../../main/util/util';
import {routesMiddleware} from '../../main/middleware/routesMiddleware';
import {LocaisMock} from '../../mock/LocaisMock';

import {UsersService} from '../../main/service/usersService';
import UsersMock from '../../mock/usersMock';

describe('LocaisRouterTest', () => {

    const app = express();
    routesMiddleware.set(app);

    const token = UsersMock.getToken();

    /**
     * Retorna a requisição desejada em /locais/:idLocal
     *
     * @param {String} metodoHttp     Método http do endpoint a ser testado.
     * @param {String} [idLocal = ''] Id do local a ser realizado GET. Se não passado, retorna listagem.
     */
    function requisicaoLocais(metodoHttp, idLocal = '') {
        return request(app)[_.toLower(metodoHttp)](`${_.CONSTANTES_LOCAL.URI}/${idLocal}`)
            .set('Authorization', `Bearer ${token}`)
            .set(_.ACCESS_TOKEN, token);
    }

    /**
     * Testa um endpoint para que o mesmo tenha resposta Forbidden (403).
     * Função auxiliar para aumentar o reúso de código.
     *
     * @param {String}   metodoHttp Método http do endpoint a ser testado.
     * @param {String}   uri        URI do endpoint.
     * @param {Object}   reqBody    Objeto a ser enviado.
     * @param {Function} done       Função chamada quando o teste acabar.
     */
    function testeEndPointForbidden({metodoHttp, uri, reqBody = {}, done}) {
        UsersMock.cacheUsuarioComum(UsersService);
        request(app)[_.toLower(metodoHttp)](uri)
            .set('Authorization', `Bearer ${token}`)
            .set(_.ACCESS_TOKEN, token)
            .send(reqBody)
            .expect(_.FORBIDDEN).end((err, res) => {

            expect(err).to.not.be.ok;

            const erro = res.body;
            expect(erro.mensagem).to.be.eql(_.ERRO_USUARIO_SEM_PERMISSAO);
            done();
        });
    }

    /**
     * Testa um endpoint para que o mesmo tenha resposta Not Found (404).
     * Função auxiliar para aumentar o reúso de código.
     *
     * @param {String}   metodoHttp Método http do endpoint a ser testado.
     * @param {String}   idLocal    Id do local.
     * @param {Object}   reqBody    Objeto a ser enviado.
     * @param {Function} done       Função chamada quando o teste acabar.
     */
    function testeEndPointNotFound({metodoHttp, idLocal = mongoose.Types.ObjectId(), reqBody = {}, done}) {
        requisicaoLocais(metodoHttp, idLocal)
            .send(reqBody)
            .expect(_.NOT_FOUND).end((err, res) => {

            expect(err).to.not.be.ok;

            const erro = res.body;
            expect(erro.mensagem).to.be.eql(_.CONSTANTES_LOCAL.ERRO_LOCAL_NAO_ENCONTRADO);
            done();
        });
    }

    beforeEach(() => {
        UsersMock.cacheUsuarioAdmin(UsersService);
    });

    describe('GET /api/locais deve', () => {
        it('retornar um array de Locais', done => {
            requisicaoLocais('GET').expect(_.OK).end((err, res) => {
                expect(err).to.not.be.ok;

                const locais = res.body;
                expect(_.isArray(locais)).to.be.true;
                done();
            });
        });

        it('retornar um array com todos os locais cadastrados', done => {
            const localMock = LocaisMock.getLocal();
            requisicaoLocais('POST').send(localMock)
                .expect(_.CREATED).end((err, res) => {

                expect(err).to.not.be.ok;
                const localCadastrado = res.body;

                requisicaoLocais('GET').expect(_.OK).end((err, res) => {

                    expect(err).to.not.be.ok;

                    const locais = res.body;
                    expect(_.isArray(locais)).to.be.true;
                    expect(_.some(locais, localCadastrado)).to.be.true;
                    done();
                });
            });
        });
    });

    describe('POST /api/locais deve', () => {
        it('retornar 403 (Forbidden) se o usuário não possuir role admin', done => {
            const metodoHttp = 'POST',
                uri = _.CONSTANTES_LOCAL.URI,
                reqBody = LocaisMock.getLocal();
            testeEndPointForbidden({metodoHttp, uri, reqBody, done});
        });

        it('retornar mensagem de erro caso haja o mesmo no cadastro', done => {
            const localMock = LocaisMock.getLocal();
            delete localMock.nome;

            requisicaoLocais('POST').send(localMock)
                .expect(_.BAD_REQUEST).end((err, res) => {

                expect(err).to.not.be.ok;

                const erro = res.body;
                expect(erro.mensagem).to.be.eql(`Erro de validação: ${_.CONSTANTES_LOCAL.ERRO_VALIDACAO_NOME}.`);
                done();
            });
        });

        it('cadastrar corretamente o local e retornar a entidade persistida', done => {
            const localMock = LocaisMock.getLocal();

            requisicaoLocais('POST').send(localMock)
                .expect(_.CREATED).end((err, res) => {

                expect(err).to.not.be.ok;

                const local = res.body;
                expect(local._id).to.be.ok;
                expect(_.isObject(local)).to.be.true;
                done();
            });
        });
    });

    describe('GET /api/locais/:id deve', () => {
        it('retornar o erro corretamente caso o local com o id informado não exista', done => {
            const metodoHttp = 'GET';
            testeEndPointNotFound({metodoHttp, done});
        });

        it('retornar o local dado o id do mesmo', done => {
            const localMock = LocaisMock.getLocal();

            requisicaoLocais('POST').send(localMock)
                .expect(_.CREATED).end((err, res) => {

                expect(err).to.not.be.ok;
                const localCadastrado = res.body;

                requisicaoLocais('GET', localCadastrado._id).expect(_.OK).end((err, res) => {

                    expect(err).to.not.be.ok;

                    const localConsultado = res.body;
                    expect(localConsultado).to.be.eql(localCadastrado);
                    done();
                });
            });
        });
    });

    describe('DELETE /api/locais/:id deve', () => {
        it('retornar 403 (Forbidden) se o usuário não possuir role admin', done => {
            const metodoHttp = 'DELETE',
                uri = `${_.CONSTANTES_LOCAL.URI}/${mongoose.Types.ObjectId()}`,
                reqBody = LocaisMock.getLocal();
            testeEndPointForbidden({metodoHttp, uri, reqBody, done});
        });

        it('retornar o erro corretamente caso o local com o id informado não exista', done => {
            const metodoHttp = 'DELETE';
            testeEndPointNotFound({metodoHttp, done});
        });

        it('retornar o local removido e remover o mesmo corretamente', done => {
            const localMock = LocaisMock.getLocal();

            // Cadastrar Local
            requisicaoLocais('POST').send(localMock)
                .expect(_.CREATED).end((err, res) => {

                expect(err).to.not.be.ok;
                const localCadastrado = res.body;

                // Deletar local
                requisicaoLocais('DELETE', localCadastrado._id).expect(_.OK).end((err, res) => {

                    expect(err).to.not.be.ok;

                    const localRemovido = res.body;
                    expect(localRemovido).to.be.eql(localCadastrado);

                    // Consulta novamente o local.
                    testeEndPointNotFound({metodoHttp: 'GET', done});
                });
            });
        });
    });

    describe('PUT /api/locais/:id', () => {
        let localCadastrado;

        beforeEach(done => {
            const localMock = LocaisMock.getLocal();
            requisicaoLocais('POST').send(localMock)
                .expect(_.CREATED).end((err, res) => {

                expect(err).to.not.be.ok;
                localCadastrado = res.body;
                done()
            });
        });

        it('retornar 403 (Forbidden) se o usuário não possuir role admin', done => {
            const metodoHttp = 'PUT',
                uri = `${_.CONSTANTES_LOCAL.URI}/${mongoose.Types.ObjectId()}`,
                reqBody = LocaisMock.getLocal();
            testeEndPointForbidden({metodoHttp, uri, reqBody, done});
        });

        it('retornar corretamente o erro caso haja', done => {
            const novoLocal = _.clone(localCadastrado);
            delete novoLocal.bloco;
            requisicaoLocais('PUT', localCadastrado._id).send(novoLocal)
                .expect(_.BAD_REQUEST).end((err, res) => {

                expect(err).to.not.be.ok;
                const erro = res.body;
                expect(erro.mensagem).to.be.eql(`Erro de validação: ${_.CONSTANTES_LOCAL.ERRO_VALIDACAO_BLOCO}.`);
                done();
            });
        });

        it('atualizar o local e retornar o local atualizado', done => {
            const novoLocal = _.clone(localCadastrado);
            novoLocal.bloco = 'LCC3';
            requisicaoLocais('PUT', localCadastrado._id).send(novoLocal)
                .expect(_.OK).end((err, res) => {

                expect(err).to.not.be.ok;
                const localAtualizado = res.body;
                expect(localAtualizado).to.be.eql(novoLocal);
                done();
            });
        });
    });
});


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace AppCampus.Signboard.Enums
{
    public enum TransitionType
    {
        None,
        Fade
    }
}


text:
<?xml version="1.0" encoding="ascii"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
          "DTD/xhtml1-transitional.dtd">

  <title>pomerge</title>
  <link rel="stylesheet" href="epydoc.css" type="text/css" />

Module pomerge

Functions

    main
    mergestore
    mergestores
    str2bool

[hide private]


text:
				{{msg.title}}
				<time>{{imsgnfo.time}}</time>
				{{msg.subject}}
				{{msg.message}}


text:
function Token(value, definition) {
    this.value = value;
    this.definition = definition;
    this.evaluate = function() {
        return this.definition.evaluator.apply(this, arguments);
    }
}

function TokenFactory(definitions, container) {

    this.container = container;
    this.tokenDefinitions = {};

    //Operators
    this.tokenDefinitions[TokenFactory.prototype.OPERATOR] = {
         '^': {
            value: '^',
            precedence: 2,
            type: TokenFactory.prototype.OPERATOR,
            evaluator: (a, b) => {
                a = parseFloat(a);
                b = parseFloat(b);
                if(isNaN(a) || isNaN(b)) { throw 'Incorrect argument types'; }
                return Math.pow(a, b);
            }
        },
        '/': {
            value: '/',
            precedence: 1,
            type: TokenFactory.prototype.OPERATOR,
            evaluator: (a, b) => {
                a = parseFloat(a);
                b = parseFloat(b);
                if(isNaN(a) || isNaN(b)) { throw 'Incorrect argument types'; }
                return a / b;
            }
        },
        '*': {
            value: '*',
            precedence: 1,
            type: TokenFactory.prototype.OPERATOR,
            evaluator: (a, b) => {
                a = parseFloat(a);
                b = parseFloat(b);
                if(isNaN(a) || isNaN(b)) { throw 'Incorrect argument types'; }
                return a * b;
            }
        },
        '-': {
            value: '-',
            precedence: 0,
            type: TokenFactory.prototype.OPERATOR,
            evaluator: (a, b) => {
                var tA = parseFloat(a);
                var tB = parseFloat(b);
                if(isNaN(tA) || isNaN(tB)) { throw 'Incorrect argument types: ' + a + ', ' + b; }
                return tA - tB;
            }
        },
        '+': {
            value: '+',
            precedence: 0,
            type: TokenFactory.prototype.OPERATOR,
            evaluator: (a, b) => {
                a = parseFloat(a);
                b = parseFloat(b);
                if(isNaN(a) || isNaN(b)) { throw 'Incorrect argument types'; }
                return a + b;
            }
        },
        '=': {
            value: '=',
            precedence: 0,
            type: TokenFactory.prototype.OPERATOR,
            evaluator: () => {
                return this.value;
            }
        },
        '(': {
            value: '(',
            precedence: 0,
            type: TokenFactory.prototype.OPERATOR,
            evaluator: () => {
                return this.value;
            }
        },
        ')': {
            value: ')',
            precedence: 0,
            type: TokenFactory.prototype.OPERATOR,
            evaluator: () => {
                return this.value;
            }
        },
        ',': {
            value: ',',
            precedence: 0,
            type: TokenFactory.prototype.OPERATOR,
            evaluator: () => {
                return this.value;
            }
        }
    };

    //Numbers
    this.tokenDefinitions[TokenFactory.prototype.NUMBER] = {};
    this.tokenDefinitions[TokenFactory.prototype.NUMBER][TokenFactory.prototype.NUMBER] = {
        value: null,
        precedence: 0,
        type: TokenFactory.prototype.NUMBER,
        evaluator: () => {
            return this.value;
        }
    };

    //Variables
    this.tokenDefinitions[TokenFactory.prototype.VARIABLE] = {};
    this.tokenDefinitions[TokenFactory.prototype.VARIABLE][TokenFactory.prototype.VARIABLE] = {
        value: null,
        precedence: 0,
        type: TokenFactory.prototype.VARIABLE,
        evaluator: () => {
            return this.value;
        }
    };

    //Functions
    this.tokenDefinitions[TokenFactory.prototype.FUNCTION] = {
        sin: {
            value: 'sin',
            precedence: 0,
            type: TokenFactory.prototype.FUNCTION,
            evaluator: (n) => {
                var n = parseFloat(n);
                if(isNaN(n)) { throw 'Incorrect argument types'; }
                return Math.sin(n);
            }
        },
        cos: {
            value: 'cos',
            precedence: 0,
            type: TokenFactory.prototype.FUNCTION,
            evaluator: (n) => {
                var n = parseFloat(n);
                if(isNaN(n)) { throw 'Incorrect argument types'; }
                return Math.cos(n);
            }
        },
        tan: {
            value: 'tan',
            precedence: 0,
            type: TokenFactory.prototype.FUNCTION,
            evaluator: (n) => {
                var n = parseFloat(n);
                if(isNaN(n)) { throw 'Incorrect argument types'; }
                return Math.tan(n);
            }
        }
    };

    //Constants
    this.tokenDefinitions[TokenFactory.prototype.CONSTANT] = {
        pi: {
            value: 'pi',
            precedence: 0,
            type: TokenFactory.prototype.FUNCTION,
            evaluator: () => {
                return Math.PI;
            }
        }
    };

    //Extend the definitions with any user supplied definitions
    this.tokenDefinitions = Object.assign(this.tokenDefinitions, definitions);

    this.tokenDefinitionMap = {};

    for(td in this.tokenDefinitions) {
        Object.assign(this.tokenDefinitionMap, this.tokenDefinitions[td]);
    }

    //Retrieve the token values for use in our regex
    var functions = Object.keys(this.tokenDefinitions[TokenFactory.prototype.FUNCTION]);
    var operators = Object.keys(this.tokenDefinitions[TokenFactory.prototype.OPERATOR]);
    var constants = Object.keys(this.tokenDefinitions[TokenFactory.prototype.CONSTANT]);
}

TokenFactory.prototype.OPERATOR = 'operator';
TokenFactory.prototype.VARIABLE = 'variable';
TokenFactory.prototype.NUMBER = 'number';
TokenFactory.prototype.FUNCTION = 'function';
TokenFactory.prototype.CONSTANT = 'constant';

TokenFactory.prototype.getFunctionValues = function() {
    return Object.keys(this.tokenDefinitions[TokenFactory.prototype.FUNCTION]);

}

TokenFactory.prototype.getConstantValues = function() {
    return Object.keys(this.tokenDefinitions[TokenFactory.prototype.CONSTANT]);
}

TokenFactory.prototype.getOperatorValues = function() {
    return Object.keys(this.tokenDefinitions[TokenFactory.prototype.OPERATOR]);
}

TokenFactory.prototype.createToken = function(value) {

    //Look up the token definition by value
    var definition = this.tokenDefinitionMap.hasOwnProperty(value) ? this.tokenDefinitionMap[value] : null;

    if(!definition) {
        var numeric = !isNaN(parseFloat(value));
        if(!numeric) {
            definition = this.tokenDefinitionMap[TokenFactory.prototype.VARIABLE];
        } else {
            definition = this.tokenDefinitionMap[TokenFactory.prototype.NUMBER];
        }
    }

    return this.container.new('Token', { value: value, definition: definition });

}

module.exports = TokenFactory;


text:
import EmberObject from "@ember/object";
import {
    UnwrapComputedPropertyGetter,
    UnwrapComputedPropertyGetters
} from "@ember/object/-private/types";

/**
 * `Ember.ObjectProxy` forwards all properties not defined by the proxy itself
 * to a proxied `content` object.
 */
export default class ObjectProxy<T extends object = object> extends EmberObject {
    /**
     * The object whose properties will be forwarded.
     */
    content: T | undefined;

    get<K extends keyof this>(key: K): UnwrapComputedPropertyGetter<this[K]>;
    get<K extends keyof T>(key: K): UnwrapComputedPropertyGetter<T[K]> | undefined;

    getProperties<K extends keyof this>(
        list: K[]
    ): Pick<UnwrapComputedPropertyGetters<this>, K>;
    getProperties<K extends keyof this>(
        ...list: K[]
    ): Pick<UnwrapComputedPropertyGetters<this>, K>;
    getProperties<K extends keyof T>(
        list: K[]
    ): Pick<Partial<UnwrapComputedPropertyGetters<T>>, K>;
    getProperties<K extends keyof T>(
        ...list: K[]
    ): Pick<Partial<UnwrapComputedPropertyGetters<T>>, K>;
}


text:
layout: kanji
v4: 2841
v6: 322
kanji: 冥
keyword: Hades
elements: hades, crown, sun, day, six
strokes: 10
image: E586A5
on-yomi: メイ、ミョウ
kun-yomi: くら.い
permalink: /rtk/冥/
prev: 冗
next: 軍
---

1) [mcfate] 2-11-2007(68): The beast of hades one day will wear a crown, and the number of the beast is 666.

2) [mantixen] 30-7-2009(45): In Hades you have to work six days a week before crowning it with something vaguely resembling a weekend. Oh wait, that's Japan.

3) [cb4960] 16-2-2009(21): In Hades, as punishment, souls are forced to wear crowns as hot as the sun for 666 days.

4) [Neobeo] 21-2-2009(7): If you can survive Hades for six days they give you a crown as a reward.

5) [Megaqwerty] 18-7-2007(7): It's dark in Hades, for the sun is covered by a crown. Oh, yeah, and the number six is just a wee bit popular down there.


text:
<mvc:View
	controllerName="sap.m.sample.PlanningCalendarViews.Page"
	xmlns:mvc="sap.ui.core.mvc"
	xmlns:unified="sap.ui.unified"
	xmlns:core="sap.ui.core"
	xmlns="sap.m">
	<VBox class="sapUiSmallMargin">
		<PlanningCalendar
			id="PC1"
			startDate="{path: '/startDate'}"
			viewKey="D"
			rows="{path: '/people'}"
			appointmentsVisualization="Filled"
			appointmentSelect="handleAppointmentSelect"
			intervalSelect="handleIntervalSelect"
			showEmptyIntervalHeaders="false"
			viewChange = "handleViewChange">
			<toolbarContent>
				<Title text="Title" titleStyle="H4"/>
				<Label id="label" text="Select a date from the interval to mark/unmark it as a non-working day."/>
				<Select id="select" tooltip="Group appointments mode" change="handleGroupModeChange">
					<core:Item key="Collapsed" text="Collapsed"/>
					<core:Item key="Expanded" text="Expanded"/>
				</Select>
			</toolbarContent>
			<views>
				<PlanningCalendarView
					key="A"
					intervalType="Hour"
					description="hours view"
					intervalsS="2"
					intervalsM="4"
					intervalsL="6"
					showSubIntervals="true">
				</PlanningCalendarView>
				<PlanningCalendarView
					key="D"
					intervalType="Day"
					description="days view"
					intervalsS="1"
					intervalsM="3"
					intervalsL="7"
					showSubIntervals="true">
				</PlanningCalendarView>
				<PlanningCalendarView
					key="M"
					intervalType="Month"
					description="months view"
					intervalsS="1"
					intervalsM="2"
					intervalsL="3"
					showSubIntervals="true">
				</PlanningCalendarView>
				<PlanningCalendarView
					key="nonWorking"
					intervalType="Day"
					description="days with non-working dates"
					intervalsS="1"
					intervalsM="5"
					intervalsL="9">
				</PlanningCalendarView>
			</views>
			<rows>
				<PlanningCalendarRow
					icon="{pic}"
					title="{name}"
					text="{role}"
					nonWorkingDays="{freeDays}"
					nonWorkingHours= "{freeHours}"
					appointments="{path : 'appointments', templateShareable: false}"
					intervalHeaders="{path: 'headers', templateShareable: false}">
					<appointments>
						<unified:CalendarAppointment
							startDate="{start}"
							endDate="{end}"
							icon="{pic}"
							title="{title}"
							text="{info}"
							type="{type}"
							tentative="{tentative}">
						</unified:CalendarAppointment>
					</appointments>
					<intervalHeaders>
						<unified:CalendarAppointment
							startDate="{start}"
							endDate="{end}"
							icon="{pic}"
							title="{title}"
							type="{type}">
						</unified:CalendarAppointment>
					</intervalHeaders>
				</PlanningCalendarRow>
			</rows>
		</PlanningCalendar>
		<Label text="Add available built-in views to the example:"/>
		<MultiComboBox
				selectionFinish="handleSelectionFinish"
				width="230px"
				placeholder="Choose built-in views">
			<core:Item key="Hour" text="Hour" />
			<core:Item key="Day" text="Day" />
			<core:Item key="Month" text="Month" />
			<core:Item key="Week" text="1 week" />
			<core:Item key="One Month" text="1 month" />
		</MultiComboBox>
		<Label text="Add or remove custom views:"/>
		<ToggleButton text="Toggle custom views" press="onPress" />
	</VBox>
</mvc:View>


text:
package com.example.administrator.imtest.core;

import android.util.Log;

import com.example.administrator.imtest.bean.Message;
import com.example.administrator.imtest.global.LocalConstant;
import com.example.administrator.imtest.listener.MessageReceiveListener;
import com.example.administrator.imtest.listener.RemoteServerStatusListenner;
import com.example.administrator.imtest.util.ConnectionRegisterException;
import com.example.administrator.imtest.util.ThreadManager;

import org.java_websocket.WebSocket;
import org.java_websocket.WebSocketImpl;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft_17;
import org.java_websocket.handshake.ServerHandshake;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;

/**
 * 类名称:
 * 类描述:
 * 创建人:quzongyang
 * 创建时间:2016/8/9. 15:36
 * 版本:
 */
public class WebSocketConnection {

    private WebSocketClient mClient; //消息连接通道
    private List<MessageReceiveListener> mMessageReceiveListeners = new ArrayList<>();
    private List<RemoteServerStatusListenner> mRemoteServerStatusListeners = new ArrayList<>();
    private static volatile WebSocketConnection mInstance;

    private WebSocketConnection() {

    }

    /***
     * 获取实例对象
     *
     * @return
     */
    public static WebSocketConnection getInstance() {
        if (mInstance == null) {
            synchronized (WebSocketConnection.class) {
                if (mInstance == null) {
                    mInstance = new WebSocketConnection();
                }
            }
        }
        return mInstance;
    }

    /**
     * 判断当前连接是否正常
     *
     * @return
     */
    public boolean socketIsConnected() {
        if (mClient != null) {
            if (mClient.getReadyState() == WebSocket.READYSTATE.OPEN) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    /***
     * 添加到消息监听
     *
     * @param _listener
     */
    public void addMessageReceiveListener(MessageReceiveListener _listener) {
        if (_listener != null && mMessageReceiveListeners != null && !mMessageReceiveListeners.contains(_listener))
            mMessageReceiveListeners.add(_listener);
    }

    /***
     * 移除消息监听
     *
     * @param _listener
     */
    public void removeMessageReceiveListenner(MessageReceiveListener _listener) {
        if (_listener != null && mMessageReceiveListeners != null) {
            mMessageReceiveListeners.remove(_listener);
        }
    }

    /***
     * 添加消息通道状态监听
     *
     * @param _listener
     */
    public void addRemoteServerStatusListener(RemoteServerStatusListenner _listener) {
        if (_listener != null && mRemoteServerStatusListeners != null && !mRemoteServerStatusListeners.contains(_listener))
            mRemoteServerStatusListeners.add(_listener);
    }

    /***
     * 移除消息通道状态监听
     *
     * @param _listener
     */
    public void removeRemoteServerStatusListener(RemoteServerStatusListenner _listener) {
        if (_listener != null && mRemoteServerStatusListeners != null) {
            mRemoteServerStatusListeners.remove(_listener);
        }
    }

    /**
     * 初始化连接通道
     **/
    private void init() {
        try {
            mClient = new WebSocketClient(new URI(LocalConstant.REMOTE_ADDRESS + ":" + LocalConstant.REMOTE_PORT), new Draft_17()) {
                @Override
                public void onOpen(final ServerHandshake handshakedata) {
                    ThreadManager.newInstance().executeShortTack(new Runnable() {
                        @Override
                        public void run() {
                            for (RemoteServerStatusListenner listener : mRemoteServerStatusListeners) {
                                if (listener != null) {
                                    listener.on0pen(handshakedata);
                                }
                            }
                        }
                    });
                }

                @Override
                public void onMessage(final String message) {
                    ThreadManager.newInstance().executeShortTack(new Runnable() {
                        @Override
                        public void run() {
                            for (MessageReceiveListener listener : mMessageReceiveListeners) {
                                if (listener != null) {
                                    listener.onMessageReceive(message);
                                }
                            }
                        }
                    });
                }

                @Override
                public void onClose(final int code, final String reason, final boolean remote) {
                    ThreadManager.newInstance().executeShortTack(new Runnable() {
                        @Override
                        public void run() {
                            for (RemoteServerStatusListenner listener : mRemoteServerStatusListeners) {
                                if (listener != null) {
                                    listener.onClose(code, reason, remote);
                                }
                            }
                        }
                    });
                }

                @Override
                public void onError(final Exception ex) {
                    ThreadManager.newInstance().executeShortTack(new Runnable() {
                        @Override
                        public void run() {
                            for (RemoteServerStatusListenner listener : mRemoteServerStatusListeners) {
                                if (listener != null) {
                                    listener.onError(ex);
                                }
                            }
                        }
                    });
                }
            };
            WebSocketImpl.DEBUG = true;
            System.setProperty("java.net.preferIPv6Addresses", "false");
            System.setProperty("java.net.preferIPv4Stack", "true");
        } catch (URISyntaxException _e) {
            _e.printStackTrace();
        }
    }

    /***
     * 连接夫妇器
     */
    private void open() throws IllegalStateException {
        if (mClient == null) {
            init();
        }
        WebSocket tempConnection = mClient.getConnection();
        /**判断通道是否已经打开,如果没有打开,再去连接**/
        if (tempConnection != null) {
            Log.i(WebSocketConnection.class.getSimpleName(), tempConnection.getReadyState() + "");
        }
        if (tempConnection.getReadyState() != WebSocket.READYSTATE.OPEN) {
            mClient.connect();
        }
    }

    /***
     * 注册服务
     */
    public void registerService() throws ConnectionRegisterException {
        try {
            open();
        } catch (IllegalStateException exception) {
            throw new ConnectionRegisterException("websocket通道连接异常");
        }
    }

    /****
     * 断开连接
     */
    public void close() throws Exception {
        if (mClient != null) {
            mClient.close();
            mClient = null;
        }
    }

    /***
     * 发送消息
     *
     * @param _message
     */
    public void sendMessage(final Message _message) {
        if (mClient != null) {
            ThreadManager.newInstance().executeShortTack(new Runnable() {
                @Override
                public void run() {
                    mClient.send(_message.toJson());
                }
            });
        }
    }
}


text:
var path = require('path');
var publicPath = path.resolve(__dirname, 'public');

var config = require('./config');

config.dev = {
    publicPath: publicPath,
    buildFolder: '/assets/'
};

module.exports = config;


text:
package com.jtbdevelopment.games.players;

import java.io.Serializable;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.springframework.stereotype.Component;

/**
 * Date: 11/26/14 Time: 8:51 PM
 */
@Component
public class PlayerMasker<ID extends Serializable, P extends AbstractPlayer<ID>> {

  private static final String MASKED_MD5 = "md5";
  private static final String DISPLAY_NAME = "displayName";

  public List<Map<String, String>> maskFriendsV2(final Set<P> friends) {
    List<Map<String, String>> maskedFriends = new LinkedList<>();
    friends.forEach(friend -> {
      Map<String, String> maskedFriend = new HashMap<>();
      maskedFriend.put(MASKED_MD5, friend.getMd5());
      maskedFriend.put(DISPLAY_NAME, friend.getDisplayName());
      maskedFriends.add(maskedFriend);
    });
    return maskedFriends;
  }
}


text:
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Vino.Core.TimedTask;
using Vino.Core.TimedTask.Common;

namespace Microsoft.Extensions.DependencyInjection
{
    public static class TimedTaskExtensions
    {
        public static IServiceCollection AddTimedTask(this IServiceCollection self)
        {
            self.TryAddSingleton<IAssemblyLocator, VinoAssemblyLocator>();
            return self.AddSingleton<ITimedTaskService, TimedTaskService>();
        }
    }
}

namespace Microsoft.AspNetCore.Builder
{
    public static class TimedTaskExtensions
    {
        public static IServiceProvider UseTimedTask(this IServiceProvider self)
        {
            self.GetRequiredService<ITimedTaskService>();
            return self;
        }
    }
}


text:
package org.gradle.api.internal.notations;

import org.gradle.api.Project;
import org.gradle.api.artifacts.Dependency;
import org.gradle.api.file.FileCollection;
import org.gradle.api.internal.ClassPathRegistry;
import org.gradle.api.internal.artifacts.DefaultProjectDependencyFactory;
import org.gradle.api.internal.artifacts.dependencies.DefaultExternalModuleDependency;
import org.gradle.api.internal.artifacts.dsl.dependencies.DependencyFactory;
import org.gradle.api.internal.file.FileLookup;
import org.gradle.api.internal.impldeps.GradleImplDepsProvider;
import org.gradle.internal.installation.CurrentGradleInstallation;
import org.gradle.internal.reflect.Instantiator;
import org.gradle.internal.typeconversion.NotationParser;
import org.gradle.internal.typeconversion.NotationParserBuilder;

public class DependencyNotationParser {
    public static NotationParser<Object, Dependency> parser(Instantiator instantiator, DefaultProjectDependencyFactory dependencyFactory, ClassPathRegistry classPathRegistry, FileLookup fileLookup, GradleImplDepsProvider gradleImplDepsProvider, CurrentGradleInstallation currentGradleInstallation) {
        return NotationParserBuilder
            .toType(Dependency.class)
            .fromCharSequence(new DependencyStringNotationConverter<DefaultExternalModuleDependency>(instantiator, DefaultExternalModuleDependency.class))
            .converter(new DependencyMapNotationConverter<DefaultExternalModuleDependency>(instantiator, DefaultExternalModuleDependency.class))
            .fromType(FileCollection.class, new DependencyFilesNotationConverter(instantiator))
            .fromType(Project.class, new DependencyProjectNotationConverter(dependencyFactory))
            .fromType(DependencyFactory.ClassPathNotation.class, new DependencyClassPathNotationConverter(instantiator, classPathRegistry, fileLookup.getFileResolver(), gradleImplDepsProvider, currentGradleInstallation))
            .invalidNotationMessage("Comprehensive documentation on dependency notations is available in DSL reference for DependencyHandler type.")
            .toComposite();
    }
}


text:
body {
    padding-top: 80px;
    padding-bottom: 20px;
}

/* Wrapping element */
/* Set some basic padding to keep content from hitting the edges */
.body-content {
    padding-left: 15px;
    padding-right: 15px;
}

/* Set widths on the form inputs since otherwise they're 100% wide */
input,
select,
textarea {
    max-width: 280px;
}

.k-datepicker {
  display: block !important;
}


text:
layout: doc
title: Documentation
---

[ << ]
[ >> ]
[Top]
[Contents]
[Index]
[ ? ]

B. Bugs and Enhancements

For an up-to-date description of bugs and other issues, please consult
the bugs file included in the distribution:
‘<tt>BUGS</tt>’.

If you discover a problem which isn’t mentioned in ‘<tt>BUGS</tt>’, please
use the search facility on our Trac tracking system at
http://proofgeneral.inf.ed.ac.uk/trac.  If you cannot find the
problem mentioned, please add a ticket, giving a careful description of
how to repeat your problem, and saying exactly which versions of all
Emacs and theorem prover you are using.

If you have some suggested enhancements to request or contribute, please
also use the tracking system at
http://proofgeneral.inf.ed.ac.uk/trac for this.

[ << ]
[ >> ]
[Top]
[Contents]
[Index]
[ ? ]

  This document was generated on September 30, 2022 using texi2html 1.82.