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

using GoogleCloudExtension.ManageAccounts;
using GoogleCloudExtension.TitleBar;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;

namespace GoogleCloudExtensionUnitTests.TitleBar
{
    [TestClass]
    public class TitleBarViewModelTests : ExtensionTestBase
    {
        private TitleBarViewModel _objectUnderTest;

        [TestInitialize]
        public void BeforeEach() => _objectUnderTest = new TitleBarViewModel();

        [TestMethod]
        public void TestGoToAccountManagementCommand_PromptsUser()
        {
            _objectUnderTest.OnGotoAccountManagementCommand.Execute(null);

            PackageMock.Verify(p => p.UserPromptService.PromptUser(It.IsAny<ManageAccountsWindowContent>()));
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.codehaus.httpcache4j;

import org.junit.Test;

import java.net.URI;
import java.util.Arrays;

import static org.junit.Assert.assertEquals;

/**
 * @author Erlend Hamnaberg
 * @version $Revision: $
 */
public class LinkDirectiveBuilderTest {
  @Test
  public void testLinkBuilderWithAllNormalFields() {
      LinkDirectiveBuilder builder = LinkDirectiveBuilder.create(URI.create("foo"));
      LinkDirective linkDirective = builder.title("title").anchor(URI.create("#hey")).rel("rel").rev("rev").build();
      assertEquals("title", linkDirective.getTitle());
      assertEquals(URI.create("#hey"), linkDirective.getAnchor());
      assertEquals("rel", linkDirective.getRel());
      assertEquals("rev", linkDirective.getRev());
      assertEquals(4, linkDirective.getParameters().size());
      String expected = "<foo>; title=\"title\"; anchor=\"#hey\"; rel=\"rel\"; rev=\"rev\"";
      assertEquals(expected, linkDirective.toString());
      assertEquals(new Header("Link", new Directives(Arrays.<Directive>asList(linkDirective))), new Header("Link", expected));
  }
}


text:
package io.prediction.examples.java.recommendations.tutorial2;

import io.prediction.examples.java.recommendations.tutorial1.TrainingData;
import io.prediction.examples.java.recommendations.tutorial1.Query;
import io.prediction.examples.java.recommendations.tutorial1.DataSource;
import io.prediction.examples.java.recommendations.tutorial1.DataSourceParams;

import io.prediction.controller.java.EmptyParams;
import io.prediction.controller.java.IJavaEngineFactory;
import io.prediction.controller.java.JavaSimpleEngine;
import io.prediction.controller.java.JavaSimpleEngineBuilder;
import io.prediction.controller.java.JavaEngineParams;
import io.prediction.controller.java.JavaEngineParamsBuilder;
import io.prediction.controller.java.JavaWorkflow;
import io.prediction.controller.java.WorkflowParamsBuilder;
import java.util.HashMap;

public class Runner1 {

  // During development, one can build a semi-engine, only add the first few layers. In this
  // particular example, we only add until dataSource layer
  private static class HalfBakedEngineFactory implements IJavaEngineFactory {
    public JavaSimpleEngine<TrainingData, Object, Query, Float, Object> apply() {
      return new JavaSimpleEngineBuilder<
        TrainingData, Object, Query, Float, Object> ()
        .dataSourceClass(DataSource.class)
        .build();
    }
  }

  public static void runComponents(String filePath) {
    JavaEngineParams engineParams = new JavaEngineParamsBuilder()
      .dataSourceParams(new DataSourceParams(filePath))
      .build();

    JavaWorkflow.runEngine(
      (new HalfBakedEngineFactory()).apply(),
      engineParams,
      null,
      new EmptyParams(),
      new WorkflowParamsBuilder().batch("MyEngine").verbose(3).build()
    );
  }

  public static void main(String[] args) {
    if (args.length == 0) {
      System.out.println("Error: Please specify the file path as argument");
      System.exit(1);
    }
    runComponents(args[0]);
    System.exit(0); // clean shutdown is needed for spark
  }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Uses of Class org.drip.math.autodiff.DerivativeControl</title>
<meta name="date" content="2013-02-01">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
org.drip.math.autodiff.DerivativeControl

Packages that use DerivativeControl

Package
Description

org.drip.math.autodiff

Uses of DerivativeControl in org.drip.math.autodiff

Constructors in org.drip.math.autodiff with parameters of type DerivativeControl

Constructor and Description

ObjectiveFunction(DerivativeControl dc)

Objective Function constructor

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
<?php
/**
 * Created by Kutuzov Alexey Konstantinovich <lexus.1995@mail.ru>.
 * Author: Kutuzov Alexey Konstantinovich <lexus.1995@mail.ru>
 * Project: jungle
 * IDE: PhpStorm
 * Date: 20.05.2016
 * Time: 19:00
 */
namespace Jungle\Util\Data\Schema\OuterInteraction {

	use Jungle\Util\Data\Record\PropertyRegistryInterface;
	use Jungle\Util\Data\Schema\OuterInteraction\ValueAccessor\Getter;
	use Jungle\Util\Data\Schema\OuterInteraction\ValueAccessor\GetterInterface;
	use Jungle\Util\Data\Schema\OuterInteraction\ValueAccessor\Setter;
	use Jungle\Util\Data\Schema\OuterInteraction\ValueAccessor\SetterInterface;

	/**
	 * Class ValueAccessor
	 * @package Jungle\Util\Data\Schema\OuterInteraction
	 */
	class ValueAccessor{

		/** @var  ValueAccessor */
		protected static $singletone;

		/** @var bool  */
		protected static $singletone_already_used = false;

		/** @var  mixed */
		protected $data;

		/** @var  ValueAccessAwareInterface */
		protected $accessor;

		/**
		 * @return ValueAccessor
		 */
		public static function useSingletone(){
			if(self::$singletone_already_used){
				throw new \LogicException('Instance already in use!');
			}
			if(!self::$singletone){
				self::$singletone = new ValueAccessor();
			}
			return self::$singletone;
		}

		/**
		 *
		 */
		public static function idleSingletone(){
			self::$singletone_already_used = false;
		}

		/**
		 * @param ValueAccessAwareInterface $accessor
		 * @return $this
		 */
		public function setAccessor(ValueAccessAwareInterface $accessor){
			$this->accessor = $accessor;
			return $this;
		}

		/**
		 * @return ValueAccessAwareInterface
		 */
		public function getAccessor(){
			return $this->accessor;
		}

		/**
		 * @param $data
		 * @return $this
		 */
		public function setData($data){
			$this->data = $data;
			return $this;
		}

		/**
		 * @return mixed
		 */
		public function getData(){
			return $this->data;
		}

		/**
		 * @param $name
		 * @return mixed
		 */
		public function __get($name){
			return $this->accessor->valueAccessGet($this->data, $name);
		}

		/**
		 * @param $name
		 * @param $value
		 * @return mixed
		 */
		public function __set($name,$value){
			$this->data = $this->accessor->valueAccessSet($this->data, $name,$value);
		}

		/**
		 * @param $name
		 * @return bool
		 */
		public function __isset($name){
			return $this->accessor->valueAccessExists($name);
		}

		/**
		 * @return SetterInterface
		 */
		public static function getDefaultSetter(){
			static $setter;
			if(!$setter){
				$setter = new Setter();
			}
			return $setter;
		}

		/**
		 * @return GetterInterface
		 */
		public static function getDefaultGetter(){
			static $getter;
			if(!$getter){
				$getter = new Getter();
			}
			return $getter;
		}

		/**
		 * @param $getter
		 * @return mixed
		 */
		public static function checkoutGetter($getter){
			$array = is_array($getter);
			if($getter instanceof GetterInterface || $getter instanceof \Closure || $array){
				if($array){
					/** @var array $getter */
					$getter = array_replace([
						'prefix' => null,
						'method' => null,
						'arguments' => []
					],$getter);
					if(!$getter['prefix'] && !$getter['method']){
						throw new \LogicException('Error object access getter');
					}
				}
				return $getter;
			}

			throw new \LogicException('Error invalid access getter');

		}

		/**
		 * @param $setter
		 * @return mixed
		 */
		public static function checkoutSetter($setter){
			$array = is_array($setter);
			if($setter instanceof SetterInterface || $setter instanceof \Closure || $array){
				if($array){
					/** @var array $setter */
					$setter = array_replace([
						'prefix'                    => null,
						'method'                    => null,
						'arguments'                 => [],
						'arguments_value_capture'   => null
					],$setter);
					if(!$setter['prefix'] && !$setter['method']){
						throw new \LogicException('Error object access getter');
					}
				}
				return $setter;
			}
			throw new \LogicException('Error invalid access setter');
		}

		/**
		 * @param $getter
		 * @param $data
		 * @param $key
		 * @param array $argumentsAhead
		 * @return mixed|null
		 */
		public static function handleGetter($getter, $data, $key, array $argumentsAhead = []){
			if(is_callable($getter)){
				$arguments = [$data, $key];
				if($argumentsAhead){
					$arguments = array_merge($arguments, $argumentsAhead);
				}
				return call_user_func_array($getter, $arguments);
			}elseif(is_array($getter)){
				$getter = array_replace([
					'prefix' => null,
					'method' => null,
					'arguments' => []
				],$getter);
				$methodName = null;
				if($getter['prefix']){
					$methodName =  $getter['prefix'] . ucfirst($key);
				}elseif($getter['method']){
					$methodName = $getter['method'];
				}
				$arguments = [];
				if($getter['arguments']){
					$arguments = $getter['arguments'];
				}
				if($methodName){
					return call_user_func_array([$data, $methodName], (array)$arguments);
				}else{
					throw new \LogicException('Object value access failure!');
				}
			}else{
				return null;
			}
		}

		public static function handleSetter($setter, $data, $key, $value,array $argumentsAhead = []){
			if(is_callable($setter)){
				$arguments =[$data, $key, $value];
				if($argumentsAhead){
					$arguments = array_merge($arguments, $argumentsAhead);
				}
				return call_user_func_array($setter, $arguments);
			}elseif(is_array($setter)){
				$setter = array_replace([
					'prefix'                    => null,
					'method'                    => null,
					'arguments'                 => [],
					'arguments_value_capture'   => null
				],$setter);

				$methodName = null;
				if($setter['prefix']){
					$methodName =  $setter['prefix'] . ucfirst($key);

				}elseif($setter['method']){
					$methodName = $setter['method'];
				}
				if($setter['arguments']){
					$arguments = $setter['arguments'];
					$valueCapture = $setter['arguments_value_capture'];

					if(is_string($valueCapture)){
						switch($valueCapture){
							case 'append':
								$arguments[] = $value;
								break;
							case 'prepend':
								array_unshift($arguments, $value);
								break;
						}
					}elseif(is_array($valueCapture)){
						if(!isset($valueCapture['type'])){
							throw new \LogicException('Value capture error array definition: invalid type parameter');
						}
						if(!isset($valueCapture['offset'])){
							throw new \LogicException('Value capture error array definition: invalid offset parameter');
						}
						$offset = $valueCapture['offset'];
						if($offset < 0 || $offset > count($arguments)){
							throw new \LogicException('Value capture error array definition: invalid offset parameter not range');
						}
						switch($valueCapture['type']){
							case 'insert':
								array_splice($arguments, $valueCapture['offset'], 0, [$value]);
								break;
							case 'replace':
								array_splice($arguments, $valueCapture['offset'], 1, [$value]);
								break;
						}
					}else{

					}
				}else{
					$arguments = [$value];
				}

				if($methodName){
					call_user_func_array([$data, $methodName], (array)$arguments);
					return $data;
				}else{
					throw new \LogicException('Object value access failure!');
				}
			}else{
				throw new \LogicException();
			}
		}

		/**
		 * @param ValueAccessAwareInterface|callable|null $access
		 * @param \Jungle\Util\Data\Record\PropertyRegistryInterface|mixed $data
		 * @param string $key
		 * @return mixed
		 */
		public static function handleAccessGet($access, $data, $key){
			if($data instanceof PropertyRegistryInterface){
				$value = $data->getProperty($key);
			}elseif($access instanceof ValueAccessAwareInterface){
				$value = $access->valueAccessGet($data,$key);
			}elseif(is_array($access) || is_callable($access)){
				$value = self::handleGetter($access, $data, $key);
			}else{
				throw new \LogicException();
			}
			return $value;
		}

		/**
		 * @param ValueAccessAwareInterface|callable|null $access
		 * @param \Jungle\Util\Data\Record\PropertyRegistryInterface|mixed $data
		 * @param string $key
		 * @param mixed $value
		 * @return \Jungle\Util\Data\Record\PropertyRegistryInterface|mixed
		 */
		public static function handleAccessSet($access, $data, $key, $value){
			if($data instanceof PropertyRegistryInterface){
				$data->setProperty($key, $value);
			}elseif($access instanceof ValueAccessAwareInterface){
				$data = $access->valueAccessSet($data,$key, $value);
			}elseif(is_array($access) || is_callable($access)){
				$data = self::handleSetter($access, $data, $key, $value);
			}else{
				throw new \LogicException();
			}
			return $data;
		}

	}
}


text:
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/select.h>

#include <fcntl.h>
#include <errno.h>
#include <unistd.h>
#include <stdio.h>

#include "HuboRT/LogRelay.hpp"
#include "HuboRT/utils.hpp"
#include "HuboRT/Manager.hpp"

namespace HuboRT {

LogRelay::LogRelay()
{
    _initialize();
}

void LogRelay::_initialize()
{
    _channels_opened = false;
    _log_directory = hubo_rt_default_log_dir;
    open_channels();
}

bool LogRelay::open_channels()
{
    if(_channels_opened)
        return true;

    _channels_opened = true;
    ach_status_t result = ach_open(&_log_chan, HUBO_RT_LOG_RELAY_CHAN, NULL);
    if( ACH_OK != result )
    {
        std::cout << "Error opening log relay channel: "
                  << ach_result_to_string(result) << std::endl;
        _channels_opened = false;
    }

    return _channels_opened;
}

bool LogRelay::receive(std::string& log_name, std::string& contents, int timeout)
{
    if(!_channels_opened)
    {
        std::cerr << "[LogRelay::receive] Attempting to receive log data before Ach channels are opened!"
                  << std::endl;
        return false;
    }

    bool new_message = false;

    struct timespec t;
    clock_gettime(ACH_DEFAULT_CLOCK, &t);
    t.tv_sec += timeout;

    size_t fs;
    ach_status_t r = ach_get(&_log_chan, &_buffer, sizeof(_buffer), &fs, &t, ACH_O_WAIT);
    if( ACH_OK == r || ACH_MISSED_FRAME == r )
    {
        new_message = true;
        log_name = std::string(_buffer.log_name);
        if(_buffer.content_size > LOG_MESSAGE_CONTENT_SIZE)
        {
            std::cout << "LogRelay received invalid message size: "
                      << _buffer.content_size << ". Cannot exceed "
                      << LOG_MESSAGE_CONTENT_SIZE << std::endl;
            return false;
        }

        strncpy(_transition, _buffer.contents, _buffer.content_size);
        _transition[_buffer.content_size] = '\0';
        contents = std::string(_transition);
    }

    return new_message;
}

bool LogRelay::send(double timeout)
{
    if(!_channels_opened)
    {
        std::cerr << "[LogRelay::send] Attempting to send log data before Ach channels are opened!"
                  << std::endl;
        return false;
    }

    _check_for_new_logs();
    _check_for_log_reset();

//    fd_set set;
//    FD_ZERO(&set);
//    int nfds = 0;
//    for(size_t i=0; i<_handles.size(); ++i)
//    {
//        int fd = _handles[i].fd;
//        FD_SET(fd, &set);
//        if(fd > nfds)
//            nfds = fd;
//    }
//    ++nfds;

//    struct timespec t;
//    memset(&t, 0, sizeof(t));
//    t.tv_sec += timeout;

//    int err = pselect(nfds, &set, NULL, NULL, &t, NULL);
//    if(err==-1)
//    {
//        std::cout << "Error while trying to read logs ("
//                  << strerror(err) << ")" << std::endl;
//        return false;
//    }

    for(size_t i=0; i<_handles.size(); ++i)
    {
//        if(FD_ISSET(_handles[i].fd, &set)!=0)
//        {
            _read_through_fd(_handles[i]);
//        }
    }

    usleep((int)(timeout*1e6));

    return true;
}

void LogRelay::_read_through_fd(FileHandle& fh)
{
    strcpy(_buffer.log_name, fh.filename.c_str());

    ssize_t s = LOG_MESSAGE_CONTENT_SIZE;
    while( s == LOG_MESSAGE_CONTENT_SIZE )
    {
        s = read(fh.fd, _buffer.contents, LOG_MESSAGE_CONTENT_SIZE);
        if( s < 0 && errno != EINTR )
        {
            std::cout << "[LogRelay::_read_through_fd] Error in attempting to read log of '"
                      << fh.filename << "': " << strerror(errno) << std::endl;
            break;
        }
        else if( s == 0 )
            break;

        fh.read_so_far += s;
        _buffer.content_size = s;
        ach_put(&_log_chan, &_buffer, sizeof(_buffer));
    }
}

void LogRelay::_check_for_new_logs()
{
    StringArray root_logs = grab_files_in_dir(_log_directory);
    for(size_t i=0; i<root_logs.size(); ++i)
    {
        _add_file_descriptor(_log_directory, root_logs[i]);
    }

    StringArray log_dirs = grab_dirs_in_dir(_log_directory);

    StringArray logs;
    for(size_t i=0; i<log_dirs.size(); ++i)
    {
        logs = grab_files_in_dir(_log_directory+"/"+log_dirs[i]);
        for(size_t j=0; j<logs.size(); ++j)
        {
            _add_file_descriptor(_log_directory, log_dirs[i]+"/"+logs[j]);
        }
    }
}

void LogRelay::_check_for_log_reset()
{
//    struct stat stats;
    char stamp_test[LOG_STAMP_SIZE];
    for(size_t i=0; i<_handles.size(); ++i)
    {
        FileHandle& handle = _handles[i];

        // Get the header and check that it's the correct size
        lseek(handle.fd, 0, SEEK_SET);
        ssize_t bytes_read = read(handle.fd, stamp_test, LOG_STAMP_SIZE);
        if( bytes_read != LOG_STAMP_SIZE )
        {
            if(!handle.header_errored)
            {
                std::cerr << "Error checking the stamp of log '" << handle.filename
                          << "'. Bytes read was " << bytes_read << " when it should be "
                          << LOG_STAMP_SIZE;
                if( bytes_read < 0 )
                {
                    std::cerr << ". Error: " << strerror(errno);
                }
                std::cerr << std::endl;
                handle.header_errored = true;
            }
            continue;
        }

        handle.header_errored = false;

        if( strncmp(stamp_test, handle.last_stamp, LOG_STAMP_SIZE) != 0 )
        {
            // If the header has changed, start over from the beginning of the file
            strncpy(handle.last_stamp, stamp_test, LOG_STAMP_SIZE);

            strcpy(_buffer.log_name, handle.filename.c_str());
            strcpy(_buffer.contents, "\n .::. ===== LOG RESTARTED ===== .::. \n");
            _buffer.content_size = strlen(_buffer.contents);
            ach_put(&_log_chan, &_buffer, sizeof(_buffer));

            lseek(handle.fd, 0, SEEK_SET);
            handle.read_so_far = 0;
        }
        else
        {
            // If the header is unchanged, continue reading where we left off
            lseek(handle.fd, handle.read_so_far, SEEK_SET);
        }
    }
}

void LogRelay::_add_file_descriptor(const std::string& directory, const std::string &log_name)
{
    std::string path = directory+"/"+log_name;
    std::map<std::string,size_t>::iterator check = _fd_tracker.find(path);
    if(check == _fd_tracker.end())
    {
        int new_fd = open(path.c_str(), O_RDONLY);
        if(new_fd >= 0)
        {
            FileHandle fh;
            fh.fd = new_fd;
            fh.filename = log_name;
            _handles.push_back(fh);
            _fd_tracker[path] = _handles.size()-1;
        }
        else
        {
            std::cerr << "[LogRelay::_add_file_descriptor] Error while trying to open log file '"
                      << path << "' (" << strerror(errno) << ") " << errno << std::endl;
        }
    }
}

size_t LogRelay::fd_count() const
{
    return _handles.size();
}

} // namespace HuboRT


text:
layout: post

title: "Meet the Electron: a cellular dev kit with a simple data plan"
cover_image: blog-cover.jpg

excerpt: Announcing Spark's latest solution - this time for cellular products.

author:
  name: Zach Supalla
  twitter: zsupalla
  bio: CEO
  image: zach.jpg
---

Dearest Spark Friends,

Today is a very exciting day! We're proud to announce the newest addition to the Spark family — the Electron, our cellular development kit that we hope will open up the Internet of Things to a whole new category of connected products. Best of all, we're going back to our roots and launching the Electron on Kickstarter, the same crowdfunding platform where we first met so many of you way back in May of 2013.  Visit our Kickstarter campaign to pre-order an Electron and be one of the first to own this amazing addition to the Spark lineup.

The Electron works a lot like our other development kits, the Spark Core and Photon, except it connects to the Internet using a 2G or 3G cellular connection instead of Wi-Fi. This means it works anywhere your phone does, and can go wherever you need it to — your backyard, your bicycle, or your banana grove.

## Back to Kickstarter

Throughout the past two years, we've grown our team from 4 to 24, raised venture capital, and shipped tens of thousands of Spark Cores to engineers, designers, and product creators all over the world. We're grown up a bunch since our tender years, which begs the question —why Kickstarter?

The reason we're so excited about the Electron is that we think the world of builders and creators really needs it. The cellular version of the Internet of Things (often called "Machine to Machine" or "M2M") has quite a few barriers, and it's not set up for the little guys (or even the medium-sized guys). For most companies outside of Tier 1 handset and automative manufacturers, building a cellular-connected product is nearly impossible due to opaque pricing, drawn out negotiations, high volume expectations, and complicated certifications.

We're back on Kickstarter to change all that. Our hope is that by rallying support around a development experience that is affordable, easy to use, and open, we can disrupt the cellular industry and open up the floodgates to a new generation of incredible connected products. The best way to disrupt an industry is to raise a rumpus, and we think that Kickstarter is the perfect venue to do just that.

The campaign is now live, and we'd love if you helped us spread the word by sharing with your friends and family!

## Forward looking, backwards compatible

We're also happy to announce that the Electron provides a whole new way to connect to the world while maintaining compatibility with the accessories, software, and development tools you're already familiar with.

With the introduction of Spark OS, the Photon, and now the Electron, Spark has become much more than the development kit we launched in 2013. We've got our sights set on changing the way people and things everywhere connect with one another, which is only possible with the help, enthusiasm, and support of you all.

Bottom line: we love you guys, and we're proud and excited to take this leap into unexplored territory together.

If you have feedback, please send it to our way — we'd love to hear from you :-)

High fives all around.

Cheers and Spark love,

Zach and the Spark team


text:
using Csla.Core;
using Csla.Rules;
using Csla.Rules.CommonRules;
using Rolodex.Business.BusinessClasses;

namespace Rolodex.Business.Rules
{
  public class IsDuplicateNameAsync : CommonBusinessRule
  {
    private IPropertyInfo SecondaryProperty { get; set; }

    public IsDuplicateNameAsync(IPropertyInfo primaryProperty, IPropertyInfo secondaryProperty)
      : base(primaryProperty)
    {
      SecondaryProperty = secondaryProperty;

      InputProperties.Add(primaryProperty);
      InputProperties.Add(secondaryProperty);

      IsAsync = true;

      // setting all to false will only allow the rule to run when the property is set - typically by the user from the UI.
      CanRunAsAffectedProperty = false;
      CanRunInCheckRules = false;
      CanRunOnServer = false;
    }

    protected override void Execute(IRuleContext context)
    {
      var value1 = (int) context.InputPropertyValues[PrimaryProperty];
      var value2 = (string) context.InputPropertyValues[SecondaryProperty];

      // uses the async methods in DataPortal to perform data access on a background thread.
      DuplicateCompanyCommand.BeginExecute(value1, value2, (o, e) =>
      {
        if (e.Error != null)
        {
          context.AddErrorResult(string.Format("Error checking for duplicate company name.  {0}", e.Error));
        }
        else if (e.Object.IsDuplicate)
        {
          context.AddErrorResult("Duplicate company name.");
        }

        context.Complete();
      });
    }
  }
}


text:
"""
Copyright (c) 2004-Present Pivotal Software, Inc.

This program and the accompanying materials are made available under
the terms of the under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""

import mpp.gpdb.tests.storage.walrepl.run.promote

class pg_ctl(mpp.gpdb.tests.storage.walrepl.run.promote.PromoteTestCase):
    promote_using_pg_ctl = True


text:
from balancer import controller
from behaviorTree import behaviorTree as btree
from logs import sonarlog
from twisted.internet import defer, reactor
import behaviors
import hosts
import configuration
import conf_domains

######################
# CONFIGURATION     ##
######################
START_BT = True
######################

# Force production mode
configuration.force_production_mode()

# Setup logging
logger = sonarlog.getLogger('start_benchmark')

# Strategy instance
controller = controller.Controller()

def errback(failure):
    print 'Error while executing'
    print failure
    import sys
    sys.exit(1)

def finished(status):
    print 'Behavior reached end'
    if status == False:
        import sys
        sys.exit(1)

def main():
    logger.log(sonarlog.SYNC, 'starting BTree')

    # Blackboard with hosts manager
    bb = btree.BlackBoard()
    bb.hosts = hosts.RelayHosts()

    # Use the domain setup type configuration in the domains module to fill hosts
    for entry in conf_domains.initial_domains_setup_types:
        bb.hosts.add_host(*entry)

    # Add load drivers to hosts
    bb.hosts.add_host('load0', 'load')
    bb.hosts.add_host('load1', 'load')

    # Start benchmark ###################################
    start = btree.Sequence(bb)

    # Log sync marker
    start.add(behaviors.SyncMarker('start of startup sequence'))

    # Stop everything
    start.add(behaviors.ShutdownAllDomains())

    # Add bheaviors to start and initialize the domains
    start.add(behaviors.AllocateDomains(controller))

    # Connect with all relay services
    start.add(behaviors.ConnectRelay())

    # Configure glassfish
    start.add(behaviors.ConfigureGlassfish())

    # Start Glassfish and Database
    pl = btree.ParallelNode(bb)
    pl.add(behaviors.StartGlassfish())
    pl.add(behaviors.StartDatabase())
    start.add(pl)

    # Start Rain and connect with its control service
    start.add(behaviors.StartRain())
    start.add(behaviors.ConnectRain())

    # Start controller
    start.add(behaviors.StartController(controller))

    # Trigger load generation in Rain
    start.add(behaviors.TriggerRain())

    # Stop benchmark ####################################
    stop = btree.Sequence(bb)
    stop.add(behaviors.ConnectRelay())
    stop.add(behaviors.StopGlassfishRain())

    # Execute Behavior Trees ############################
    if START_BT:
        print 'Running start BTree'
        defer = start.execute()
    else:
        print 'Running stop BTree'
        defer = stop.execute()

    # Finished callback to clean up
    defer.addCallback(finished)

    # Start the Twisted reactor
    reactor.run()

if __name__ == '__main__':
    # Connect with Sonar logging
    sonarlog.connect()

    # Run main method
    main()


text:
BASE="/home/lijunsong/github/LambdaS5/tests/"
export PATH="/local/bin:/home/lijunsong/.opam/4.02.0/bin/:$PATH"

get_usage () {
echo "to use this script, create a directory and put two files in it.
  1. config.txt, which has one line that specifies s5 optimization arguments;
  2. jslists.txt, which contains test262 js absolute file path.

  run qsub -t 1-100 cloud-test262.sh"

exit 1
}
get_filepath_list () {
    base=`pwd`
    jsfiles=`find $BASE/test262/test262/test/suite/ch* -name '*.js'`
    echo "$jsfiles"
}

get_filepath () {
    # the $1 is the index, $2 is the file
    cat $2 | sed -n "$1 p"
}

################# functions above ###############

# config file: the file MUST contain one line, which
# specifies s5 arguments for optimization phases
configfilename=config.txt
listname=jslists.txt

config_dir=`pwd`
output_dir=$config_dir

configpath=$config_dir/$configfilename
listpath=$config_dir/$listname

[ ! -f $configfilename ] && echo "$configfilename is not found" && get_usage
[ ! -f $listname ] && echo "$listpath is not found" && get_usage

# todo: wen running on grid, will anything significant var be defined?
fileindex=$SGE_TASK_ID
if [ -z $SGE_TASK_ID ]; then
    echo "debug mode"

    if [ -z $1 ]; then
        # if no argument is passed in
        fileindex=879
    elif echo $1 | egrep -q '^[0-9]+$'; then
        # if argument is passed in and the argument is a number
        fileindex=$1
    else
        # if argument is passed in and the argument is a string, fetch the line number
        fileindex=`grep -n $1 $listpath | cut -d':' -f1`
    fi
fi
filepath=`get_filepath $fileindex $listpath`

[ -z $filepath ] && echo "$filepath is empty" && exit 2

# get optimization command from file
optargs=`cat $configpath | head -n 1`
[ -z "$optargs" ] && echo "opt args is empty" && exit 3

################## start running test ##################

# working directory is in tests/
cd $BASE
filename=$(basename $filepath)
#  NOTE: filename should contains .js. S8.4-A1
#  will test A1, A10, A11, A1*
chapter=`echo $filepath | grep -o 'ch[0-9][0-9]'`
[ -z $chapter ] && echo "chapter is empty" && exit 4
# start testing the strict mode

nonstrictdir=$output_dir/$chapter-nonstrict
mkdir -p $nonstrictdir
python test262/test262/tools/packaging/test262.py \
  --non_strict_only \
  --tests test262/test262/ \
  --command "optimization/test-js.sh {{path}} $nonstrictdir $optargs" \
  $filename > $nonstrictdir/$filename.nonstrict.result

# start testing the non-strict mode
strictdir=$output_dir/$chapter-strict
mkdir -p $strictdir
python test262/test262/tools/packaging/test262.py \
  --strict_only \
  --tests test262/test262/ \
  --command "optimization/test-js.sh {{path}} $strictdir $optargs" \
  $filename > $strictdir/$filename.strict.result

exit 0


text:
/*
 * $Id$
 */

/*

Copyright (c) 2000-2005 Board of Trustees of Leland Stanford Jr. University,
all rights reserved.

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
STANFORD UNIVERSITY 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.

Except as contained in this notice, the name of Stanford University shall not
be used in advertising or otherwise to promote the sale, use or other dealings
in this Software without prior written authorization from Stanford University.

*/

package org.lockss.daemon;

import java.util.*;

import org.lockss.app.LockssDaemon;
import org.lockss.config.*;
import org.lockss.util.*;

/** LockssThread abstracts out common features of LOCKSS daemon threads,
 * notably watchdog timers.  The methods in this class should be called
 * only from the thread.  New code should probably use LockssRunnable
 * instead.
 */
public abstract class LockssThread extends Thread implements LockssWatchdog {
  static final String PREFIX = Configuration.PREFIX + "thread.";

  /** If true, a thread that exits due to an otherwise unhandled
   * OutOfMemoryError will cause the daemon to exit.  If {@link
   * #triggerWDogOnExit(boolean true)} has been called then {@link
   * #threadExited()} will be called instead (which may cause daemon
   * exit). */
  static final String PARAM_EXIT_DAEMON_ON_OOME = PREFIX + "exitDaemonOnOome";
  static final boolean DEFAULT_EXIT_DAEMON_ON_OOME = false;

  static final String PARAM_THREAD_WDOG_HUNG_DUMP = PREFIX + "hungThreadDump";
  static final boolean DEFAULT_THREAD_WDOG_HUNG_DUMP = false;

  public static final String PARAM_NAMED_WDOG_INTERVAL =
    PREFIX + "<name>.watchdog.interval";

  public static final String PARAM_NAMED_THREAD_PRIORITY =
    PREFIX + "<name>.priority";

  private static Logger log = Logger.getLogger("LockssThread");

  private OneShotSemaphore runningSem = new OneShotSemaphore();
  private OneShotSemaphore exitedSem = new OneShotSemaphore();
  private Map wdogParamNameMap = new HashMap();
  private Map prioParamNameMap = new HashMap();
  private volatile boolean triggerOnExit = false;
  private volatile long interval = 0;
  private TimerQueue.Request timerReq;
  private Deadline timerDead;
  private TimerQueue.Callback timerCallback =
    new TimerQueue.Callback() {
      public void timerExpired(Object cookie) {
	threadHung();
      }
      public String toString() {
	return "Thread Watchdog: " + getName();
      }
    };

  protected LockssThread(String name) {
    super(name);
  }

  /** Declare that the thread is running and initialized. */
  protected void nowRunning() {
    runningSem.fill();
  }

  /** Declare that the thread is just about to exit. */
  private void nowExited() {
    exitedSem.fill();
  }

  /** Wait until the thread is running and initialized.  Useful to ensure
   * the thread has finished its initialization before it is asked to do
   * anything.  If used in the method that starts the thread, prevents test
   * code from finishing before the thread starts, which can cause
   * watchdogs to trigger spuriously.
   * @param timeout Deadline that limits how long to wait for the thread to
   * start running.
   * @return true iff the thread has said it's running, false if timeout or
   * interrupted.
   */
  public boolean waitRunning(Deadline timeout) {
    try {
      return runningSem.waitFull(timeout);
    } catch (InterruptedException e) {
    }
    return runningSem.isFull();
  }

  /** Wait until the thread is running and initialized.  Useful to ensure
   * the thread has finished its initialization before it is asked to do
   * anything.  If used in the method that starts the thread, prevents test
   * code from finishing before the thread starts, which can cause
   * watchdogs to trigger spuriously.
   * @return true iff the thread has said it's running, false if timeout or
   * interrupted.
   */
  public boolean waitRunning() {
    return waitRunning(Deadline.MAX);
  }

  /** Wait until the thread has exited (more precisely, until just before
   * it exits).  Useful to wait for socket activity, etc. to terminate
   * before proceding.  It's likely a bad idea to call this from a block
   * that's synchronized with code that runs in the thread.
   * @param timeout Deadline that limits how long to wait for the thread to
   * exit.
   * @return true iff the thread has exited, false if timeout or
   * interrupted.
   */
  public boolean waitExited(Deadline timeout) {
    if (isInterrupted()) return false;
    try {
      if (log.isDebug3()) log.debug3("Waiting for " + getName() + " to exit");
      return exitedSem.waitFull(timeout);
    } catch (InterruptedException e) {
      interrupt();			// maintain interrupted status
    }
    return exitedSem.isFull();
  }

  /** Wait until the thread has exited (more precisely, until just before
   * it exits).  Useful to wait for socket activity, etc. to terminate
   * before proceding.  It's likely a bad idea to call this from a block
   * that's synchronized with code that runs in the thread.
   * @return true iff the thread has exited, false if timeout or
   * interrupted.
   */
  public boolean waitExited() {
    return waitExited(Deadline.MAX);
  }

  /** Set the priority of the thread from a parameter value
   * @param name Used to derive a configuration parameter name
   * (org.lockss.thread.name.priority) whose value is the priority
   * @param defaultPriority the default priority if the config param has no
   * value.  If this is -1 and the config param has no value, the priority
   * will not be changed.
   */
  public void setPriority(String name, int defaultPriority) {
    int prio = getPriorityFromParam(name, defaultPriority);
    if (prio == -1) {
      log.debug3("Leaving priority of " + getName() +
		 " thread at " + getPriority());
      return;
    }
    log.debug2("Setting priority of " + getName() + " thread to " + prio);
    setPriority(prio);
  }

  /** Start a watchdog timer that will expire if not poked for interval
   * milliseconds.  Calls {@link #threadHung()} if triggered.
   * @param interval milliseconds after which watchdog will go off.
   */
  public void startWDog(long interval) {
    stopWDog();
    if (interval != 0) {
      this.interval = interval;
      logEvent("Starting", true);
      timerDead = Deadline.in(interval);
      timerReq = TimerQueue.schedule(timerDead, timerCallback, null);
    } else {
      logEvent("Not starting", true);
    }
  }

  /** Start a watchdog timer that will expire if not poked for interval
   * milliseconds.  Calls {@link #threadHung()} if triggered.
   * @param name Used to derive a configuration parameter name
   * (org.lockss.thread.name.watchdog.interval) whose value is the
   * watchdog interval.
   * @param defaultInterval the default interval if the config param has no
   * value.
   */
  public void startWDog(String name, long defaultInterval) {
    startWDog(getIntervalFromParam(name, defaultInterval));
  }

  /** Stop the watchdog so that it will not trigger. */
  public void stopWDog() {
    if (interval != 0) {
      interval = 0;
      if (timerReq != null) {
	TimerQueue.cancel(timerReq);
	timerReq = null;
      }
      logEvent("Stopping", false);
    }
  }

  public long getWDogInterval() {
    return interval;
  }

  /** Refresh the watchdog for another interval milliseconds. */
  public void pokeWDog() {
    if (timerDead != null && interval != 0) {
      timerDead.expireIn(interval);
      logEvent("Resetting", false);
    }
  }

  /** Set whether thread death should trigger the watchdog.  The default is
   * false; threads that are supposed to be persistent and never exit
   * should set this true. */
  public void triggerWDogOnExit(boolean triggerOnExit) {
    if (this.triggerOnExit != triggerOnExit) {
      logEvent(triggerOnExit ?
	       "Enabling thread exit" : "Disabling thread exit",
	       false);
    }
    this.triggerOnExit = triggerOnExit;
  }

  private boolean isWDogExpired() {
    return (interval != 0 && timerDead != null && timerDead.expired());
  }

  /** Called if thread is hung (hasn't poked the watchdog in too long).
   * Default action is to exit the daemon; should be overridden if thread
   * is able to take some less drastic corrective action (e.g., close
   * socket for hung socket reads.)  Unless
   * org.lockss.thread.hungThreadDump is false, attempts to log a thread
   * dump, waits 30 seconds and attempts another thread dump.
   */
  protected void threadHung() {
    // Don't trigger the watchdog if it has been turned off.  This could
    // happen if the timer event happens as it's being cancelled.
    if (!isWDogExpired()) {
      return;
    }
    if (CurrentConfig.getBooleanParam(PARAM_THREAD_WDOG_HUNG_DUMP,
                                      DEFAULT_THREAD_WDOG_HUNG_DUMP)) {
      log.error("Thread hung for " +
		StringUtil.timeIntervalToString(interval) + ": " + getName());
      PlatformUtil.getInstance().threadDump(false);
      try {
	Thread.sleep(30 * Constants.SECOND);
      } catch (InterruptedException ignore) {}
      PlatformUtil.getInstance().threadDump(true);
    }
    if (isWDogExpired()) {
      exitDaemon(Constants.EXIT_CODE_THREAD_HUNG,
		 "Thread hung for " +
		 StringUtil.timeIntervalToString(interval));
    } else {
      log.info("Thread woke up, continuing: " + getName());
    }
  }

  /** Called if thread exited unexpectedly.  Default action is to exit the
   * daemon; can be overridden is thread is able to take some less drastic
   * corrective action. */
  protected void threadExited(Throwable cause) {
    exitDaemon(Constants.EXIT_CODE_THREAD_EXIT, "Thread exited");
  }

  protected void exitDaemon(int exitCode, String msg) {
    boolean exitImm = true;
    try {
      try {
	WatchdogService wdog = (WatchdogService)
	  LockssDaemon.getManager(LockssDaemon.WATCHDOG_SERVICE);
	if (wdog != null) {
	  wdog.forceStop();
	}
      } catch (RuntimeException e) {
	// IllegalArgumentException can happen when stopping unit tests;
	// don't let it prevent us from finding correct value for exitImm
      }
      log.error(msg + ": " + getName());
      exitImm = LockssRunnable.isExitImm();
      if (exitImm) {
	log.error("Daemon exiting.");
      }
    } finally {
      if (exitImm) {
	System.exit(exitCode);
      }
    }
  }

  long getIntervalFromParam(String name, long defaultInterval) {
    String param = (String)wdogParamNameMap.get(name);
    if (param == null) {
      param = StringUtil.replaceString(PARAM_NAMED_WDOG_INTERVAL,
				       "<name>", name);
      wdogParamNameMap.put(name, param);
    }
    return CurrentConfig.getTimeIntervalParam(param, defaultInterval);
  }

  int getPriorityFromParam(String name, int defaultInterval) {
    String param = (String)prioParamNameMap.get(name);
    if (param == null) {
      param = StringUtil.replaceString(PARAM_NAMED_THREAD_PRIORITY,
				       "<name>", name);
      prioParamNameMap.put(name, param);
    }
    int prio = CurrentConfig.getIntParam(param, defaultInterval);
    if (prio == -1) return prio;
    if (prio < Thread.MIN_PRIORITY) {
      log.warning("Thread " + getName() + ", priority " + prio +
		  " less than min (" + Thread.MIN_PRIORITY + ")");
      prio = Thread.MIN_PRIORITY;
    }
    if (prio > Thread.MAX_PRIORITY) {
      log.warning("Thread " + getName() + ", priority " + prio +
		  " greater than max (" + Thread.MAX_PRIORITY + ")");
      prio = Thread.MAX_PRIORITY;
    }
    return prio;
  }

  private void logEvent(String event, boolean includeInterval) {
    if (log.isDebug3()) {
      StringBuffer sb = new StringBuffer();
      sb.append(event);
      sb.append(" thread watchdog (");
      sb.append(getName());
      sb.append(")");
      if (includeInterval) {
	sb.append(": ");
	sb.append(StringUtil.timeIntervalToString(interval));
      }
      log.debug3(sb.toString());
    }
  }

  /** Invoke the subclass's lockssRun() method, then cancel any outstanding
   * thread watchdog */
  public final void run() {
    boolean exitDaemonOnOome =
      CurrentConfig.getBooleanParam(PARAM_EXIT_DAEMON_ON_OOME,
				    DEFAULT_EXIT_DAEMON_ON_OOME);
    Throwable exitCause = null;
    try {
      lockssRun();
      String msg = getName() + " lockssRun() returned";
      if (triggerOnExit) {
	log.warning(msg);
      } else {
	log.debug2(msg);
      }
    } catch (Exception e) {
      exitCause = e;
      log.error("Thread threw", e);
    } catch (OutOfMemoryError e) {
      exitCause = e;
      if (exitDaemonOnOome && !triggerOnExit) {
	exitDaemon(Constants.EXIT_CODE_THREAD_EXIT,
		   "Thread exited with OutOfMemoryError");
      }
      log.error("Thread threw", e);
    } catch (Throwable e) {
      exitCause = e;
      log.error("Thread threw Throwable", e);
    } finally {
      try {
	if (triggerOnExit) {
	  threadExited(exitCause);
	} else {
	  stopWDog();
	}
      } finally {
	// Signal thread exited.  This is too early.  If it ever matters,
	// use another thread to join() this one, then call nowExited();
	nowExited();
      }
    }
  }

  /** Subclasses must implement this in place of the run() method */
  protected abstract void lockssRun();
}


text:
package main

import (
	"../common"
	"../common/error"
	"../common/protocol"
	"../common/room"
	"encoding/json"
	"fmt"
	"gtnet"
	"io/ioutil"
	"net/http"
	"runtime"
	"strconv"
	"utils"
)

var clientServer *gtnet.GTUdpServer

//var bsServer *gtnet.GTUdpServer

var recvChan chan *gtnet.GTUDPPacket

func udpServiceInit() {
	recvChan = make(chan *gtnet.GTUDPPacket, 1024)
	startUDPServer()
	startRecvProcess()
}

func startRecvProcess() {
	var numCPU = runtime.NumCPU()

	for i := 0; i < numCPU; i++ {
		go func() {
			for packet := range recvChan {
				pack := packet
				//var msgtype int16
				//utils.BytesToNum(pack.Buff[4:8], &msgtype)
				msgtype := gtprotocol.GetMsgType(pack.Buff)
				// pack := packet
				// proto := new(gtprotocol.Protocol)
				// proto.Parse(pack.Buff)
				//index := bytes.IndexByte(pack.Buff[8:40], 0)
				roomname := gtprotocol.GetRoomName(pack.Buff) //string(pack.Buff[8 : 8+index])
				//b, _ := json.Marshal(roomMap)
				//fmt.Println(string(b))
				rsroom, ok := roomMap[roomname]

				//fmt.Println("process msgtype:", msgtype)
				//fmt.Println("room name:", roomname+"222")
				if ok {
					if msgtype == common.MSG_REQ_LOGIN {
						go processLogin(pack, rsroom)
					} else if msgtype == common.MSG_DATA_TRANS {
						for _, bsconn := range rsroom.BSList {
							//fmt.Println("send to bs server")
							//fmt.Println("data:", pack.Buff)
							bsconn.Write(pack.Buff)
						}
					}
				} else {
					fmt.Println("room not on server")
					retLoginFailMsg(pack)
				}

			}
		}()
	}
}

func onRecv(packet *gtnet.GTUDPPacket) {
	recvChan <- packet
}

// func onBSRecv(packet *gtnet.GTUDPPacket) {
// 	recvChan <- packet
// }

func startUDPServer() {
	clientServer = gtnet.NewUdpServer(sip, sport)
	clientServer.OnRecv = onRecv
	err := clientServer.Start()

	if err != nil {
		fmt.Println("Server start error:" + err.Error())
	}

	// bsServer = gtnet.NewUdpServer(sip, sport-1)
	// bsServer.OnRecv = onBSRecv
	// err = bsServer.Start()

	// if err != nil {
	// 	fmt.Println("Server start error:" + err.Error())
	// }
}

func processLogin(packet *gtnet.GTUDPPacket, rsroom *gtroom.RSRoom) {
	proto := new(gtprotocol.ReqLoginProtocol)
	err := proto.Parse(packet.Buff)

	if err != nil {
		fmt.Println(err.Error())
	}

	strsid := utils.Uint64ToStr(proto.SessionId)
	fmt.Println("login sessionid is ", proto.SessionId)
	roomname := utils.BytesToStr(proto.RoomName[:])
	fmt.Println("http://" + scip + ":" + strconv.Itoa(scport) + "/checklogin?servertype=rs&sessionid=" + strsid + "&roomname=" + roomname)
	resp, err := http.Get("http://" + scip + ":" + strconv.Itoa(scport) + "/checklogin?servertype=rs&sessionid=" + strsid + "&roomname=" + roomname)

	if err != nil {
		fmt.Println(err.Error())
		retLoginFailMsg(packet)
		return
	}

	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)

	if err != nil {
		fmt.Println(err.Error())
		retLoginFailMsg(packet)
		return
	}

	var gterr gterror.Error
	json.Unmarshal(body, &gterr)

	if gterr.ErrorCode != 0 {
		fmt.Println(string(body))
		retLoginFailMsg(packet)
		return
	}

	//add client to room
	rsroom.AddClient(strsid, packet.Raddr)

	//ret login success msg
	retproto := new(gtprotocol.RetLoginProtocol)
	retproto.DataSize = 1
	retproto.MsgType = common.MSG_RET_LOGIN
	retproto.Result = 1

	packet.Buff = retproto.ToBytes()
	clientServer.Send(packet)
}

func retLoginFailMsg(packet *gtnet.GTUDPPacket) {
	retproto := new(gtprotocol.RetLoginProtocol)
	retproto.DataSize = 1
	retproto.MsgType = common.MSG_RET_LOGIN
	retproto.Result = 0

	packet.Buff = retproto.ToBytes()
	clientServer.Send(packet)
}


text:
<?php

/* $Id: InputSerialItemsExisting.php 6941 2014-10-26 23:18:08Z daintree $*/

/**
If the User has selected Keyed Entry, show them this special select list...
it is just in the way if they are doing file imports
it also would not be applicable in a PO and possible other situations...
**/
if ($_POST['EntryType'] == 'KEYED'){
        /*Also a multi select box for adding bundles to the dispatch without keying */
     $sql = "SELECT serialno, quantity
			FROM stockserialitems
			INNER JOIN locationusers ON locationusers.loccode=stockserialitems.loccode AND locationusers.userid='" .  $_SESSION['UserID'] . "' AND locationusers.canupd=1
			WHERE stockid='" . $StockID . "'
			AND stockserialitems.loccode ='" . $LocationOut."'
			AND quantity > 0";

	$ErrMsg = '
' .  _('Could not retrieve the items for'). ' ' . $StockID;
    $Bundles = DB_query($sql, $ErrMsg );
	echo '

';
	if (DB_num_rows($Bundles)>0){
		$AllSerials=array();

		foreach ($LineItem->SerialItems as $Itm){
			$AllSerials[$Itm->BundleRef] = $Itm->BundleQty;
		}

		echo '' .  _('Select Existing Items'). '
';

		echo '<form action="' . htmlspecialchars($_SERVER['PHP_SELF'],ENT_QUOTES,'UTF-8') . '?identifier=' . $identifier . '" method="post">';
		echo '<input type="hidden" name="FormID" value="' . $_SESSION['FormID'] . '" />';
		echo '<input type="hidden" name="LineNo" value="' . $LineNo . '">
			<input type="hidden" name="StockID" value="' . $StockID . '">
			<input type="hidden" name="EntryType" value="KEYED">
			<input type="hidden" name="identifier" value="' . $identifier . '">
			<input type="hidden" name="EditControlled" value="true">
			<select name=Bundles[] multiple="multiple">';

		$id=0;
		$ItemsAvailable=0;
		while ($myrow=DB_fetch_array($Bundles,$db)){
			if ($LineItem->Serialised==1){
				if ( !array_key_exists($myrow['serialno'], $AllSerials) ){
					echo '<option value="' . $myrow['serialno'] . '">' . $myrow['serialno'] . '</option>';
					$ItemsAvailable++;
				}
			} else {

				if ( !array_key_exists($myrow['serialno'], $AllSerials)  OR
					($myrow['quantity'] - $AllSerials[$myrow['serialno']] >= 0) ) {
					//Use the $InOutModifier to ajust the negative or postive direction of the quantity. Otherwise the calculated quantity is wrong.
					$RecvQty = $myrow['quantity'] - $InOutModifier*$AllSerials[$myrow['serialno']];
					echo '<option value="' . $myrow['serialno'] . '/|/'. $RecvQty .'">' . $myrow['serialno'].' - ' . _('Qty left'). ': ' . $RecvQty . '</option>';
					$ItemsAvailable += $RecvQty;
				}
			}
		}
		echo '</select>

';
		echo '

<input type="submit" name="AddBatches" value="'. _('Enter'). '">

';
		echo '</form>';
		echo $ItemsAvailable . ' ' . _('items available');
		echo '	';
	} else {
		echo '' .  prnMsg( _('There does not appear to be any of') . ' ' . $StockID . ' ' . _('left in'). ' '. $LocationOut , 'warn') . '	';
	}
	echo '

';
}


text:
oasis.connect('close', function(port) {
  port.on('ping', function() {
    port.send('pong');
  });

  port.send('sandboxInitialized');
});


text:
package net.finmath.montecarlo.interestrate.products.components;

import java.util.ArrayList;
import java.util.Set;

import net.finmath.exception.CalculationException;
import net.finmath.montecarlo.conditionalexpectation.MonteCarloConditionalExpectationRegression;
import net.finmath.montecarlo.interestrate.LIBORModelMonteCarloSimulationInterface;
import net.finmath.montecarlo.interestrate.products.AbstractLIBORMonteCarloProduct;
import net.finmath.stochastic.RandomVariableInterface;

/**
 * Implements (a numerical approximation of) the function
 * \(
 * (t,V) \mapsto E( V(t) \vert \mathcal{F}_t )
 * \)
 * where \( V(t) \) is the (sum of) discounted future value(s) of an underlying \( V \), discounted to \( t \)
 * and \( t \) is a given evaluation time.
 *
 * The conditional expectation is estimated using a regression.
 *
 * @author Christian Fries
 * @version 1.3
 * @see net.finmath.montecarlo.interestrate.products.AbstractLIBORMonteCarloProduct
 */
public class ExposureEstimator extends AbstractProductComponent {

	private static final long serialVersionUID = 2987369289230532162L;

	private final AbstractLIBORMonteCarloProduct	underlying;

	/**
	 * Creates (a numerical approximation of) the function
	 * \(
	 * (t,V) \mapsto E( V(t) \vert \mathcal{F}_t )
	 * \)
	 * where \( V(t) \) is the (sum of) discounted future value(s) of an underlying \( V \), discounted to \( t \)
	 * and \( t \) is a given evaluation time.
	 *
	 * @param underlying The underlying.
	 */
	public ExposureEstimator(AbstractLIBORMonteCarloProduct underlying) {
		super();
		this.underlying		= underlying;
	}

	@Override
	public String getCurrency() {
		return underlying.getCurrency();
	}

	@Override
	public Set<String> queryUnderlyings() {
		if(underlying instanceof AbstractProductComponent)	return ((AbstractProductComponent)underlying).queryUnderlyings();
		else												throw new IllegalArgumentException("Underlying cannot be queried for underlyings.");
	}

	/**
	 * This method returns the value random variable of the product within the specified model, evaluated at a given evalutationTime.
	 * Note: For a lattice this is often the value conditional to evalutationTime, for a Monte-Carlo simulation this is the (sum of) value discounted to evaluation time.
	 * Cashflows prior evaluationTime are not considered.
	 *
	 * @param evaluationTime The time on which this products value should be observed.
	 * @param model The model used to price the product.
	 * @return The random variable representing the value of the product discounted to evaluation time
	 * @throws net.finmath.exception.CalculationException Thrown if the valuation fails, specific cause may be available via the cause() method.
	 */
	@Override
	public RandomVariableInterface getValue(double evaluationTime, LIBORModelMonteCarloSimulationInterface model) throws CalculationException {

		final RandomVariableInterface one	= model.getRandomVariableForConstant(1.0);
		final RandomVariableInterface zero	= model.getRandomVariableForConstant(0.0);

		RandomVariableInterface values = underlying.getValue(evaluationTime, model);

		if(values.getFiltrationTime() > evaluationTime) {
			RandomVariableInterface filterNaN = values.isNaN().sub(1.0).mult(-1.0);
			RandomVariableInterface valuesFiltered = values.mult(filterNaN);

			/*
			 * Cut off two standard deviations from regression
			 */
			double valuesMean		= valuesFiltered.getAverage();
			double valuesStdDev	= valuesFiltered.getStandardDeviation();
			double valuesFloor		= valuesMean*(1.0-Math.signum(valuesMean)*1E-5)-3.0*valuesStdDev;
			double valuesCap		= valuesMean*(1.0+Math.signum(valuesMean)*1E-5)+3.0*valuesStdDev;
			RandomVariableInterface filter = values
					.barrier(values.sub(valuesFloor), one, zero)
					.mult(values.barrier(values.sub(valuesCap).mult(-1.0), one, zero));
			filter = filter.mult(filterNaN);
			// Filter values and regressionBasisFunctions
			values = values.mult(filter);

			RandomVariableInterface[] regressionBasisFunctions			= getRegressionBasisFunctions(evaluationTime, model);
			RandomVariableInterface[] filteredRegressionBasisFunctions	= new RandomVariableInterface[regressionBasisFunctions.length];
			for(int i=0; i<regressionBasisFunctions.length; i++) filteredRegressionBasisFunctions[i] = regressionBasisFunctions[i].mult(filter);

			// Remove foresight through conditional expectation
			MonteCarloConditionalExpectationRegression condExpEstimator = new MonteCarloConditionalExpectationRegression(filteredRegressionBasisFunctions, regressionBasisFunctions);

			// Calculate cond. expectation. Note that no discounting (numeraire division) is required!
			values         = condExpEstimator.getConditionalExpectation(values);
		}

		// Return values
		return values;
	}

	/**
	 * Return the regression basis functions.
	 *
	 * @param evaluationTime The date w.r.t. which the basis functions should be measurable.
	 * @param model The model.
	 * @return Array of random variables.
	 * @throws net.finmath.exception.CalculationException Thrown if the valuation fails, specific cause may be available via the cause() method.
	 */
	private RandomVariableInterface[] getRegressionBasisFunctions(double evaluationTime, LIBORModelMonteCarloSimulationInterface model) throws CalculationException {

		ArrayList<RandomVariableInterface> basisFunctions = new ArrayList<RandomVariableInterface>();

		RandomVariableInterface basisFunction;

		// Constant
		basisFunction = model.getRandomVariableForConstant(1.0);
		basisFunctions.add(basisFunction);

		// LIBORs
		int liborPeriodIndex, liborPeriodIndexEnd;
		RandomVariableInterface rate;

		// 1 Period
		basisFunction = model.getRandomVariableForConstant(1.0);
		liborPeriodIndex = model.getLiborPeriodIndex(evaluationTime);
		if(liborPeriodIndex < 0) liborPeriodIndex = -liborPeriodIndex-1;
		liborPeriodIndexEnd = liborPeriodIndex+1;
		double periodLength1 = model.getLiborPeriod(liborPeriodIndexEnd) - model.getLiborPeriod(liborPeriodIndex);

		rate = model.getLIBOR(evaluationTime, model.getLiborPeriod(liborPeriodIndex), model.getLiborPeriod(liborPeriodIndexEnd));
		basisFunction = basisFunction.discount(rate, periodLength1);
		basisFunctions.add(basisFunction);//.div(Math.sqrt(basisFunction.mult(basisFunction).getAverage())));

		basisFunction = basisFunction.discount(rate, periodLength1);
		basisFunctions.add(basisFunction);//.div(Math.sqrt(basisFunction.mult(basisFunction).getAverage())));

		// n/2 Period
		basisFunction = model.getRandomVariableForConstant(1.0);
		liborPeriodIndex = model.getLiborPeriodIndex(evaluationTime);
		if(liborPeriodIndex < 0) liborPeriodIndex = -liborPeriodIndex-1;
		liborPeriodIndexEnd = (liborPeriodIndex + model.getNumberOfLibors())/2;

		double periodLength2 = model.getLiborPeriod(liborPeriodIndexEnd) - model.getLiborPeriod(liborPeriodIndex);

		if(periodLength2 != periodLength1) {
			rate = model.getLIBOR(evaluationTime, model.getLiborPeriod(liborPeriodIndex), model.getLiborPeriod(liborPeriodIndexEnd));
			basisFunction = basisFunction.discount(rate, periodLength2);
			basisFunctions.add(basisFunction);//.div(Math.sqrt(basisFunction.mult(basisFunction).getAverage())));

			basisFunction = basisFunction.discount(rate, periodLength2);
//			basisFunctions.add(basisFunction);//.div(Math.sqrt(basisFunction.mult(basisFunction).getAverage())));

			basisFunction = basisFunction.discount(rate, periodLength2);
//			basisFunctions.add(basisFunction);//.div(Math.sqrt(basisFunction.mult(basisFunction).getAverage())));
		}

		// n Period
		basisFunction = model.getRandomVariableForConstant(1.0);
		liborPeriodIndex = model.getLiborPeriodIndex(evaluationTime);
		if(liborPeriodIndex < 0) liborPeriodIndex = -liborPeriodIndex-1;
		liborPeriodIndexEnd = model.getNumberOfLibors();
		double periodLength3 = model.getLiborPeriod(liborPeriodIndexEnd) - model.getLiborPeriod(liborPeriodIndex);

		if(periodLength3 != periodLength1 && periodLength3 != periodLength2) {
			rate = model.getLIBOR(evaluationTime, model.getLiborPeriod(liborPeriodIndex), model.getLiborPeriod(liborPeriodIndexEnd));
			basisFunction = basisFunction.discount(rate, periodLength3);
			basisFunctions.add(basisFunction);//.div(Math.sqrt(basisFunction.mult(basisFunction).getAverage())));

			basisFunction = basisFunction.discount(rate, periodLength3);
//			basisFunctions.add(basisFunction);//.div(Math.sqrt(basisFunction.mult(basisFunction).getAverage())));
		}

		return basisFunctions.toArray(new RandomVariableInterface[0]);
	}
}


text:
<?php
/**
 * Created by PhpStorm.
 * User: delamare
 * Date: 19/09/2017
 * Time: 23:04
 */

namespace AppBundle\Repository;

use AppBundle\Entity\StatsParJournee;
use Doctrine\ORM\EntityRepository;

class StatsParJourneeRepository extends EntityRepository
{
    public function findByCategOrderByJournee($categ){
        return $this->createQueryBuilder('c')
            ->join('c.equipe', 'e', 'WITH', 'e.id = c.equipe')
            ->where('e.categorie = :categ')
            ->orderBy('c.journee', 'ASC')
            ->setParameter('categ', $categ)
            ->getQuery()
            ->getResult();
    }

    public function findNbJourneeByCateg($categ){
        return $this->createQueryBuilder('s')
            ->select('s.journee')
            ->where('s.category = :categ')
            ->orderBy('s.journee', 'ASC')
            ->setParameter('categ', $categ)
            ->distinct()
            ->getQuery()
            ->getResult();
    }

    public function findLastJourneeByCateg($categ){
        return $this->createQueryBuilder('s')
            ->select('s.journee')
            ->where('s.category = :categ')
            ->orderBy('s.journee', 'ASC')
            ->setParameter('categ', $categ)
            ->setMaxResults(1)
            ->distinct()
            ->getQuery()
            ->getOneOrNullResult();
    }

    public function findByCategorie($categorie){
        return $this->createQueryBuilder('s')
            ->join('s.equipe','e','WITH', 'e.id = s.equipe')
            ->where('e.categorie = :categorie')
            ->setParameter('categorie',$categorie)
            ->getQuery()
            ->execute();
    }
}


text:
<properties XML_version="1.2">
<property Type="stringfield" Value="1.212" id="GNUOptionsVersion"></property>
<property Type="stringfield" Value="-mmcu=msp430f5502 -lc -lgcc --gc-sections -L ${CCS_BASE_ROOT}/msp430/include_gcc " id="GNULinkerBuildOptions"></property>
<property Type="stringfield" Value="-mmcu=msp430f5502 -I${CCS_BASE_ROOT}/msp430/include_gcc -Os -mhwmult=f5series" id="GNUCompilerBuildOptions"></property>
<property Type="stringfield" Value="../include_gcc/msp430f5502.ld" id="GNUFilesToCopy"></property>
</properties>


text:
from django import template
from django.template import Library
register = Library()
from django.utils.safestring import mark_safe
import os

@register.filter(name="to_queries")
def to_queries(value):
    """Compiles search queries from keywords"""

    li = []
    kws = value.split(',')
    for kw in kws:
        li.append('%s' % (kw, kw))

    output = ', '.join(li)
    return mark_safe(output)

@register.filter(name="ext")
def ext(path):
    """ Returns the extension"""
    try:
        s = os.path.splitext(path)[1].replace('.','')
    except:
        s = None

    return s


text:
package com.maxmind.jmeter.generators;

import java.util.Random;
import java.util.function.Function;

/**
 * An base class for generators that map over one generator T -> U.
 */
public abstract class MapperGen<T, U> extends BaseGenerator<U> {

private final Generator<T> wrappedGen;
private final Function<T, U> mapper;

MapperGen(
    Random random,
    Generator<T> wrappedGen,
    Function<T, U> mapper) {
    super(random);
    this.wrappedGen = wrappedGen;
    this.mapper = mapper;
}

@Override
public U generate() {
    return mapper.apply(wrappedGen.generate());
}
}


text:
<?php

/**
 * Adminhtml weee tax item renderer
 *
 * @category   Mage
 * @package    Mage_Adminhtml
 * @author      Magento Core Team <core@magentocommerce.com>
 */
class Mage_Weee_Block_Renderer_Weee_Tax extends Mage_Adminhtml_Block_Widget implements Varien_Data_Form_Element_Renderer_Interface
{

    protected $_element = null;
    protected $_countries = null;
    protected $_websites = null;

    public function __construct()
    {
        $this->setTemplate('weee/renderer/tax.phtml');
    }

    public function getProduct()
    {
        return Mage::registry('product');
    }

    public function render(Varien_Data_Form_Element_Abstract $element)
    {
        $this->setElement($element);
        $this->_setAddButton();
        return $this->toHtml();
    }

    public function setElement(Varien_Data_Form_Element_Abstract $element)
    {
        $this->_element = $element;
        return $this;
    }

    public function getElement()
    {
        return $this->_element;
    }

    public function getValues()
    {
        $values =array();
        $data = $this->getElement()->getValue();

        if (is_array($data) && count($data)) {
            usort($data, array($this, '_sortWeeeTaxes'));
            $values = $data;
        }
        return $values;
    }

    protected function _sortWeeeTaxes($a, $b)
    {
        if ($a['website_id']!=$b['website_id']) {
            return $a['website_id']<$b['website_id'] ? -1 : 1;
        }
        if ($a['country']!=$b['country']) {
            return $a['country']<$b['country'] ? -1 : 1;
        }
        return 0;
    }

    public function getWebsiteCount()
    {
        return count($this->getWebsites());
    }

    public function isMultiWebsites()
    {
        return !Mage::app()->isSingleStoreMode();
    }

    public function getCountries()
    {
        if (is_null($this->_countries)) {
            $this->_countries = Mage::getModel('adminhtml/system_config_source_country')
                ->toOptionArray();
        }

        return $this->_countries;
    }

    public function getWebsites()
    {
        if (!is_null($this->_websites)) {
            return $this->_websites;
        }
        $websites = array();
        $websites[0] = array(
            'name'      => $this->__('All Websites'),
            'currency'  => Mage::app()->getBaseCurrencyCode()
        );

        if (!Mage::app()->isSingleStoreMode() && !$this->getElement()->getEntityAttribute()->isScopeGlobal()) {
            if ($storeId = $this->getProduct()->getStoreId()) {
                $website = Mage::app()->getStore($storeId)->getWebsite();
                $websites[$website->getId()] = array(
                    'name'      => $website->getName(),
                    'currency'  => $website->getConfig(Mage_Directory_Model_Currency::XML_PATH_CURRENCY_BASE),
                );
            } else {
                foreach (Mage::app()->getWebsites() as $website) {
                    if (!in_array($website->getId(), $this->getProduct()->getWebsiteIds())) {
                        continue;
                    }
                    $websites[$website->getId()] = array(
                        'name'      => $website->getName(),
                        'currency'  => $website->getConfig(Mage_Directory_Model_Currency::XML_PATH_CURRENCY_BASE),
                    );
                }
            }
        }
        $this->_websites = $websites;
        return $this->_websites;
    }

    protected function _setAddButton()
    {
        $this->setChild('add_button',
            $this->getLayout()->createBlock('adminhtml/widget_button')
                ->setData(array(
                    'label'     => Mage::helper('catalog')->__('Add Tax'),
                    'onclick'   => "weeeTaxControl.addItem('".$this->getElement()->getHtmlId()."')",
                    'class' => 'add'
                )));
    }

    public function getAddButtonHtml()
    {
        return $this->getChildHtml('add_button');
    }

}


text:
package com.bupt.edison.autocompletetextviewandpopwindow;

import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.io.IOException;
import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {

    @Bind(R.id.typeText)
    FormatAutoCompleteTextView typeText;

    private static final String[] COUNTRIES = new String[]{
            "1234567890AB", "12345678CDEF", "12345678CD90", "1234987690AB", "12345690AB90"
    };
    @Bind(R.id.play)
    Button play;
    @Bind(R.id.stop)
    Button stop;
    @Bind(R.id.oldEdit)
    EditText oldEdit;
    @Bind(R.id.readText)
    Button readText;
    @Bind(R.id.putText)
    Button putText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);

//        simpleAutoCompleteTextView();
        powerfulAutoCompleteTextView();
    }

    //AutoCompleteTextView初级用法,https://developer.android.com/training/keyboard-input/style.html
    private void simpleAutoCompleteTextView() {
        ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
                android.R.layout.simple_dropdown_item_1line, COUNTRIES);
        typeText.setAdapter(adapter);
        typeText.setThreshold(0);
    }

    ArrayList<BankCardModel> models;
    BankCardFilterAdapter adapter;

    //自定义AutoCompleteTextView - ,功能强大。详见 FormatAutoCompleteTextView
    private void powerfulAutoCompleteTextView() {
        BankCardModel model1 = new BankCardModel();
        model1.setBankCardNo("1234567890AB");
        model1.setBankName("特朗普");
        BankCardModel model2 = new BankCardModel();
        model2.setBankCardNo("12345678CDEF");
        model2.setBankName("普京");
        BankCardModel model3 = new BankCardModel();
        model3.setBankCardNo("12345678CD90");
        model3.setBankName("埃尔多安");
        BankCardModel model4 = new BankCardModel();
        model4.setBankCardNo("1234987690AB");
        model4.setBankName("习大大");
        BankCardModel model5 = new BankCardModel();
        model5.setBankCardNo("12345690AB90");
        model5.setBankName("布朗");

        models = new ArrayList<>();
        models.add(model1);
        models.add(model2);
        models.add(model3);
        models.add(model4);
        models.add(model5);

        adapter = new BankCardFilterAdapter(MainActivity.this, models);
        adapter.setFormatAutoCompleteTextView(typeText);
        typeText.setAdapter(adapter); //如果不设置adapter,不会有自动补全功能。
        typeText.setThreshold(1);
        typeText.setOnItemClickListener(this); //设置自动补全列表的点击事件

        //调整自动补全列表的大小和位置
        typeText.setDropDownHorizontalOffset(-dipToPx(60));
        DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
        typeText.setDropDownWidth(displayMetrics.widthPixels - dipToPx(30));
    }

    private int dipToPx(int dip) {
        final DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
        return (int) (displayMetrics.density * dip + 0.5f);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        //由于有过滤规则,需要使用adapter获得BankCardModel
        typeText.setContentText(adapter.getItem(position).getBankCardNo());
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ButterKnife.unbind(this);
    }

    MediaPlayer mediaPlayer;

    /**
     * RingtoneManager.TYPE_NOTIFICATION;   通知声音
     * RingtoneManager.TYPE_ALARM;  警告
     * RingtoneManager.TYPE_RINGTONE; 铃声
     *
     * @param context
     * @param position
     */
    public void playSystemRing(Context context, int position) {
        final AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
        RingtoneManager ringtoneManager = new RingtoneManager(context);
        ringtoneManager.setType(RingtoneManager.TYPE_ALARM);
        ringtoneManager.getCursor();
        Uri ringUri = ringtoneManager.getRingtoneUri(position);

        audioManager.setStreamVolume(AudioManager.STREAM_ALARM, 7, AudioManager.ADJUST_SAME);
        mediaPlayer = new MediaPlayer();
        mediaPlayer.reset();
        try {
            mediaPlayer.setDataSource(context, ringUri);
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
            mediaPlayer.prepare();
            mediaPlayer.start();
            mediaPlayer.setLooping(true);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void stopPlay() {
        if (mediaPlayer != null && mediaPlayer.isPlaying()) {
            mediaPlayer.stop();
        }
    }

    @OnClick({R.id.play, R.id.stop, R.id.readText, R.id.putText})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.play:
                playSystemRing(MainActivity.this, 1);
                break;
            case R.id.stop:
                stopPlay();
                break;
            case R.id.readText:
                Toast.makeText(this, typeText.getRealText(), Toast.LENGTH_SHORT).show();
                break;
            case R.id.putText:
                typeText.setContentText("ABCD1234abcd5678");
                break;
        }
    }
}


text:
using System;

namespace BTDB.IOC
{
    interface IBuildContext
    {
        ICRegILGen? ResolveNeedBy(Type type, object? key);
        IBuildContext? IncrementEnumerable();
        IBuildContext FreezeMulti();
    }
}


text:
<package xmlns="http://expath.org/ns/pkg" name="https://github.com/expkg-zone58/ex-thumbnailator"
	abbrev="thumbnailator" version="8.0.1" spec="1.0">

	<title>An XQuery interface to thumbnailator the thumbnail generator library.</title>

	<xquery>
		<namespace>expkg-zone58:image.thumbnailator</namespace>
		<file>thumbnailator.xqm</file>
	</xquery>
	<xsd>
		<import-uri>expkg-zone58:image.thumbnailator/schema/task.xsd</import-uri>
		<file>task.xsd</file>
	</xsd>
</package>


text:
title: 'i18n'
sidebarDepth: 2
---

# i18n

VCalendar utilizes the [well supported](https://caniuse.com/#feat=internationalization) Internationalization API to derive month and weekday names and formatting. This helps keep the package size down, as well as supporting multiple locales in the most performant and isomorphic way.

## Locales

A locale includes multiple settings that are typically assigned on a per region basis. This currently includes the following:

| Setting | Description |
| --- | --- |
| `firstDayOfWeek` | The day the specified the first day of the week. This is a number from 1 to 7 (Sunday to Saturday, respectfully). |
| `masks` | Set of masks to use for common sections of the calendar including the title, weekday labels, month labels in the navigation pane and more. |
| `dayNames` | Full length identifiers for the days of the week. |
| `dayNamesShort` | 3-character identifiers for the days of the week. |
| `dayNamesShorter` | 2-character identifiers for the days of the week. |
| `dayNamesNarrow` | 1-character identifiers for the days of the week. |
| `monthNames` | Full length identifiers for the months of the year. |
| `monthNamesShort` | Abbreviated identifiers for the months of the year. |

There are multiple ways which you can configure the locale for a specific calendar. Locales may be configured globally via the defaults object as well as on a per-calendar basis with the `locale` prop.

## Default Locale

```html
<v-calendar />
```

With no locale specified, the locale detected by the Internationalization API is used.

## Default Locale and Props

```html
<v-calendar :first-day-of-week="2" :masks="{ title: 'MMM YYYY' }" />
```

  <v-calendar :first-day-of-week="2" :masks="{ title: 'MMM YYYY' }" />

Uses the detected locale with customized `firstDayOfWeek` or `masks` that will override the built-in locale settings. When using a customized `masks` prop, the default masks will supply any masks that are missing, so you are free to provide single overrides.

## String Locales

```html
<v-calendar locale="es" />
```

  <v-calendar locale="es" />

With a string locale, the locale with the matching identifier is used. The Internationalization API is used to generate the `dayNames`, `dayNamesShort`, `dayNamesShorter`, `dayNamesNarrow`, `monthNames` and `monthNamesShort` properties.

Because the API does not provide common values for the `firstDayOfWeek` or `masks` these are loaded from the plugin defaults (unless specifically provided via props).

#### Object Locales

```html
<v-calendar :locale="{ id: 'da', firstDayOfWeek: 2, masks: { weekdays: 'WW' } }" />
```

  <v-calendar :locale="{ id: 'da', firstDayOfWeek: 2, masks: { weekdays: 'WW' } }" />

With an object locale, you can simply provide all the settings you need together in a single object.

Note that `firstDayOfWeek` and `masks` props will override this object.

#### Global Locales

More conveniently, you may override or provide missing locale information via the `locales` property of the defaults object when using VCalendar. This should be an object with the locale identifier as the key and an object with the locale settings.

```js
import Vue from 'vue'
import VCalendar from 'v-calendar'

Vue.use(VCalendar, {
  locales: {
    'pt-PT': {
      firstDayOfWeek: 1,
      masks: {
        L: 'YYYY-MM-DD',
        // ...optional `title`, `weekdays`, `navMonths`, etc
      }
    }
  }
});
```

Then, all you need to do is reference your locale when using the calendar component.

```html
<v-calendar locale="pt-PT" />
```

  <v-calendar locale="pt-PT" />


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<title></title>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<link rel="stylesheet" type="text/css" href="search.css"/>

Loading...

  UndefinedPropertyException

  unscan
  StringScanner

  updateMessage
  BaseException

  useAttsHelper
  Element

Searching...

No Matches


text:
import json
import pathlib

from django.conf import settings
from django.shortcuts import render

from extensions.views import admin_extension, tab_extension, TabExtensionDelegate
from infrastructure.models import Server
from jobs.models import Job
from utilities.decorators import json_view
from utilities.permissions import cbadmin_required

class AWSInspectorServerTabDelegate(TabExtensionDelegate):
    def should_display(self):
        server: Server = self.instance
        return server.get_value_for_custom_field('aws_inspector_findings') is not None

@tab_extension(model=Server, title='Inspector', delegate=AWSInspectorServerTabDelegate)
def server_tab(request, obj_id):
    context = {
        'server_id': obj_id
    }
    return render(request, 'aws_network_policy/templates/server_tab.html', context=context)

@json_view
def aws_network_policy_server_json(request, server_id):
    server = Server.objects.get(id=server_id)
    response = json.loads(server.aws_inspector_findings)
    findings = []

    for finding in response:
        row = [
            finding['title'],
            finding['description'],
            finding['recommendation'],
            finding['severity'],
        ]
        findings.append(row)

    return {
        # unaltered from client-side value, but cast to int to avoid XSS
        # http://datatables.net/usage/server-side
        "sEcho": int(request.GET.get('sEcho', 1)),
        "iTotalRecords": 10,
        "iTotalDisplayRecords": 10,
        'aaData': findings,
    }

@admin_extension(title='AWS Network Policy Settings', description='Enable/Disable and Schedule the Caching of Inspector Findings')
@cbadmin_required
def aws_network_policy_config(request):
    """
    View for managing the reccurring job that caches inspector findings
    """
    profile = request.get_user_profile()
    recurring_job = create_recurring_job_if_necessary()

    completed_spawned_jobs = recurring_job.spawned_jobs.filter(
        status__in=Job.COMPLETED_STATUSES
    ).order_by("-start_date")

    if completed_spawned_jobs:
        last_duration = completed_spawned_jobs.first().get_duration()
    else:
        last_duration = 'N/A'

    # note: the last job may be queued, pending, or active, so it may not be in past_10_jobs
    last_job = recurring_job.spawned_jobs.last()

    last_success_job = completed_spawned_jobs.filter(status="SUCCESS").first()
    failed_spawned_jobs = completed_spawned_jobs.filter(status="FAILURE")
    last_failed_job = failed_spawned_jobs.first()

    total_count = completed_spawned_jobs.count()
    failure_count = failed_spawned_jobs.count()

    return render(request, 'aws_network_policy/templates/main.html', dict(
        profile=profile,
        recurring_job=recurring_job,
        last_job=last_job,
        last_success_job=last_success_job,
        last_failed_job=last_failed_job,
        last_duration=last_duration,
        total_count=total_count,
        failure_count=failure_count
    ))

def create_recurring_job_if_necessary():
    recurring_job = {
        'name': 'AWS Network Policy Caching',
        'enabled': True,
        'description': 'Create local cached files for aws specific inspector findings',
        'type': 'recurring_action',
        'hook_name': 'AWS Network Policy Caching',
        # once a day at 12:05am
        'schedule': '5 0 * * *',
    }

    recurring_job_hook = {
        'name': 'AWS Network Policy Caching',
        'description': 'Create local cached files for aws specific inspector findings',
        'hook_point': None,
        'module':  pathlib.Path(
            settings.PROSERV_DIR, 'xui/aws_network_policy/actions/fetch_update_findings.py'
        ),
    }

    from initialize.create_objects import create_recurring_job, create_hooks
    from cbhooks.models import RecurringActionJob

    create_hooks([recurring_job_hook])
    job = create_recurring_job(recurring_job)
    if not job:
        # this only happens if it already exists
        job = RecurringActionJob.objects.filter(name=recurring_job['name']).first()

    return job


text:
package rbac

import (
	"github.com/cloudawan/cloudone_utility/logger"
)

var log = logger.GetLog("rbac")


text:
REGISTER_TEST_CASE(OutputProtectionPrivate);

TestOutputProtectionPrivate::TestOutputProtectionPrivate(
    TestingInstance* instance)
    : TestCase(instance) {
}

bool TestOutputProtectionPrivate::Init() {
  output_protection_interface_ =
      static_cast<const PPB_OutputProtection_Private*>(
          pp::Module::Get()->GetBrowserInterface(
              PPB_OUTPUTPROTECTION_PRIVATE_INTERFACE_0_1));
  return output_protection_interface_ && CheckTestingInterface();
}

void TestOutputProtectionPrivate::RunTests(const std::string& filter) {
  RUN_TEST(QueryStatus, filter);
  RUN_TEST(EnableProtection, filter);
}

std::string TestOutputProtectionPrivate::TestQueryStatus() {
  TestCompletionCallback callback(instance_->pp_instance(), callback_type());

  PP_Resource output_protection_resource = output_protection_interface_->
      Create(instance_->pp_instance());
  uint32_t link_mask;
  uint32_t protection_mask;
  callback.WaitForResult(
      output_protection_interface_->QueryStatus(
          output_protection_resource,
          &link_mask,
          &protection_mask,
          callback.GetCallback().pp_completion_callback()));
  CHECK_CALLBACK_BEHAVIOR(callback);

  PASS();
}

std::string TestOutputProtectionPrivate::TestEnableProtection() {
  TestCompletionCallback callback(instance_->pp_instance(), callback_type());

  PP_Resource output_protection_resource = output_protection_interface_->
      Create(instance_->pp_instance());
  callback.WaitForResult(
      output_protection_interface_->EnableProtection(
          output_protection_resource,
          PP_OUTPUT_PROTECTION_METHOD_PRIVATE_NONE,
          callback.GetCallback().pp_completion_callback()));
  CHECK_CALLBACK_BEHAVIOR(callback);

  PASS();
}


text:
<title>
Crooked to the top
</title>

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<?php include "../../legacy-includes/Script.htmlf" ?>

<?php include "../../legacy-includes/TopLogo.htmlf" ?>

<?php include "../../legacy-includes/TopAd.htmlf" ?>

<?php include "../../legacy-includes/LeftButtons.htmlf" ?>

<?php include "../../legacy-includes/BodyInsert.htmlf" ?>

Enron and the White House

Crooked to the top

May 31, 2002 | Page 1

SINCE LAST December, the Bush administration has claimed to be an innocent bystander in the collapse of energy giant Enron. But documents released by the White House last week show that the Bush gang was best buddies with these corporate crooks.

The records reveal dozens of contacts between administration officials and Enron executives last year--four times more than the White House admitted in January. As the largest corporate contributors by far to George W. Bush's political career, Enron executives enjoyed a place of honor in the new White House.

Even as the company was plummeting toward bankruptcy, these corporate con artists were begging their pals for a bailout. Of course, that was after they had sold more than $1 billion worth of company stock--getting out before the price tanked, while Enron workers saw their retirement savings go up in smoke.

When Enron went into free fall, the Bush administration mounted a full-scale damage-control campaign, coordinated by Bush's inner circle of advisers. There are more revelations to come.

Last week, a federal judge ruled that the government watchdog group Judicial Watch can continue its efforts to obtain records from Dick Cheney's energy task force. This could finally reveal proof of what most people assume--that Enron and the other giants of the energy industry bought access to write the administration's policy for their own benefit.

White House officials insist that Enron's crash is an isolated case of corporate irresponsibility--and has nothing to do with them. But for many people, Enron has come to symbolize everything that's wrong with crony capitalism, American style.

As an editorial in the far-from-radical Washington Post put it: "[The Enron scandal's] many tentacles are united by a sense that rich insiders are rigging the system at the expense of ordinary Americans. Enron's energy dealers ripped off California's consumers--and got away with this behavior because of Enron's clout in Washington."

Enron may have bought influence in Washington more aggressively than other big corporations. But it's hardly an exception. And thanks to their servants in Washington, most of Corporate America's rip-offs are perfectly legal--even if they wreck the lives of working people.

Enron is only the clearest example of a system that serves corporate power--at our expense.

<?php include "../../legacy-includes/BottomNavLinks.htmlf" ?>

<?php include "../../legacy-includes/RightAdFolder.htmlf" ?>


text:
Panic-Button-XBMC
=================

Help resource for Corvust XBMC boxes


text:
hostsfile LWRP
==============
[![Build Status](https://travis-ci.org/customink-webops/hostsfile.png?branch=master)](https://travis-ci.org/customink-webops/hostsfile)

`hostsfile` provides an LWRP for managing your hosts file using Chef.

Requirements
------------
- Chef 11 or higher
- Ruby 1.9.3 or higher

Note: Any of the `1.x.y` series of this cookbook will work with Chef 10 and Ruby 1.8.7.

Attributes
----------

    Attribute
    Description
    Example
    Default

    ip_address
    (name attribute) the IP address for the entry
    <tt>1.2.3.4</tt>

    hostname
    (required) the hostname associated with the entry
    <tt>example.com</tt>

    aliases
    array of aliases for the entry
    <tt>['www.example.com']</tt>
    <tt>[]</tt>

    comment
    a comment to append to the end of the entry
    <tt>'interal DNS server'</tt>
    <tt>nil</tt>

    priority
    the relative position of this entry
    <tt>20</tt>
    (varies, see **Priorities** section)

Actions
-------
**Please note**: As of `v0.1.2`, specifying a hostname or alias that exists in another entry will remove that hostname from the other entry before adding to this one. For example:

    1.2.3.4          example.com www.example.com

and

```ruby
hostsfile_entry '2.3.4.5' do
  hostname  'www.example.com'
end
```

would yield an /etc/hosts file like this:

    1.2.3.4          example.com
    2.3.4.5          www.example.com

#### `create`
Creates a new hosts file entry. If an entry already exists, it will be overwritten by this one.

```ruby
hostsfile_entry '1.2.3.4' do
  hostname  'example.com'
  action    :create
end
```

This will create an entry like this:

    1.2.3.4          example.com

#### `create_if_missing`
Create a new hosts file entry, only if one does not already exist for the given IP address. If one exists, this does nothing.

```ruby
hostsfile_entry '1.2.3.4' do
  hostname  'example.com'
  action    :create_if_missing
end
```

#### `append`
Append a hostname or alias to an existing record. If the given IP address doesn't not already exist in the hostsfile, this method behaves the same as create. Otherwise, it will append the additional hostname and aliases to the existing entry.

    1.2.3.4         example.com www.example.com # Created by Chef

```ruby
hostsfile_entry '1.2.3.4' do
  hostname  'www2.example.com'
  aliases   ['foo.com', 'foobar.com']
  comment   'Append by Recipe X'
  action    :append
end
```

would yield:

    1.2.3.4         example.com www.example.com www2.example.com foo.com foobar.com # Created by Chef, Appended by Recipe X

#### `update`
Updates the given hosts file entry. Does nothing if the entry does not exist.

```ruby
hostsfile_entry '1.2.3.4' do
  hostname  'example.com'
  comment   'Update by Chef'
  action    :update
end
```

This will create an entry like this:

    1.2.3.4           example # Updated by Chef

#### `remove`
Removes an entry from the hosts file. Does nothing if the entry does not
exist.

```ruby
hostsfile_entry '1.2.3.4' do
  action    :remove
end
```

This will remove the entry for `1.2.3.4`.

Usage
-----
If you're using [Berkshelf](http://berkshelf.com/), just add `hostsfile` to your `Berksfile`:

```ruby
cookbook 'hostsfile'
```

Otherwise, install the cookbook from the community site:

    knife cookbook site install hostsfile

Have any other cookbooks *depend* on hostsfile by editing editing the `metadata.rb` for your cookbook.

```ruby
# metadata.rb
depends 'hostsfile'
```

Priority
--------
Priority is a relatively new addition to the cookbook. It gives you the ability to (somewhat) specify the relative order of entries. By default, the priority is calculated for you as follows:

1. Local, loopback
2. IPV4
3. IPV6

However, you can override it using the `priority` option.

Contributing
------------
1. Fork the project
2. Create a feature branch corresponding to you change
3. Commit and test thoroughly
4. Create a Pull Request on github
    - ensure you add a detailed description of your changes

License and Authors
-------------------
- Author:: Seth Vargo (sethvargo@gmail.com)

Copyright 2012 Seth Vargo, CustomInk, LLC

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.


text:
package collector

import (
	"github.com/prometheus/client_golang/prometheus"
)

func init() {
	registerCollector("adfs", newADFSCollector, "AD FS")
}

type adfsCollector struct {
	adLoginConnectionFailures        *prometheus.Desc
	certificateAuthentications       *prometheus.Desc
	deviceAuthentications            *prometheus.Desc
	extranetAccountLockouts          *prometheus.Desc
	federatedAuthentications         *prometheus.Desc
	passportAuthentications          *prometheus.Desc
	passiveRequests                  *prometheus.Desc
	passwordChangeFailed             *prometheus.Desc
	passwordChangeSucceeded          *prometheus.Desc
	tokenRequests                    *prometheus.Desc
	windowsIntegratedAuthentications *prometheus.Desc
}

// newADFSCollector constructs a new adfsCollector
func newADFSCollector() (Collector, error) {
	const subsystem = "adfs"

	return &adfsCollector{
		adLoginConnectionFailures: prometheus.NewDesc(
			prometheus.BuildFQName(Namespace, subsystem, "ad_login_connection_failures"),
			"Total number of connection failures to an Active Directory domain controller",
			nil,
			nil,
		),
		certificateAuthentications: prometheus.NewDesc(
			prometheus.BuildFQName(Namespace, subsystem, "certificate_authentications"),
			"Total number of User Certificate authentications",
			nil,
			nil,
		),
		deviceAuthentications: prometheus.NewDesc(
			prometheus.BuildFQName(Namespace, subsystem, "device_authentications"),
			"Total number of Device authentications",
			nil,
			nil,
		),
		extranetAccountLockouts: prometheus.NewDesc(
			prometheus.BuildFQName(Namespace, subsystem, "extranet_account_lockouts"),
			"Total number of Extranet Account Lockouts",
			nil,
			nil,
		),
		federatedAuthentications: prometheus.NewDesc(
			prometheus.BuildFQName(Namespace, subsystem, "federated_authentications"),
			"Total number of authentications from a federated source",
			nil,
			nil,
		),
		passportAuthentications: prometheus.NewDesc(
			prometheus.BuildFQName(Namespace, subsystem, "passport_authentications"),
			"Total number of Microsoft Passport SSO authentications",
			nil,
			nil,
		),
		passiveRequests: prometheus.NewDesc(
			prometheus.BuildFQName(Namespace, subsystem, "passive_requests"),
			"Total number of passive (browser-based) requests",
			nil,
			nil,
		),
		passwordChangeFailed: prometheus.NewDesc(
			prometheus.BuildFQName(Namespace, subsystem, "password_change_failed"),
			"Total number of failed password changes",
			nil,
			nil,
		),
		passwordChangeSucceeded: prometheus.NewDesc(
			prometheus.BuildFQName(Namespace, subsystem, "password_change_succeeded"),
			"Total number of successful password changes",
			nil,
			nil,
		),
		tokenRequests: prometheus.NewDesc(
			prometheus.BuildFQName(Namespace, subsystem, "token_requests"),
			"Total number of token requests",
			nil,
			nil,
		),
		windowsIntegratedAuthentications: prometheus.NewDesc(
			prometheus.BuildFQName(Namespace, subsystem, "windows_integrated_authentications"),
			"Total number of Windows integrated authentications (Kerberos/NTLM)",
			nil,
			nil,
		),
	}, nil
}

type perflibADFS struct {
	AdLoginConnectionFailures        float64 `perflib:"AD login Connection Failures"`
	CertificateAuthentications       float64 `perflib:"Certificate Authentications"`
	DeviceAuthentications            float64 `perflib:"Device Authentications"`
	ExtranetAccountLockouts          float64 `perflib:"Extranet Account Lockouts"`
	FederatedAuthentications         float64 `perflib:"Federated Authentications"`
	PassportAuthentications          float64 `perflib:"Microsoft Passport Authentications"`
	PassiveRequests                  float64 `perflib:"Passive Requests"`
	PasswordChangeFailed             float64 `perflib:"Password Change Failed Requests"`
	PasswordChangeSucceeded          float64 `perflib:"Password Change Successful Requests"`
	TokenRequests                    float64 `perflib:"Token Requests"`
	WindowsIntegratedAuthentications float64 `perflib:"Windows Integrated Authentications"`
}

func (c *adfsCollector) Collect(ctx *ScrapeContext, ch chan<- prometheus.Metric) error {
	var adfsData []perflibADFS
	err := unmarshalObject(ctx.perfObjects["AD FS"], &adfsData)
	if err != nil {
		return err
	}

	ch <- prometheus.MustNewConstMetric(
		c.adLoginConnectionFailures,
		prometheus.CounterValue,
		adfsData[0].AdLoginConnectionFailures,
	)

	ch <- prometheus.MustNewConstMetric(
		c.certificateAuthentications,
		prometheus.CounterValue,
		adfsData[0].CertificateAuthentications,
	)

	ch <- prometheus.MustNewConstMetric(
		c.deviceAuthentications,
		prometheus.CounterValue,
		adfsData[0].DeviceAuthentications,
	)

	ch <- prometheus.MustNewConstMetric(
		c.extranetAccountLockouts,
		prometheus.CounterValue,
		adfsData[0].ExtranetAccountLockouts,
	)

	ch <- prometheus.MustNewConstMetric(
		c.federatedAuthentications,
		prometheus.CounterValue,
		adfsData[0].FederatedAuthentications,
	)

	ch <- prometheus.MustNewConstMetric(
		c.passportAuthentications,
		prometheus.CounterValue,
		adfsData[0].PassportAuthentications,
	)

	ch <- prometheus.MustNewConstMetric(
		c.passiveRequests,
		prometheus.CounterValue,
		adfsData[0].PassiveRequests,
	)

	ch <- prometheus.MustNewConstMetric(
		c.passwordChangeFailed,
		prometheus.CounterValue,
		adfsData[0].PasswordChangeFailed,
	)

	ch <- prometheus.MustNewConstMetric(
		c.passwordChangeSucceeded,
		prometheus.CounterValue,
		adfsData[0].PasswordChangeSucceeded,
	)

	ch <- prometheus.MustNewConstMetric(
		c.tokenRequests,
		prometheus.CounterValue,
		adfsData[0].TokenRequests,
	)

	ch <- prometheus.MustNewConstMetric(
		c.windowsIntegratedAuthentications,
		prometheus.CounterValue,
		adfsData[0].WindowsIntegratedAuthentications,
	)
	return nil
}