text:
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading.Tasks;

namespace Octokit
{
    ///
    /// A client for GitHub's Issue Milestones API.
    ///
    /// <remarks>
    /// See the Issue Milestones API documentation for more information.
    /// </remarks>
    public interface IMilestonesClient
    {
        ///
        /// Gets a single Milestone by number.
        ///
        /// <remarks>
        /// http://developer.github.com/v3/issues/milestones/#get-a-single-milestone
        /// </remarks>
        /// <returns></returns>
        [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Get",
             Justification = "Method makes a network request")]
        Task<Milestone> Get(string owner, string name, int number);

        ///
        /// Gets a single Milestone by number.
        ///
        /// <remarks>
        /// http://developer.github.com/v3/issues/milestones/#get-a-single-milestone
        /// </remarks>
        /// <returns></returns>
        [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Get",
             Justification = "Method makes a network request")]
        Task<Milestone> Get(long repositoryId, int number);

        ///
        /// Gets all open milestones for the repository.
        ///
        /// <remarks>
        /// http://developer.github.com/v3/issues/milestones/#list-milestones-for-a-repository
        /// </remarks>
        /// <param name="owner">The owner of the repository</param>
        /// <param name="name">The name of the repository</param>
        /// <returns></returns>
        Task<IReadOnlyList<Milestone>> GetAllForRepository(string owner, string name);

        ///
        /// Gets all open milestones for the repository.
        ///
        /// <remarks>
        /// http://developer.github.com/v3/issues/milestones/#list-milestones-for-a-repository
        /// </remarks>
        /// <param name="repositoryId">The Id of the repository</param>
        /// <returns></returns>
        Task<IReadOnlyList<Milestone>> GetAllForRepository(long repositoryId);

        ///
        /// Gets all open milestones for the repository.
        ///
        /// <remarks>
        /// http://developer.github.com/v3/issues/milestones/#list-milestones-for-a-repository
        /// </remarks>
        /// <param name="owner">The owner of the repository</param>
        /// <param name="name">The name of the repository</param>
        /// <param name="options">Options for changing the API response</param>
        /// <returns></returns>
        Task<IReadOnlyList<Milestone>> GetAllForRepository(string owner, string name, ApiOptions options);

        ///
        /// Gets all open milestones for the repository.
        ///
        /// <remarks>
        /// http://developer.github.com/v3/issues/milestones/#list-milestones-for-a-repository
        /// </remarks>
        /// <param name="repositoryId">The Id of the repository</param>
        /// <param name="options">Options for changing the API response</param>
        /// <returns></returns>
        Task<IReadOnlyList<Milestone>> GetAllForRepository(long repositoryId, ApiOptions options);

        ///
        /// Gets all open milestones for the repository.
        ///
        /// <remarks>
        /// http://developer.github.com/v3/issues/milestones/#list-milestones-for-a-repository
        /// </remarks>
        /// <param name="owner">The owner of the repository</param>
        /// <param name="name">The name of the repository</param>
        /// <param name="request">Used to filter and sort the list of Milestones returned</param>
        /// <returns></returns>
        Task<IReadOnlyList<Milestone>> GetAllForRepository(string owner, string name, MilestoneRequest request);

        ///
        /// Gets all open milestones for the repository.
        ///
        /// <remarks>
        /// http://developer.github.com/v3/issues/milestones/#list-milestones-for-a-repository
        /// </remarks>
        /// <param name="repositoryId">The Id of the repository</param>
        /// <param name="request">Used to filter and sort the list of Milestones returned</param>
        /// <returns></returns>
        Task<IReadOnlyList<Milestone>> GetAllForRepository(long repositoryId, MilestoneRequest request);

        ///
        /// Gets all open milestones for the repository.
        ///
        /// <remarks>
        /// http://developer.github.com/v3/issues/milestones/#list-milestones-for-a-repository
        /// </remarks>
        /// <param name="owner">The owner of the repository</param>
        /// <param name="name">The name of the repository</param>
        /// <param name="request">Used to filter and sort the list of Milestones returned</param>
        /// <param name="options">Options for changing the API response</param>
        /// <returns></returns>
        Task<IReadOnlyList<Milestone>> GetAllForRepository(string owner, string name, MilestoneRequest request, ApiOptions options);

        ///
        /// Gets all open milestones for the repository.
        ///
        /// <remarks>
        /// http://developer.github.com/v3/issues/milestones/#list-milestones-for-a-repository
        /// </remarks>
        /// <param name="repositoryId">The Id of the repository</param>
        /// <param name="request">Used to filter and sort the list of Milestones returned</param>
        /// <param name="options">Options for changing the API response</param>
        /// <returns></returns>
        Task<IReadOnlyList<Milestone>> GetAllForRepository(long repositoryId, MilestoneRequest request, ApiOptions options);

        ///
        /// Creates a milestone for the specified repository. Any user with pull access to a repository can create an
        /// Milestone.
        ///
        /// <remarks>http://developer.github.com/v3/issues/milestones/#create-a-milestone</remarks>
        /// <param name="owner">The owner of the repository</param>
        /// <param name="name">The name of the repository</param>
        /// <param name="newMilestone">A <see cref="NewMilestone"/> instance describing the new Milestone to create</param>
        /// <returns></returns>
        Task<Milestone> Create(string owner, string name, NewMilestone newMilestone);

        ///
        /// Creates a milestone for the specified repository. Any user with pull access to a repository can create an
        /// Milestone.
        ///
        /// <remarks>http://developer.github.com/v3/issues/milestones/#create-a-milestone</remarks>
        /// <param name="repositoryId">The Id of the repository</param>
        /// <param name="newMilestone">A <see cref="NewMilestone"/> instance describing the new Milestone to create</param>
        /// <returns></returns>
        Task<Milestone> Create(long repositoryId, NewMilestone newMilestone);

        ///
        /// Creates a milestone for the specified repository. Any user with pull access to a repository can create an
        /// Milestone.
        ///
        /// <remarks>http://developer.github.com/v3/issues/milestones/#update-a-milestone</remarks>
        /// <param name="owner">The owner of the repository</param>
        /// <param name="name">The name of the repository</param>
        /// <param name="number">The Milestone number</param>
        /// <param name="milestoneUpdate">An <see cref="MilestoneUpdate"/> instance describing the changes to make to the Milestone
        /// </param>
        /// <returns></returns>
        Task<Milestone> Update(string owner, string name, int number, MilestoneUpdate milestoneUpdate);

        ///
        /// Creates a milestone for the specified repository. Any user with pull access to a repository can create an
        /// Milestone.
        ///
        /// <remarks>http://developer.github.com/v3/issues/milestones/#update-a-milestone</remarks>
        /// <param name="repositoryId">The Id of the repository</param>
        /// <param name="number">The Milestone number</param>
        /// <param name="milestoneUpdate">An <see cref="MilestoneUpdate"/> instance describing the changes to make to the Milestone
        /// </param>
        /// <returns></returns>
        Task<Milestone> Update(long repositoryId, int number, MilestoneUpdate milestoneUpdate);

        ///
        /// Deletes a milestone for the specified repository. Any user with pull access to a repository can create an
        /// Milestone.
        ///
        /// <remarks>http://developer.github.com/v3/issues/milestones/#delete-a-milestone</remarks>
        /// <param name="owner">The owner of the repository</param>
        /// <param name="name">The name of the repository</param>
        /// <param name="number">The milestone number</param>
        /// <returns></returns>
        Task Delete(string owner, string name, int number);

        ///
        /// Deletes a milestone for the specified repository. Any user with pull access to a repository can create an
        /// Milestone.
        ///
        /// <remarks>http://developer.github.com/v3/issues/milestones/#delete-a-milestone</remarks>
        /// <param name="repositoryId">The Id of the repository</param>
        /// <param name="number">The milestone number</param>
        /// <returns></returns>
        Task Delete(long repositoryId, int number);
    }
}


