text:
"use strict";
var scan_1 = require('../operators/scan');
/* tslint:enable:max-line-length */
/**
 * Applies an accumulator function over the source Observable, and returns each
 * intermediate result, with an optional seed value.
 *
 * It's like {@link reduce}, but emits the current
 * accumulation whenever the source emits a value.
 *
 *
 *
 * Combines together all values emitted on the source, using an accumulator
 * function that knows how to join a new source value into the accumulation from
 * the past. Is similar to {@link reduce}, but emits the intermediate
 * accumulations.
 *
 * Returns an Observable that applies a specified `accumulator` function to each
 * item emitted by the source Observable. If a `seed` value is specified, then
 * that value will be used as the initial value for the accumulator. If no seed
 * value is specified, the first item of the source is used as the seed.
 *
 * @example
Count the number of click events

 * var clicks = Rx.Observable.fromEvent(document, 'click');
 * var ones = clicks.mapTo(1);
 * var seed = 0;
 * var count = ones.scan((acc, one) => acc + one, seed);
 * count.subscribe(x => console.log(x));
 *
 * @see {@link expand}
 * @see {@link mergeScan}
 * @see {@link reduce}
 *
 * @param {function(acc: R, value: T, index: number): R} accumulator
 * The accumulator function called on each source value.
 * @param {T|R} [seed] The initial accumulation value.
 * @return {Observable<R>} An observable of the accumulated values.
 * @method scan
 * @owner Observable
 */
function scan(accumulator, seed) {
    if (arguments.length >= 2) {
        return scan_1.scan(accumulator, seed)(this);
    }
    return scan_1.scan(accumulator)(this);
}
exports.scan = scan;
//# sourceMappingURL=scan.js.map


text:
import Controller from '../../core/Controller';
import Model from '../../core/Model';
import View from '../../core/View';
import Notification from '../observer/Notification';

class Facade {
  controller = null;
  model = null;
  view = null;
  multitonKey = null;
  constructor(key) {
    if (Facade.instanceMap[key] != null) {
      throw new Error(Facade.MULTITON_MSG);
    }

    this.initializeNotifier(key);
    Facade.instanceMap[key] = this;
    this.initializeFacade();
  }

  initializeFacade() {
    this.initializeModel();
    this.initializeController();
    this.initializeView();
  }

  initializeController() {
    if (this.controller != null) {
      return;
    }

    this.controller = Controller.getInstance(this.multitonKey);
  }

  initializeModel() {
    if (this.model != null) {
      return;
    }

    this.model = Model.getInstance(this.multitonKey);
  }

  initializeView() {
    if (this.view != null) {
      return;
    }

    this.view = View.getInstance(this.multitonKey);
  }

  registerCommand(notificationName, commandClassRef) {
    this.controller.registerCommand(notificationName, commandClassRef);
  }

  removeCommand(notificationName) {
    this.controller.removeCommand(notificationName);
  }

  hasCommand(notificationName) {
    return this.controller.hasCommand(notificationName);
  }

  registerProxy(proxy) {
    this.model.registerProxy(proxy);
  }

  retrieveProxy(proxyName) {
    return this.model.retrieveProxy(proxyName);
  }

  removeProxy(proxyName) {
    let proxy = null;
    if (this.model != null) {
      proxy = this.model.removeProxy(proxyName);
    }

    return proxy;
  }

  hasProxy(proxyName) {
    return this.model.hasProxy(proxyName);
  }

  registerMediator(mediator) {
    if (this.view != null) {
      this.view.registerMediator(mediator);
    }
  }

  retrieveMediator(mediatorName) {
    return this.view.retrieveMediator(mediatorName);
  }

  removeMediator(mediatorName) {
    var mediator = null;
    if (this.view != null) {
      mediator = this.view.removeMediator(mediatorName);
    }

    return mediator;
  }

  hasMediator(mediatorName) {
    return this.view.hasMediator(mediatorName);
  }

  sendNotification(notificationName, body, type) {
    this.notifyObservers(new Notification(notificationName, body, type));
  }

  notifyObservers(notification) {
    if (this.view != null) {
      this.view.notifyObservers(notification);
    }
  }

  initializeNotifier(key) {
    this.multitonKey = key;
  }

  static instanceMap = [];
  static MULTITON_MSG = "Facade instance for this Multiton key already constructed!";

  static hasCore(key) {
    return Facade.instanceMap[key] != null;
  }

  static removeCore(key) {
    if (Facade.instanceMap[key] == null) {
      return;
    }

    Model.removeModel(key);
    View.removeView(key);
    Controller.removeController(key);
    delete Facade.instanceMap[key];
  }

  static getInstance(key) {
    if (null == key) {
      return null;
    }

    if (Facade.instanceMap[key] == null) {
      Facade.instanceMap[key] = new Facade(key);
    }

    return Facade.instanceMap[key];
  }
}

export default Facade;

redpajama_set_name: RedPajamaGithub


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

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>org.apache.lucene.facet.taxonomy (Lucene 6.0.1 API)</title>
<meta name="date" content="2016-05-23">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Help

Prev Package

Next Package

Frames

No Frames

All Classes

Package org.apache.lucene.facet.taxonomy

Taxonomy of Categories.

See: Description

Interface Summary

Interface
Description

TaxonomyWriter

TaxonomyWriter is the interface which the faceted-search library uses
 to dynamically build the taxonomy at indexing time.

Class Summary

Class
Description

AssociationFacetField

Add an instance of this to your Document to add
  a facet label associated with an arbitrary byte[].

CachedOrdinalsReader

A per-segment cache of documents' facet ordinals.

CachedOrdinalsReader.CachedOrds

Holds the cached ordinals in two parallel int[] arrays.

DocValuesOrdinalsReader

Decodes ordinals previously indexed into a BinaryDocValues field

FacetLabel

Holds a sequence of string components, specifying the hierarchical name of a
 category.

FastTaxonomyFacetCounts

Computes facets counts, assuming the default encoding
  into DocValues was used.

FloatAssociationFacetField

Add an instance of this to your Document to add
  a facet label associated with a float.

FloatTaxonomyFacets

Base class for all taxonomy-based facets that aggregate
  to a per-ords float[].

IntAssociationFacetField

Add an instance of this to your Document to add
  a facet label associated with an int.

IntTaxonomyFacets

Base class for all taxonomy-based facets that aggregate
  to a per-ords int[].

LRUHashMap<K,V>

LRUHashMap is an extension of Java's HashMap, which has a bounded size();
 When it reaches that size, each time a new element is added, the least
 recently used (LRU) entry is removed.

OrdinalMappingLeafReader

A FilterLeafReader for updating facets ordinal references,
 based on an ordinal map.

OrdinalsReader

Provides per-document ordinals.

OrdinalsReader.OrdinalsSegmentReader

Returns ordinals for documents in one segment.

ParallelTaxonomyArrays

Returns 3 arrays for traversing the taxonomy:

 parents: parents[i] denotes the parent of category
 ordinal i.
 children: children[i] denotes a child of category ordinal
 i.
 siblings: siblings[i] denotes the sibling of category
 ordinal i.

 To traverse the taxonomy tree, you typically start with children[0]
 (ordinal 0 is reserved for ROOT), and then depends if you want to do DFS or
 BFS, you call children[children[0]] or siblings[children[0]]
 and so forth, respectively.

PrintTaxonomyStats

Prints how many ords are under each dimension.

SearcherTaxonomyManager

Manages near-real-time reopen of both an IndexSearcher
 and a TaxonomyReader.

SearcherTaxonomyManager.SearcherAndTaxonomy

Holds a matched pair of IndexSearcher and
  TaxonomyReader

TaxonomyFacetCounts

Reads from any OrdinalsReader; use FastTaxonomyFacetCounts if you are using the
  default encoding from BinaryDocValues.

TaxonomyFacets

Base class for all taxonomy-based facets impls.

TaxonomyFacetSumFloatAssociations

Aggregates sum of int values previously indexed with
  FloatAssociationFacetField, assuming the default
  encoding.

TaxonomyFacetSumIntAssociations

Aggregates sum of int values previously indexed with
  IntAssociationFacetField, assuming the default
  encoding.

TaxonomyFacetSumValueSource

Aggregates sum of values from FunctionValues.doubleVal(int), for each facet label.

TaxonomyFacetSumValueSource.ScoreValueSource

ValueSource that returns the score for each
  hit; use this to aggregate the sum of all hit scores
  for each facet label.

TaxonomyMergeUtils

Utility methods for merging index and taxonomy directories.

TaxonomyReader

TaxonomyReader is the read-only interface with which the faceted-search
 library uses the taxonomy during search time.

TaxonomyReader.ChildrenIterator

An iterator over a category's children.

Package org.apache.lucene.facet.taxonomy Description

Taxonomy of Categories.

 Facets are defined using a hierarchy of categories, known as a Taxonomy.
 For example, the taxonomy of a book store application might have the following structure:

Author

Mark Twain

J. K. Rowling

Date

2010

March

April

2009

 The Taxonomy translates category-paths into integer identifiers (often termed ordinals) and vice versa.
 The category Author/Mark Twain adds two nodes to the taxonomy: Author and
 Author/Mark Twain, each is assigned a different ordinal. The taxonomy maintains the invariant that a
 node always has an ordinal that is < all its children.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Help

Prev Package

Next Package

Frames

No Frames

All Classes

          Copyright © 2000-2016 Apache Software Foundation.  All Rights Reserved.


text:
/**
 * @file
 * @brief Board configuration macros for the ia32 platform
 *
 * This header file is used to specify and describe board-level aspects for
 * the 'ia32' platform.
 */

#ifndef __SOC_H_
#define __SOC_H_

#include <zephyr/sys/util.h>

#ifndef _ASMLANGUAGE
#include <zephyr/device.h>
#include <zephyr/random/rand32.h>
#endif

/* PCI definitions */
/* FIXME: The values below copied from generic ia32 soc, we need to get the
 * correct numbers for Atom and the minnowboard
 *
 * This is added now to get basic enumeration of devices and verify that PCI
 * driver is functional.
 */
#define PCI_BUS_NUMBERS 1

#define PCI_CTRL_ADDR_REG 0xCF8
#define PCI_CTRL_DATA_REG 0xCFC

#define PCI_INTA 1
#define PCI_INTB 2
#define PCI_INTC 3
#define PCI_INTD 4

/**
 *
 * @brief Convert PCI interrupt PIN to IRQ
 *
 * @return IRQ number, -1 if the result is incorrect
 *
 */

static inline int pci_pin2irq(int bus, int dev, int pin)
{
	ARG_UNUSED(bus);

	if ((pin < PCI_INTA) || (pin > PCI_INTD)) {
		return -1;
	}
	return 10 + (((pin + dev - 1) >> 1) & 1);
}

#endif /* __SOC_H_ */


text:
<?xml version="1.0"?>
<!DOCTYPE validators PUBLIC
          "-//Apache Struts//XWork Validator 1.0.2//EN"
          "http://struts.apache.org/dtds/xwork-validator-1.0.2.dtd">
<validators>

  <field name="restid">
      <field-validator type="requiredstring">
      	   <message key="requiredfield"/>
      </field-validator>
  </field>

</validators>


text:
<?xml version="1.0" encoding="UTF-8"?>
<sbml xmlns="http://www.sbml.org/sbml/level2/version2" level="2" version="2">
    <model>
        <listOfCompartments>
            <compartment id="cell" size="0.013"/>
        </listOfCompartments>
        <listOfSpecies>
            <species id="X0" compartment="cell" spatialSizeUnits="volume"/>
        </listOfSpecies>
    </model>
