text:
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
import time
####awwww yeeeeuuhhhhhhh#####
from collections import Counter

def createExamples():
    numberArrayExamples = open('numArEx.txt','a')
    numbersWeHave = range(1,10)
    for eachNum in numbersWeHave:
        for furtherNum in numbersWeHave:
            print(str(eachNum)+'.'+str(furtherNum))
            imgFilePath = 'images/numbers/'+str(eachNum)+'.'+str(furtherNum)+'.png'
            ei = Image.open(imgFilePath)
            eiar = np.array(ei)
            eiarl = str(eiar.tolist())

            #time.sleep(555)
            lineToWrite = str(eachNum)+'::'+eiarl+'\n'
            numberArrayExamples.write(lineToWrite)

def threshold(imageArray):
    balanceAr = []
    newAr = imageArray
    for eachPart in imageArray:
        for theParts in eachPart:
            avgNum = reduce(lambda x, y: x + y, theParts[:3]) / len(theParts[:3])
            balanceAr.append(avgNum)
    balance = reduce(lambda x, y: x + y, balanceAr) / len(balanceAr)
    for eachRow in newAr:
        for eachPix in eachRow:
            if reduce(lambda x, y: x + y, eachPix[:3]) / len(eachPix[:3]) > balance:
                eachPix[0] = 255
                eachPix[1] = 255
                eachPix[2] = 255
                eachPix[3] = 255
            else:
                eachPix[0] = 0
                eachPix[1] = 0
                eachPix[2] = 0
                eachPix[3] = 255
    return newAr

def whatNumIsThis(filePath):

    matchedAr = []
    loadExamps = open('numArEx.txt','r').read()
    loadExamps = loadExamps.split('\n')

    i = Image.open(filePath)
    iar = np.array(i)
    iarl = iar.tolist()

    inQuestion = str(iarl)

    #dont forget to clear out that array!!!!#
    for eachExample in loadExamps:
        try:
            splitEx = eachExample.split('::')
            currentNum = splitEx[0]
            currentAr = splitEx[1]
            #print currentAr

            #okay not the most professional way to do it, but
            #since we are not blurring, and we are going pixil by pix,
            #this will be fine and very simple.
            eachPixEx = currentAr.split('],')
            eachPixInQ = inQuestion.split('],')

            x = 0

            while x < len(eachPixEx):
                if eachPixEx[x] == eachPixInQ[x]:
                    matchedAr.append(int(currentNum))

                x+=1
        except Exception as e:
            print(str(e))

    print(matchedAr)
    x = Counter(matchedAr)
    print(x)
    print(x[0])

whatNumIsThis('images/test.png')

#createExamples()


text:
layout: page
title: Fire Falls Industries Award Ceremony
date: 2016-05-24
author: Emma Wagner
tags: weekly links, java
status: published
summary: Suspendisse potenti. Donec mollis lacus sed maximus euismod. Morbi quis.
banner: images/banner/meeting-01.jpg
booking:
  startDate: 06/18/2017
  endDate: 06/22/2017
  ctyhocn: SBNSQHX
  groupCode: FFIAC
published: true
---
Nunc at leo ut risus elementum aliquet at et justo. Curabitur elementum semper arcu. In non pulvinar turpis, id mattis sapien. Etiam ornare nisl eget nulla tincidunt porta ac non turpis. Maecenas eu rhoncus libero. Praesent vitae scelerisque sapien. Suspendisse quis tellus quis sem rhoncus tincidunt. Cras in felis urna. Phasellus sed massa fermentum, laoreet mauris tincidunt, euismod augue. Pellentesque placerat, lectus at finibus fringilla, ligula arcu imperdiet nibh, quis maximus mi lacus vitae nulla. Proin vitae urna faucibus, suscipit enim nec, rhoncus orci. Cras laoreet ante molestie neque dapibus auctor sed eu magna.

* Integer tincidunt ipsum at odio placerat, eget auctor felis placerat
* Etiam consectetur libero semper sollicitudin feugiat
* Ut vitae augue quis neque faucibus congue sit amet quis erat
* Nunc sit amet dui pulvinar, mollis enim quis, ultrices lectus
* Phasellus ut magna ac lorem blandit mollis.

Praesent ultricies tristique pulvinar. Nam tincidunt dapibus odio, eget semper magna cursus ut. Maecenas accumsan ultricies facilisis. Cras id blandit tortor, vel mattis ipsum. Ut pellentesque ut metus at lobortis. Sed sit amet imperdiet velit, mollis bibendum lectus. Curabitur vel est mauris. Sed rutrum diam enim, vitae sollicitudin arcu aliquet et. Praesent eleifend felis quis urna eleifend, lacinia rutrum orci venenatis. Morbi maximus aliquet quam, ac ultrices magna maximus sed.

redpajama_set_name: RedPajamaGithub


text:
package com.amazonaws.services.sagemaker.model.transform;

import java.util.Map;
import java.util.List;
import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.services.sagemaker.model.*;

import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;