text:
namespace MAD
{
	enum class MessageBoxType
	{
		Default, // [ OK ] [ Cancel ]
		Ok,      // [ OK ]
		Error,   // [ Abort ] [ Retry ] [ Ignore ]
		YesNo,   // [ Yes ] [ No ]
	};

	enum class MessageBoxResult
	{
		OK = 1,
		Cancel,
		Abort,
		Retry,
		Ignore,
		Yes,
		No,
	};

	extern MessageBoxResult MAD_MessageBox(const char* inTitle, const char* inText, MessageBoxType inType);

#ifdef _DEBUG
	extern bool AssertFunc(bool inExpr, const char* inExprStr, const char* inDesc, int inLine, const char* inFileName);

#define MAD_ASSERT_DESC(expr, desc)															\
	do																						\
	{																						\
		if (AssertFunc((expr), #expr, desc, __LINE__, __FILE__)) { EASTL_DEBUG_BREAK(); }	\
	} while (0)

#define MAD_CHECK_DESC(expr, desc) MAD_ASSERT_DESC(expr, desc)

#else
#define MAD_ASSERT_DESC(expr, desc) (void)0
#define MAD_CHECK_DESC(expr, desc) expr
#endif
}

redpajama_set_name: RedPajamaGithub


text:
layout: wiki
title: prog-cheat-sheet
---

Limits

    #include <limits.h>

    INT_MIN
    INT_MAX


text:
PROJECT_NAME := mmu

include $(IDF_PATH)/make/project.mk


text:
0. `sally` Secure audit logging
1. `express`
    * Standard express request/response middleware (compression, bodyParser, ...)
    * self-test - verifies that a response is correct
2. `security`
    * multi-tenancy - Determines the tenant based on the URL and prevents returning other tenant's data
    * authentication - identity the user
    * authorization - activity based permissions
3. `mung` Resource/document transformation
    * Redact - removing sensitive data
    * Metadata - adding `_metadata` and
    * Upgrade - gradual upgrade of a resource
4. `plug-ins` Mini applications
    * `/api/media`
    * `/api/:type`
    * `/forex`
    * `/api-test`

When a lower ring needs access to a higher level ring it must call the server via `myself` - [dog food #70](https://github.com/richardschneider/yapp/issues/70)

````
myself(req)
   .get('/api/tenant/123')
   .then(tentant => ...);
````

Components at the same ring level can off-load work to each other using the `handle` method.  Here `media` lets `crud` do some of the work.

````
router.get('/media', function(req, res, next) {
    return crud.handle(req, res, next);
});

router.get('/media/:id', function(req, res, next) {
    return crud.handle(req, res, next);
});
````


text:
package com.mongodb.reactivestreams.client;

import com.mongodb.TransactionOptions;
import org.reactivestreams.Publisher;

/**
 * A client session that supports transactions.
 *
 * @since 1.9
 */
public interface ClientSession extends com.mongodb.session.ClientSession {
    /**
     * Returns true if there is an active transaction on this session, and false otherwise
     *
     * @return true if there is an active transaction on this session
     * @mongodb.server.release 4.0
     */
    boolean hasActiveTransaction();

    /**
     *  Notify the client session that a message has been sent.
     *

     *      For internal use only
     *

     *
     * @return true if this is the first message sent, false otherwise
     * @since 4.0
     */
    boolean notifyMessageSent();

    /**
     * Notify the client session that command execution is being initiated. This should be called before server selection occurs.
     *

     * For internal use only
     *

     * @param operation the operation
     */
    void notifyOperationInitiated(Object operation);

    /**
     * Gets the transaction options.  Only call this method of the session has an active transaction
     *
     * @return the transaction options
     */
    TransactionOptions getTransactionOptions();

    /**
     * Start a transaction in the context of this session with default transaction options. A transaction can not be started if there is
     * already an active transaction on this session.
     *
     * @mongodb.server.release 4.0
     */
    void startTransaction();

    /**
     * Start a transaction in the context of this session with the given transaction options. A transaction can not be started if there is
     * already an active transaction on this session.
     *
     * @param transactionOptions the options to apply to the transaction
     *
     * @mongodb.server.release 4.0
     */
    void startTransaction(TransactionOptions transactionOptions);

    /**
     * Commit a transaction in the context of this session.  A transaction can only be commmited if one has first been started.
     *
     * @return an empty publisher that indicates when the operation has completed
     * @mongodb.server.release 4.0
     */
    Publisher<Void> commitTransaction();

    /**
     * Abort a transaction in the context of this session.  A transaction can only be aborted if one has first been started.
     *
     * @return an empty publisher that indicates when the operation has completed
     * @mongodb.server.release 4.0
     */
    Publisher<Void> abortTransaction();
}


text:
package model;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/*
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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.
 *
 */

public class SQLData {
	private String tableName;
	private Map<String,List<String>> fieldData;
	private List<String> primaryKeys;
	private Map<String,ForiegnKeyData> foriegnKeys;

	public static class ForiegnKeyData{
		public String tableAndField;
		public String jpaClassName;
		public String jpaResourceClassName;
		public ForiegnKeyData(String tableAndField, String jpaClassName,String jpaResourceClassName) {
			this.tableAndField = tableAndField;
			this.jpaClassName = jpaClassName;
			this.jpaResourceClassName = jpaResourceClassName;
		}
	}

	public String getTableName() {
		return tableName;
	}
	public void setTableName(String tableName) {
		this.tableName = tableName;
	}
	public Map<String, List<String>> getFieldData() {
		if (fieldData==null){
			fieldData=new HashMap<String, List<String>>();
		}
		return fieldData;
	}

	public void setFieldData(Map<String, List<String>> fieldData) {
		this.fieldData = fieldData;
	}
	public List<String> getPrimaryKeys() {
		if (primaryKeys==null){
			primaryKeys=new ArrayList<String>();
		}
		return primaryKeys;
	}
	public void setPrimaryKeys(List<String> primaryKeys) {
		this.primaryKeys = primaryKeys;
	}
	public Map<String,ForiegnKeyData> getForiegnKeys() {
		if (foriegnKeys==null){
			foriegnKeys=new HashMap<String, ForiegnKeyData>();
		}
		return foriegnKeys;
	}
	public void setForiegnKeys(Map<String,ForiegnKeyData> foriegnKeys) {
		this.foriegnKeys = foriegnKeys;
	}
}


text:
#include <CGAL/Exact_rational.h>
#include <CGAL/Cartesian.h>
#include <CGAL/Timer.h>

#include <CGAL/Env_triangle_traits_3.h>
#include <CGAL/envelope_3.h>
#include "Envelope_triangles_test_3.h"

#include <iostream>
#include <cassert>
#include <list>
#include <set>
#include <vector>
#include <map>

// leda_rational, or Gmpq, or Quotient<MP_float>
typedef CGAL::Exact_rational                                     NT;
typedef CGAL::Cartesian<NT>                                      Kernel;

typedef Kernel::Point_3                                          Point_3;
typedef Kernel::Triangle_3                                       Triangle_3;

typedef CGAL::Env_triangle_traits_3<Kernel>                      Traits_3;

typedef Traits_3::Xy_monotone_surface_3                          Xy_monotone_surface_3;
typedef Traits_3::Surface_3                                      Surface_3;

typedef CGAL::Envelope_diagram_2<Traits_3>                       Envelope_diagram_2;
typedef CGAL::Envelope_triangles_test_3<Traits_3,
                                        Envelope_diagram_2>      Envelope_test;

std::ostream & operator << (std::ostream  & os, Triangle_3* p_data)
{
  return os << *p_data;
}

using std::cout;
using std::endl;

bool test_one_file(std::ifstream& inp)
{
  Traits_3 traits;
  std::vector<Surface_3> triangles;

  int triangles_num = 0;
  inp >> triangles_num;
  std::cout << "number of triangles to read: " << triangles_num << std::endl;
  Point_3 a,b,c;
  for(int i=0; i<triangles_num; ++i)
  {
    inp >> a >> b >> c;
    Surface_3 p_triangle(a,b,c);
    triangles.push_back(p_triangle);
  }
  cout << "deal with " << triangles.size() << " triangles" << endl;

  // make xy-monotone surfaces
  std::vector<Surface_3>::iterator begin;
  std::vector<Xy_monotone_surface_3> xy_monotones;

  for(begin = triangles.begin(); begin != triangles.end(); ++begin)
    traits.make_xy_monotone_3_object()(*begin, true, std::back_inserter(xy_monotones));

  CGAL::Timer timer;
  Envelope_diagram_2 result, test_result;
  timer.start();
  CGAL::lower_envelope_xy_monotone_3(xy_monotones.begin(), xy_monotones.end(), result);
  timer.stop();
  cout << "construct envelope took " << timer.time() << " seconds" << endl;
  timer.reset();

  cout << "after lower envelope construction result has " << endl <<
          result.number_of_vertices() << " vertices" << endl <<
          result.number_of_halfedges() << " halfedges (" << result.number_of_edges() << " edges)" << endl <<
          result.number_of_faces() << " faces" << endl;

  Envelope_test env_test;
  timer.start();
  env_test.construct_lu_envelope(xy_monotones.begin(), xy_monotones.end(), test_result);
  timer.stop();
  cout << "construct test map took " << timer.time() << " seconds" << endl;
  timer.reset();

  cout << "finished computing test map. it has " << endl <<
          test_result.number_of_vertices() << " vertices" << endl <<
          test_result.number_of_halfedges() << " halfedges (" <<
          test_result.number_of_edges() << " edges)" << endl <<
          test_result.number_of_faces() << " faces" << endl;

  timer.start();
  bool test2 = env_test.compare_lu_envelopes_test2(test_result, result, /*only faces = */false);
  timer.stop();

  return test2;
}

int main(int argc, char **argv)
{
  if(argc < 2)
  {
    std::cerr<<"Missing input file\n";
    std::exit (-1);
  }

  int success = 0;
  for(int i=1; i<argc; ++i)
  {
    std::string str(argv[i]);
    if(str.empty())
      continue;

    std::ifstream inp(argv[i]);
    if(!inp.is_open())
    {
      std::cerr<<"Failed to open " <<str<<"\n";
      return (-1);
    }
    if (! test_one_file(inp))
    {
      inp.close();
      std::cout<<str<<": ERROR\n";
      success = -1;
    }
    else
    {
      std::cout<<str<<": succeeded\n";
    }
    inp.close();
  }

  return success;
}


text:
import logging

logger = logging.getLogger(__name__)

# Pump rate in mL/s (4.3 L/min)
_PUMP_RATE_ML_PER_SEC = 4300.0 / 60.0

# Default amount of water to add to the plant (in mL) when pump manager detects
# low soil moisture.
DEFAULT_PUMP_AMOUNT = 200

class Pump(object):
    """Wrapper for a Seaflo 12V water pump."""

    def __init__(self, pi_io, clock, pump_pin):
        """Creates a new Pump wrapper.

        Args:
            pi_io: Raspberry Pi I/O interface.
            clock: A clock interface.
            pump_pin: Raspberry Pi pin to which the pump is connected.
        """
        self._pi_io = pi_io
        self._clock = clock
        self._pump_pin = pump_pin

    def pump_water(self, amount_ml):
        """Pumps the specified amount of water.

        Args:
            amount_ml: Amount of water to pump (in mL).

        Raises:
            ValueError: The amount of water to be pumped is invalid.
        """
        if amount_ml == 0.0:
            return
        elif amount_ml < 0.0:
            raise ValueError('Cannot pump a negative amount of water')
        else:
            logger.info('turning pump on (with GPIO pin %d)', self._pump_pin)
            self._pi_io.turn_pin_on(self._pump_pin)

            wait_time_seconds = amount_ml / _PUMP_RATE_ML_PER_SEC
            self._clock.wait(wait_time_seconds)

            logger.info('turning pump off (with GPIO pin %d)', self._pump_pin)
            self._pi_io.turn_pin_off(self._pump_pin)
            logger.info('pumped %.f mL of water', amount_ml)

        return

class PumpManager(object):
    """Pump Manager manages the water pump."""

    def __init__(self, pump, pump_scheduler, moisture_threshold, pump_amount,
                 timer):
        """Creates a PumpManager object, which manages a water pump.

        Args:
            pump: A pump instance, which supports water pumping.
            pump_scheduler: A pump scheduler instance that controls the time
                periods in which the pump can be run.
            moisture_threshold: Soil moisture threshold. If soil moisture is
                below this value, manager pumps water on pump_if_needed calls.
            pump_amount: Amount (in mL) to pump every time the water pump runs.
            timer: A timer that counts down until the next forced pump. When
                this timer expires, the pump manager runs the pump once,
                regardless of the moisture level.
        """
        self._pump = pump
        self._pump_scheduler = pump_scheduler
        self._moisture_threshold = moisture_threshold
        self._pump_amount = pump_amount
        self._timer = timer

    def pump_if_needed(self, moisture):
        """Run the water pump if there is a need to run it.

        Args:
            moisture: Soil moisture level

        Returns:
            The amount of water pumped, in mL.
        """
        if self._should_pump(moisture):
            self._pump.pump_water(self._pump_amount)
            self._timer.reset()
            return self._pump_amount

        return 0

    def _should_pump(self, moisture):
        """Returns True if the pump should be run."""
        if not self._pump_scheduler.is_running_pump_allowed():
            return False
        return (moisture < self._moisture_threshold) or self._timer.expired()

class PumpScheduler(object):
    """Controls when the pump is allowed to run."""

    def __init__(self, local_clock, sleep_windows):
        """Creates new PumpScheduler instance.

        Args:
            local_clock: A local clock interface
            sleep_windows: A list of 2-tuples, each representing a sleep window.
                Tuple items are datetime.time objects.
        """
        self._local_clock = local_clock
        self._sleep_windows = sleep_windows

    def is_running_pump_allowed(self):
        """Returns True if OK to run pump, otherwise False.

        Pump is not allowed to run from the start of a sleep window (inclusive)
        to the end of a sleep window (exclusive).
        """
        current_time = self._local_clock.now().time()

        for sleep_time, wake_time in self._sleep_windows:
            # Check if sleep window wraps midnight.
            if wake_time < sleep_time:
                if current_time >= sleep_time or current_time < wake_time:
                    return False
            else:
                if sleep_time <= current_time < wake_time:
                    return False

        return True


text:
/**
 *     This code was auto-generated by a Codezu.
 *
 *     Changes to this file may cause incorrect behavior and will be lost if
 *     the code is regenerated.
 */
package com.mozu.api.contracts.pricingruntime;

import java.util.List;
import java.util.HashMap;
import java.io.Serializable;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import org.joda.time.DateTime;
import java.io.IOException;
import java.lang.ClassNotFoundException;
import com.mozu.api.contracts.pricingruntime.ProductAttribute;
import com.mozu.api.contracts.pricingruntime.ProductPropertyValue;

/**
 *	Details of a property defined for a product.
 */
@JsonIgnoreProperties(ignoreUnknown = true)
public class ProductProperty implements Serializable
{
	// Default Serial Version UID
	private static final long serialVersionUID = 1L;

	/**
	 * The fully qualified name of the attribute, which is a user defined attribute identifier.
	 */
	protected  String attributeFQN;

	public String getAttributeFQN() {
		return this.attributeFQN;
	}

	public void setAttributeFQN(String attributeFQN) {
		this.attributeFQN = attributeFQN;
	}

	/**
	 * Indicates if the object is hidden or breaks inheritance, primarily used by facets, products, and attribute vocabulary values. For example, if true, the attribute vocabulary value does not appear in the list when defining a value for an attribute.
	 */
	protected  Boolean isHidden;

	public Boolean getIsHidden() {
		return this.isHidden;
	}

	public void setIsHidden(Boolean isHidden) {
		this.isHidden = isHidden;
	}

	/**
	 * Indicates if the object has or can have multiple properties or values. If true, the object can have more than one value, selectable by shoppers through the storefront or configurable through the catalogs.
	 */
	protected  Boolean isMultiValue;

	public Boolean getIsMultiValue() {
		return this.isMultiValue;
	}

	public void setIsMultiValue(Boolean isMultiValue) {
		this.isMultiValue = isMultiValue;
	}

	/**
	 * Detail data for a product or product options attribute. This acts as a wrapper for the properties to configure or generate from the system in the product Admin. Properties may include namespace, attribute code, attribute sequence, site group ID, input type, and value.
	 */
	protected  ProductAttribute attributeDetail;

	public ProductAttribute getAttributeDetail() {
		return this.attributeDetail;
	}

	public void setAttributeDetail(ProductAttribute attributeDetail) {
		this.attributeDetail = attributeDetail;
	}

	/**
	 * List of value data for objects.
	 */
	protected List<ProductPropertyValue> values;
	public List<ProductPropertyValue> getValues() {
		return this.values;
	}
	public void setValues(List<ProductPropertyValue> values) {
		this.values = values;
	}

}


text:
from django.conf.urls import patterns, include, url

urlpatterns = patterns('',
	# incoming hook
	url(r'^payload$', 'posthooks.views.payload')
)


text:
using FluentAssertions;
using NUnit.Framework;
using Trinity.Extensions;

namespace Trinity.Unit.Tests
{
    public class UT_Fixed8
    {
        [Test]
        public void Basic_equality()
        {
            var a = Fixed8.FromDecimal(1.23456789m);
            var b = Fixed8.Parse("1.23456789");
            a.Should().Be(b);
        }

        [Test]
        public void Can_parse_exponent_notation()
        {
            var expected = Fixed8.FromDecimal(1.23m);
            var actual = Fixed8.Parse("1.23E-0");
            actual.Should().Be(expected);
        }
    }
}


text:
using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Drawing;
using System.IO;
using System.Runtime.CompilerServices;
using System.Windows;
using System.Windows.Input;
using IOUtils;
using LogUtils;
using Microsoft.Win32;
using ProjectMarkdown.Annotations;
using ProjectMarkdown.Model;
using ProjectMarkdown.Services;
using ProjectMarkdown.Statics;
using ProjectMarkdown.Windows;

namespace ProjectMarkdown.ViewModels
{
    public class PreferencesViewModel : INotifyPropertyChanged, IRequireViewIdentification
    {
        private PreferencesModel _currentPreferences;
        private ObservableCollection<string> _logLevels;
        private ObservableCollection<string> _fontSizes;
        private ObservableCollection<string> _fonts;
        private ObservableCollection<string> _languages;
        private ObservableCollection<string> _colors;

        public Guid ViewID { get; }

        public ObservableCollection<string> Languages
        {
            get { return _languages; }
            set
            {
                _languages = value;
                OnPropertyChanged();
            }
        }

        public ObservableCollection<string> Fonts
        {
            get { return _fonts; }
            set
            {
                _fonts = value;
                OnPropertyChanged();
            }
        }

        public ObservableCollection<string> FontSizes
        {
            get { return _fontSizes; }
            set
            {
                _fontSizes = value;
                OnPropertyChanged();
            }
        }

        public ObservableCollection<string> Colors
        {
            get { return _colors; }
            set
            {
                _colors = value;
                OnPropertyChanged();
            }
        }

        public ObservableCollection<string> LogLevels
        {
            get { return _logLevels; }
            set
            {
                _logLevels = value;
                OnPropertyChanged();
            }
        }

        public PreferencesModel CurrentPreferences
        {
            get { return _currentPreferences; }
            set
            {
                _currentPreferences = value;
                OnPropertyChanged();
            }
        }

        public ICommand SelectLogFileCommand { get; set; }
        public ICommand CancelPreferenceChangesCommand { get; set; }
        public ICommand SavePreferencesCommand { get; set; }

        public PreferencesViewModel()
        {
            Logger.GetInstance().Debug("PreferencesViewModel() >>");

            try
            {
                ViewID = Guid.NewGuid();

                if (DesignerProperties.GetIsInDesignMode(new DependencyObject()))
                {
                    return;
                }

                LoadCommands();

                if (File.Exists(FilePaths.PreferencesFilePath))
                {
                    var gxs = new GenericXmlSerializer<PreferencesModel>();
                    CurrentPreferences = gxs.DeSerialize(FilePaths.PreferencesFilePath);
                }
                else
                {
                    throw new Exception(FilePaths.PreferencesFilePath + " file does not exist!");
                }

                LogLevels = new ObservableCollection<string> { "DEBUG", "INFO", "ERROR" };

                var fonts = new ObservableCollection<string>();
                foreach (var fontFamily in FontFamily.Families)
                {
                    fonts.Add(fontFamily.Name);
                }
                Fonts = fonts;

                FontSizes = new ObservableCollection<string>
            {
                "8",
                "9",
                "10",
                "11",
                "12",
                "14",
                "18",
                "24",
                "30",
                "36",
                "48",
                "60",
                "72"
            };

                Languages = new ObservableCollection<string> { "English" };
                Colors = new ObservableCollection<string> {"Amber", "Blue", "BlueGrey", "Brown", "Cyan", "DeepOrange", "DeepPurple", "Green", "Grey", "Indigo", "LightBlue", "LightGreen", "Lime",
                "Orange", "Pink", "Purple", "Red", "Teal", "Yellow"};
            }
            catch (Exception e)
            {
                Logger.GetInstance().Error(e.ToString());
                MessageBox.Show(e.Message, "An error occured while initializing the window", MessageBoxButton.OK, MessageBoxImage.Error);
            }

            Logger.GetInstance().Debug("<< PreferencesViewModel()");
        }

        private void LoadCommands()
        {
            Logger.GetInstance().Debug("LoadCommands() >>");

            try
            {
                SelectLogFileCommand = new RelayCommand(SelectLogFile, CanSelectLogFile);
                CancelPreferenceChangesCommand = new RelayCommand(CancelPreferences, CanCancelPreferences);
                SavePreferencesCommand = new RelayCommand(SavePreferences, CanSavePreferences);
            }
            catch (Exception e)
            {
                Logger.GetInstance().Error(e.ToString());
                MessageBox.Show(e.Message, "An error occured while loading commands", MessageBoxButton.OK, MessageBoxImage.Error);
            }

            Logger.GetInstance().Debug("<< LoadCommands()");
        }

        public bool CanSelectLogFile(object obj)
        {
            return true;
        }

        public void SelectLogFile(object obj)
        {
            Logger.GetInstance().Debug("SelectLogFile() >>");

            try
            {
                var saveFileDialog = new SaveFileDialog();
                saveFileDialog.CreatePrompt = true;
                saveFileDialog.Title = "Select a LOG file";
                saveFileDialog.Filter = "LOG file | *.log";
                var result = saveFileDialog.ShowDialog();

                if (result != null)
                {
                    if (result == true)
                    {
                        CurrentPreferences.LogFilePath = saveFileDialog.FileName;
                    }
                }
            }
            catch (Exception e)
            {
                Logger.GetInstance().Error(e.ToString());
                MessageBox.Show(e.Message, "An error occured while selecting the LOG file", MessageBoxButton.OK,
                    MessageBoxImage.Error);
            }

            Logger.GetInstance().Debug("<< SelectLogFile()");
        }

        public bool CanCancelPreferences(object obj)
        {
            return true;
        }

        public void CancelPreferences(object obj)
        {
            Logger.GetInstance().Debug("CancelPreferences() >>");

            try
            {
                WindowManager.GetInstance().CloseWindow(ViewID);
            }
            catch (Exception e)
            {
                Logger.GetInstance().Error(e.ToString());
                MessageBox.Show(e.Message, "An error occured while closing the preferences window", MessageBoxButton.OK,
                    MessageBoxImage.Error);
            }

            Logger.GetInstance().Debug("<< CancelPreferences()");
        }

        public bool CanSavePreferences(object obj)
        {
            return true;
        }

        public void SavePreferences(object obj)
        {
            Logger.GetInstance().Debug("SavePreferences() >>");

            try
            {
                var gxs = new GenericXmlSerializer<PreferencesModel>();

                gxs.Serialize(CurrentPreferences, FilePaths.PreferencesFilePath);

                SharedEventHandler.GetInstance().RaiseOnPreferencesSaved(CurrentPreferences);

                WindowManager.GetInstance().CloseWindow(ViewID);
            }
            catch (Exception e)
            {
                Logger.GetInstance().Error(e.ToString());
                MessageBox.Show(e.Message, "An error occured while saving preferences", MessageBoxButton.OK,
                    MessageBoxImage.Error);
            }

            Logger.GetInstance().Debug("<< SavePreferences()");
        }

        public event PropertyChangedEventHandler PropertyChanged;

        [NotifyPropertyChangedInvocator]
        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}


text:
const createValidityAssertion = require('../lib/validityAssertion');

module.exports = createValidityAssertion({
  pass: (valid) => valid,
  passName: 'valid',
  failName: 'invalid',
});


text:
import { Resource } from './Resource';
import { determineCrossOrigin } from '@pixi/utils';
import { ALPHA_MODES } from '@pixi/constants';

import type { BaseTexture, ImageSource } from '../BaseTexture';
import type { Renderer } from '../../Renderer';
import type { GLTexture } from '../GLTexture';
/**
 * Base for all the image/canvas resources
 * @class
 * @extends PIXI.Resource
 * @memberof PIXI
 */
export class BaseImageResource extends Resource
{
    public source: ImageSource;
    public noSubImage: boolean;

    /**
     * @param {HTMLImageElement|HTMLCanvasElement|HTMLVideoElement|SVGElement} source
     */
    constructor(source: ImageSource)
    {
        const sourceAny = source as any;
        const width = sourceAny.naturalWidth || sourceAny.videoWidth || sourceAny.width;
        const height = sourceAny.naturalHeight || sourceAny.videoHeight || sourceAny.height;

        super(width, height);

        /**
         * The source element
         * @member {HTMLImageElement|HTMLCanvasElement|HTMLVideoElement|SVGElement}
         * @readonly
         */
        this.source = source;

        /**
         * If set to `true`, will force `texImage2D` over `texSubImage2D` for uploading.
         * Certain types of media (e.g. video) using `texImage2D` is more performant.
         * @member {boolean}
         * @default false
         * @private
         */
        this.noSubImage = false;
    }

    /**
     * Set cross origin based detecting the url and the crossorigin
     * @protected
     * @param {HTMLElement} element - Element to apply crossOrigin
     * @param {string} url - URL to check
     * @param {boolean|string} [crossorigin=true] - Cross origin value to use
     */
    static crossOrigin(element: HTMLImageElement|HTMLVideoElement, url: string, crossorigin?: boolean|string): void
    {
        if (crossorigin === undefined && url.indexOf('data:') !== 0)
        {
            element.crossOrigin = determineCrossOrigin(url);
        }
        else if (crossorigin !== false)
        {
            element.crossOrigin = typeof crossorigin === 'string' ? crossorigin : 'anonymous';
        }
    }

    /**
     * Upload the texture to the GPU.
     * @param {PIXI.Renderer} renderer - Upload to the renderer
     * @param {PIXI.BaseTexture} baseTexture - Reference to parent texture
     * @param {PIXI.GLTexture} glTexture
     * @param {HTMLImageElement|HTMLCanvasElement|HTMLVideoElement|SVGElement} [source] - (optional)
     * @returns {boolean} true is success
     */
    upload(renderer: Renderer, baseTexture: BaseTexture, glTexture: GLTexture, source?: ImageSource): boolean
    {
        const gl = renderer.gl;
        const width = baseTexture.realWidth;
        const height = baseTexture.realHeight;

        source = source || this.source;

        gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, baseTexture.alphaMode === ALPHA_MODES.UNPACK);

        if (!this.noSubImage
            && baseTexture.target === gl.TEXTURE_2D
            && glTexture.width === width
            && glTexture.height === height)
        {
            gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, baseTexture.format, glTexture.type, source);
        }
        else
        {
            glTexture.width = width;
            glTexture.height = height;

            gl.texImage2D(baseTexture.target, 0, glTexture.internalFormat, baseTexture.format, glTexture.type, source);
        }

        return true;
    }

    /**
     * Checks if source width/height was changed, resize can cause extra baseTexture update.
     * Triggers one update in any case.
     */
    update(): void
    {
        if (this.destroyed)
        {
            return;
        }

        const source = this.source as any;

        const width = source.naturalWidth || source.videoWidth || source.width;
        const height = source.naturalHeight || source.videoHeight || source.height;

        this.resize(width, height);

        super.update();
    }

    /**
     * Destroy this BaseImageResource
     * @override
     */
    dispose(): void
    {
        this.source = null;
    }
}


text:
package org.jadira.usertype.dateandtime.joda;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Table;

import org.jadira.usertype.dateandtime.joda.testmodel.JodaLocalDateTimeHolder;
import org.jadira.usertype.dateandtime.joda.testmodel.LocalDateTimeJoda;
import org.jadira.usertype.dateandtime.shared.dbunit.DatabaseCapable;
import org.joda.time.LocalDateTime;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;

public class TestPersistentLocalDateTime extends DatabaseCapable {

    private static final LocalDateTime[] localDateTimes     = new LocalDateTime[] { new LocalDateTime(2004, 2, 25, 12, 11, 10), new LocalDateTime(1980, 3, 11, 13, 12, 11) };
    private static final LocalDateTime[] jodaLocalDateTimes = new LocalDateTime[] { new LocalDateTime(2004, 2, 25, 12, 11, 10), new LocalDateTime(1980, 3, 11, 13, 12, 11) };

    private static EntityManagerFactory factory;

    @BeforeClass
    public static void setup() {
        factory = Persistence.createEntityManagerFactory("test1");
    }

    @AfterClass
    public static void tearDown() {
        factory.close();
    }

    @Test
    public void testPersist() {

        EntityManager manager = factory.createEntityManager();

        manager.getTransaction().begin();

        for (int i = 0; i < localDateTimes.length; i++) {

            JodaLocalDateTimeHolder item = new JodaLocalDateTimeHolder();
            item.setId(i);
            item.setName("test_" + i);
            item.setLocalDateTime(localDateTimes[i]);

            manager.persist(item);
        }

        manager.flush();

        manager.getTransaction().commit();

        manager.close();

        manager = factory.createEntityManager();

        for (int i = 0; i < localDateTimes.length; i++) {

            JodaLocalDateTimeHolder item = manager.find(JodaLocalDateTimeHolder.class, Long.valueOf(i));

            assertNotNull(item);
            assertEquals(i, item.getId());
            assertEquals("test_" + i, item.getName());
            assertEquals(localDateTimes[i], item.getLocalDateTime());
        }

        verifyDatabaseTable(manager, JodaLocalDateTimeHolder.class.getAnnotation(Table.class).name());

        manager.close();
    }

    @Test @Ignore // Joda Time Contrib does not support Hibernate 4 yet
    public void testRoundtripWithJodaTime() {

        EntityManager manager = factory.createEntityManager();

        manager.getTransaction().begin();
        for (int i = 0; i < localDateTimes.length; i++) {
            manager.remove(manager.find(JodaLocalDateTimeHolder.class, Long.valueOf(i)));
        }
        manager.flush();
        manager.getTransaction().commit();

        manager.getTransaction().begin();

        for (int i = 0; i < localDateTimes.length; i++) {

            LocalDateTimeJoda item = new LocalDateTimeJoda();
            item.setId(i);
            item.setName("test_" + i);
            item.setLocalDateTime(jodaLocalDateTimes[i]);

            manager.persist(item);
        }

        manager.flush();

        manager.getTransaction().commit();

        manager.close();

        manager = factory.createEntityManager();

        for (int i = 0; i < localDateTimes.length; i++) {

            JodaLocalDateTimeHolder item = manager.find(JodaLocalDateTimeHolder.class, Long.valueOf(i));

            assertNotNull(item);
            assertEquals(i, item.getId());
            assertEquals("test_" + i, item.getName());
            assertEquals(localDateTimes[i], item.getLocalDateTime());
        }
        manager.close();
    }

    @Test @Ignore // Nanos are not properly supported by JodaTime type
    public void testNanosWithJodaTime() {

        EntityManager manager = factory.createEntityManager();

        manager.getTransaction().begin();
        for (int i = 0; i < localDateTimes.length; i++) {
            manager.remove(manager.find(JodaLocalDateTimeHolder.class, Long.valueOf(i)));
        }
        manager.flush();
        manager.getTransaction().commit();

        manager.getTransaction().begin();

        JodaLocalDateTimeHolder item = new JodaLocalDateTimeHolder();
        item.setId(1);
        item.setName("test_nanos1");
        item.setLocalDateTime(new LocalDateTime(2010, 8, 1, 10, 10, 10, 111444444));

        manager.persist(item);
        manager.flush();

        manager.getTransaction().commit();

        manager.close();

        manager = factory.createEntityManager();

        LocalDateTimeJoda jodaItem = manager.find(LocalDateTimeJoda.class, Long.valueOf(1));

        assertNotNull(jodaItem);
        assertEquals(1, jodaItem.getId());
        assertEquals("test_nanos1", jodaItem.getName());
        assertEquals(new org.joda.time.LocalDateTime(2010, 8, 1, 10, 10, 10, 111), jodaItem.getLocalDateTime());

        manager.close();

        manager = factory.createEntityManager();

        item = manager.find(JodaLocalDateTimeHolder.class, Long.valueOf(1));

        assertNotNull(item);
        assertEquals(1, item.getId());
        assertEquals("test_nanos1", item.getName());
//        assertEquals(new LocalDateTime(2010, 8, 1, 10, 10, 10, 111444444), item.getLocalDateTime());

        manager.close();
    }
}


text:
import { intFromBase64, intToBase64, isBase64 } from './../base64';

class InvalidCreature extends Error {
}

const decodeHealth = encoded => intFromBase64(encoded);

const encodeHealth = health =>
    intToBase64(Math.floor(health), 2);

const decodeColor = encoded => {
    const value = intFromBase64(encoded);
    return {
        isRed: !!(value & 0x1),
        isGreen: !!(value & 0x2),
        isBlue: !!(value & 0x4)
    };
};

const encodeColor = ({ isRed, isGreen, isBlue }) =>
    intToBase64((isRed ? 0x1 : 0) + (isGreen ? 0x2 : 0) + (isBlue ? 0x4 : 0));

const decodeVelocity = encoded => {
    const value = intFromBase64(encoded);
    return {
        angle: value & 0x1FF,
        isMoving: !!((value & 0x200) >> 9),
        isFast: !!((value & 0x400) >> 10),
        isAggressive: !!((value & 0x800) >> 11)
    };
};

const encodeVelocity = ({ angle, isAggressive, isMoving, isFast }) =>
    intToBase64(
        ((isAggressive ? 1 : 0) << 11) +
        ((isFast ? 1 : 0) << 10) +
        ((isMoving ? 1 : 0) << 9) +
        Math.floor(angle), 2);

const decodeLocation = encoded => intFromBase64(encoded);

const encodeLocation = location => intToBase64(Math.floor(location), 4);

const decodeID = encoded => encoded;

const encodeID = id => id;

const decodeAge = encoded => intFromBase64(encoded);

const encodeAge = age => intToBase64(Math.floor(age), 5);

const decodeType = encoded => !!intFromBase64(encoded);

const encodeType = isCarnivore => isCarnivore ? '1' : '0';

const decodeAnatomy = encoded => {
    const value = intFromBase64(encoded);
    return {
        body: (value >> 9) & 0x7,
        eyes: (value >> 6) & 0x7,
        legs: (value >> 3) & 0x7,
        mouth: value & 0x7
    };
};

const encodeAnatomy = ({ body, eyes, legs, mouth }) =>
    intToBase64(
        ((body & 0x7) << 9) |
        ((eyes & 0x7) << 6) |
        ((legs & 0x7) << 3) |
        (mouth & 0x7), 2);

const decodeHeader = encoded => {
    const version = encoded[0];
    if (version !== '1') {
        throw new InvalidCreature('Unexpected version');
    }

    return {
        version
    };
};

const encodeHeader = header => header.version;

const decodeSlices = (encoded, slicing) => {
    let currentIndex = 0;

    const decoded = slicing.reduce(
        (aggregate, { property, length, decoder }) => {
            if (!length) {
                length = encoded.length - currentIndex;
            }

            if ((currentIndex === encoded.length) ||
                (currentIndex + length > encoded.length)) {
                throw new InvalidCreature(`Creature missing ${property}`);
            }

            const encodedProperty = encoded.substr(currentIndex, length);
            aggregate[property] = decoder(encodedProperty);
            currentIndex += length;

            return aggregate;
        },
        {});

    return decoded;
};

const encodeSlices = (decoded, slicing) =>
    slicing.reduce(
        (aggregate, { property, encoder }) =>
            aggregate + encoder(decoded[property]),
        '');

const makeSlicing = makeDNA => [
    {
        property: 'header',
        length: 1,
        decoder: decodeHeader,
        encoder: encodeHeader
    },
    {
        property: 'id',
        length: 5,
        decoder: decodeID,
        encoder: encodeID
    },
    {
        property: 'age',
        length: 5,
        decoder: decodeAge,
        encoder: encodeAge
    },
    {
        property: 'x',
        length: 4,
        decoder: decodeLocation,
        encoder: encodeLocation
    },
    {
        property: 'y',
        length: 4,
        decoder: decodeLocation,
        encoder: encodeLocation
    },
    {
        property: 'velocity',
        length: 2,
        decoder: decodeVelocity,
        encoder: encodeVelocity
    },
    {
        property: 'health',
        length: 2,
        decoder: decodeHealth,
        encoder: encodeHealth
    },
    {
        property: 'color',
        length: 1,
        decoder: decodeColor,
        encoder: encodeColor
    },
    {
        property: 'isCarnivore',
        length: 1,
        decoder: decodeType,
        encoder: encodeType
    },
    {
        property: 'anatomy',
        length: 2,
        decoder: decodeAnatomy,
        encoder: encodeAnatomy
    },
    {
        property: 'dna',
        decoder: encodedDNA => makeDNA(encodedDNA),
        encoder: dna => dna.toString()
    }
];

export const deserializeCreature = (encoded, makeDNA) => {
    if (!isBase64(encoded)) {
        throw new InvalidCreature('Encoded creature is not a base64 string');
    }

    return decodeSlices(encoded, makeSlicing(makeDNA));
};

export const serializeCreature = (data, makeDNA) =>
    encodeSlices(data, makeSlicing(makeDNA));