</sbml>


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

namespace CJia.Parking.Models
{
    public class MainFormModel : CJia.Parking.Tools.Model
    {
        /// <summary>
        /// 查询登录用户所拥有权限
        /// </summary>
        /// <param name="userId">登录用户ID</param>
        /// <returns></returns>
        public DataTable QueryLogionUserRoles(long userId)
        {
            object[] sqlParams = new object[] { userId };
            return CJia.DefaultPostgre.Query(SqlTools.SqlQueryLoginUserRoles,sqlParams);
        }
    }
}


text:
// Working Files List
// Visual Studio extension tool window that shows a selectable list of files
// that are open in the editor
// Copyright © 2016 Anthony Fung

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

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

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

using System;
using System.ComponentModel;
using WorkingFilesList.Core.Interface;

namespace WorkingFilesList.Core.Model.SortOption
{
    /// <summary>
    /// Represents an option for criteria on sorting the displayed document
    /// metadata
    /// </summary>
    public abstract class SortOptionBase : ISortOption
    {
        /// <summary>
        /// Indicates whether calling <see cref="GetSortDescription"/> should
        /// return a valid <see cref="SortDescription"/>
        /// </summary>
        public bool HasSortDescription { get; }

        /// <summary>
        /// Indicates desired order of appearance when displayed in a sorted list
        /// </summary>
        public int DisplayIndex { get; set; }

        /// <summary>
        /// Indicates which project items types derived classes are applicable
        /// to
        /// </summary>
        public ProjectItemType ApplicableType { get; }

        /// <summary>
        /// Name that this set of sorting criteria will be displayed as
        /// </summary>
        public string DisplayName { get; }

        /// <summary>
        /// Name of the property used as sorting criteria
        /// </summary>
        public string PropertyName { get; }

        /// <summary>
        /// Direction that sorting should occur
        /// </summary>
        public ListSortDirection SortDirection { get; }

        protected SortOptionBase(string displayName, ProjectItemType applicableTypes)
        {
            ApplicableType = applicableTypes;
            DisplayName = displayName;
            HasSortDescription = false;
        }

        protected SortOptionBase(
            string displayName,
            string propertyName,
            ListSortDirection sortDirection,
            ProjectItemType applicableTypes)
        {
            ApplicableType = applicableTypes;
            DisplayName = displayName;
            PropertyName = propertyName;
            SortDirection = sortDirection;
            HasSortDescription = true;
        }

        /// <summary>
        /// Creates a <see cref="SortDescription"/> that can be added to the
        /// sort descriptions of an <see cref="ICollectionView"/>
        /// </summary>
        /// <returns>
        /// A <see cref="SortDescription"/> that describes the sorting criteria
        /// represented by this <see cref="ISortOption"/> instance
        /// </returns>
        public SortDescription GetSortDescription()
        {
            if (HasSortDescription)
            {
                var sortDescription = new SortDescription(
                    PropertyName,
                    SortDirection);

                return sortDescription;
            }
            else
            {
                throw new NotSupportedException(
                    "This type does not represent usable sorting criteria");
            }
        }
    }
}


text:
#pragma once
#include <aws/ce/CostExplorer_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
namespace Utils
{
namespace Json
{
  class JsonValue;
  class JsonView;
} // namespace Json
} // namespace Utils
namespace CostExplorer
{
namespace Model
{

  /**
   *
The aggregated value for a metric.

See Also:
   AWS API
   * Reference

   */
  class AWS_COSTEXPLORER_API MetricValue
  {
  public:
    MetricValue();
    MetricValue(Aws::Utils::Json::JsonView jsonValue);
    MetricValue& operator=(Aws::Utils::Json::JsonView jsonValue);
    Aws::Utils::Json::JsonValue Jsonize() const;

    /**
     *
The actual number that represents the metric.

     */
    inline const Aws::String& GetAmount() const{ return m_amount; }

    /**
     *
The actual number that represents the metric.

     */
    inline bool AmountHasBeenSet() const { return m_amountHasBeenSet; }

    /**
     *
The actual number that represents the metric.

     */
    inline void SetAmount(const Aws::String& value) { m_amountHasBeenSet = true; m_amount = value; }

    /**
     *
The actual number that represents the metric.

     */
    inline void SetAmount(Aws::String&& value) { m_amountHasBeenSet = true; m_amount = std::move(value); }

    /**
     *
The actual number that represents the metric.

     */
    inline void SetAmount(const char* value) { m_amountHasBeenSet = true; m_amount.assign(value); }

    /**
     *
The actual number that represents the metric.

     */
    inline MetricValue& WithAmount(const Aws::String& value) { SetAmount(value); return *this;}

    /**
     *
The actual number that represents the metric.

     */
    inline MetricValue& WithAmount(Aws::String&& value) { SetAmount(std::move(value)); return *this;}

    /**
     *
The actual number that represents the metric.

     */
    inline MetricValue& WithAmount(const char* value) { SetAmount(value); return *this;}

    /**
     *
The unit that the metric is given in.

     */
    inline const Aws::String& GetUnit() const{ return m_unit; }

    /**
     *
The unit that the metric is given in.

     */
    inline bool UnitHasBeenSet() const { return m_unitHasBeenSet; }

    /**
     *
The unit that the metric is given in.

     */
    inline void SetUnit(const Aws::String& value) { m_unitHasBeenSet = true; m_unit = value; }

    /**
     *
The unit that the metric is given in.

     */
    inline void SetUnit(Aws::String&& value) { m_unitHasBeenSet = true; m_unit = std::move(value); }

    /**
     *
The unit that the metric is given in.

     */
    inline void SetUnit(const char* value) { m_unitHasBeenSet = true; m_unit.assign(value); }

    /**
     *
The unit that the metric is given in.

     */
    inline MetricValue& WithUnit(const Aws::String& value) { SetUnit(value); return *this;}

    /**
     *
The unit that the metric is given in.

     */
    inline MetricValue& WithUnit(Aws::String&& value) { SetUnit(std::move(value)); return *this;}

    /**
     *
The unit that the metric is given in.

     */
    inline MetricValue& WithUnit(const char* value) { SetUnit(value); return *this;}

  private:

    Aws::String m_amount;
    bool m_amountHasBeenSet = false;

    Aws::String m_unit;
    bool m_unitHasBeenSet = false;
  };

} // namespace Model
} // namespace CostExplorer
} // namespace Aws


text:
namespace supermarx
{

template<typename T>
class reference
{
private:
	id_t id;

public:
	reference(id_t _id)
	: id(_id)
	{}

	id_t unseal() const // No implicit conversion
	{
		return id;
	}

	bool operator==(reference<T> const& rhs) const
	{
		return id == rhs.id;
	}

	bool operator<(reference<T> const& rhs) const
	{
		return id < rhs.id;
	}
};

template<typename T>
static inline std::ostream& operator<<(std::ostream& os, reference<T> const& rhs)
{
	os << rhs.unseal();
	return os;
}

}


text:
Yet, just another bot to generate totp