/**
 * UpdateActionRequestMarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class UpdateActionRequestMarshaller {

    private static final MarshallingInfo<String> ACTIONNAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("ActionName").build();
    private static final MarshallingInfo<String> DESCRIPTION_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("Description").build();
    private static final MarshallingInfo<String> STATUS_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("Status").build();
    private static final MarshallingInfo<Map> PROPERTIES_BINDING = MarshallingInfo.builder(MarshallingType.MAP).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("Properties").build();
    private static final MarshallingInfo<List> PROPERTIESTOREMOVE_BINDING = MarshallingInfo.builder(MarshallingType.LIST)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("PropertiesToRemove").build();

    private static final UpdateActionRequestMarshaller instance = new UpdateActionRequestMarshaller();

    public static UpdateActionRequestMarshaller getInstance() {
        return instance;
    }

    /**
     * Marshall the given parameter object.
     */
    public void marshall(UpdateActionRequest updateActionRequest, ProtocolMarshaller protocolMarshaller) {

        if (updateActionRequest == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(updateActionRequest.getActionName(), ACTIONNAME_BINDING);
            protocolMarshaller.marshall(updateActionRequest.getDescription(), DESCRIPTION_BINDING);
            protocolMarshaller.marshall(updateActionRequest.getStatus(), STATUS_BINDING);
            protocolMarshaller.marshall(updateActionRequest.getProperties(), PROPERTIES_BINDING);
            protocolMarshaller.marshall(updateActionRequest.getPropertiesToRemove(), PROPERTIESTOREMOVE_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

}


text:
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
 * You can obtain one at http://mozilla.org/MPL/2.0/. */

/* Utilities for hashing. */

/*
 * This file exports functions for hashing data down to a 32-bit value,
 * including:
 *
 *  - HashString    Hash a char* or uint16_t/wchar_t* of known or unknown
 *                  length.
 *
 *  - HashBytes     Hash a byte array of known length.
 *
 *  - HashGeneric   Hash one or more values.  Currently, we support uint32_t,
 *                  types which can be implicitly cast to uint32_t, data
 *                  pointers, and function pointers.
 *
 *  - AddToHash     Add one or more values to the given hash.  This supports the
 *                  same list of types as HashGeneric.
 *
 *
 * You can chain these functions together to hash complex objects.  For example:
 *
 *  class ComplexObject
 *  {
 *      char* str;
 *      uint32_t uint1, uint2;
 *      void (*callbackFn)();
 *
 *    public:
 *      uint32_t hash() {
 *        uint32_t hash = HashString(str);
 *        hash = AddToHash(hash, uint1, uint2);
 *        return AddToHash(hash, callbackFn);
 *      }
 *  };
 *
 * If you want to hash an nsAString or nsACString, use the HashString functions
 * in nsHashKeys.h.
 */

#ifndef mozilla_HashFunctions_h_
#define mozilla_HashFunctions_h_

#include "mozilla/Assertions.h"
#include "mozilla/Attributes.h"
#include "mozilla/StandardInteger.h"
#include "mozilla/Types.h"

#ifdef __cplusplus
namespace mozilla {

/**
 * The golden ratio as a 32-bit fixed-point value.
 */
static const uint32_t GoldenRatioU32 = 0x9E3779B9U;

inline uint32_t
RotateBitsLeft32(uint32_t value, uint8_t bits)
{
  MOZ_ASSERT(bits < 32);
  return (value << bits) | (value >> (32 - bits));
}

namespace detail {

inline uint32_t
AddU32ToHash(uint32_t hash, uint32_t value)
{
  /*
   * This is the meat of all our hash routines.  This hash function is not
   * particularly sophisticated, but it seems to work well for our mostly
   * plain-text inputs.  Implementation notes follow.
   *
   * Our use of the golden ratio here is arbitrary; we could pick almost any
   * number which:
   *
   *  * is odd (because otherwise, all our hash values will be even)
   *
   *  * has a reasonably-even mix of 1's and 0's (consider the extreme case
   *    where we multiply by 0x3 or 0xeffffff -- this will not produce good
   *    mixing across all bits of the hash).
   *
   * The rotation length of 5 is also arbitrary, although an odd number is again
   * preferable so our hash explores the whole universe of possible rotations.
   *
   * Finally, we multiply by the golden ratio *after* xor'ing, not before.
   * Otherwise, if |hash| is 0 (as it often is for the beginning of a message),
   * the expression
   *
   *   (GoldenRatioU32 * RotateBitsLeft(hash, 5)) |xor| value
   *
   * evaluates to |value|.
   *
   * (Number-theoretic aside: Because any odd number |m| is relatively prime to
   * our modulus (2^32), the list
   *
   *    [x * m (mod 2^32) for 0 <= x < 2^32]
   *
   * has no duplicate elements.  This means that multiplying by |m| does not
   * cause us to skip any possible hash values.
   *
   * It's also nice if |m| has large-ish order mod 2^32 -- that is, if the
   * smallest k such that m^k == 1 (mod 2^32) is large -- so we can safely
   * multiply our hash value by |m| a few times without negating the
   * multiplicative effect.  Our golden ratio constant has order 2^29, which is
   * more than enough for our purposes.)
   */
  return GoldenRatioU32 * (RotateBitsLeft32(hash, 5) ^ value);
}

/**
 * AddUintptrToHash takes sizeof(uintptr_t) as a template parameter.
 */
template<size_t PtrSize>
inline uint32_t
AddUintptrToHash(uint32_t hash, uintptr_t value);

template<>
inline uint32_t
AddUintptrToHash<4>(uint32_t hash, uintptr_t value)
{
  return AddU32ToHash(hash, static_cast<uint32_t>(value));
}

template<>
inline uint32_t
AddUintptrToHash<8>(uint32_t hash, uintptr_t value)
{
  /*
   * The static cast to uint64_t below is necessary because this function
   * sometimes gets compiled on 32-bit platforms (yes, even though it's a
   * template and we never call this particular override in a 32-bit build).  If
   * we do value >> 32 on a 32-bit machine, we're shifting a 32-bit uintptr_t
   * right 32 bits, and the compiler throws an error.
   */
  uint32_t v1 = static_cast<uint32_t>(value);
  uint32_t v2 = static_cast<uint32_t>(static_cast<uint64_t>(value) >> 32);
  return AddU32ToHash(AddU32ToHash(hash, v1), v2);
}

} /* namespace detail */

/**
 * AddToHash takes a hash and some values and returns a new hash based on the
 * inputs.
 *
 * Currently, we support hashing uint32_t's, values which we can implicitly
 * convert to uint32_t, data pointers, and function pointers.
 */
template<typename A>
MOZ_WARN_UNUSED_RESULT
inline uint32_t
AddToHash(uint32_t hash, A a)
{
  /*
   * Try to convert |A| to uint32_t implicitly.  If this works, great.  If not,
   * we'll error out.
   */
  return detail::AddU32ToHash(hash, a);
}

template<typename A>
MOZ_WARN_UNUSED_RESULT
inline uint32_t
AddToHash(uint32_t hash, A* a)
{
  /*
   * You might think this function should just take a void*.  But then we'd only
   * catch data pointers and couldn't handle function pointers.
   */

  MOZ_STATIC_ASSERT(sizeof(a) == sizeof(uintptr_t),
                    "Strange pointer!");

  return detail::AddUintptrToHash<sizeof(uintptr_t)>(hash, uintptr_t(a));
}

template<>
MOZ_WARN_UNUSED_RESULT
inline uint32_t
AddToHash(uint32_t hash, uintptr_t a)
{
  return detail::AddUintptrToHash<sizeof(uintptr_t)>(hash, a);
}

template<typename A, typename B>
MOZ_WARN_UNUSED_RESULT
uint32_t
AddToHash(uint32_t hash, A a, B b)
{
  return AddToHash(AddToHash(hash, a), b);
}

template<typename A, typename B, typename C>
MOZ_WARN_UNUSED_RESULT
uint32_t
AddToHash(uint32_t hash, A a, B b, C c)
{
  return AddToHash(AddToHash(hash, a, b), c);
}

template<typename A, typename B, typename C, typename D>
MOZ_WARN_UNUSED_RESULT
uint32_t
AddToHash(uint32_t hash, A a, B b, C c, D d)
{
  return AddToHash(AddToHash(hash, a, b, c), d);
}

template<typename A, typename B, typename C, typename D, typename E>
MOZ_WARN_UNUSED_RESULT
uint32_t
AddToHash(uint32_t hash, A a, B b, C c, D d, E e)
{
  return AddToHash(AddToHash(hash, a, b, c, d), e);
}

/**
 * The HashGeneric class of functions let you hash one or more values.
 *
 * If you want to hash together two values x and y, calling HashGeneric(x, y) is
 * much better than calling AddToHash(x, y), because AddToHash(x, y) assumes
 * that x has already been hashed.
 */
template<typename A>
MOZ_WARN_UNUSED_RESULT
inline uint32_t
HashGeneric(A a)
{
  return AddToHash(0, a);
}

template<typename A, typename B>
MOZ_WARN_UNUSED_RESULT
inline uint32_t
HashGeneric(A a, B b)
{
  return AddToHash(0, a, b);
}

template<typename A, typename B, typename C>
MOZ_WARN_UNUSED_RESULT
inline uint32_t
HashGeneric(A a, B b, C c)
{
  return AddToHash(0, a, b, c);
}

template<typename A, typename B, typename C, typename D>
MOZ_WARN_UNUSED_RESULT
inline uint32_t
HashGeneric(A a, B b, C c, D d)
{
  return AddToHash(0, a, b, c, d);
}

template<typename A, typename B, typename C, typename D, typename E>
MOZ_WARN_UNUSED_RESULT
inline uint32_t
HashGeneric(A a, B b, C c, D d, E e)
{
  return AddToHash(0, a, b, c, d, e);
}

namespace detail {

template<typename T>
uint32_t
HashUntilZero(const T* str)
{
  uint32_t hash = 0;
  for (T c; (c = *str); str++)
    hash = AddToHash(hash, c);
  return hash;
}

template<typename T>
uint32_t
HashKnownLength(const T* str, size_t length)
{
  uint32_t hash = 0;
  for (size_t i = 0; i < length; i++)
    hash = AddToHash(hash, str[i]);
  return hash;
}

} /* namespace detail */

/**
 * The HashString overloads below do just what you'd expect.
 *
 * If you have the string's length, you might as well call the overload which
 * includes the length.  It may be marginally faster.
 */
MOZ_WARN_UNUSED_RESULT
inline uint32_t
HashString(const char* str)
{
  return detail::HashUntilZero(str);
}

MOZ_WARN_UNUSED_RESULT
inline uint32_t
HashString(const char* str, size_t length)
{
  return detail::HashKnownLength(str, length);
}

MOZ_WARN_UNUSED_RESULT
inline uint32_t
HashString(const uint16_t* str)
{
  return detail::HashUntilZero(str);
}

MOZ_WARN_UNUSED_RESULT
inline uint32_t
HashString(const uint16_t* str, size_t length)
{
  return detail::HashKnownLength(str, length);
}

/*
 * On Windows, wchar_t (PRUnichar) is not the same as uint16_t, even though it's
 * the same width!
 */
#ifdef WIN32
MOZ_WARN_UNUSED_RESULT
inline uint32_t
HashString(const wchar_t* str)
{
  return detail::HashUntilZero(str);
}

MOZ_WARN_UNUSED_RESULT
inline uint32_t
HashString(const wchar_t* str, size_t length)
{
  return detail::HashKnownLength(str, length);
}
#endif

/**
 * Hash some number of bytes.
 *
 * This hash walks word-by-word, rather than byte-by-byte, so you won't get the
 * same result out of HashBytes as you would out of HashString.
 */
MOZ_WARN_UNUSED_RESULT
extern MFBT_API uint32_t
HashBytes(const void* bytes, size_t length);

} /* namespace mozilla */
#endif /* __cplusplus */
#endif /* mozilla_HashFunctions_h_ */


text:
ENV['RACK_ENV'] = 'test'
ENV['logger_path'] = 'tmp/sewc-test.log'

require 'rack/test'
require 'json'
require 'rspec'
require 'rspec/given'
require 'factory_girl'
require './sendgrid_event_webhook_collector'

ActiveRecord::Base.logger = Logger.new(STDOUT)

class AppPath
  module Test
    def self.fixture
      AppPath.root.join('spec', 'fixtures')
    end

    def self.support
      AppPath.root.join('spec', 'support')
    end
  end
end

require AppPath::Test.support.join('json_fixture')
require AppPath::Test.support.join('null_logger')

module Rack
  module Test
    module Methods
      def build_rack_mock_session
        Rack::MockSession.new(app, 'api.myapp.com')
      end
    end
  end
end

API.logger = NullLogger.new
FactoryGirl.find_definitions

RSpec.configure do |config|
  config.expect_with :rspec do |expectations|
    expectations.include_chain_clauses_in_custom_matcher_descriptions = true
  end

  config.mock_with :rspec do |mocks|
    mocks.verify_partial_doubles = true
  end

  config.filter_run :focus
  config.run_all_when_everything_filtered = true
  #config.warnings = true
  config.order = :random # Run specs in random order
  config.include FactoryGirl::Syntax::Methods
end

def app
  API
end

def json_response
  begin
    JSON.parse(last_response.body)
  rescue JSON::ParserError
    raise "response body should be JSON but it's not"
  end
end

def event_url(uid)
  "http://api.myapp.com/v1/events/#{uid}"
end


text:
[![Build Status](https://travis-ci.org/adkron/grovepi.svg?branch=master)](https://travis-ci.org/adkron/grovepi)

Use the [GrovePi+][dexter] and sensors in Elixir on a Raspberry Pi. If you have
a Beaglebone Green or other port that has direct access to sensors (rather than
going through a GrovePi+), take a look at [nerves_grove][nerves_grove].

## Installation

If [available in Hex](https://hex.pm/docs/publish), the package can be installed
by adding `grovepi` to your list of dependencies in `mix.exs`:

```elixir
def deps do
  [{:grovepi, "~> 0.5.1"}]
end
```

The `grovepi` library uses [Elixir Circuits - I2C][circuits_i2c] for I2C communication to the
GrovePi+. This only works on Raspberry Pi computers. If you're working on
another platform, a stub is available for debugging and testing. When building
`grovepi` standalone, be aware that `circuits_i2c` is only used for `MIX_ENV=prod`
builds. To use the stub in your own programs, add the following to your
configuration:

```elixir
  config :grovepi, :i2c, GrovePi.I2C
```

## API Documentation

See the generated documentation at [hexdocs.pm/grovepi][docs].

# Contributions

We welcome contributions to tackle issues in GrovePi.

## Setup

First fork the repository and fetch your own copy

```bash
mix deps.get
mix test
```

## Submitting a Pull Request

1. [Fork the repository.][fork]
2. [Create a topic branch.][branch]
3. Add tests for your unimplemented feature or bug fix.
4. Run `mix test`. If your tests pass, return to step 3.
5. Implement your feature or bug fix.
6. Run `mix test`. If your tests fail, return to step 5.
7. Commit, and push your changes.
8. [Submit a pull request.][pr]

## Running Tests

All tests can be run with `mix test` or a single test file can be run
with `mix test path/to/file_test.exs`.

If you would like tests to run in the background as you change files you
can run `mix test.watch`.

[dexter]: https://www.dexterindustries.com/grovepi/
[nerves_grove]: https://github.com/bendiken/nerves_grove/
[circuits_i2c]: https://hex.pm/packages/circuits_i2c
[docs]: https://hexdocs.pm/grovepi
[fork]: https://help.github.com/fork-a-repo/
[branch]: https://help.github.com/articles/creating-and-deleting-branches-within-your-repository/
[pr]: https://help.github.com/articles/creating-a-pull-request/


text:
angular.module("luzenly").directive("lzyContentUploadSelector", ['lzyPostService',
       function(lzyPostService) {
		return {
			replace : "E",
			scope : {
				type : "=",
				title : "=",
				url : "=",
				textEntry : "="
			},
			templateUrl : "/templates/lzyContentUploadSelector.html",
			link : function($scope, $element, $attrs) {
				$scope.onTypeChange = function() {
					$scope.title = "";
					$scope.url = "";
					$scope.textEntry = "";
				};

				$scope.submitButtonClick = function() {
					lzyPostService.createPost($scope.title,
							$scope.url, $scope.type.toUpperCase()
									.charAt(0), $scope.textEntry || '',
							function(response) {
								console.log("success");
							}, function(error) {
								console.log("error");
							});
				};

			}
		}
	}]);


text:
<!DOCTYPE html>

    <title>Etiquette</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <link rel="icon" href="/favicon.png" type="image/png"/>
    <link rel="stylesheet" href="/static/css/common.css">
    <link rel="stylesheet" href="/static/css/etiquette.css">
    {% if theme %}<link rel="stylesheet" href="/static/css/theme_{{theme}}.css">{% endif %}

        {%- if motd is string -%}
        {{motd}}
        {%- elif motd[0] == "html" -%}
        {{motd[1]|safe}}
        {%- else -%}
        {{motd[1]}}
        {%- endif -%}

    Search
    Browse tags
    Browse albums
    Bookmarks
    {% if session.user %}
    {{session.user.display_name}}
    {% else %}
    Log in
    {% endif %}

        Turquoise
        Slate
        Pearl

        GitHub
        GitLab
        Codeberg


text:
table.t1 {width: 100%;border-collapse:collapse;}
a.wt{color: white;}
a.wt:link{color: white;}
a.wt:visited {color: white;}
a.wt:hover {color: #0000FF;}
p.headp1 {font-family: Calibri, Arial, Helvetica, sans-serif; margin:0;color:white;font-size:50px}
p.headp2 {font-family: Calibri, Arial, Helvetica, sans-serif; margin:0;color:white;font-size:20px}
td.tdhead1 {padding-left:0px;}
td.head3 {color:white;border-style: none;font-size:14px;font-family: Arial, Helvetica, sans-serif;text-align: right;vertical-align: top;}
td.head4 {width: 30px;border-style: none;}
#head a {text-decoration: none; color: white;}
#head a:link{text-decoration: none; color: white;}
#head a:visited {text-decoration: none; color: white;}
#head a:hover {text-decoration: none; color: #0000FF;}


text:
/**
 * Base classes for objects that map to StackMob data. Subclass {@link StackMobModel} or {@link StackMobUser} to create
 * objects that know how to synchronize themselves with the cloud. This creates a very powerful abstraction where you
 * can use data objects throughout your application and save them without worrying about the details of serialization and network
 * interaction.
 * @see StackMobModel
 * @see StackMobUser
 */
package com.stackmob.sdk.model;


text:
.. _basic_usage:

===========
Basic Usage
===========

Connection Handling
===================

To begin using Kazoo, a :class:`~kazoo.client.KazooClient` object must be
created and a connection established:

.. code-block:: python

    from kazoo.client import KazooClient

    zk = KazooClient(hosts='127.0.0.1:2181')
    zk.start()

By default, the client will connect to a local Zookeeper server on the default
port (2181). You should make sure Zookeeper is actually running there first,
or the ``start`` command will be waiting until its default timeout.

Once connected, the client will attempt to stay connected regardless of
intermittent connection loss or Zookeeper session expiration. The client can be
instructed to drop a connection by calling `stop`:

.. code-block:: python

    zk.stop()

Logging Setup
-------------

If logging is not setup for your application, you can get following message:

.. code-block:: python

    No handlers could be found for logger "kazoo.client"

To avoid this issue you can at the very minimum do the following:

.. code-block:: python

    import logging
    logging.basicConfig()

Read `Python's logging tutorial <https://docs.python.org/howto/logging.html>`_
for more details.

Listening for Connection Events
-------------------------------

It can be useful to know when the connection has been dropped, restored, or
when the Zookeeper session has expired. To simplify this process Kazoo uses a
state system and lets you register listener functions to be called when the
state changes.

.. code-block:: python

    from kazoo.client import KazooState

    def my_listener(state):
        if state == KazooState.LOST:
            # Register somewhere that the session was lost
        elif state == KazooState.SUSPENDED:
            # Handle being disconnected from Zookeeper
        else:
            # Handle being connected/reconnected to Zookeeper

    zk.add_listener(my_listener)

When using the :class:`kazoo.recipe.lock.Lock` or creating ephemeral nodes, its
highly recommended to add a state listener so that your program can properly
deal with connection interruptions or a Zookeeper session loss.

Understanding Kazoo States
--------------------------

The :class:`~kazoo.protocol.states.KazooState` object represents several states
the client transitions through. The current state of the client can always be
determined by viewing the :attr:`~kazoo.client.KazooClient.state` property. The
possible states are:

- LOST
- CONNECTED
- SUSPENDED

When a :class:`~kazoo.client.KazooClient` instance is first created, it is in
the `LOST` state. After a connection is established it transitions to the
`CONNECTED` state. If any connection issues come up or if it needs to connect
to a different Zookeeper cluster node, it will transition to `SUSPENDED` to let
you know that commands cannot currently be run. The connection will also be
lost if the Zookeeper node is no longer part of the quorum, resulting in a
`SUSPENDED` state.

Upon re-establishing a connection the client could transition to `LOST` if the
session has expired, or `CONNECTED` if the session is still valid.

.. note::

    These states should be monitored using a listener as described previously
    so that the client behaves properly depending on the state of the
    connection.

When a connection transitions to `SUSPENDED`, if the client is performing an
action that requires agreement with other systems (using the Lock recipe for
example), it should pause what it's doing. When the connection has been
re-established the client can continue depending on if the state is `LOST` or
transitions directly to `CONNECTED` again.

When a connection transitions to `LOST`, any ephemeral nodes that have been
created will be removed by Zookeeper. This affects all recipes that create
ephemeral nodes, such as the Lock recipe. Lock's will need to be re-acquired
after the state transitions to `CONNECTED` again. This transition occurs when
a session expires or when you stop the clients connection.

**Valid State Transitions**

- *LOST -> CONNECTED*

  New connection, or previously lost one becoming connected.
- *CONNECTED -> SUSPENDED*

  Connection loss to server occurred on a connection.
- *CONNECTED -> LOST*

  Only occurs if invalid authentication credentials are provided after the
  connection was established.
- *SUSPENDED -> LOST*

  Connection resumed to server, but then lost as the session was expired.
- *SUSPENDED -> CONNECTED*

  Connection that was lost has been restored.

Read-Only Connections
---------------------

.. versionadded:: 0.6

Zookeeper 3.4 and above `supports a read-only mode
<http://wiki.apache.org/hadoop/ZooKeeper/GSoCReadOnlyMode>`_. This mode
must be turned on for the servers in the Zookeeper cluster for the
client to utilize it. To use this mode with Kazoo, the
:class:`~kazoo.client.KazooClient` should be called with the
`read_only` option set to `True`. This will let the client connect to
a Zookeeper node that has gone read-only, and the client will continue
to scan for other nodes that are read-write.

.. code-block:: python

    from kazoo.client import KazooClient

    zk = KazooClient(hosts='127.0.0.1:2181', read_only=True)
    zk.start()

A new attribute on :class:`~kazoo.protocol.states.KeeperState` has been
added, `CONNECTED_RO`. The connection states above are still valid,
however upon `CONNECTED`, you will need to check the clients non-
simplified state to see if the connection is `CONNECTED_RO`. For
example:

.. code-block:: python

    from kazoo.client import KazooState
    from kazoo.client import KeeperState

    @zk.add_listener
    def watch_for_ro(state):
        if state == KazooState.CONNECTED:
            if zk.client_state == KeeperState.CONNECTED_RO:
                print("Read only mode!")
            else:
                print("Read/Write mode!")

It's important to note that a `KazooState` is passed in to the listener
but the read-only information is only available by comparing the
non-simplified client state to the `KeeperState` object.

.. warning::

    A client using read-only mode should not use any of the recipes.

Zookeeper CRUD
==============

Zookeeper includes several functions for creating, reading, updating, and
deleting Zookeeper nodes (called znodes or nodes here). Kazoo adds several
convenience methods and a more Pythonic API.

Creating Nodes
--------------

Methods:

* :meth:`~kazoo.client.KazooClient.ensure_path`
* :meth:`~kazoo.client.KazooClient.create`

:meth:`~kazoo.client.KazooClient.ensure_path` will recursively create the node
and any nodes in the path necessary along the way, but can not set the data for
the node, only the ACL.

:meth:`~kazoo.client.KazooClient.create` creates a node and can set the data on
the node along with a watch function. It requires the path to it to exist
first, unless the `makepath` option is set to `True`.

.. code-block:: python

    # Ensure a path, create if necessary
    zk.ensure_path("/my/favorite")

    # Create a node with data
    zk.create("/my/favorite/node", b"a value")

Reading Data
------------

Methods:

* :meth:`~kazoo.client.KazooClient.exists`
* :meth:`~kazoo.client.KazooClient.get`
* :meth:`~kazoo.client.KazooClient.get_children`

:meth:`~kazoo.client.KazooClient.exists` checks to see if a node exists.

:meth:`~kazoo.client.KazooClient.get` fetches the data of the node along with
detailed node information in a :class:`~kazoo.protocol.states.ZnodeStat`
structure.

:meth:`~kazoo.client.KazooClient.get_children` gets a list of the children of
a given node.

.. code-block:: python

    # Determine if a node exists
    if zk.exists("/my/favorite"):
        # Do something

    # Print the version of a node and its data
    data, stat = zk.get("/my/favorite")
    print("Version: %s, data: %s" % (stat.version, data.decode("utf-8")))

    # List the children
    children = zk.get_children("/my/favorite")
    print("There are %s children with names %s" % (len(children), children))

Updating Data
-------------

Methods:

* :meth:`~kazoo.client.KazooClient.set`

:meth:`~kazoo.client.KazooClient.set` updates the data for a given node. A
version for the node can be supplied, which will be required to match before
updating the data, or a :exc:`~kazoo.exceptions.BadVersionError` will be
raised instead of updating.

.. code-block:: python

    zk.set("/my/favorite", b"some data")

Deleting Nodes
--------------

Methods:

* :meth:`~kazoo.client.KazooClient.delete`

:meth:`~kazoo.client.KazooClient.delete` deletes a node, and can optionally
recursively delete all children of the node as well. A version can be
supplied when deleting a node which will be required to match the version of
the node before deleting it or a :exc:`~kazoo.exceptions.BadVersionError`
will be raised instead of deleting.

.. code-block:: python

    zk.delete("/my/favorite/node", recursive=True)

.. _retrying_commands:

Retrying Commands
=================

Connections to Zookeeper may get interrupted if the Zookeeper server goes down
or becomes unreachable. By default, kazoo does not retry commands, so these
failures will result in an exception being raised. To assist with failures
kazoo comes with a :meth:`~kazoo.client.KazooClient.retry` helper that will
retry a function should one of the Zookeeper connection exceptions get raised.

Example:

.. code-block:: python

    result = zk.retry(zk.get, "/path/to/node")

Some commands may have unique behavior that doesn't warrant automatic retries
on a per command basis. For example, if one creates a node a connection might
be lost before the command returns successfully but the node actually got
created. This results in a :exc:`kazoo.exceptions.NodeExistsError` being
raised when it runs again. A similar unique situation arises when a node is
created with ephemeral and sequence options set,
`documented here on the Zookeeper site
<http://zookeeper.apache.org/doc/trunk/recipes.html#sc_recipes_errorHandlingNote>`_.

Since the :meth:`~kazoo.client.KazooClient.retry` method takes a function to
call and its arguments, a function that runs multiple Zookeeper commands could
be passed to it so that the entire function will be retried if the connection
is lost.

This snippet from the lock implementation shows how it uses retry to re-run the
function acquiring a lock, and checks to see if it was already created to
handle this condition:

.. code-block:: python

    # kazoo.recipe.lock snippet

    def acquire(self):
        """Acquire the mutex, blocking until it is obtained"""
        try:
            self.client.retry(self._inner_acquire)
            self.is_acquired = True
        except KazooException:
            # if we did ultimately fail, attempt to clean up
            self._best_effort_cleanup()
            self.cancelled = False
            raise

    def _inner_acquire(self):
        self.wake_event.clear()

        # make sure our election parent node exists
        if not self.assured_path:
            self.client.ensure_path(self.path)

        node = None
        if self.create_tried:
            node = self._find_node()
        else:
            self.create_tried = True

        if not node:
            node = self.client.create(self.create_path, self.data,
                ephemeral=True, sequence=True)
            # strip off path to node
            node = node[len(self.path) + 1:]

`create_tried` records whether it has tried to create the node already in the
event the connection is lost before the node name is returned.

Custom Retries
--------------

Sometimes you may wish to have specific retry policies for a command or
set of commands that differs from the
:meth:`~kazoo.client.KazooClient.retry` method. You can manually create
a :class:`~kazoo.retry.KazooRetry` instance with the specific retry
policy you prefer:

.. code-block:: python

    from kazoo.retry import KazooRetry

    kr = KazooRetry(max_tries=3, ignore_expire=False)
    result = kr(client.get, "/some/path")

This will retry the ``client.get`` command up to 3 times, and raise a
session expiration if it occurs. You can also make an instance with the
default behavior that ignores session expiration during a retry.

Watchers
========

Kazoo can set watch functions on a node that can be triggered either when the
node has changed or when the children of the node change. This change to the
node or children can also be the node or its children being deleted.

Watchers can be set in two different ways, the first is the style that
Zookeeper supports by default for one-time watch events. These watch functions
will be called once by kazoo, and do *not* receive session events, unlike the
native Zookeeper watches. Using this style requires the watch function to be
passed to one of these methods:

* :meth:`~kazoo.client.KazooClient.get`
* :meth:`~kazoo.client.KazooClient.get_children`
* :meth:`~kazoo.client.KazooClient.exists`

A watch function passed to :meth:`~kazoo.client.KazooClient.get` or
:meth:`~kazoo.client.KazooClient.exists` will be called when the data on the
node changes or the node itself is deleted. It will be passed a
:class:`~kazoo.protocol.states.WatchedEvent` instance.

.. code-block:: python

    def my_func(event):
        # check to see what the children are now

    # Call my_func when the children change
    children = zk.get_children("/my/favorite/node", watch=my_func)

Kazoo includes a higher level API that watches for data and children
modifications that's easier to use as it doesn't require re-setting the watch
every time the event is triggered. It also passes in the data and
:class:`~kazoo.protocol.states.ZnodeStat` when watching a node or the list of
children when watching a nodes children. Watch functions registered with this
API will be called immediately and every time there's a change, or until the
function returns False. If `allow_session_lost` is set to `True`, then the
function will no longer be called if the session is lost.

The following methods provide this functionality:

* :class:`~kazoo.recipe.watchers.ChildrenWatch`
* :class:`~kazoo.recipe.watchers.DataWatch`

These classes are available directly on the :class:`~kazoo.client.KazooClient`
instance and don't require the client object to be passed in when used in this
manner. The instance returned by instantiating either of the classes can be
called directly allowing them to be used as decorators:

.. code-block:: python

    @zk.ChildrenWatch("/my/favorite/node")
    def watch_children(children):
        print("Children are now: %s" % children)
    # Above function called immediately, and from then on

    @zk.DataWatch("/my/favorite")
    def watch_node(data, stat):
        print("Version: %s, data: %s" % (stat.version, data.decode("utf-8")))

Transactions
============

.. versionadded:: 0.6

Zookeeper 3.4 and above supports the sending of multiple commands at
once that will be committed as a single atomic unit. Either they will
all succeed or they will all fail. The result of a transaction will be
a list of the success/failure results for each command in the
transaction.

.. code-block:: python

    transaction = zk.transaction()
    transaction.check('/node/a', version=3)
    transaction.create('/node/b', b"a value")
    results = transaction.commit()

The :meth:`~kazoo.client.KazooClient.transaction` method returns a
:class:`~kazoo.client.TransactionRequest` instance. It's methods may be
called to queue commands to be completed in the transaction. When the
transaction is ready to be sent, the
:meth:`~kazoo.client.TransactionRequest.commit` method on it is called.

In the example above, there's a command not available unless a
transaction is being used, `check`. This can check nodes for a specific
version, which could be used to make the transaction fail if a node
doesn't match a version that it should be at. In this case the node
`/node/a` must be at version 3 or `/node/b` will not be created.


text:
import Base

class System:
  def __init__(self, conn, id, name, pos):
    self.conn = conn
    self.name = name
    self.pos = pos
    self.id = id

  def getPosition(self):
    return self.pos

  def getName(self):
    return self.name

  def getId(self):
    return self.id

  def getStations(self):
    return self.conn.getBasesOfSystem(self.id)

  def addStation(self, name, distance):
    baseData = [{"name" : name,
                "distance" : distance,
                "systemId" : self.id}]

    self.conn.importBases(baseData)
    base = [i for i in self.getStations() if i.getName() == name][0]

    baseInfo = [{
      "id" : base.getId(),
      "blackMarket" : False,
      "landingPadSize" : 2
    }]
    self.conn.importBaseInfos(baseInfo)

  def __str__(self):
    return self.__repr__()

  def __repr__(self):
    return "System(id = {0}, name = \"{1}\", pos = {2})".format(self.id, self.name, self.pos)


text:
A simple countdown made to experiment with elm. [DEMO](https://daspinola.github.io/elm-countdown/)

# Install

1. Download elm [elm](https://guide.elm-lang.org/install.html)

2. Clone this repo with

    ``` git clone https://github.com/daspinola/elm-countdown.git ```

3. To run the local server

    ``` elm-reactor ```

4. To export the elm file to HTML or JS

    ``` elm-make main.elm --output="index.html" ```

# License

[MIT Licence](./LICENSE)


text:
package com.taobao.weex.ui.component;

import com.taobao.weex.WXSDKInstance;
import com.taobao.weex.dom.WXDomObject;
import com.taobao.weex.ui.view.WXFrameLayout;

/**
 * div component
 */
public class WXDiv extends WXVContainer {

  public WXDiv(WXSDKInstance instance, WXDomObject node, WXVContainer parent, String instanceId, boolean lazy) {
    super(instance, node, parent, instanceId, lazy);
  }

  @Override
  protected void initView() {
    mHost = new WXFrameLayout(mContext);
  }

  @Override
  public WXFrameLayout getView() {
    return (WXFrameLayout) super.getView();
  }

}


text:
package com.simplealertdialog.test;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import java.util.List;

public class SweetsAdapter extends ArrayAdapter<Sweets> {

    public SweetsAdapter(Context context, List<Sweets> objects) {
        super(context, com.simplealertdialog.test.R.layout.list_item_support_sweets, com.simplealertdialog.test.R.id.id, objects);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view = super.getView(position, convertView, parent);
        Sweets s = getItem(position);
        ((TextView) view.findViewById(com.simplealertdialog.test.R.id.id)).setText(s.id);
        ((TextView) view.findViewById(com.simplealertdialog.test.R.id.name)).setText(s.name);
        return view;
    }

}


text:
package org.kuali.rice.core.api;

/**
 * This class contains constants used by the core module. They are public to all and both clients
 * and other rice modules are allowed to use them.
 *
 * @author Kuali Rice Team (rice.collab@kuali.org)
 *
 */
public final class CoreConstants {

    public static final class Services {
        public static final String DATETIME_SERVICE = "dateTimeService";
        public static final String ENCRYPTION_SERVICE = "encryptionService";
        public static final String MAILER = "mailer";

        private Services() {
    		throw new UnsupportedOperationException("do not call");
    	}
	}

    public final static String SERVICE_PATH_SOAP = "soap/" + Namespaces.MODULE_NAME + "/" + Versions.VERSION_2_0;

    public static final class Versions {

    	public static final String UNSPECIFIED = "unspecifiedVersion";

    	/**
    	 * Name for major version 2.0 of Kuali Rice which should be used in XML namespaces for data elements compatible with Kuali Rice 2.0.x.
    	 * This constant value should never be changed!  If it is changed then it will break compatibility with legacy clients.
    	 */
    	public static final String VERSION_2_0 = "v2_0";

        /**
         *  Name for complete version 2.1.2 of Kuali Rice which is used to compare against the version of callback services to ensure
         *  that backwards compatibility is not broken
         */
        public static final String VERSION_2_1_2 = "2.1.2";

    }

    public static final class Namespaces {
    	public static final String ROOT_NAMESPACE_PREFIX = "http://rice.kuali.org";
        public static final String MODULE_NAME = "core";
        public static final String CORE_NAMESPACE_PREFIX = CoreConstants.Namespaces.ROOT_NAMESPACE_PREFIX + "/" + MODULE_NAME;

        public static final String UNSPECIFIED = "unspecifiedNamespace";

    	/**
    	 * Namespace for the core module which is compatible with Kuali Rice 2.0.x.
    	 */
    	public static final String CORE_NAMESPACE_2_0 = CORE_NAMESPACE_PREFIX + "/" + Versions.VERSION_2_0;

        private Namespaces() {
		    throw new UnsupportedOperationException("do not call");
	    }
    }

    public static final String CORE_SERVICE_DISTRIBUTED_CACHE = "coreServiceDistributedCacheManager";

    public static final class CommonElements {
        public static final String FUTURE_ELEMENTS = "_futureElements";
        public static final String VERSION_NUMBER = "versionNumber";
        public static final String OBJECT_ID = "objectId";
        public static final String ACTIVE = "active";
        public static final String ACTIVE_FROM_DATE = "activeFromDate";
        public static final String ACTIVE_TO_DATE = "activeToDate";
        public static final String ATTRIBUTES = "attributes";

        private CommonElements() {
		    throw new UnsupportedOperationException("do not call");
	    }
    }

	public static final String STRING_TO_DATE_FORMATS = "STRING_TO_DATE_FORMATS";
    public static final String STRING_TO_TIMESTAMP_FORMATS = "STRING_TO_TIMESTAMP_FORMATS";
    public static final String DATE_TO_STRING_FORMAT_FOR_USER_INTERFACE = "DATE_TO_STRING_FORMAT_FOR_USER_INTERFACE";
    public static final String TIMESTAMP_TO_STRING_FORMAT_FOR_USER_INTERFACE = "TIMESTAMP_TO_STRING_FORMAT_FOR_USER_INTERFACE";
    public static final String DATE_TO_STRING_FORMAT_FOR_FILE_NAME = "DATE_TO_STRING_FORMAT_FOR_FILE_NAME";
    public static final String TIMESTAMP_TO_STRING_FORMAT_FOR_FILE_NAME = "TIMESTAMP_TO_STRING_FORMAT_FOR_FILE_NAME";

    public static final String DATA_TYPE_STRING = "string";
    public static final String DATA_TYPE_DATE = "datetime";
    public static final String DATA_TYPE_LONG = "long";
    public static final String DATA_TYPE_FLOAT = "float";
    public static final String DATA_TYPE_BOOLEAN = "boolean";
    public static final String EMPTY_STRING = "";

    public static final class Config {
    	public static final String APPLICATION_ID = "application.id";
        //FIXME: this should be a core config property
        public static final String INSTANCE_ID = "rice.ksb.bus.instanceId";
    }

	private CoreConstants() {
		throw new UnsupportedOperationException("do not call");
	}
}


text:
package org.apache.camel.component.websocket;

import org.apache.camel.Consumer;
import org.apache.camel.Processor;
import org.apache.camel.Producer;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.InOrder;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.times;

@RunWith(MockitoJUnitRunner.class)
public class WebsocketEndpointTest {

    private static final String REMAINING = "foo/bar";
    private static final String URI = "websocket://" + REMAINING;

    @Mock
    private WebsocketComponent component;

    @Mock
    private Processor processor;

    private WebsocketEndpoint websocketEndpoint;

    @Before
    public void setUp() throws Exception {
        websocketEndpoint = new WebsocketEndpoint(component, URI, REMAINING, null);
        component = new WebsocketComponent();
        component.setPort(1988);
        component.setHost("localhost");
        component.createServer();
    }

    /**
     * Test method for {@link org.apache.camel.component.websocket.WebsocketEndpoint#createConsumer(org.apache.camel.Processor)} .
     */
    @Test
    public void testCreateConsumer() throws Exception {
        Consumer consumer = websocketEndpoint.createConsumer(processor);
        component.connect((WebsocketProducerConsumer) consumer);

        assertNotNull(consumer);
        assertEquals(WebsocketConsumer.class, consumer.getClass());
        InOrder inOrder = inOrder(component, processor);
        ArgumentCaptor<NodeSynchronization> synchronizationCaptor = ArgumentCaptor.forClass(NodeSynchronization.class);
        ArgumentCaptor<WebsocketConsumer> consumerCaptor = ArgumentCaptor.forClass(WebsocketConsumer.class);
        inOrder.verify(component, times(1)).addServlet(synchronizationCaptor.capture(), consumerCaptor.capture(), eq(REMAINING));
        inOrder.verifyNoMoreInteractions();

        assertEquals(DefaultNodeSynchronization.class, synchronizationCaptor.getValue().getClass());

        assertEquals(consumer, consumerCaptor.getValue());
    }

    /**
     * Test method for {@link org.apache.camel.component.websocket.WebsocketEndpoint#createProducer()} .
     */
    @Test
    public void testCreateProducer() throws Exception {
        Producer producer = websocketEndpoint.createProducer();
        component.connect((WebsocketProducerConsumer) producer);

        assertNotNull(producer);
        assertEquals(WebsocketProducer.class, producer.getClass());
        InOrder inOrder = inOrder(component, processor);
        ArgumentCaptor<NodeSynchronization> synchronizationCaptor = ArgumentCaptor.forClass(NodeSynchronization.class);
        inOrder.verify(component, times(1)).addServlet(synchronizationCaptor.capture(), (WebsocketConsumer) isNull(), eq(REMAINING));
        inOrder.verifyNoMoreInteractions();

        assertEquals(DefaultNodeSynchronization.class, synchronizationCaptor.getValue().getClass());
    }

    /**
     * Test method for {@link org.apache.camel.component.websocket.WebsocketEndpoint#isSingleton()} .
     */
    @Test
    public void testIsSingleton() {
        assertTrue(websocketEndpoint.isSingleton());
    }
}


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

import java.io.Serializable;
import java.util.Objects;

import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;

import org.ovirt.engine.core.common.businessentities.network.VmNic;
import org.ovirt.engine.core.common.utils.MacAddressValidationPatterns;
import org.ovirt.engine.core.compat.Guid;

public class MacRange implements Serializable {
    private static final long serialVersionUID = 5706298268467442698L;

    private Guid macPoolId;

    @Pattern(regexp = MacAddressValidationPatterns.VALID_MAC_ADDRESS_FORMAT,
            message = VmNic.VALIDATION_MESSAGE_MAC_ADDRESS_INVALID)
    @NotNull(message= "VALIDATION.VM.NETWORK.MAC.ADDRESS.NOT_NULL")
    private String macFrom;

    @Pattern(regexp = MacAddressValidationPatterns.VALID_MAC_ADDRESS_FORMAT,
            message = VmNic.VALIDATION_MESSAGE_MAC_ADDRESS_INVALID)
    @NotNull(message = "VALIDATION.VM.NETWORK.MAC.ADDRESS.NOT_NULL")
    private String macTo;

    public String getMacFrom() {
        return macFrom;
    }

    public void setMacFrom(String macFrom) {
        this.macFrom = macFrom;
    }

    public String getMacTo() {
        return macTo;
    }

    public void setMacTo(String macTo) {
        this.macTo = macTo;
    }

    public Guid getMacPoolId() {
        return macPoolId;
    }

    public void setMacPoolId(Guid macPoolId) {
        this.macPoolId = macPoolId;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (!(obj instanceof MacRange)) {
            return false;
        }
        MacRange other = (MacRange) obj;
        return Objects.equals(macFrom, other.macFrom)
                && Objects.equals(macPoolId, other.macPoolId)
                && Objects.equals(macTo, other.macTo);
    }

    @Override
    public int hashCode() {
        return Objects.hash(
                macFrom,
                macPoolId,
                macTo
        );
    }
}


text:
import launchkey
from . import mockito
from six.moves.urllib.parse import parse_qs
from twisted.internet import defer
from twisted.internet.defer import Deferred
from twisted.python.failure import Failure
from twisted.web.http_headers import Headers
from launchkey_twisted.twisted_api import JSONResponseBodyParser, JSONToURLEncodedFormDataBodyProducer, \
    RequestError
from .api_test_base import TwistedAPITestBase

class TwistedAPIAuthorizeTest(TwistedAPITestBase):
    """
    Tests for API authorize

    All tests that check final result will have to process two instances of callback as the first call
    will return a deferred that is waiting on the it's response, a deferred, to be called by the response body
    processor
    """

    def setUp(self):
        super(TwistedAPIAuthorizeTest, self).setUp()
        self._lk_public_key = 'Expected Public Key'
        self._lk_time = '2015-01-01 00:00:00'
        mockito.when(self._api).ping() \
            .thenReturn(defer.succeed({'key': self._lk_public_key, 'launchkey_time': self._lk_time}))

    def test_calls_request_with_post_method(self):
        self._api.authorize('Expected Username')
        mockito.verify(self._agent).request('POST', mockito.any(), mockito.any(), mockito.any())

    def test_calls_request_with_proper_uri(self):
        self._api.authorize('Expected Username')
        expected = '{0}/{1}/auths'.format(self._api_host, self._version)
        mockito.verify(self._agent).request(mockito.any(), expected, mockito.any(), mockito.any())

    def test_calls_request_with_correct_headers(self):
        expected = Headers({
            'User-Agent': ['LaunchKey Twisted Client'],
            'Accept-Type': ['application/json'],
            'Content-Type': ['application/x-www-form-urlencoded']
        })
        self._api.authorize('Expected Username')
        mockito.verify(self._agent).request(mockito.any(), mockito.any(), expected, mockito.any())

    def test_calls_request_with_form_data_producer(self):
        self._api.authorize('Expected Username')
        mockito.verify(self._agent) \
            .request(mockito.any(), mockito.any(), mockito.any(), mockito.any(JSONToURLEncodedFormDataBodyProducer))

    def test_signs_data_for_secret_key(self):
        self._api.authorize('Expected Username')
        mockito.verify(launchkey).sign_data(mockito.any(), mockito.any())

    def test_encrypts_with_lk_public_key_for_secret_key(self):
        self._api.authorize('Expected Username')
        mockito.verify(launchkey).encrypt_RSA(self._lk_public_key, mockito.any())

    def test_encrypts_correct_data_for_secret_key(self):
        self._api.authorize('Expected Username')
        expected = str({'secret': self._app_secret, 'stamped': self._lk_time})
        actual = mockito.getCallArgument(launchkey, 'encrypt_RSA', 2)
        self.assertEquals(actual, expected)

    def test_signs_encrypted_data_with_private_key_for_secret_key(self):
        self._api.authorize('Expected Username')
        mockito.verify(launchkey).sign_data(self._private_key, mockito.any())

    def test_signs_encrypted_data_for_secret_key(self):
        self._api.authorize('Expected Username')
        mockito.verify(launchkey).sign_data(mockito.any(), self._rsa_encrypted)

    def test_calls_request_with_correct_form_data(self):
        self._api.authorize('Expected Username', 'Expected Session Value', 'Expected User Push ID Value')
        expected = JSONToURLEncodedFormDataBodyProducer({
            'username': 'Expected Username',
            'user_push_id': 'Expected User Push ID Value',
            'app_key': 'Expected Rocket Key',
            'session': 'Expected Session Value',
            'signature': 'Base64 Encoded RSA Signed Value',
            'secret_key': 'RSA Encrypted Value'
        })
        actual = mockito.getCallArgument(self._agent, 'request', 4)
        self.assertEquals(parse_qs(actual.body), parse_qs(expected.body))

    def test_calls_request_with_context_in_form_data_if_priovided(self):
        self._api.authorize('Expected Username',
                            'Expected Session Value',
                            'Expected User Push ID Value',
                            'Expected Context')
        expected = JSONToURLEncodedFormDataBodyProducer({
            'username': 'Expected Username',
            'user_push_id': 'Expected User Push ID Value',
            'app_key': 'Expected Rocket Key',
            'session': 'Expected Session Value',
            'signature': 'Base64 Encoded RSA Signed Value',
            'secret_key': 'RSA Encrypted Value',
            'context': 'Expected Context'
        })
        actual = mockito.getCallArgument(self._agent, 'request', 4)
        self.assertEquals(parse_qs(actual.body), parse_qs(expected.body))

    def test_returns_correct_failure_for_non_json_response(self):
        self._response.headers = Headers({'content-type': ['text/html']})
        deferred = self._api.authorize('Expected Username')
        self._agent_request_deferred.callback(self._response)
        self.assertIsInstance(deferred.result, Failure,
                              'Unexpected Deferred result.  Expected {0} but was {1}'.format(
                                  Failure.__name__, deferred.result.__class__.__name__))
        self.assertIsInstance(deferred.result.value, Exception,
                              'Unexpected Failure value.  Expected Expected {0} but was {1}'.format(
                                  Exception.__name__, deferred.result.value.__class__.__name__))
        self.assertEqual(str(deferred.result.value), 'Non JSON response from API received')

    def test_returns_correct_failure_for_no_auth_request_response(self):
        deferred = self._api.authorize('Expected Username')
        self._agent_request_deferred.callback(self._response)
        self._agent_request_deferred.result.callback({})
        self.assertIsInstance(deferred.result, Failure,
                              'Unexpected Deferred result.  Expected {0} but was {1}'.format(
                                  Failure.__name__, deferred.result.__class__.__name__))
        self.assertIsInstance(deferred.result.value, RequestError,
                              'Unexpected Failure value.  Expected {0} but was {1}'.format(
                                  RequestError.__name__, deferred.result.value.__class__.__name__))
        self.assertEqual(str(deferred.result.value), '[0] Invalid Response - No auth_request value in response')

    def test_response_has_deferred_result_before_data_is_written(self):
        deferred = self._api.authorize('Expected Username')
        self._agent_request_deferred.callback(self._response)
        self.assertIsInstance(deferred.result, Deferred)

    def test_response_had_deliver_body_called_with_json_body_response_parser(self):
        self._api.authorize('Expected Username')
        self._agent_request_deferred.callback(self._response)
        self._agent_request_deferred.result.callback({'auth_request': 'Expected Auth Request ID'})
        mockito.verify(self._response).deliverBody(mockito.any(JSONResponseBodyParser))

    def test_response_callback_value_is_not_failure_when_error_not_returned_in_response(self):
        deferred = self._api.authorize('Expected Username')
        self._agent_request_deferred.callback(self._response)
        self._agent_request_deferred.result.callback({'auth_request': 'Expected Auth Request ID'})
        self.assertNotIsInstance(deferred.result, Failure)

    def test_response_callback_value_is_failure_when_error_is_returned_in_response(self):
        deferred = self._api.authorize('Expected Username')
        self._agent_request_deferred.callback(self._response)
        self._agent_request_deferred.result.callback({'status_code': 500})
        self.assertIsInstance(deferred.result, Failure)

    def test_final_value_is_body_parsed_value(self):
        expected = 'Expected Auth Request ID'
        deferred = self._api.authorize('Expected Username')
        self._agent_request_deferred.callback(self._response)
        self._agent_request_deferred.result.callback({'auth_request': expected})
        self.assertEquals(deferred.result, expected)


text:
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
using ParentLoad.DataAccess;
using ParentLoad.DataAccess.ERCLevel;

namespace ParentLoad.DataAccess.Sql.ERCLevel
{
    /// <summary>
    /// DAL SQL Server implementation of <see cref="IB05_SubContinent_ReChildDal"/>
    /// </summary>
    public partial class B05_SubContinent_ReChildDal : IB05_SubContinent_ReChildDal
    {
        /// <summary>
        /// Inserts a new B05_SubContinent_ReChild object in the database.
        /// </summary>
        /// <param name="subContinent_ID2">The parent Sub Continent ID2.</param>
        /// <param name="subContinent_Child_Name">The Sub Continent Child Name.</param>
        public void Insert(int subContinent_ID2, string subContinent_Child_Name)
        {
            using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
            {
                using (var cmd = new SqlCommand("AddB05_SubContinent_ReChild", ctx.Connection))
                {
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.AddWithValue("@SubContinent_ID2", subContinent_ID2).DbType = DbType.Int32;
                    cmd.Parameters.AddWithValue("@SubContinent_Child_Name", subContinent_Child_Name).DbType = DbType.String;
                    cmd.ExecuteNonQuery();
                }
            }
        }

        /// <summary>
        /// Updates in the database all changes made to the B05_SubContinent_ReChild object.
        /// </summary>
        /// <param name="subContinent_ID2">The parent Sub Continent ID2.</param>
        /// <param name="subContinent_Child_Name">The Sub Continent Child Name.</param>
        public void Update(int subContinent_ID2, string subContinent_Child_Name)
        {
            using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
            {
                using (var cmd = new SqlCommand("UpdateB05_SubContinent_ReChild", ctx.Connection))
                {
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.AddWithValue("@SubContinent_ID2", subContinent_ID2).DbType = DbType.Int32;
                    cmd.Parameters.AddWithValue("@SubContinent_Child_Name", subContinent_Child_Name).DbType = DbType.String;
                    var rowsAffected = cmd.ExecuteNonQuery();
                    if (rowsAffected == 0)
                        throw new DataNotFoundException("B05_SubContinent_ReChild");
                }
            }
        }

        /// <summary>
        /// Deletes the B05_SubContinent_ReChild object from database.
        /// </summary>
        /// <param name="subContinent_ID2">The parent Sub Continent ID2.</param>
        public void Delete(int subContinent_ID2)
        {
            using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
            {
                using (var cmd = new SqlCommand("DeleteB05_SubContinent_ReChild", ctx.Connection))
                {
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.AddWithValue("@SubContinent_ID2", subContinent_ID2).DbType = DbType.Int32;
                    cmd.ExecuteNonQuery();
                }
            }
        }
    }
}


text:
module Gatehouse
  # Base class for Gatehouse error/exception classes.
  class Error < StandardError; end
end


text:
:- ensure_loaded('$REGULUS/PrologLib/compatibility').

%---------------------------------------------------------------

:- module(make_verb_transforms,
	  [make_verb_transforms/2,
	   make_inverse_verb_transforms/2,
	   make_indicative_verb_list/2,
	   make_verb_taking_subjunctive_list/2,
	   test_make_verb_transforms/1
	   ]
      ).

%---------------------------------------------------------------

:- use_module('$REGULUS/PrologLib/utilities').

:- use_module(library(lists)).

%---------------------------------------------------------------

test_make_verb_transforms(transforms) :-
	make_verb_transforms('$ACCEPT/MT/Europarl/Mmorph/verbs.pl',
			     '$ACCEPT/MT/Europarl/Mmorph/verb_transforms.pl').

test_make_verb_transforms(transforms_faire) :-
	make_verb_transforms('$ACCEPT/MT/Europarl/Mmorph/verbs_faire.pl',
			     '$ACCEPT/MT/Europarl/Mmorph/verb_transforms_faire.pl').

test_make_verb_transforms(inverse_transforms) :-
	make_inverse_verb_transforms('$ACCEPT/MT/Europarl/Mmorph/verb_transforms.pl',
				     '$ACCEPT/MT/Europarl/Mmorph/verb_transforms_2sing_to_2pl.pl').

test_make_verb_transforms(verbs) :-
	make_verb_list('$ACCEPT/MT/Europarl/Mmorph/verbs.pl',
		       '$ACCEPT/MT/Europarl/Mmorph/verbs_with_mood.pl').

test_make_verb_transforms(verbs_taking_subjunctive) :-
	make_verb_taking_subjunctive_list('$ACCEPT/MT/Europarl/Mmorph/verbs.pl',
					  '$ACCEPT/MT/Europarl/Mmorph/verbs_taking_subjunctive.pl').

test_make_verb_transforms(indicative_verbs1) :-
	make_indicative_verb_list1('$ACCEPT/MT/Europarl/Mmorph/verbs.pl',
				   '$ACCEPT/MT/Europarl/Mmorph/verbs_with_mood.pl').

%---------------------------------------------------------------

make_verb_transforms(VerbFile, TransformFile) :-
	init_make_verb_transforms(VerbFile),
	make_verb_transforms1(TransformFile).

make_verb_transforms1(TransformFile) :-
	safe_absolute_file_name(TransformFile, AbsTransformFile),
	find_transforms(Transforms),
	write_out_transforms(Transforms, AbsTransformFile).

%---------------------------------------------------------------

make_inverse_verb_transforms(TransformFile, InverseTransformFile) :-
	safe_absolute_file_name(TransformFile, AbsTransformFile),
	safe_absolute_file_name(InverseTransformFile, AbsInverseTransformFile),

	safe_prolog_file_to_list_printing_statistics(AbsTransformFile, Transforms),

	invert_verb_transforms(Transforms, InverseTransforms0),
	sort(InverseTransforms0, InverseTransforms),

	length(InverseTransforms, NOut),
	list_to_prolog_file(InverseTransforms, AbsInverseTransformFile),

	format('~N--- Written file (~d items) ~w~n', [NOut, AbsInverseTransformFile]),
	!.

%---------------------------------------------------------------

make_verb_list(VerbFile, VerbListFile) :-
	init_make_verb_transforms(VerbFile),
	make_verb_list1(VerbListFile).

make_verb_list1(File) :-
	safe_absolute_file_name(File, AbsFile),
	find_verbs(Verbs),
	write_out_transforms(Verbs, AbsFile).

%---------------------------------------------------------------

make_verb_taking_subjunctive_list(VerbFile, VerbListFile) :-
	init_make_verb_transforms(VerbFile),
	make_verb_taking_subjunctive_list1(VerbListFile).

make_verb_taking_subjunctive_list1(File) :-
	safe_absolute_file_name(File, AbsFile),
	find_verbs_taking_subjunctive(Verbs),
	find_non_verbs_taking_subjunctive(NonVerbs),
	append(Verbs, NonVerbs, All),
	write_out_transforms(All, AbsFile).

%---------------------------------------------------------------

init_make_verb_transforms(VerbFile) :-
	safe_absolute_file_name(VerbFile, AbsVerbFile),
	format('~N--- Loading verb file: ~w~n', [AbsVerbFile]),
	compile(VerbFile).

%---------------------------------------------------------------

find_verbs(Transforms) :-
	findall(verb(Verb, Mode, Person, Number),
		(   mmorph_entry([surface=Verb, lemma=_Lemma, pos='Verb' | OtherFeats]),
		    member(mode=Modes, OtherFeats),
		    (   member(number=Numbers, OtherFeats) ->
			true
		    ;
			Numbers = [no_number]
		    ),
		    (   member(person=Persons, OtherFeats) ->
			true
		    ;
			Persons = [no_number]
		    ),
		    member(Mode, Modes),
		    member(Person, Persons),
		    member(Number, Numbers)
		),
		Transforms
	       ).

%---------------------------------------------------------------

find_verbs_taking_subjunctive(Transforms) :-
	findall(verb_taking_subjunctive(Verb),
		(   mmorph_entry([surface=Verb, lemma=Lemma, pos='Verb', (mode)=Modes,
				  tense=_Tenses, number=_Number, person=_Person | _OtherFeats]),
		    verb_taking_subjunctive(Lemma),
		    member(indicative, Modes)
		),
		Transforms
	       ).

find_non_verbs_taking_subjunctive(Transforms) :-
	findall(non_verb_taking_subjunctive(Word),
		non_verb_taking_subjunctive(Word),
		Transforms
	       ).

/*
aimer que
apprécier que
attendre que
consentir à ce que
défendre que
désirer que
douter que
être content que
être désolé que
être étonné que
être fâché que
être furieux que
être heureux que
être ravi que
être surpris que
être triste que
exiger que
il convient que
il est bon que
il est dommage que
il est douteux que
il est essentiel que
il est important que
il est impossible que
il est improbable que
il est juste que
il est nécessaire que
il est obligatoire que
il est peu probable que
il est rare que
il est possible que
il est préférable que
il est utile que
il est regrettable que
il est temps que
il semble que
il faut que
il ne faut pas que
interdire que
il suffit que
il vaut mieux que
recommander que
ordonner que
proposer que
s'opposer à ce que
refuser que
s'attendre à ce que
vouloir que
souhaiter que
tenir à ce que
*/

verb_taking_subjunctive(aimer).
verb_taking_subjunctive(apprécier).
verb_taking_subjunctive(attendre).
verb_taking_subjunctive(attendre).
verb_taking_subjunctive(consentir).
verb_taking_subjunctive(convient).
verb_taking_subjunctive(douter).
verb_taking_subjunctive(défendre).
verb_taking_subjunctive(désirer).
verb_taking_subjunctive(falloir).
verb_taking_subjunctive(faut).
verb_taking_subjunctive(interdire).
verb_taking_subjunctive(opposer).
verb_taking_subjunctive(ordonner).
verb_taking_subjunctive(proposer).
verb_taking_subjunctive(recommander).
verb_taking_subjunctive(refuser).
verb_taking_subjunctive(semble).
verb_taking_subjunctive(souhaiter).
verb_taking_subjunctive(suffire).
verb_taking_subjunctive(suffit).
verb_taking_subjunctive(tenir).
verb_taking_subjunctive(valoir).
verb_taking_subjunctive(vouloir).

non_verb_taking_subjunctive(bon).
non_verb_taking_subjunctive(dommage).
non_verb_taking_subjunctive(douteux).
non_verb_taking_subjunctive(essentiel).
non_verb_taking_subjunctive(important).
non_verb_taking_subjunctive(improbable).
non_verb_taking_subjunctive(juste).
non_verb_taking_subjunctive(nécessaire).
non_verb_taking_subjunctive(obligatoire).
non_verb_taking_subjunctive(probable).
non_verb_taking_subjunctive(rare).
non_verb_taking_subjunctive(possible).
non_verb_taking_subjunctive(préférable).
non_verb_taking_subjunctive(utile).
non_verb_taking_subjunctive(regrettable).
non_verb_taking_subjunctive(temps).

%---------------------------------------------------------------

find_transforms(Transforms) :-
	findall([surface=V2Plur, lemma=Lemma, (mode)=ModeP, tense=TenseP | OtherFeats],
		(   mmorph_entry([surface=V2Plur, lemma=Lemma, pos='Verb', (mode)=ModeP,
				  tense=TenseP, number=[plural], person=PersonP | OtherFeats]),
		    member('2', PersonP)
		),
		PluralTuples
	       ),
	length(PluralTuples, NPluralTuples),
	format('~N--- Found ~d 2nd person plural verbs~n', [NPluralTuples]),
	find_transforms1(PluralTuples, Transforms).

find_transforms1(PluralTuples, Transforms) :-
	find_transforms2(PluralTuples, TransformsForTuples, 0),
	append_list(TransformsForTuples, Transforms),
	length(Transforms, NTransforms),
	format('~N--- Found ~d 2nd person plural to singular transforms~n', [NTransforms]),
	!.

find_transforms2([], [], _I).
find_transforms2([F | R], [F1 | R1], I) :-
	all_transforms_for_tuple(F, F1),
	I1 is I + 1,
	(   0 is I1 mod 100 ->
	    format('~d ', [I1]),
	    flush_output(user)
	;
	    otherwise ->
	    true
	),
	!,
	find_transforms2(R, R1, I1).

all_transforms_for_tuple(Tuple, Transforms) :-
	findall(Transform,
		verb_transforms_for_tuple(Tuple, Transform),
		Transforms),
	(   Transforms = [] ->
	    warn_about_missing_transforms_for_tuple(Tuple)
	;
	    otherwise ->
	    true
	).

warn_about_missing_transforms_for_tuple(Tuple) :-
	format('~N--- Warning: no 2nd plur -> 2nd sing transforms found for ~w~n', [Tuple]).

write_out_transforms(Transforms, AbsTransformFile) :-
	length(Transforms, N),
	list_to_prolog_file(Transforms, AbsTransformFile),
	format('~N--- Written verb file (~d elements): ~w~n', [N, AbsTransformFile]),
	!.

%mmorph_entry([surface=accueillez,lemma=accueillir,pos='Verb',(mode)=[indicative,imperative],tense=[present],number=[plural],person=['2'],form=[surface],type=['3']]).
%mmorph_entry([surface=accueilles,lemma=accueillir,pos='Verb',(mode)=[indicative],tense=[present],number=[singular],person=['2'],form=[surface],type=['3']]).

% mmorph_entry([surface=faites,lemma=faire,pos='Verb',(mode)=[indicative,imperative],tense=[present],number=[plural],person=['2'],form=[surface]]).
% mmorph_entry([surface=fais,lemma=faire,pos='Verb',(mode)=[indicative],tense=[present],number=[singular],person=['1','2'],form=[surface],type=['3']]).

verb_transforms_for_tuple(Tuple, verb_2_pl_to_verb_2_sing(V2Plur, V2Sing, Mode, Tense)) :-
	Tuple = [surface=V2Plur, lemma=Lemma, (mode)=ModeP, tense=TenseP | _OtherFeats],
	mmorph_entry([surface=V2Sing, lemma=Lemma, pos='Verb', (mode)=ModeS, tense=TenseS, number=[singular], person=PersonS | _OtherFeats1]),
	member('2', PersonS),
	compatible_feats(ModeP, ModeS, Mode),
	compatible_feats(TenseP, TenseS, Tense).

compatible_feats(Feats1, Feats2, Feat) :-
	member(Feat, Feats1),
	member(Feat, Feats2),
	!.

invert_verb_transforms([], []).
invert_verb_transforms([F | R], [F1 | R1]) :-
	invert_verb_transform(F, F1),
	!,
	invert_verb_transforms(R, R1).

invert_verb_transform(verb_2_pl_to_verb_2_sing(V2Plur, V2Sing, Mode, Tense),
		      verb_2_sing_to_verb_2_pl(V2Sing, V2Plur, Mode, Tense)) :-
	!.
invert_verb_transform(F, F1) :-
	format('~N*** Error: bad call: ~w~n', [invert_verb_transform(F, F1)]),
	fail.


text:
(function() {
    var redismock = typeof require === 'function' ? require('../../redis-mock.js') : window.redismock;
    if (typeof chai === 'undefined') {
        var chai = typeof require === 'function' ? require('chai') : window.chai;
    }
    chai.config.includeStack = true;
    var expect = chai.expect;

    var ignorekeys = [
        'Array',
        'SortedSet',
        'ifType',
        'randomkey',
        'multi',
        'info',
        'punsubscribe',
        'discard',
        'unwatch',
        'script_flush',
        'script_kill',
        'script_load',
        'ping',
        'quit',
        'select',
        'bgrewriteaof',
        'bgsave',
        'client_kill',
        'client_list',
        'client_getname',
        'cluster_slots',
        'command',
        'command_count',
        'command_getkeys',
        'command_info',
        'config_get',
        'config_rewrite',
        'config_resetstat',
        'dbsize',
        'debug_segfault',
        'flushall',
        'flushdb',
        'lastsave',
        'monitor',
        'role',
        'save',
        'shutdown',
        'sync',
        'time',
        'toPromiseStyle',
        'copy',
        'toNodeRedis',
        'createClient',
        'unsubscribe',
        'unref'
    ];

    describe('args check', function () {
        it('returns an error if we do not have the right number of arguments', function () {
            for (var key in redismock) {
                if (typeof redismock[key] === "function") {
                    if (ignorekeys.indexOf(key) !== -1) {
                        // 0 args, so skip, or intentionally skip.
                        continue;
                    }
                    err = redismock[key]();
                    expect(err).to.be.an.instanceof(Error);
                    expect(err.message.indexOf('ERR')).to.be.above(-1);
                    expect(err.message.indexOf(key)).to.be.above(-1);
                    expect(err.message.indexOf('wrong number of arguments')).to.be.above(-1);
                }
            }
        });
    });

}).call(this);


text:
'use strict';

var ash = require('ash');

module.exports = new ash.Action('destroyCompleted');


text:
/*
 * lnlist.c
 *      Author: Karsten-Kai König <KKoenig@posteo.de>
 *      License: MIT
 */

#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>

#include "lnlists.h"

head_t *new_list() {
	/*
	 *Initialize a new list
	 *
	 *The return value is a pointer to the new list or NULL if
	 *the operation was not successful
	 */

	head_t *new = calloc(1, sizeof(head_t));

	if (new == NULL)
		return NULL;

	new->first = NULL;
	new->current = NULL;
	new->last = NULL;
	new->index = -1;
	new->size = 0;

	return new;
}

element_t *add_element(head_t *list) {
	/*
	 * Append an empty element to the end of the list. The element
	 * becomes the current element of the list.
	 *
	 * @list: The list
	 *
	 * Return a pointer to the new element or NULL
	 */

	element_t *new;
	new = calloc(1, sizeof(element_t));
	if (new == NULL) {
		fprintf(stderr, "<add_element>: Failed to allocate memory for a new element!\n");
		return NULL;
	}

	if (list->size == 0) {
		new->left = NULL;
		new->right = NULL;

		list->first = new;
		list->current = new;
		list->last = new;
		list->size = 1;
		list->index = 0;
	}
	else if (list->size > 0) {
		new->left = list->last;
		new->right = NULL;

		list->current->right = new;
		list->current = new;
		list->last = new;
		list->size += 1;
		list->index = list->size-1;
	}
	else if (list->size < 0) {
		fprintf(stderr, "<add_element>: Negative size of a list is not possible; list is broken!\n");
		free(new);
		return NULL;
	}

	return new;
}

int change_current_element(head_t *list, element_t *element) {
	/*
	 * Changes the current element, to the given one. The
	 * element must exist in the list.
	 *
	 * @list: The list
	 * @element: A pointer to the element
	 *
	 * The function returns 1 in the case of success or 0 if
	 * the operations was not successful
	 */

	int i;
	element_t *tmp;

	tmp = list->first;

	for (i = 1; i <= list->size; i++) {
		if (tmp == element) {
			list->index = i-1;
			break;
		}
		if (tmp->right == NULL) {
			fprintf(stderr, "<change_current_element>: The element doesn't exist in the list!\n");
			return 0;
		}
		tmp = tmp->right;
	}

	list->current = element;

	return 1;
}

int clear_list(head_t *list) {
	/*
	 * Remove all elements of the list, but the list is still
	 * usable
	 *
	 * @list: The list
	 *
	 * The return value is 1
	 */

	int i;
	element_t *tmp1, *tmp2;

	tmp1 = list->first;

	for(i = 1; i <= list->size; i++) {
		tmp2 = tmp1->right;
		free(tmp1);
		tmp1 = tmp2;
	}

	list->current = NULL;
	list->first = NULL;
	list->last = NULL;
	list->size = 0;
	list->index = -1;

	return 1;
}

int copy_list(head_t *list1, head_t *list2) {
	/*
	 * Copy on list into another, so they are identical
	 *
	 * @list1: The origin list
	 * @list2: The destination of list1
	 *
	 * The return value is 1
	 */

	clear_list(list2);
	list2->first = list1->first;
	list2->current = list1->current;
	list2->last = list1->last;
	list2->size = list1->size;
	list2->index = list1->index;

	return 1;
}

int delete_element(head_t *list, ...) {
	/*
	 * Delete the current element and sets the current element
	 * to the previous one. If the deleted element was the
	 * first one the new current element is NULL. If you set
	 * the optional argument to 1 than the current element will
	 * be the second one.
	 *
	 * @list: The list
	 * @optional: 1 or nothing (if it's something else nothing
	 * will happen)
	 *
	 * Returns 1 or 0, if the operation was not successful
	 */

	va_list ptr;
	int flag;
	element_t *current;

	va_start(ptr, *list);
	flag = va_arg(ptr, int);
	va_end(ptr);
	if (flag != 1) {
		flag = 0;
	}

	current = list->current;
	if (current == NULL) {
		fprintf(stderr, "<delete_element>: There is no current element!}\n");
		return 0;
	}
	if (list->first == current) {
		if (list->size > 1)
			current->right->left = NULL;
		if (flag) {
			list->current = current->right;
			list->index += 1;
		}
		else {
			list->current = NULL;
			list->index -= 1;
		}
	}
	else if (list->last == current) {
		if (list->size > 1)
			current->left->right = NULL;
		list->current = current->left;
		list->index -= 1;
	}
	else {
		current->left->right = current->right;
		current->right->left = current->left;
		list->current = current->left;
		list->index -= 1;
	}

	list->size -= 1;
	free(current);

	return 1;
}

element_t *first_element(head_t *list) {
	/*
	 * Set the list to the first element.
	 *
	 * @list: The address of a list head
	 *
	 * Returns a pointer to the first element
	 */

	list->current = list->first;
	list->index = 0;
	return list->current;
}

int free_list(head_t *list) {
	/*
	 * Delete the whole list including it's head, so the memory
	 * is no longer allocated and the list is no longer usable
	 *
	 * @list: The list
	 *
	 * Returns 1
	 */

	int i;
	element_t *tmp1, *tmp2;

	tmp1 = list->first;

	for(i = 1; i <= list->size; i++) {
		tmp2 = tmp1->right;
		free(tmp1);
		tmp1 = tmp2;
	}

	free(list);

	return 1;
}

element_t *insert_element(head_t *list) {
	/*
	 * Inserts an empty element before the current one. If the
	 * list is empty the new element is the first. The new
	 * element will be the current one.
	 *
	 * @list: The list
	 *
	 * Returns a pointer to the new element.
	 */

	element_t *new;

	new = calloc(1, sizeof(element_t));
	if (new == NULL) {
		fprintf(stderr, "<insert_element>: Failed to allocate memory for a new element!\n");
		return NULL;
	}

	if (list->size == 0) {
		list->first = new;
		list->current = new;
		list->last = new;
		list->size = 1;
		list->index = 0;

		new->right = NULL;
		new->left = NULL;
	}
	else if (list->size > 0) {
		new->right = list->current;
		new->left = list->current->left;

		if (list->current == list->first) {
			list->current->left = new;
			list->first = new;
		}
		else {
			list->current->left->right = new;
			list->current->left = new;
		}
		list->current = new;
		list->size++;
	}
	else if (list->size < 0) {
		fprintf(stderr, "<insert_element>: Negative size of a list is not possible; list is broken!\n");
		free(new);
		return NULL;
	}

	return new;
}

element_t *last_element(head_t *list) {
	/*
	 * Sets the current element of the given list to it's last
	 * one.
	 *
	 * @list: The list
	 *
	 * Returns a pointer to the last element or NULL.
	 */

	list->current = list->last;
	list->index = list->size-1;
	return list->current;
}

int list_index(head_t *list) {
	/*
	 * Returns the index number of the current element starting
	 * with 0.
	 *
	 * @list: The list
	 *
	 * Returns the index starting with 0 for the first element.
	 * Returns -1 if there is no current element.
	 */

	return list->index;
}

int list_size(head_t *list) {
	/*
	 * Returns the number of elements in the list.
	 *
	 * @list: The list
	 *
	 * The return value is the size of the list.
	 */

	return list->size;
}

element_t *next_element(head_t *list) {
	/*
	 * Set the current element to the next one. If there is no
	 * current element, the next element is the first.
	 *
	 * @list: The list
	 *
	 * The function returns a pointer to the new current element
	 * or NULL if it's the end of the list.
	 */

	if (list->current != NULL) {
		if (list->current->right != NULL) {
			list->current = list->current->right;
			list->index += 1;
			return list->current;
		}
		else
			return NULL;
	}
	else if (list->current == NULL && list->size != 0) {
		list->current = list->first;
		list->index += 1;
		return list->current;
	}
	else {
		fprintf(stderr, "<next_element>: There are no elements in the list!\n");
		return NULL;
	}
}

element_t *previous_element(head_t *list) {
	/*
	 * Sets the current element to the list to the previous one.
	 *
	 * @list: The list
	 *
	 * Returns the pointer to the new current element or NULL
	 * if the list is empty or if the old current element is the
	 * first one. If there is no current element, the return
	 * value is NULL, too.
	 */

	if (list->current != NULL && list->current != list->first) {
		list->current = list->current->left;
		list->index -= 1;
		return list->current;
	}
	else
		return NULL;
}

int reset_list(head_t *list) {
	/*
	 * Sets the current element to NULL, so there is no current
	 * element.
	 *
	 * @list: The list
	 *
	 * Returns 1
	 */

	list->current = NULL;
	list->index = -1;

	return 1;
}

int select_element(head_t *list, int index) {
	/*
	 * Sets the current element to that one with the specified
	 * index. The indexes start with 0.
	 *
	 * @list: The list
	 * @index: The index
	 *
	 * Returns 1 if everything was fine or 0
	 */

	int i;

	if (index > list->size-1 || index < 0) {
		fprintf(stderr, "<select_element>: The given index doesn't exists!\n");
		return 0;
	}
	else {
		list->current = list->first;
		for (i = 0; i < index; i++) {
			list->current = list->current->right;
		}
	}

	list->index = index;
	return 1;
}

int swap_elements(head_t *list, element_t *element1, element_t *element2) {
	/*
	 * This function swaps the given elements. They must be in
	 * the same list.
	 *
	 * @list: The list
	 * @element1: Pointer to the 1st element
	 * @element2:Pointer to the 2nd element
	 *
	 * Returns 1 if everything was fine or 0
	 */

	int i, counter;
	element_t *tmp;

	counter = 0;
	tmp = list->first;

	for (i = 1; i <= list->size; i++) {
		if (tmp == element1 || tmp == element2) {
			if (counter < 1) {
				counter++;
				continue;
			}
			break;
		}
		if (tmp->right == NULL) {
			fprintf(stderr, "<swap_elements>: One ore more elements doesn't exist in the list!\n");
			return 0;
		}
		tmp = tmp->right;
	}

	if (element1 == list->first && element2 == list->last) {
		element1->right->left = element2;
		element2->left->right = element1;
		list->first = element2;
		list->last = element1;
	}
	else if (element2 == list->first && element1 == list->last) {
		element2->right->left = element1;
		element1->left->right = element2;
		list->first = element1;
		list->last = element2;
	}
	else if (element1 == list->first) {
		element1->right->left = element2;
		element2->right->left = element1;
		element2->left->right = element1;
		list->first = element2;
	}
	else if (element1 == list->last) {
		element1->left->right = element2;
		element2->right->left = element1;
		element2->left->right = element1;
		list->last = element2;
	}
	else if (element2 == list->first) {
		element2->right->left = element1;
		element1->right->left = element2;
		element1->left->right = element2;
		list->first = element1;
	}
	else if (element2 == list->last) {
		element2->left->right = element1;
		element1->right->left = element2;
		element1->left->right = element2;
		list->last = element1;
	}
	else {
		element1->left->right = element2;
		element1->right->left = element2;
		element2->right->left = element1;
		element2->left->right = element1;
	}

	tmp = (element_t *) malloc(sizeof(element_t));
	tmp->right = element1->right;
	tmp->left = element1->left;

	element1->right = element2->right;
	element1->left = element2->left;

	element2->right = tmp->right;
	element2->left = tmp->left;

	free(tmp);
	return 1;
}


text:
namespace SPALM.SPSF.Library.ValueProviders
{
    using System.Collections.Specialized;
    using EnvDTE;
    using Microsoft.Practices.Common;
    using Microsoft.Practices.ComponentModel;
    using Microsoft.Practices.RecipeFramework;

    [ServiceDependency(typeof(DTE))]
    public class ApplicationConfigValueProvider : ValueProvider, IAttributesConfigurable
    {
        private string _ConfigValue = "";
        public string ConfigValue
        {
            get { return _ConfigValue; }
            set { _ConfigValue = value; }
        }

        private string _DefaultValue = "";
        public string DefaultValue
        {
          get { return _DefaultValue; }
          set { _DefaultValue = value; }
        }

        public override bool OnBeginRecipe(object currentValue, out object newValue)
        {
          if (currentValue != null)
          {
            // Do not assign a new value, and return false to flag that
            // we don't want the current value to be changed.
            newValue = null;
            return false;
          }

            newValue = "";

            DTE service = (DTE)this.GetService(typeof(DTE));

            newValue = Helpers.GetApplicationConfigValue(service, ConfigValue, DefaultValue);
            return true;
        }

        #region IAttributesConfigurable Members

        void IAttributesConfigurable.Configure(StringDictionary attributes)
        {
            if(attributes["ConfigValue"] != null)
            {
                ConfigValue = attributes["ConfigValue"];
            }
            if (attributes["DefaultValue"] != null)
            {
              DefaultValue = attributes["DefaultValue"];
            }
        }

        #endregion
    }
}


text:
/**
 * ApiToggler
 *
 * @constructor
 * @param {Object} aliases
 * @public
 *
 * @example
 *
 *   var someApiToggler = new ApiToggler({
 *     name: 'first_name',
 *     surname: 'last_name'
 *   });
 *
 *   // String
 *   someApiToggler.toggle('name');
 *   //=> 'first_name'
 *
 *   // Object
 *   someApiToggler.toggle({first_name: 'Vladimir', last_name: 'Rodkin'});
 *   //=> {name: 'Vladimir', surname: 'Rodkin'}
 *
 *   // Array
 *   someApiToggler.toggle([{
 *     first_name: 'Vladimir',
 *     last_name: 'Rodkin'
 *   }, {
 *     first_name: 'Foo',
 *     last_name: 'Bar'
 *   }]);
 *   //=> [{name: 'Vladimir', surname: 'Rodkin'}, {name: 'Foo', surname: 'Bar'}]
 */
var ApiToggler = function (aliases) {
	aliases = aliases || {};

	// Fill mirrored aliases
	for (const [key, value] of Object.entries(aliases)) {
		aliases[value] = key;
	}

	// @private
	this.aliases = aliases;
};

ApiToggler.prototype = {
	/**
	 * @param {string} key
	 * @returns {string}
	 * @public
	 */
	toggleApiKey: function (key) {
		return this.aliases[key] ? this.aliases[key] : key;
	},

	/**
	 * @param {Object} data
	 * @returns {Object}
	 * @public
	 */
	toggleApiObject: function (data) {
		var result = {};

		for (const [key, value] of Object.entries(data)) {
			result[this.toggleApiKey(key)] = value;
		}

		return result;
	},

	/**
	 * @param {string|Object|Array} data
	 * @returns {string|Object|Array}
	 * @public
	 */
	toggle: function (data) {
		if (typeof data === 'string') {
			// Is String
			return this.toggleApiKey(data);
		}

		if (!Array.isArray(data)) {
			// Is Object
			return this.toggleApiObject(data);
		}

		// Is Array
		return data.map(data => this.toggleApiObject(data));
	}
};

module.exports = ApiToggler;


text:
package nuist.qlib.dss.net;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.util.Properties;

import org.apache.log4j.Logger;

/**
 *
 * 接收IP的线程
 *
 */
public class ReceIP implements Runnable // 接收
{
	private MulticastSocket dsock; // 广播套接字
	private String host;
	private Logger logger;
	private Properties pro;

	public ReceIP(MulticastSocket dsock) {
		logger = Logger.getLogger(ReceIP.class.getName());
		this.dsock = dsock;
		this.host = "239.0.0.1";
		pro = new Properties();
	}

	public void run() {
		try {
			InetAddress ip = InetAddress.getByName(this.host);
			dsock.joinGroup(ip); // 加入到广播组
			while (true) {
				byte[] data = new byte[256];

				DatagramPacket packet = new DatagramPacket(data, data.length);
				dsock.receive(packet);
				String message = new String(packet.getData(), 0,
						packet.getLength());
				// 根据角色更新该角色记录的时间
				String role = message.split("/")[0];
				String databaseIp = message.split("/")[1];
				if (role != null && !role.equals("")) {
					if (role.contains("Editor")) {
						String relativelyPath=System.getProperty("user.dir");
						FileInputStream in = new FileInputStream(
								relativelyPath+"\\dataBase.properties");
						pro.load(in);
						in.close();
						pro.setProperty("ip", databaseIp);
						FileOutputStream out = new FileOutputStream(
								relativelyPath+"\\dataBase.properties");
						pro.store(out, "update");
						out.close();
					}
				}
			}
		} catch (Exception e) {
			throw new RuntimeException("接受失败!");
		} finally {
			dsock.close();
		}
	}
}