To use the bot access [OneTimePassBot](https://t.me/OneTimePassBot) and be happy

## If dont believe in my server
Fork the project, rename `.env.dist` to `.env`, set the necessary values to environments and be happy with your own server and your own bot

## Contributing
If you are interested in fixing issues and contributing directly to the code
base, please see the document [How to Contribute](CONTRIBUTING.md),

## Tests
Do not exist, if you want to help with this project, fork, implement and make a pull request to this repository.

## License
Licensed under the MIT License.


text: introse project


text:
// Copyright (c) Lex Li. All rights reserved.
//
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

namespace JexusManager.Features.MimeMap
{
    using System;

    using Properties;

    using Microsoft.Web.Management.Client;
    using Microsoft.Web.Management.Server;

    internal class MimeMapModule : Module
    {
        protected override void Initialize(IServiceProvider serviceProvider, ModuleInfo moduleInfo)
        {
            base.Initialize(serviceProvider, moduleInfo);
            var controlPanel = (IControlPanel)this.GetService(typeof(IControlPanel));
            var modulePage = new ModulePageInfo(this, typeof(MimeMapPage), "MIME Types",
                "Configure extensions and associated content types that are served as static files", Resources.mime_map_36,
                Resources.mime_map_36);
            controlPanel.RegisterPage(modulePage);
        }
    }
}


text:
/**
 * Broadcast updates to client when the model changes
 */

'use strict';

var PollEvents = require('./poll.events');

// Model events to emit
var events = ['save', 'remove'];

export function register(socket) {
  // Bind model events to socket events
  for (var i = 0, eventsLength = events.length; i < eventsLength; i++) {
    var event = events[i];
    var listener = createListener('poll:' + event, socket);

    PollEvents.on(event, listener);
    socket.on('disconnect', removeListener(event, listener));
  }
}

function createListener(event, socket) {
  return function(doc) {
    socket.emit(event, doc);
  };
}

function removeListener(event, listener) {
  return function() {
    PollEvents.removeListener(event, listener);
  };
}


text:
package fault

import "github.com/go-ozzo/ozzo-routing/v2"

type (
	// LogFunc logs a message using the given format and optional arguments.
	// The usage of format and arguments is similar to that for fmt.Printf().
	// LogFunc should be thread safe.
	LogFunc func(format string, a ...interface{})

	// ConvertErrorFunc converts an error into a different format so that it is more appropriate for rendering purpose.
	ConvertErrorFunc func(*routing.Context, error) error
)

// Recovery returns a handler that handles both panics and errors occurred while servicing an HTTP request.
// Recovery can be considered as a combination of ErrorHandler and PanicHandler.
//
// The handler will recover from panics and render the recovered error or the error returned by a handler.
// If the error implements routing.HTTPError, the handler will set the HTTP status code accordingly.
// Otherwise the HTTP status is set as http.StatusInternalServerError. The handler will also write the error
// as the response body.
//
// A log function can be provided to log a message whenever an error is handled. If nil, no message will be logged.
//
// An optional error conversion function can also be provided to convert an error into a normalized one
// before sending it to the response.
//
//     import (
//         "log"
//         "github.com/go-ozzo/ozzo-routing/v2"
//         "github.com/go-ozzo/ozzo-routing/v2/fault"
//     )
//
//     r := routing.New()
//     r.Use(fault.Recovery(log.Printf))
func Recovery(logf LogFunc, errorf ...ConvertErrorFunc) routing.Handler {
	handlePanic := PanicHandler(logf)
	return func(c *routing.Context) error {
		if err := handlePanic(c); err != nil {
			if logf != nil {
				logf("%v", err)
			}
			if len(errorf) > 0 {
				err = errorf[0](c, err)
			}
			writeError(c, err)
			c.Abort()
		}
		return nil
	}
}


text:
package nxt.http;

import nxt.NxtException;
import nxt.Order;
import org.json.simple.JSONStreamAware;

import javax.servlet.http.HttpServletRequest;

import static nxt.http.JSONResponses.UNKNOWN_ORDER;

public final class GetBidOrder extends APIServlet.APIRequestHandler {

    static final GetBidOrder instance = new GetBidOrder();

    private GetBidOrder() {
        super("order");
    }

    @Override
    JSONStreamAware processRequest(HttpServletRequest req) throws NxtException {
        Long orderId = ParameterParser.getOrderId(req);
        Order.Bid bidOrder = Order.Bid.getBidOrder(orderId);
        if (bidOrder == null) {
            return UNKNOWN_ORDER;
        }
        return JSONData.bidOrder(bidOrder);
    }

}


text:
module Api::Views::MarketEntries
  class Search
    include Api::View

    def render
      market_entries.to_json
    end
  end
end


text:
var express = require('express');
var connection = require('../models/mysql.js')();
var router = express.Router();
var crypto = require('../models/crypto.js');

var loginCheck = function(req, res, next) {

	console.log('bellow is req.session.p_id');
	console.log(req.session.p_id);

	if(req.session.p_id) {
		console.log('success loginCheck with sessionID');

		var checkSession = 'select * from account where p_id = ' + connection.escape(req.session.p_id);

		connection.query(checkSession, function(err, results) {

			console.log('results');
			console.log(Object.keys(results).length);

			console.log('err');
			console.log(err);

			if(Object.keys(results).length !== 0) {
				// アカウントは存在する

				if(req.session.o_id) {

					// sessionに保存されているo_idとdbに保存されているo_idの整合性を確かめる
					if(results[0].o_id != req.session.o_id) {
						req.session.o_id = undefined;
					}
				}
				else {
					if(results[0].o_id) {
						// 団体に所属しているのにもかかわらず、sessionに保存されていない... So, save the o_id on session store
						req.session.o_id = results[0].o_id;
					}
				}

				next();
			}
			else {
				// アカウントは存在しない
				faild();
			}
		});

	}
	else {
		faild();
	}

	function faild() {
		console.log('faild loginCheck with sessionID. redirect login form');
		res.send({'results': false, 'err': 'ログインに失敗しました.'});
	}
};

// get /organization/
router.get('/', loginCheck, function(req, res) {
	// 団体画面の出力

	var p_id = req.session.p_id;

	// o_id抽出
	var extractOrganizationIdSql = 'select o_id from account where p_id = ' + p_id;

	connection.query(extractOrganizationIdSql, function(err, extractOrganizationIdResults) {

		var o_id;

		if(extractOrganizationIdResults != undefined) {
			o_id = extractOrganizationIdResults[0].o_id;
		}

		console.log('o_id');
		console.log(o_id);

		if(o_id != undefined) {
			// 責任者idを抽出するためのSQL文
			var organizationAdminIdSql = 'select p_id from organization where o_id = ' + connection.escape(o_id);

			// 責任者idを抽出
			connection.query(organizationAdminIdSql, function(err, organizationAdminIdResults) {

				// 団体データを抽出
				var organizationDataSql = 'select o_id, organizationName, DATE_FORMAT(establish, "%Y/%m/%d") as establish, (select count(*) from account where o_id = ' + connection.escape(o_id) + ') as members, (select concat(account.lastName, account.firstName) as admin from account where account.p_id = ' + organizationAdminIdResults[0].p_id + ') as admin, place, email from organization where organization.o_id = ' + connection.escape(o_id);

				connection.query(organizationDataSql, function(err, organizationDataResults) {

					var extractMembersSql = 'select account.p_id, concat(account.lastName, account.firstName) as playerName, DATE_FORMAT(account.birth, "%Y/%m/%d") as birth, account.email from account where account.o_id = ' + connection.escape(o_id);

					console.log(extractMembersSql);

					console.log('extractMembersSql');
					console.log(extractMembersSql);

					// メンバー一覧を抽出
					connection.query(extractMembersSql, function(err, extractMembersResults) {

						console.log('extractMembersResults');
						console.log(extractMembersResults);

						organizationDataResults[0]['status'] = 1;

						organizationDataResults[0]['memberList'] = extractMembersResults;

						organizationDataResults[0]['permission'] = organizationAdminIdResults[0].p_id == p_id ? true : false;

						console.log('organizationDataResults[0]');
						console.log(organizationDataResults[0]);

						res.send(organizationDataResults[0]);
					});
				});
			});
		}
		else{
			// アプリ側のo_idに所属していない時の処理
			res.send({"status": 0});
		}
	});
});

// post /organization/
router.post('/', loginCheck, function(req, res) {

	// 団体作成

	console.log('req.body');
	console.log(req.body);

	var p_id = req.session.p_id;

	// 団体を作成するためのSQL文
	var insertOrganizationSql = 'insert into `organization`(p_id, organizationName, establish, place, email) values(' + connection.escape(p_id) + ', ' + connection.escape(req.body.organizationName) + ', now(), ' + connection.escape(req.body.place) + ', ' + connection.escape(req.body.email) + ')';

	// 団体を作成
	connection.query(insertOrganizationSql, function(err, insertOrganizationResults) {
		console.log('insertOrganizationResults');
		console.log(insertOrganizationResults);

		// 作成したユーザーを団体に所属させるためのSQL文
		var joinOrganizationSql = 'update account set o_id = ' + insertOrganizationResults.insertId + ' where p_id = ' + p_id;

		console.log('joinOrganizationSql');
		console.log(joinOrganizationSql);

		// 作成したユーザーを団体に所属させる
		connection.query(joinOrganizationSql, function(err, joinOrganizationResults) {

			console.log('joinOrganizationResults');
			console.log(joinOrganizationResults);

			var responseData = {};

			if(!err){
				responseData['results'] = true;
				responseData['err'] = null;

				req.session.o_id = insertOrganizationResults.insertId;
			}
			else {
				responseData['results'] = false;
				responseData['err'] = err;
			}

			res.send(responseData);
		});
	});
});

// delete /organization/:id
router.delete('/:id', loginCheck, function(req, res) {
	// :idの団体の削除

	console.log(':id');
	console.log(req.params.id);

	var o_id = req.params.id;

	var resData = {'results': false, 'err': null};

	if(o_id != 'undefined') {

		// sessionを参照し、このp_idのユーザーがこの団体を削除する権限があるかどうか調べる
		// 現段階ではorganizationの設立者のみが削除できるようにSQL文を書く
		var permissionCheckSql = 'select p_id from organization where o_id = ' + connection.escape(o_id);

		// 削除したい団体の設立者を抽出
		connection.query(permissionCheckSql, function(err, permissionCheckResults) {

			if(!err) {
				// 団体の設立者のみが削除可能
				if(permissionCheckResults[0].p_id === req.session.p_id) {

					// 団体削除SQL
					var deleteOrganizationSql = 'delete from organization where o_id = ' + connection.escape(o_id);

					// 団体に所属しているユーザーのo_idを更新
					//var updateOrganizationSql = 'update account set account.o_id = NULL where account.o_id = ' + connection.escape(o_id);

					// 団体削除
					connection.query(deleteOrganizationSql, function(err, deleteOrganizationResults) {
						if(!err) {
							//団体削除完了. So 団体に所属していたユーザーのo_idを更新
							//connection.query(updateOrganizationSql, function(err, updateOrganizationResults) {

								if(!err) {
									req.session.o_id = undefined;

									console.log('団体の削除が完了しました');
									resData['results'] = true;
								}
								else {
									console.log('ユーザーの団体情報更新に失敗しました');
									resData['err'] = 'ユーザーの団体情報更新に失敗しました';
								}

								res.send(resData);
							//});
						}
						else {
							console.log('団体の削除に失敗しました');
							resData['err'] = '団体の削除に失敗しました';
							res.send(resData);
						}
					});
				}
				else {
					console.log('団体削除の権限がありません');
					resData['err'] = '団体削除の権限がありません';
					res.send(resData);
				}
			}
			else {
				console.log('不正な団体IDです');
				resData['err'] = '不正な団体IDです';
				res.send(resData);
			}
		});
	}
	else {
		console.log('不正な団体IDです');
		resData['err'] = '不正な団体IDです';
		res.send(resData);
	}

});

// get /organization/members
router.get('/members', loginCheck, function(req, res) {

	// メンバー管理画面

	var p_id = req.session.p_id;

	// o_id抽出
	var extractOrganizationIdSql = 'select o_id from account where p_id = ' + p_id;

	connection.query(extractOrganizationIdSql, function(err, extractOrganizationIdResults) {
		var o_id;

		if(extractOrganizationIdResults != undefined) {
			o_id = extractOrganizationIdResults[0].o_id;
		}

		// ユーザーが団体に所属している
		if (o_id !== undefined && o_id !== null) {

			var extractOrganizationSql = 'select organization.organizationName, (select count(*) from account where account.o_id = ' + connection.escape(o_id) + ') as members from organization where organization.o_id = ' + connection.escape(o_id);

			console.log('extractOrganizationSql');
			console.log(extractOrganizationSql);

			connection.query(extractOrganizationSql, function(err, extractOrganizationData) {

				console.log('extractOrganizationData');
				console.log(extractOrganizationData);

				var extractMembersSql = 'select account.p_id, concat(account.lastName, account.firstName) as playerName, DATE_FORMAT(account.birth, "%Y/%m/%d") as birth, account.email from account where account.o_id = ' + connection.escape(o_id);

				console.log('extractMembersSql');
				console.log(extractMembersSql);

				connection.query(extractMembersSql, function(err, extractMembersResults) {

					console.log('extractMembersResults');
					console.log(extractMembersResults);

					extractOrganizationData[0]['memberList'] = extractMembersResults;

		 			res.send(extractOrganizationData[0]);
				});
			});
		}
		// ユーザーが団体に所属していない
		else {
			res.send(null);
		}
	});
});

router.post('/members', loginCheck, function(req, res) {
	// メンバー追加API

	console.log('req.body');
	console.log(req.body);

	// 1. ログイン処理
	var loginSql = 'select p_id, o_id, password from account where email = ' + connection.escape(req.body.email);

	connection.query(loginSql, function(err, results) {
		console.log('results of loginSql');
		console.log(results);

		// ログイン成功
		if(Object.keys(results).length !== 0) {

			if(crypto.decryption(results[0].password) === req.body.password) {

				console.log('success to login');

				if(!results[0].o_id) {

					// 団体に参加したいユーザーのp_id
					var addP_id = results[0].p_id;

					// 団体メンバーのp_id
					var memberP_id = req.session.p_id;

					// extract o_id
					var extractO_idSql = 'select o_id from account where p_id = ' + memberP_id;

					connection.query(extractO_idSql, function(err, extractO_idResults) {

						var o_id = extractO_idResults[0].o_id;

						var updateO_idSql = 'update account set o_id = ' + connection.escape(o_id) + ' where p_id = ' + connection.escape(addP_id);

						connection.query(updateO_idSql, function(err, updateO_idResults) {

							var resData = {};

							if(!err) {
								resData['results'] = true;
								resData['err'] = null;
							}
							else {
								resData['results'] = false;
								resData['err'] = 'メンバーの追加に失敗しました。';
							}

							console.log('send response about add member');
							console.log(resData);

							res.send(resData);
						});
					});
				}
				else {
					res.send({'results': false, 'err': 'そのユーザーはすでに他の団体に所属しています'});
				}
			}
			else {
				res.send({'results': false, 'err': 'ログインに失敗しました。Eメールアドレスとパスワードをもう一度確認してください。'});
			}
		}
		// ログイン失敗
		else {
			console.log('faild to login');

			res.send({'results': false, 'err': 'ログインに失敗しました。Eメールアドレスとパスワードをもう一度確認してください。'});
		}
	});
});

router.delete('/members/:id', loginCheck, function(req, res) {
	// :idのメンバーを団体から脱退させる

	var p_id = req.params.id;
	var o_id = req.session.o_id;

	// sessionで参照できるo_idの団体に所属しているp_idのユーザーを、団体から脱退させる

	// 権限があるユーザーのみの削除を受け付ける

	var checkOrganizationCreaterSql = 'select p_id from organization where o_id = ' + connection.escape(o_id);

	connection.query(checkOrganizationCreaterSql, function(err, checkOrganizationCreaterData) {
		if(!err){
			// データが存在するか確認
			if(Object.keys(checkOrganizationCreaterData).length !== 0) {

				if(checkOrganizationCreaterData[0].p_id == req.session.p_id){
					// このユーザーは団体の設立者	so, 要求を受け入れる

					if(req.session.p_id != req.params.id) {
						// 団体の責任者は自分自身を団体から除外することはできない
						// データを更新
						var updateAccountSql = 'update account set o_id = NULL where p_id = ' + connection.escape(p_id) + ' and o_id = ' + connection.escape(o_id);

						connection.query(updateAccountSql, function(err, updateAccountResults) {
							if(!err) {
								res.send({'results': true, 'err': null});
							}
							else{
								res.send({'results': false, 'err': '要求された動作の実行に失敗しました'});
							}
						});
					}
					else {
						res.send({'results': false, 'err': '団体のリーダーは自分自身を団体から削除することはできません。'});
					}
				}
				else {
					res.send({'results': false, 'err': '要求された動作の実行に失敗しました。権限がありません。'});
				}
			}
			else {
				res.send({'results': false, 'err': '要求された動作の実行に失敗しました。団体が存在しません。'});
			}
		}
	});

});

module.exports = router;


text:
package release_1_3

import (
	"github.com/golang/glog"
	v1core "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_3/typed/core/v1"
	v1beta1extensions "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_3/typed/extensions/v1beta1"
	restclient "k8s.io/kubernetes/pkg/client/restclient"
	discovery "k8s.io/kubernetes/pkg/client/typed/discovery"
)

type Interface interface {
	Discovery() discovery.DiscoveryInterface
	Core() v1core.CoreInterface
	Extensions() v1beta1extensions.ExtensionsInterface
}

// Clientset contains the clients for groups. Each group has exactly one
// version included in a Clientset.
type Clientset struct {
	*discovery.DiscoveryClient
	*v1core.CoreClient
	*v1beta1extensions.ExtensionsClient
}

// Core retrieves the CoreClient
func (c *Clientset) Core() v1core.CoreInterface {
	return c.CoreClient
}

// Extensions retrieves the ExtensionsClient
func (c *Clientset) Extensions() v1beta1extensions.ExtensionsInterface {
	return c.ExtensionsClient
}

// Discovery retrieves the DiscoveryClient
func (c *Clientset) Discovery() discovery.DiscoveryInterface {
	return c.DiscoveryClient
}

// NewForConfig creates a new Clientset for the given config.
func NewForConfig(c *restclient.Config) (*Clientset, error) {
	var clientset Clientset
	var err error
	clientset.CoreClient, err = v1core.NewForConfig(c)
	if err != nil {
		return &clientset, err
	}
	clientset.ExtensionsClient, err = v1beta1extensions.NewForConfig(c)
	if err != nil {
		return &clientset, err
	}

	clientset.DiscoveryClient, err = discovery.NewDiscoveryClientForConfig(c)
	if err != nil {
		glog.Errorf("failed to create the DiscoveryClient: %v", err)
	}
	return &clientset, err
}

// NewForConfigOrDie creates a new Clientset for the given config and
// panics if there is an error in the config.
func NewForConfigOrDie(c *restclient.Config) *Clientset {
	var clientset Clientset
	clientset.CoreClient = v1core.NewForConfigOrDie(c)
	clientset.ExtensionsClient = v1beta1extensions.NewForConfigOrDie(c)

	clientset.DiscoveryClient = discovery.NewDiscoveryClientForConfigOrDie(c)
	return &clientset
}

// New creates a new Clientset for the given RESTClient.
func New(c *restclient.RESTClient) *Clientset {
	var clientset Clientset
	clientset.CoreClient = v1core.New(c)
	clientset.ExtensionsClient = v1beta1extensions.New(c)

	clientset.DiscoveryClient = discovery.NewDiscoveryClient(c)
	return &clientset
}


text:
dotfiles=$HOME/.dotfiles

echo "Bootstrap $dotfiles"

# BASH Config
# ln -s $dotfiles/bash/bash_prompt $HOME/.bash_prompt

# ZSH Config
# ln -s $dotfiles/zsh/zshrc $HOME/.zshrc
# ln -s $dotfiles/zsh/oh-my-zsh $HOME/.oh-my-zsh

# TMUX Config
ln -s $dotfiles/tmux/tmux.conf $HOME/.tmux.conf

# VIM Config
ln -s $dotfiles/vim/vimrc $HOME/.vimrc

# SUBLIME TEXT Config (Sublime Text 2.x)
#SublimeTextPackagesDir="$HOME/Library/Application Support/Sublime Text 3/Packages"
# mkdir -vp "$SublimeTextPackagesDir/tsugliani-colorscheme"
# ln -s $dotfiles/SublimeText/tsugliani-colorscheme.tmTheme "$SublimeTextPackagesDir/tsugliani-colorscheme/"
# rm -vf "$SublimeTextPackagesDir/User/Preferences.sublime-settings"
# ln -s $dotfiles/SublimeText/Preferences.sublime-settings "$SublimeTextPackagesDir/User/"

# GIT config
ln -s $dotfiles/git/gitconfig $HOME/.gitconfig
ln -s $dotfiles/git/gitignore_global $HOME/.gitignore_global


text:
import re
import os
import semver
import yaml

# Read the release file path from an environment variable
release_file = os.environ['RELEASE_FILE']

# Read the RPC release series name from an environment variable
release_series = os.environ['RPC_PRODUCT_RELEASE']

# Read the maas_release to set from an an environment variable
maas_release = os.environ['MAAS_TAG']

# Read the osa_release to set from an environment variable
osa_release = os.environ['OSA_SHA']

# Read the rpc_rc_release version from an environment variable
rpc_rc_release = os.environ['RC_BRANCH_VERSION']

# Read the file contents
with open(release_file) as f:
    release_file_content = yaml.safe_load(f.read())

# Read the series-specific data
release_data = release_file_content['rpc_product_releases'][release_series]

# Get the current rpc_release version
rpc_release = release_data['rpc_release']

# Validate that the version complies with the RPC-O
# version naming standards.
# ref: https://rpc-openstack.atlassian.net/browse/RE-1199
#
# This is important for all PR's to ensure that we're
# changing the version to something matching the right
# standard.

release_naming_standard = re.compile(
    "^r[0-9]+.[0-9]+.[0-9]+(-(alpha|beta).[0-9]+)?$")

assert release_naming_standard.match(rpc_release), (
    "The rpc_release value of %s does not comply with the release naming"
    " standard. Please correct it!" % rpc_release)

# Extract the SemVer-compliant portion of the version (no 'r' prefix)
rpc_release_semver = re.sub('^r', '', rpc_release)

# If the rpc_rc_release and rpc_release versions match,
# then we need to increment the value of rpc_release.
if rpc_rc_release == rpc_release:

    # If the current version is a prerelease version,
    # then increment the prerelease.
    rpc_release_parts = semver.parse(rpc_release_semver)
    if rpc_release_parts['prerelease'] is not None:
        rpc_release_semver_new = semver.bump_prerelease(rpc_release_semver)

    # Otherwise, this is a standard release and we
    # just need to do a patch version increment.
    else:
        rpc_release_semver_new = semver.bump_patch(rpc_release_semver)

    # Now add the 'r' prefix back on for the final version
    rpc_release = "r" + rpc_release_semver_new

# Adjust the maas release
release_data['maas_release'] = maas_release

# Adjust the OSA SHA
release_data['osa_release'] = osa_release

# Adjust the RPC release version
release_data['rpc_release'] = rpc_release

# Write the file
with open(release_file, 'w') as f:
    f.write(
        yaml.safe_dump(
            release_file_content, default_flow_style=False, width=1000))

# Output the details for debugging purposes
print('Product release set: [%s]' % release_data)


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

<title>D-Index</title>
<meta name="date" content="2015-06-28">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes

A C D E F G I M N P Q R S T U V W

D

DataAccessObject<T extends Entity> - Class in de.tshw.worktracker.dao

A simple abstraction for a data access object.

DataAccessObject(DatabaseProvider) - Constructor for class de.tshw.worktracker.dao.DataAccessObject

Create an instance of this DAO.

DatabaseMaintainer - Class in de.tshw.worktracker.dao

DatabaseMaintainer() - Constructor for class de.tshw.worktracker.dao.DatabaseMaintainer

DatabaseMaintainerTest - Class in de.tshw.worktracker.dao

DatabaseMaintainerTest() - Constructor for class de.tshw.worktracker.dao.DatabaseMaintainerTest

DatabaseProvider - Interface in de.tshw.worktracker.dao

DB_DRIVER - Static variable in class de.tshw.worktracker.dao.DerbyDatabaseProvider

de.tshw.worktracker - package de.tshw.worktracker

de.tshw.worktracker.controller - package de.tshw.worktracker.controller

de.tshw.worktracker.dao - package de.tshw.worktracker.dao

de.tshw.worktracker.model - package de.tshw.worktracker.model

de.tshw.worktracker.view - package de.tshw.worktracker.view

DEFAULT_DB_URL - Static variable in class de.tshw.worktracker.dao.DerbyDatabaseProvider

delete(T) - Method in class de.tshw.worktracker.dao.DataAccessObject

Deletes a known entity from the database.

deletesEntityFromTheDatabase() - Method in class de.tshw.worktracker.dao.ProjectDAOTest

deletesEntityFromTheDatabase() - Method in class de.tshw.worktracker.dao.WorkLogEntryDAOTest

DerbyDatabaseProvider - Class in de.tshw.worktracker.dao

DerbyDatabaseProvider() - Constructor for class de.tshw.worktracker.dao.DerbyDatabaseProvider

DerbyDatabaseProvider(String) - Constructor for class de.tshw.worktracker.dao.DerbyDatabaseProvider

dropTables(DatabaseProvider) - Method in class de.tshw.worktracker.dao.DatabaseMaintainer

A C D E F G I M N P Q R S T U V W

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes


text:
#include "hal_atomic.h"

/**
 * \brief Driver version
 */
#define DRIVER_VERSION 0x00000001u

/**
 * \brief Disable interrupts, enter critical section
 */
void atomic_enter_critical(hal_atomic_t volatile *atomic)
{
	*atomic = __get_PRIMASK();
  __disable_irq();
  __DMB();
}

/**
 * \brief Exit atomic section
 */
void atomic_leave_critical(hal_atomic_t volatile *atomic)
{
	__DMB();
	__set_PRIMASK(*atomic);
}

/**
 * \brief Retrieve the current driver version
 */
uint32_t atomic_get_version(void)
{
	return DRIVER_VERSION;
}


text:
"""Copyright (c) 2010, Daniel Lindsley

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the name of the tastypie nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

All rights reserved.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL tastypie BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."""

import datetime
from dateutil.parser import parse
from tastypie.fields import ApiField, RelatedField, NOT_PROVIDED
from django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned
from tastypie.bundle import Bundle
from tastypie.exceptions import ApiFieldError, NotFound
from tastypie.utils import dict_strip_unicode_keys

class ComplexRelatedField(RelatedField):

    def __init__(self, to, attribute, related_name=None, default=NOT_PROVIDED, null=False, blank=False,
                    readonly=False, full=False, unique=False, help_text=None):
        super(ComplexRelatedField, self).__init__(
            to, attribute, related_name=related_name, default=default,
            null=null, blank=blank, readonly=readonly, full=full,
            unique=unique, help_text=help_text)

    def resource_from_data(self, fk_resource, data, request=None, related_obj=None, related_name=None):
        """
        Given a dictionary-like structure is provided, a fresh related
        resource is created using that data.
        """
        # Try to hydrate the data provided.
        data = dict_strip_unicode_keys(data)
        fk_bundle = fk_resource.build_bundle(data=data, request=request)

        if related_obj:
            fk_bundle.related_obj = related_obj
            fk_bundle.related_name = related_name

        # We need to check to see if updates are allowed on the FK
        # resource. If not, we'll just return a populated bundle instead
        # of mistakenly updating something that should be read-only.
        if not fk_resource.can_update():
            return fk_resource.full_hydrate(fk_bundle)

        try:
            return fk_resource.obj_update(fk_bundle, **data)
        # HACK: gitHub commit from commits related to issue 382
        except (NotFound, TypeError):
            try:
                # Attempt lookup by primary key
                lookup_kwargs = dict((k, v) for k, v in data.iteritems() if getattr(fk_resource, k).unique)

                if not lookup_kwargs:
                    raise NotFound()

                return fk_resource.obj_update(fk_bundle, **lookup_kwargs)
            except NotFound:
                return fk_resource.full_hydrate(fk_bundle)
        except MultipleObjectsReturned:
            return fk_resource.full_hydrate(fk_bundle)

    def build_related_resource(self, value, request=None, related_obj=None, related_name=None):
        """
        Returns a bundle of data built by the related resource, usually via
        ``hydrate`` with the data provided.

        Accepts either a URI, a data dictionary (or dictionary-like structure)
        or an object with a ``pk``.
        """
        self.fk_resource = self.to_class()
        kwargs = {
            'request': request,
            'related_obj': related_obj,
            'related_name': related_name,
        }
        #HACK GitHub commits related to #382
        if isinstance(value, Bundle):
            # Already hydrated, probably nested bundles. Just return.
            return value
        elif isinstance(value, basestring):
            # We got a URI. Load the object and assign it.
            return self.resource_from_uri(self.fk_resource, value, **kwargs)
        elif hasattr(value, 'items'):
            # We've got a data dictionary.
            # Since this leads to creation, this is the only one of these
            # methods that might care about "parent" data.
            return self.resource_from_data(self.fk_resource, value, **kwargs)
        elif hasattr(value, 'pk'):
            # We've got an object with a primary key.
            return self.resource_from_pk(self.fk_resource, value, **kwargs)
        else:
            raise ApiFieldError("The '%s' field has was given data that was not a URI, not a dictionary-alike and does not have a 'pk' attribute: %s." % (self.instance_name, value))

class ToOneField(ComplexRelatedField):
    """
    Provides access to related data via foreign key.

    This subclass requires Django's ORM layer to work properly.
    """
    help_text = 'A single related resource. Can be either a URI or set of nested resource data.'

    def __init__(self, to, attribute, related_name=None, default=NOT_PROVIDED,
                 null=False, blank=False, readonly=False, full=False,
                 unique=False, help_text=None):
        super(ToOneField, self).__init__(
            to, attribute, related_name=related_name, default=default,
            null=null, blank=blank, readonly=readonly, full=full,
            unique=unique, help_text=help_text
        )
        self.fk_resource = None

    def dehydrate(self, bundle):
        try:
            foreign_obj = getattr(bundle.obj, self.attribute)
        except ObjectDoesNotExist:
            foreign_obj = None

        if not foreign_obj:
            if not self.null:
                raise ApiFieldError("The model '%r' has an empty attribute '%s' and doesn't allow a null value." % (bundle.obj, self.attribute))

            return None

        self.fk_resource = self.get_related_resource(foreign_obj)
        fk_bundle = Bundle(obj=foreign_obj, request=bundle.request)
        return self.dehydrate_related(fk_bundle, self.fk_resource)

    def hydrate(self, bundle):
        value = super(ToOneField, self).hydrate(bundle)

        if value is None:
            return value

        return self.build_related_resource(value, request=bundle.request)

class ForeignKey(ToOneField):
    """
    A convenience subclass for those who prefer to mirror ``django.db.models``.
    """
    pass

class OneToOneField(ToOneField):
    """
    A convenience subclass for those who prefer to mirror ``django.db.models``.
    """
    pass

class ToManyField(ComplexRelatedField):
    """
    Provides access to related data via a join table.

    This subclass requires Django's ORM layer to work properly.

    Note that the ``hydrate`` portions of this field are quite different than
    any other field. ``hydrate_m2m`` actually handles the data and relations.
    This is due to the way Django implements M2M relationships.
    """
    is_m2m = True
    help_text = 'Many related resources. Can be either a list of URIs or list of individually nested resource data.'

    def __init__(self, to, attribute, related_name=None, default=NOT_PROVIDED,
                 null=False, blank=False, readonly=False, full=False,
                 unique=False, help_text=None):
        super(ToManyField, self).__init__(
            to, attribute, related_name=related_name, default=default,
            null=null, blank=blank, readonly=readonly, full=full,
            unique=unique, help_text=help_text
        )
        self.m2m_bundles = []

    def dehydrate(self, bundle):
        if not bundle.obj or not bundle.obj.pk:
            if not self.null:
                raise ApiFieldError("The model '%r' does not have a primary key and can not be used in a ToMany context." % bundle.obj)

            return []

        the_m2ms = None

        if isinstance(self.attribute, basestring):
            the_m2ms = getattr(bundle.obj, self.attribute)
        elif callable(self.attribute):
            the_m2ms = self.attribute(bundle)

        if not the_m2ms:
            if not self.null:
                raise ApiFieldError("The model '%r' has an empty attribute '%s' and doesn't allow a null value." % (bundle.obj, self.attribute))

            return []

        self.m2m_resources = []
        m2m_dehydrated = []

        # TODO: Also model-specific and leaky. Relies on there being a
        #       ``Manager`` there.
        for m2m in the_m2ms.all():
            m2m_resource = self.get_related_resource(m2m)
            m2m_bundle = Bundle(obj=m2m, request=bundle.request)
            self.m2m_resources.append(m2m_resource)
            m2m_dehydrated.append(self.dehydrate_related(m2m_bundle, m2m_resource))

        return m2m_dehydrated

    def hydrate(self, bundle):
        pass

    def hydrate_m2m(self, bundle):
        if self.readonly:
            return None

        if bundle.data.get(self.instance_name) is None:
            if self.blank:
                return []
            elif self.null:
                return []
            else:
                raise ApiFieldError("The '%s' field has no data and doesn't allow a null value." % self.instance_name)
        m2m_hydrated = []
        for value in bundle.data.get(self.instance_name):
            if value is None:
                continue

            kwargs = {
                'request': bundle.request,
            }

            if self.related_name:
                kwargs['related_obj'] = bundle.obj
                kwargs['related_name'] = self.related_name

            m2m_hydrated.append(self.build_related_resource(value, **kwargs))

        return m2m_hydrated

class ManyToManyField(ToManyField):
    """
    A convenience subclass for those who prefer to mirror ``django.db.models``.
    """
    pass

class OneToManyField(ToManyField):
    """
    A convenience subclass for those who prefer to mirror ``django.db.models``.
    """
    pass

class TimeField(ApiField):
    dehydrated_type = 'time'
    help_text = 'A time as string. Ex: "20:05:23"'

    def dehydrate(self, obj):
        return self.convert(super(TimeField, self).dehydrate(obj))

    def convert(self, value):
        if isinstance(value, basestring):
            return self.to_time(value)
        return value

    def to_time(self, s):
        try:
            dt = parse(s)
        except ValueError, e:
            raise ApiFieldError(str(e))
        else:
            return datetime.time(dt.hour, dt.minute, dt.second)

    def hydrate(self, bundle):
        value = super(TimeField, self).hydrate(bundle)

        if value and not isinstance(value, datetime.time):
            value = self.to_time(value)

        return value


text:
FROM microsoft/dotnet:2.1-aspnetcore-runtime AS base
WORKDIR /app
EXPOSE 80

FROM microsoft/dotnet:2.1-sdk AS build
WORKDIR /src
COPY . .
WORKDIR /src/src/Services/Basket/Basket.API
RUN dotnet restore -nowarn:msb3202,nu1503
RUN dotnet build --no-restore -c Release -o /app

FROM build AS publish
RUN dotnet publish --no-restore -c Release -o /app

FROM base AS final
WORKDIR /app
COPY --from=publish /app .
ENTRYPOINT ["dotnet", "Basket.API.dll"]


text:
using UnityEngine;
using System.Collections;

public class WaypointLinker : MonoBehaviour {

	public Collider waypointTrigger;

	// Use this for initialization
	void Start () {

	}

	// Update is called once per frame
	void Update () {

	}
}


text:
namespace nofx
{
    namespace Math
    {
        NAN_METHOD(nofx_ofInRange);
    } // !namespace Math
} // !namespace nofx

#endif // !_NOFX_OFINRANGE_H_


text:
package com.microsoft.azure.management.storage.v2018_11_01;

import com.microsoft.azure.arm.model.HasInner;
import com.microsoft.azure.arm.resources.models.HasManager;
import com.microsoft.azure.management.storage.v2018_11_01.implementation.StorageManager;
import com.microsoft.azure.management.storage.v2018_11_01.implementation.ListContainerItemsInner;
import java.util.List;

/**
 * Type representing ListContainerItems.
 */
public interface ListContainerItems extends HasInner<ListContainerItemsInner>, HasManager<StorageManager> {
    /**
     * @return the value value.
     */
    List<ListContainerItem> value();

}


text:
<?php

namespace Sonata\BasketBundle\Form;

use Sonata\CoreBundle\Form\Type\BaseDoctrineORMSerializationType;

class ApiBasketParentType extends BaseDoctrineORMSerializationType
{
}


text:
<?php

namespace Captcha\Model\Behavior;

use Cake\Core\Configure;
use Cake\Event\EventInterface;
use Cake\Log\Log;
use Cake\ORM\Behavior;
use Cake\Validation\Validator;

/**
 * Validates the added honey pot trap field.
 */
class PassiveCaptchaBehavior extends Behavior {

	/**
	 * @var array<string, mixed>
	 */
	protected $_defaultConfig = [
		'dummyField' => 'email_homepage', // Honeypot trap
		'log' => null, // Auto detect based on debug mode
	];

	/**
	 * Behavior configuration
	 *
	 * @param array $config
	 * @return void
	 */
	public function initialize(array $config): void {
		$config += (array)Configure::read('Captcha');

		parent::initialize($config);

		if ($this->_config['log'] === null) {
			$this->_config['log'] = (bool)Configure::read('debug');
		}
	}

	/**
	 * @param \Cake\Event\EventInterface $event
	 * @param \Cake\Validation\Validator $validator
	 * @param string $name
	 * @return void
	 */
	public function buildValidator(EventInterface $event, Validator $validator, $name) {
		$this->addPassiveCaptchaValidation($validator);
	}

	/**
	 * @param \Cake\Validation\Validator $validator
	 *
	 * @return void
	 */
	public function addPassiveCaptchaValidation(Validator $validator): void {
		$fields = (array)$this->getConfig('dummyField');
		foreach ($fields as $field) {
			$validator->requirePresence($field);
			$validator->allowEmptyString($field);
			$validator->add($field, [
				$field => [
					'rule' => function ($value) {
						$ok = $value === '';
						if (!$ok && $this->_config['log']) {
							Log::write('info', 'PassiveCaptcha trigger, field value `' . (string)$value . '`');
						}

						return $ok;
					},
					'last' => true,
				],
			]);
		}
	}

}


text:
using System;
using NUnit.Framework.Constraints;

namespace NUnit.Framework.SyntaxHelpers
{
	/// <summary>
	/// SyntaxHelper is the abstract base class for all
	/// syntax helpers.
	/// </summary>
	public abstract class SyntaxHelper
	{
		#region Prefix Operators
		/// <summary>
		/// Not returns a ConstraintBuilder that negates
		/// the constraint that follows it.
		/// </summary>
		public static ConstraintBuilder Not
		{
			get { return new ConstraintBuilder().Not; }
		}

		/// <summary>
		/// All returns a ConstraintBuilder, which will apply
		/// the following constraint to all members of a collection,
		/// succeeding if all of them succeed.
		/// </summary>
		public static ConstraintBuilder All
		{
			get { return new ConstraintBuilder().All; }
		}

		/// <summary>
		/// Some returns a ConstraintBuilder, which will apply
		/// the following constraint to all members of a collection,
		/// succeeding if any of them succeed.
		/// </summary>
		public static ConstraintBuilder Some
		{
			get { return new ConstraintBuilder().Some; }
		}

		/// <summary>
		/// None returns a ConstraintBuilder, which will apply
		/// the following constraint to all members of a collection,
		/// succeeding only if none of them succeed.
		/// </summary>
		public static ConstraintBuilder None
		{
			get { return new ConstraintBuilder().None; }
		}
		#endregion
	}
}


text:
import { expect } from 'chai';
import parser from './opts-parser';

describe('opts-parser', function() {
  let opts = null;

  describe('.defaults', function() {
    before(function() {
      opts = {'foo': 'bar'};
      parser.defaults(opts, {'foo': 'default', 'fiz-biz': 1});
    });

    it('has foo', () => expect(opts).to.have.property('foo'));
    it('is bar', () => expect(opts.foo).to.equal('bar'));
    it('has fiz-biz', () => expect(opts).to.contain.keys(['fizBiz', 'fiz-biz']));
    it('is 1', () => expect(opts.fizBiz).to.equal(1));
  });

  describe('.parse', function() {
    describe('booleans', function() {
      before(() => opts = parser.parse('foo: true; bar: false;'));
      it('has true foo', () => expect(opts.foo).to.eql(true));
      it('has false bar', () => expect(opts.bar).to.eql(false));
    });

    describe('words', function() {
      before(() => opts = parser.parse('foo: bar'));
      it('has foo', () => expect(opts).to.have.property('foo'));
      it('is bar', () => expect(opts.foo).to.equal('bar'));
    });

    describe('arrays', function() {
      before(() => opts = parser.parse('foo: [hello, world]'));
      it('has foo', () => expect(opts).to.have.property('foo'));
      it('is array', () => expect(opts.foo).to.eql(['hello', 'world']));
    });

    describe('strings', function() {
      describe('single quoted', function() {
        before(() => opts = parser.parse('foo: \'hello, world\' '));
        it('has foo', () => expect(opts).to.have.property('foo'));
        it('is hello, world', () => expect(opts.foo).to.equal('hello, world'));
      });

      describe('double quoted', function() {
        before(() => opts = parser.parse('foo: "hello, world" '));
        it('has foo', () => expect(opts).to.have.property('foo'));
        it('is hello, world', () => expect(opts.foo).to.equal('hello, world'));
      });
    });

    describe('all', function() {
      before(() => opts = parser.parse('foo-baz: \'hello, world\'; helloWorld: [1,2,3]; color: #000'));
      it('has keys', () => expect(opts).to.have.keys(['fooBaz', 'foo-baz', 'helloWorld', 'color']));
      it('has color', () => expect(opts.color).to.eql('#000'));
    });
  });
});


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Windows.Storage;
using Windows.Storage.Search;

namespace SecuritySystemUWP
{
    public class LocalStorage : IStorage
    {
        // Local storage never uploads
        private DateTime lastUploadTime = DateTime.MinValue;

        /*******************************************************************************************
* PUBLIC METHODS
*******************************************************************************************/
        public DateTime LastUploadTime
        {
            get
            {
                return this.lastUploadTime;
            }
        }

        public void UploadPictures()
        {
            //The pictures are automatically stored in the local storage during image capture.
            return;
        }

        public async void DeleteExpiredPictures()
        {
            //Delete older images
            try
            {
                var querySubfolders = new QueryOptions();
                querySubfolders.FolderDepth = FolderDepth.Deep;

                var cacheFolder = KnownFolders.PicturesLibrary;
                cacheFolder = await cacheFolder.GetFolderAsync(AppSettings.FolderName);
                var result = cacheFolder.CreateFileQueryWithOptions(querySubfolders);
                var files = await result.GetFilesAsync();

                foreach (StorageFile file in files)
                {
                    //Caluclate oldest time in ticks using the user selected storage duration
                    long oldestTime = DateTime.UtcNow.Ticks - TimeSpan.FromDays(App.Controller.XmlSettings.StorageDuration).Ticks;
                    long picCreated = file.DateCreated.Ticks;
                    if (picCreated < oldestTime)
                    {
                        await file.DeleteAsync();
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Exception in deleteExpiredPictures() " + ex.Message);

                // Log telemetry event about this exception
                var events = new Dictionary<string, string> { { "LocalStorage", ex.Message } };
                TelemetryHelper.TrackEvent("FailedToDeletePicture", events);
            }
        }

        public void Dispose()
        {
            return;
        }
    }
}


text:
package com.amazonaws.services.docdb;

import com.amazonaws.AmazonClientException;
import com.amazonaws.AmazonWebServiceRequest;
import com.amazonaws.Protocol;
import com.amazonaws.Request;
import com.amazonaws.auth.AWS4Signer;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.handlers.HandlerContextKey;
import com.amazonaws.handlers.RequestHandler2;
import com.amazonaws.http.HttpMethodName;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.RegionUtils;
import com.amazonaws.util.AwsHostNameUtils;
import com.amazonaws.util.SdkHttpUtils;

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

/**
 * Abstract pre-sign handler that follows the pre-signing scheme outlined in the 'RDS Presigned URL for Cross-Region Copying' SEP.
 *
 * @param <T> The request type.
 */
abstract class PresignRequestHandler<T extends AmazonWebServiceRequest> extends RequestHandler2 {
    private static final String SERVICE_NAME = "rds";
    private static final String PARAM_SOURCE_REGION = "SourceRegion";
    private static final String PARAM_DESTINATION_REGION = "DestinationRegion";
    private static final String PARAM_PRESIGNED_URL = "PreSignedUrl";

    protected interface PresignableRequest {
        void setPreSignedUrl(String preSignedUrl);

        String getPreSignedUrl();

        String getSourceRegion();

        Request<?> marshall();
    }

    private final Class<T> requestClassToPreSign;

    protected PresignRequestHandler(Class<T> requestClassToPreSign) {
        this.requestClassToPreSign = requestClassToPreSign;
    }

    @Override
    public void beforeRequest(Request<?> request) {
        if (!requestClassToPreSign.isInstance(request.getOriginalRequest())) return;

        if (request.getParameters().containsKey(PARAM_PRESIGNED_URL)) return;

        PresignableRequest presignableRequest = adaptRequest(requestClassToPreSign.cast(
                request.getOriginalRequest()));

        String sourceRegion = presignableRequest.getSourceRegion();
        if (sourceRegion == null) return;

        String destinationRegion = AwsHostNameUtils.parseRegion(request.getEndpoint().getHost(),
                SERVICE_NAME);

        Request<?> requestToPresign = presignableRequest.marshall();
        requestToPresign.getParameters().remove(PARAM_SOURCE_REGION);
        requestToPresign.getParameters().put(PARAM_DESTINATION_REGION, Arrays.asList(destinationRegion));
        requestToPresign.setEndpoint(createEndpoint(sourceRegion, SERVICE_NAME));
        requestToPresign.setHttpMethod(HttpMethodName.GET);

        AWSCredentials credentials = request.getHandlerContext(HandlerContextKey.AWS_CREDENTIALS);

        requestToPresign = presignRequest(requestToPresign, credentials, sourceRegion);

        final String presignedUrl = generateUrl(requestToPresign);

        presignableRequest.setPreSignedUrl(presignedUrl);

        request.addParameter(PARAM_PRESIGNED_URL, presignedUrl);
        // Remove the unmodeled params to stop them getting onto the wire
        request.getParameters().remove(PARAM_SOURCE_REGION);
    }

    protected abstract PresignableRequest adaptRequest(T originalRequest);

    private Request<?> presignRequest(Request<?> request, AWSCredentials credentials, String signingRegion) {
        AWS4Signer signer = createNewSignerWithRegion(signingRegion);
        signer.presignRequest(request, credentials, null);
        return request;
    }

    private AWS4Signer createNewSignerWithRegion(String signingRegion) {
        AWS4Signer signer = new AWS4Signer(true);
        signer.setRegionName(signingRegion);
        signer.setServiceName(SERVICE_NAME);
        return signer;
    }

    private URI createEndpoint(String regionName, String serviceName) {
        final Region region = RegionUtils.getRegion(regionName);

        if (region == null) {
            throw new AmazonClientException("{" + serviceName + ", " + regionName + "} was not "
                    + "found in region metadata. Update to latest version of SDK and try again.");
        }

        return toURI(region.getServiceEndpoint(serviceName));
    }

    private String generateUrl(Request<?> request) {
        URI endpoint = request.getEndpoint();
        String uri = SdkHttpUtils.appendUri(endpoint.toString(),
                request.getResourcePath(), true);
        String encodedParams = SdkHttpUtils.encodeParameters(request);

        if (encodedParams != null && !encodedParams.isEmpty()) {
            uri += "?" + encodedParams;
        }

        return uri;

    }

    /** Returns the endpoint as a URI. */
    private static URI toURI(String endpoint) throws IllegalArgumentException {
        if (!endpoint.contains("://")) {
            endpoint = Protocol.HTTPS + "://" + endpoint;
        }

        try {
            return new URI(endpoint);
        } catch (URISyntaxException e) {
            throw new IllegalArgumentException(e);
        }
    }
}


text:
layout: blog
type: blog
blogroll: true
---

		10 Nov.
		2017

How to Install and Setup Maps and Geolocation to your Cross Platform Project

This blog post will help you to install and setup maps and geolocation to your cross platform project. ...read more

		#xamarin

		30 Sept.
		2017

Implementing Simple Local Notification in Xamarin Forms

In this blog post, I'm going to show you how to implement simple local notification in xamarin forms....read more

		#xamarin

		3 July
		2017

Simple Weather App in Xamarin Forms with MVVM using Weather API Part 1

This post will help you get started in creating simple weather app in xamarin forms connected on a weather api...read more

		#xamarin

		3 July
		2017

Simple Weather App in Xamarin Forms with MVVM using Weather API Part 2

This is the continuation of the "Simple Weather App in Xamarin Forms with MVVM using Weather API Part 1" where we are going to do the back-end development...read more

		#xamarin

		3 July
		2017

Simple Weather App in Xamarin Forms with MVVM using Weather API Part 3

This is the continuation of the "Simple Weather App in Xamarin Forms with MVVM using Weather API Part 2" where we will start putting our UI design for our simple weather app...read more

		#xamarin

		09 June
		2017

Creating Simple Xamarin Forms Crud App with RealmDB and MVVM Part 1

In this post, we'll be creating simple Xamarin.Forms crud app with Realm Database and MVVM architectural design pattern. (Part 1)...read more

		#xamarin

		10 June
		2017

Creating Simple Xamarin Forms Crud App with RealmDB and MVVM Part 2

This is the part 2 or the continuation of "Creating Simple Xamarin Forms Crud App with RealmDB and MVVM...read more

		#xamarin

		03 June
		2017

Basic Understanding How Data Binding and MVVM works in Xamarin Forms

This post will give you some insights how data binding and mvvm works in Xamarin Forms...read more

		#xamarin

		26 May
		2017

How to Use Xamarin Live Player in Visual Studio for Windows

This post will help you how to use the Xamarin Live Player on your installed Visual Studio 2017 v.15.3 with updated Xamarin for Visual Studio...read more

		#xamarin

		26 May
		2017

How To Set Up Xamarin Live Player in Visual Studio for Windows

I'll show you some steps on how to setup xamarin live player in Visual Studio 2017 v.15.3...read more

		#xamarin

		16 May
		2017

Xamarin Forms Simple Login With Rest API

If you're using asp.net web api or you want to apply this api snippets and add some logic to your xamarin forms login system, this post is very helpful ...read more

		#xamarin

{% if paginator.total_pages > 0 %}

	{% if paginator.previous_page %}

	{% else %}

	{% endif %}

	{% if paginator.next_page %}

	{% else %}

	{% endif %}

{% endif %}


text:
/* eslint quotes: ["error", "double"] */
define({
  root: ({
    commonWebmap: {
      editor: {
        loading: "Please wait while the map editor is loading",
        newTitle: "Create new map",
        editTitle: "Edit map",
        titleLbl: "Title",
        titlePh: "Map title...",
        folderLbl: "The map will be created in the same folder as the story.",
        creating: "Creating the map",
        saving: "Saving the map",
        success: "Map saved",
        successCreate: "Map created",
        cancelTitle: "Discard any unsaved changes?",
        errorDuplicate: "You already have a map with that title",
        errorCreate: "Unable to create map. Please try again.",
        errorSave: "Unable to save map. Please try again.",
        loadFail: "Fatal error, the map editor cannot be loaded",
        notavailable1: "Sorry, creating or editing a map is not supported in Firefox due to a technical limitation. You may want to build your story using a different web browser or use the following workaround.",
        notavailable2: "Sorry, creating or editing a map is not supported since the story map application is not hosted in ${PRODUCT}. Please contact your ArcGIS administrator for more information.",
        notavailable3: "Sorry, creating or editing a map is not supported on this version of Portal for ArcGIS (requires 10.4 or later). Please contact your ArcGIS administrator for more information.",
        notavailable4: "You can create a map using ${MV}, then come back here to add it to your story.",
        notavailable5: "You can edit the map using ${MV}, then come back here and ${APPLY} to see your changes.",
        notavailable6: "map viewer",
        notavailable7: "reload the map",
        close: "Close",
        save: "Save",
        yes: "Yes",
        no: "No"
      }
    }
  }),
  "ar": 1,
  "bs": 1,
  "cs": 1,
  "da": 1,
  "de": 1,
  "el": 1,
  "es": 1,
  "et": 1,
  "fi": 1,
  "fr": 1,
  "he": 1,
  "hi": 1,
  "hr": 1,
  "id": 1,
  "it": 1,
  "ja": 1,
  "ko": 1,
  "lt": 1,
  "lv": 1,
  "nl": 1,
  "nb": 1,
  "pl": 1,
  "pt-br": 1,
  "pt-pt": 1,
  "ro": 1,
  "ru": 1,
  "sr": 1,
  "sv": 1,
  "th": 1,
  "tr": 1,
  "vi": 1,
  "zh-cn": 1,
  "zh-hk": 1,
  "zh-tw": 1
});


text:
layout: post
title: Rails Deployments
date: 2008-10-01
comments: true
tags: [DevOps, Ruby, Rails]
---

This September I deployed two Rails applications with different stacks, and I wanted to share the details.

#### Personal project

 - Ubuntu Gutsy (7.10) [slicehost](http://www.slicehost.com/) image
 - Apache 2.2 with [Passenger](http://www.modrails.com/)
 - MySQL 5
 - [Hoptoad](http://www.hoptoadapp.com) exception reporting

A 256MB slice runs this low traffic application OK. For two or more applications, more memory is preferred. I developed this application with [Git](http://git.or.cz/) version control, the repository was hosted on [github](http://github.com/).

#### Work project

 - Ubuntu Hardy (8.04) [Amazon EC2 image](http://aws.amazon.com/ec2/) (customized an existing AMI)
 - Asset storage on [Amazon S3](http://aws.amazon.com/s3/) via the attachment_fu plugin
 - [nginx](http://nginx.net/) web server (static assets and load balancing)
 - [PostgreSQL 8.3](http://www.postgresql.org/) on separate instance
 - cluster of [mongrel](http://mongrel.rubyforge.org/) application servers
 - [Sphinx](http://www.sphinxsearch.com) 0.9.8 search engine
 - server monitoring with [monit](http://tildeslash.com/monit/)
 - server backups via [s3sync](http://s3sync.net/wiki)

The staging server for the development initially ran a [CentOS](http://www.centos.org/) Linux image, before I realized how painful it was to have separate production and staging environments.

The Amazon EC2 "Small Instance" has 1.8GB RAM as of this writing.  Our application puts a very small load on the server, even with many mongrels running. This application was developed with [Subversion](http://subversion.tigris.org/) version control, the repository was hosted internally.

Both applications send email. For my personal project I configured [postfix](http://www.postfix.org/). [Capistrano](http://www.capify.org/) was used for deployment in both applications.


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

<TITLE>
ContextConfiguration (Spring Framework API 2.5)
</TITLE>

<META NAME="date" CONTENT="2007-11-19">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

The Spring Framework

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: REQUIRED | OPTIONAL

DETAIL: ELEMENT

org.springframework.test.context

Annotation Type ContextConfiguration

@Retention(value=RUNTIME)
@Target(value=TYPE)
@Inherited
@Documented
public @interface ContextConfiguration

 ContextConfiguration defines class-level metadata which can be used to
 instruct client code with regard to how to load and configure an
 ApplicationContext.

Since:

2.5

Author:

Sam Brannen

See Also:
ContextLoader,
ApplicationContext

Optional Element Summary

 boolean
inheritLocations

 Whether or not resource locations from superclasses
 should be inherited.

 Class<? extends ContextLoader>
loader

 The type of ContextLoader to use for loading an
 ApplicationContext.

 String[]
locations

 The resource locations to use for loading an
 ApplicationContext.

locations

public abstract String[] locations

 The resource locations to use for loading an
 ApplicationContext.

Default:
{}

inheritLocations

public abstract boolean inheritLocations

 Whether or not resource locations from superclasses
 should be inherited.

 The default value is true, which means that an annotated
 class will inherit the resource locations defined by an
 annotated superclass. Specifically, the resource locations for an
 annotated class will be appended to the list of resource locations
 defined by an annotated superclass. Thus, subclasses have the option of
 extending the list of resource locations. In the following
 example, the
 ApplicationContext
 for ExtendedTest will be loaded from
 "base-context.xml" and
 "extended-context.xml", in that order. Beans defined in
 "extended-context.xml" may therefore override those defined in
 "base-context.xml".

 @ContextConfiguration(locations={"base-context.xml"})
 public class BaseTest {
     // ...
 }
 @ContextConfiguration(locations={"extended-context.xml"})
 public class ExtendedTest extends BaseTest {
     // ...
 }

 If inheritLocations is set to false, the
 resource locations for the annotated class will shadow and
 effectively replace any resource locations defined by a superclass.

Default:
true

loader

public abstract Class<? extends ContextLoader> loader

 The type of ContextLoader to use for loading an
 ApplicationContext.

Default:
org.springframework.test.context.ContextLoader.class

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

The Spring Framework

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: REQUIRED | OPTIONAL

DETAIL: ELEMENT

Copyright © 2002-2007 The Spring Framework.


text:
"""
Test the rabbitpy.tx classes

"""
import mock
from pamqp import specification

from rabbitpy import exceptions, tx

from . import helpers

class TxTests(helpers.TestCase):

    def test_obj_creation_does_not_invoke_select(self):
        with mock.patch('rabbitpy.tx.Tx.select') as select:
            transaction = tx.Tx(self.channel)
            self.assertFalse(transaction._selected)
            select.assert_not_called()

    def test_enter_invokes_select(self):
        with mock.patch('rabbitpy.tx.Tx.select') as select:
            with tx.Tx(self.channel):
                select.assert_called_once()

    @mock.patch('rabbitpy.tx.Tx._rpc')
    def test_exit_invokes_commit(self, rpc):
        rpc.return_value = specification.Tx.SelectOk
        with mock.patch('rabbitpy.tx.Tx.select') as select:
            with mock.patch('rabbitpy.tx.Tx.commit') as commit:
                with tx.Tx(self.channel) as transaction:
                    transaction._selected = True
                commit.assert_called_once()

    @mock.patch('rabbitpy.tx.Tx._rpc')
    def test_exit_on_exception_invokes_commit_with_selected(self, rpc):
        rpc.return_value = specification.Tx.SelectOk
        with mock.patch('rabbitpy.tx.Tx.select') as select:
            with mock.patch('rabbitpy.tx.Tx.rollback') as rollback:
                try:
                    with tx.Tx(self.channel) as transaction:
                        transaction._selected = True
                        raise exceptions.AMQPChannelError()
                except exceptions.AMQPChannelError:
                    pass
                rollback.assert_called_once()

    @mock.patch('rabbitpy.tx.Tx._rpc')
    def test_select_invokes_rpc_with_tx_select(self, rpc):
        rpc.return_value = specification.Tx.CommitOk
        with tx.Tx(self.channel):
            pass
        self.assertIsInstance(rpc.mock_calls[0][1][0],
                              specification.Tx.Select)

    @mock.patch('rabbitpy.tx.Tx._rpc')
    def test_commit_invokes_rpc_with_tx_commit(self, rpc):
        rpc.return_value = specification.Tx.SelectOk
        obj = tx.Tx(self.channel)
        obj.select()
        rpc.return_value = specification.Tx.CommitOk
        obj.commit()
        self.assertIsInstance(rpc.mock_calls[1][1][0],
                              specification.Tx.Commit)

    @mock.patch('rabbitpy.tx.Tx._rpc')
    def test_commit_raises_when_channel_closed(self, rpc):
        obj = tx.Tx(self.channel)
        obj.select()
        rpc.side_effect = exceptions.ChannelClosedException
        self.assertRaises(exceptions.NoActiveTransactionError,
                          obj.commit)

    @mock.patch('rabbitpy.tx.Tx._rpc')
    def test_rollback_invokes_rpc_with_tx_rollback(self, rpc):
        rpc.return_value = specification.Tx.SelectOk
        obj = tx.Tx(self.channel)
        obj.select()
        rpc.return_value = specification.Tx.RollbackOk
        obj.rollback()
        self.assertIsInstance(rpc.mock_calls[1][1][0],
                              specification.Tx.Rollback)

    @mock.patch('rabbitpy.tx.Tx._rpc')
    def test_rollback_raises_when_channel_closed(self, rpc):
        obj = tx.Tx(self.channel)
        obj.select()
        rpc.side_effect = exceptions.ChannelClosedException
        self.assertRaises(exceptions.NoActiveTransactionError,
                          obj.rollback)


text:
The sine of an angle (specified in radians) can be computed by making use of the
approximation `sin` x ≈  x if x is sufficiently small, and the trigonometric
identity
`sin x = 3sin(x/3) - 4sin³(x/3)`
to the size of the argument of `sin`. (For purposes of this exercise an angle is
considered "sufficiently small" if its magnitude is not greater than 0.1
radians.) These ideas are incorporated in the following procedures:
```scheme
(define (cube x) (* x x x))
(define (p x) (- (* 3 x) (* 4 (cube x))))
(define (sine angle)
  (if (not (> (abs angle) 0.1))
      angle
      (p (sine (/ angle 3.0)))))
```
a. How many times is the procedure `p` applied when `(sine 12.15)` is evaluated?

b. What is the order of growth in space and number of steps (as a function of
`a`) used by the process generated by the `sine` procedure when `(sine a)` is
evaluated?

### Solution

#### a.
```scheme
(sine 12.15)
(p (sine 4.05))
(p (p (sine 1.35)))
(p (p (p (sine 0.45))))
(p (p (p (p (sine 0.15)))))
(p (p (p (p (p (sine 0.05))))))
(p (p (p (p (p (0.05))))))
```
The procedure `p` is applied five times.

#### b.
Order of growth in space: O(log a).
Order of growth in number of steps: O(log a).


text:
package com.microsoft.azure.management.peering.v2019_08_01_preview;

import com.microsoft.azure.arm.collection.SupportsCreating;
import com.microsoft.azure.arm.resources.collection.SupportsDeletingByResourceGroup;
import com.microsoft.azure.arm.resources.collection.SupportsBatchDeletion;
import com.microsoft.azure.arm.resources.collection.SupportsGettingByResourceGroup;
import rx.Observable;
import com.microsoft.azure.arm.resources.collection.SupportsListingByResourceGroup;
import com.microsoft.azure.arm.collection.SupportsListing;
import com.microsoft.azure.management.peering.v2019_08_01_preview.implementation.PeeringsInner;
import com.microsoft.azure.arm.model.HasInner;

/**
 * Type representing Peerings.
 */
public interface Peerings extends SupportsCreating<Peering.DefinitionStages.Blank>, SupportsDeletingByResourceGroup, SupportsBatchDeletion, SupportsGettingByResourceGroup<Peering>, SupportsListingByResourceGroup<Peering>, SupportsListing<Peering>, HasInner<PeeringsInner> {
}


text:
'use strict';

// where the index.js is.
let __entryPath = __dirname + '/public/entry.js';
let webpack = require('webpack');
let HtmlWebpackPlugin = require('html-webpack-plugin');
let ExtractTextPlugin = require('extract-text-webpack-plugin');
let path = require('path');
let isProduction = process.argv.indexOf('--production') > -1;

let webpackConfig = {
  context: path.join(__dirname, '/lib'),
  entry: {
    'app': './app.js'
  },
  output: {
    path: __dirname + '/dist',
    filename: 'bundle.js',
  },
  devtool: 'source-map',
  module: {
    loaders: [
      {
        test: /\.jsx$/,
        exclude: /node_modules/,
        loader: "react-hot!babel-loader"
      },
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loader: "babel-loader"
      },
      {
        test: /\.min\.css$/,
        loader: ExtractTextPlugin.extract('style', 'css')
      },
      {
        test: /(?!.*\.min)^.*\.css$/,
        loaders: ['style', 'css-loader']
      },
      {
        test: /\.(jpe?g|png|gif|svg)$/,
        loader: 'url?limit=1024&name=img/[name].[ext]'
      },
      {
        test: /\.(woff2?|otf|eot|svg|ttf)$/i,
        loader: 'url?name=fonts/[name].[ext]'
      },
      {
        loader: 'json-loader',
        test: /\.json$/
      }
    ]
  },
  resolve: {
    // put '' after '.ts' to make webpack resolve '*.scss.ts' not '*.scss'
    extensions: ['.jsx', '.js', ''],
    modulesDirectories: [
      '',
      'node_modules',
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({
      title: 'Yezi',
    }),
    new ExtractTextPlugin("styles.css")
  ]
};

if (isProduction) {
  webpackConfig.plugins.push(new webpack.optimize.UglifyJsPlugin({
    minimize: true,
    compress: {
      warnings: false
    }
  }));
}

module.exports = webpackConfig;


text:
package gov.nih.nci.cagrid.portal.dao.catalog;

import gov.nih.nci.cagrid.portal.DaoTestBase;
import gov.nih.nci.cagrid.portal.dao.GridServiceDao;
import gov.nih.nci.cagrid.portal.domain.GridDataService;
import gov.nih.nci.cagrid.portal.domain.GridService;
import gov.nih.nci.cagrid.portal.domain.catalog.GridDataServiceEndPointCatalogEntry;
import gov.nih.nci.cagrid.portal.domain.catalog.GridServiceEndPointCatalogEntry;
import gov.nih.nci.cagrid.portal.domain.metadata.dataservice.DomainModel;
import gov.nih.nci.cagrid.portal.domain.metadata.dataservice.UMLClass;
import org.junit.Before;
import org.junit.Test;
import org.springframework.orm.hibernate3.HibernateTemplate;

import java.util.List;

import static org.junit.Assert.*;

/**
 * User: kherm
 *
 * @author kherm manav.kher@semanticbits.com
 */
public class GridServiceEndPointCatalogEntryDaoTest extends
        DaoTestBase<GridServiceEndPointCatalogEntryDao> {

    GridServiceDao pDao;
    GridService p;

    @Before
    public void setup() {
        pDao = (GridServiceDao) getApplicationContext().getBean(
                "gridServiceDao");
        p = new GridService();

    }

    @Test
    public void hide() {
        GridServiceEndPointCatalogEntry entry = new GridServiceEndPointCatalogEntry();
        getDao().save(entry);
        assertEquals(false, getDao().getById(1).isHidden());
        getDao().hide(entry);
        assertEquals(true, getDao().getById(1).isHidden());

    }

    @Test
    public void createWithNoAbout() {
        GridServiceEndPointCatalogEntry entry = new GridServiceEndPointCatalogEntry();
        getDao().save(entry);
        GridServiceEndPointCatalogEntry loaded = getDao().getById(1);
        assertNotNull(loaded);
        assertNull(loaded.getAbout());
    }

    @Test
    public void createAbout() {
        pDao.save(p);

        GridServiceEndPointCatalogEntry catalog = new GridServiceEndPointCatalogEntry();
        catalog.setAbout(p);
        p.setCatalog(catalog);
        pDao.save(p);
        getDao().save(catalog);

        assertNotNull(getDao().isAbout(p));
    }

    @Test
    public void dataType() {
        pDao.save(p);

        GridDataServiceEndPointCatalogEntry catalog = new GridDataServiceEndPointCatalogEntry();
        catalog.setAbout(p);
        p.setCatalog(catalog);
        pDao.save(p);
        getDao().save(catalog);

        assertNotNull(getDao().isAbout(p));
        assertNotNull(getDao().getAll());
    }

    // test to see if deleting the Participant deletes the catalog as well

    @Test
    public void delete() {

        pDao.save(p);

        GridServiceEndPointCatalogEntry catalog = new GridServiceEndPointCatalogEntry();
        catalog.setAbout(p);
        p.setCatalog(catalog);
        pDao.save(p);
        getDao().save(catalog);

        assertEquals(1, getDao().getAll().size());

        GridService loadedP = pDao.getById(1);
        pDao.delete(loadedP);

        interruptSession();
        assertEquals(0, getDao().getAll().size());

    }

    @Test
    public void getByPartialUrl() {
        p.setUrl("http://complete.url");
        pDao.save(p);

        GridServiceEndPointCatalogEntry catalog = new GridServiceEndPointCatalogEntry();
        catalog.setAbout(p);
        p.setCatalog(catalog);
        getDao().save(catalog);

        assertEquals(1, getDao().getByPartialUrl("http://").size());
        assertEquals(1, getDao().getByPartialUrl("url").size());
        assertEquals(1, getDao().getByPartialUrl("complete").size());
        assertEquals(0, getDao().getByPartialUrl("someother.url").size());

    }

    /**
     * Test to see tha that hidden catalogs
     * are not returned
     *
     */
    @Test
    public void getByPartialUrlHiddenCatalogs() {
        p.setUrl("http://complete.url");
        pDao.save(p);

        GridServiceEndPointCatalogEntry catalog = new GridServiceEndPointCatalogEntry();
        catalog.setAbout(p);
        p.setCatalog(catalog);
        catalog.setHidden(true);
        getDao().save(catalog);

        assertEquals(0, getDao().getByPartialUrl("http://").size());
        assertEquals(0, getDao().getByPartialUrl("url").size());

//        un-hide the catalog
        catalog.setHidden(false);
        getDao().save(catalog);
        interruptSession();
        assertEquals(1, getDao().getByPartialUrl("http://").size());
        assertEquals(1, getDao().getByPartialUrl("url").size());
    }

    @Test
    public void getByUmlClassNameAndPartialUrl() {

        HibernateTemplate templ = getDao().getHibernateTemplate();

        for (int i = 0; i < 2; i++) {
            GridDataService dSvc1 = new GridDataService();
            dSvc1.setUrl("http://dSvc" + i);
            templ.save(dSvc1);
            DomainModel model1 = new DomainModel();
            model1.setService(dSvc1);
            templ.save(model1);
            dSvc1.setDomainModel(model1);
            templ.save(dSvc1);
            UMLClass umlClass1 = new UMLClass();
            umlClass1.setPackageName("pkg" + i);
            umlClass1.setClassName("Class" + i);
            umlClass1.setModel(model1);
            templ.save(umlClass1);
            model1.getClasses().add(umlClass1);
            templ.save(model1);
            GridServiceEndPointCatalogEntry ce = new GridServiceEndPointCatalogEntry();
            ce.setName("CE" + i);
            ce.setAbout(dSvc1);
            templ.save(ce);
            dSvc1.setCatalog(ce);
            templ.save(dSvc1);
        }

        GridService svc1 = new GridService();
        svc1.setUrl("http://svc1");
        templ.save(svc1);
        GridServiceEndPointCatalogEntry ce = new GridServiceEndPointCatalogEntry();
        ce.setAbout(svc1);
        templ.save(ce);
        svc1.setCatalog(ce);
        templ.save(svc1);

        assertEquals(2, getDao().getByPartialUrl("dSvc").size());

        List<GridServiceEndPointCatalogEntry> ces = getDao()
                .getByUmlClassNameAndPartialUrl("pkg1", "Class1", "dSvc");
        assertEquals(1, ces.size());

    }

}


text:
package org.drools.guvnor.client.explorer;

import com.google.gwt.event.shared.EventHandler;
import com.google.gwt.event.shared.GwtEvent;

public class RefreshSuggestionCompletionEngineEvent extends GwtEvent<RefreshSuggestionCompletionEngineEvent.Handler> {

    public interface Handler
        extends
        EventHandler {
        void onRefreshModule(RefreshSuggestionCompletionEngineEvent refreshSuggestionCompletionEngineEvent);
    }

    public static final Type<RefreshSuggestionCompletionEngineEvent.Handler> TYPE = new Type<RefreshSuggestionCompletionEngineEvent.Handler>();

    private final String                                                     moduleName;

    public RefreshSuggestionCompletionEngineEvent(String moduleName) {
        this.moduleName = moduleName;
    }

    public String getModuleName() {
        return moduleName;
    }

    @Override
    public Type<RefreshSuggestionCompletionEngineEvent.Handler> getAssociatedType() {
        return TYPE;
    }

    @Override
    protected void dispatch(RefreshSuggestionCompletionEngineEvent.Handler handler) {
        handler.onRefreshModule( this );
    }
}