text:
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2020 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#ifndef BITCOIN_TXDB_H
#define BITCOIN_TXDB_H

#include <coins.h>
#include <dbwrapper.h>
#include <chain.h>
#include <primitives/block.h>

#include <memory>
#include <string>
#include <utility>
#include <vector>

class CBlockIndex;
class CCoinsViewDBCursor;
class uint256;

//! -dbcache default (MiB)
static const int64_t nDefaultDbCache = 450;
//! -dbbatchsize default (bytes)
static const int64_t nDefaultDbBatchSize = 16 << 20;
//! max. -dbcache (MiB)
static const int64_t nMaxDbCache = sizeof(void*) > 4 ? 16384 : 1024;
//! min. -dbcache (MiB)
static const int64_t nMinDbCache = 4;
//! Max memory allocated to block tree DB specific cache, if no -txindex (MiB)
static const int64_t nMaxBlockDBCache = 2;
//! Max memory allocated to block tree DB specific cache, if -txindex (MiB)
// Unlike for the UTXO database, for the txindex scenario the leveldb cache make
// a meaningful difference: https://github.com/bitcoin/bitcoin/pull/8273#issuecomment-229601991
static const int64_t nMaxTxIndexCache = 1024;
//! Max memory allocated to all block filter index caches combined in MiB.
static const int64_t max_filter_index_cache = 1024;
//! Max memory allocated to coin DB specific cache (MiB)
static const int64_t nMaxCoinsDBCache = 8;

// Actually declared in validation.cpp; can't include because of circular dependency.
extern RecursiveMutex cs_main;

/** CCoinsView backed by the coin database (chainstate/) */
class CCoinsViewDB final : public CCoinsView
{
protected:
    std::unique_ptr<CDBWrapper> m_db;
    fs::path m_ldb_path;
    bool m_is_memory;
public:
    /**
     * @param[in] ldb_path    Location in the filesystem where leveldb data will be stored.
     */
    explicit CCoinsViewDB(fs::path ldb_path, size_t nCacheSize, bool fMemory, bool fWipe);

    bool GetCoin(const COutPoint &outpoint, Coin &coin) const override;
    bool HaveCoin(const COutPoint &outpoint) const override;
    uint256 GetBestBlock() const override;
    std::vector<uint256> GetHeadBlocks() const override;
    bool BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock) override;
    std::unique_ptr<CCoinsViewCursor> Cursor() const override;

    //! Attempt to update from an older database format. Returns whether an error occurred.
    bool Upgrade();
    size_t EstimateSize() const override;

    //! Dynamically alter the underlying leveldb cache size.
    void ResizeCache(size_t new_cache_size) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
};

/** Access to the block database (blocks/index/) */
class CBlockTreeDB : public CDBWrapper
{
public:
    explicit CBlockTreeDB(size_t nCacheSize, bool fMemory = false, bool fWipe = false);

    bool WriteBatchSync(const std::vector<std::pair<int, const CBlockFileInfo*> >& fileInfo, int nLastFile, const std::vector<const CBlockIndex*>& blockinfo);
    bool ReadBlockFileInfo(int nFile, CBlockFileInfo &info);
    bool ReadLastBlockFile(int &nFile);
    bool WriteReindexing(bool fReindexing);
    void ReadReindexing(bool &fReindexing);
    bool WriteFlag(const std::string &name, bool fValue);
    bool ReadFlag(const std::string &name, bool &fValue);
    bool LoadBlockIndexGuts(const Consensus::Params& consensusParams, std::function<CBlockIndex*(const uint256&)> insertBlockIndex);
};

#endif // BITCOIN_TXDB_H


text:
using System.Web.Mvc;

namespace TestStack.FluentMVCTesting
{
    public partial class ControllerResultTest<T>
    {
        public EmptyResult ShouldReturnEmptyResult()
        {
            ValidateActionReturnType<EmptyResult>();
            return (EmptyResult) ActionResult;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.guardtime.ksi.unisignature.verifier.rules;

import com.guardtime.ksi.exceptions.KSIException;
import com.guardtime.ksi.unisignature.verifier.RuleResult;
import com.guardtime.ksi.unisignature.verifier.VerificationContext;
import com.guardtime.ksi.unisignature.verifier.VerificationErrorCode;
import com.guardtime.ksi.unisignature.verifier.VerificationResultCode;
import com.guardtime.ksi.util.Util;

import org.mockito.Mockito;
import org.testng.Assert;
import org.testng.annotations.Test;

public class NotRuleTest extends AbstractRuleTest {

    private VerificationContext context = Mockito.mock(VerificationContext.class);
    Rule ruleOk = new TestRule(VerificationResultCode.OK, null);
    Rule ruleNa = new TestRule(VerificationResultCode.NA, VerificationErrorCode.GEN_02);
    Rule ruleFail = new TestRule(VerificationResultCode.FAIL, VerificationErrorCode.GEN_01);

    @Test
    public void testNotOkResult_NA() throws KSIException {
        RuleResult ruleResult = new NotRule(ruleOk).verify(context);
        verifyResults(ruleResult, VerificationResultCode.NA, VerificationErrorCode.GEN_02, "Not TestRule");
    }

    @Test
    public void testNotNaResult_OK() throws KSIException {
        RuleResult ruleResult = new NotRule(ruleNa).verify(context);
        verifyResults(ruleResult, VerificationResultCode.OK, null, "Not TestRule");
    }

    @Test
    public void testNotFailResult_FAIL() throws KSIException {
        RuleResult ruleResult = new NotRule(ruleFail).verify(context);
        verifyResults(ruleResult, VerificationResultCode.FAIL, VerificationErrorCode.GEN_01, "Not TestRule");
    }

    @Test
    public void testCompositeRuleNotOkResult_NA() throws KSIException {
        Rule rule = new NotRule(new CompositeRule(true, ruleOk, ruleFail, ruleNa));
        RuleResult ruleResult = rule.verify(context);
        verifyResults(ruleResult, VerificationResultCode.NA, VerificationErrorCode.GEN_02, "Not TestRule,");
    }

    @Test
    public void testCompositeRuleNotNAResult_OK() throws KSIException {
        Rule rule = new NotRule(new CompositeRule(false, ruleNa, ruleFail, ruleOk));
        RuleResult ruleResult = rule.verify(context);
        verifyResults(ruleResult, VerificationResultCode.OK, null, "Not TestRule,");
    }

    @Test
    public void testCompositeRuleNotFailResult_Fail() throws KSIException {
        Rule rule = new NotRule(new CompositeRule(false, ruleFail, ruleOk, ruleNa));
        RuleResult ruleResult = rule.verify(context);;
        verifyResults(ruleResult, VerificationResultCode.FAIL, VerificationErrorCode.GEN_01, "Not TestRule,");
    }

    private void verifyResults(RuleResult result, VerificationResultCode resultCode, VerificationErrorCode errorCode, String ruleNameStartsWith) {
        Assert.assertEquals(result.getResultCode(),resultCode);
        Assert.assertEquals(result.getErrorCode(), errorCode);
        Assert.assertTrue(result.getRuleName().startsWith(ruleNameStartsWith));
    }

    private class TestRule extends BaseRule {
        private VerificationResultCode resultCode;
        private VerificationErrorCode errorCode;
        public TestRule(VerificationResultCode resultCode, VerificationErrorCode errorCode) {
            Util.notNull(resultCode, "VerificationResultCode");
            this.resultCode = resultCode;
            this.errorCode = errorCode;
        }

        @Override
        VerificationResultCode verifySignature(VerificationContext context) throws KSIException {
            return resultCode;
        }

        @Override
        VerificationErrorCode getErrorCode() {
            return errorCode;
        }
    }
}


text:
<!DOCTYPE html>

	<meta charset="utf-8">
	<meta name="robots" content="noindex">

	<title>File Stop.php</title>

	<link rel="stylesheet" href="resources/bootstrap.min.css?973e37a8502921d56bc02bb55321f45b072b6f71">
	<link rel="stylesheet" href="resources/style.css?49f43d3208c5d7e33fa16d36107a345bf11cc00d">

				Overview

                <form id="search" class="navbar-form navbar-left" role="search">
                    <input type="hidden" name="cx" value="">
                    <input type="hidden" name="ie" value="UTF-8">

                        <input type="text" name="q" class="search-query form-control" placeholder="Search">

				</form>

Namespace

Class

Namespaces

							CupOfTea

							TwoStream

							Console

							Contracts

							Exceptions

							Routing

							Session

							Ws

							Cookie

							Middleware

							Events

							Exceptions

							Facades

							Foundation

							Support

							Providers

							Ws

							Routing

							Server

							Session

							Middleware

Classes

CupOfTea\TwoStream\Console\Command

CupOfTea\TwoStream\Console\Output

CupOfTea\TwoStream\Cookie\Middleware\DecryptCookies

CupOfTea\TwoStream\Events\ClientConnected

CupOfTea\TwoStream\Events\ClientDisconnected

CupOfTea\TwoStream\Events\ServerStarted

CupOfTea\TwoStream\Events\ServerStopped

CupOfTea\TwoStream\Exceptions\Handler

CupOfTea\TwoStream\Facades\TwoStream

CupOfTea\TwoStream\Facades\WsRoute

CupOfTea\TwoStream\Facades\WsSession

CupOfTea\TwoStream\Foundation\Support\Providers\WsRouteServiceProvider

CupOfTea\TwoStream\Foundation\Ws\Kernel

CupOfTea\TwoStream\Install

CupOfTea\TwoStream\Routing\ControllerInspector

CupOfTea\TwoStream\Routing\Route

CupOfTea\TwoStream\Routing\WsRouter

CupOfTea\TwoStream\Server

CupOfTea\TwoStream\Server\Dispatcher

CupOfTea\TwoStream\Session\Middleware\StartSession

CupOfTea\TwoStream\Session\ReadOnly

CupOfTea\TwoStream\Stop

CupOfTea\TwoStream\TwoStream

CupOfTea\TwoStream\TwoStreamServiceProvider

Interfaces

CupOfTea\TwoStream\Contracts\Exceptions\Handler

CupOfTea\TwoStream\Contracts\Factory

CupOfTea\TwoStream\Contracts\Provider

CupOfTea\TwoStream\Contracts\Routing\Registrar

CupOfTea\TwoStream\Contracts\Session\ReadOnly

CupOfTea\TwoStream\Contracts\Ws\Kernel

Traits

CupOfTea\TwoStream\Console\Writer

Exceptions

CupOfTea\TwoStream\Exceptions\CatchableFatalErrorException

CupOfTea\TwoStream\Exceptions\InvalidRecipientException

CupOfTea\TwoStream\Exceptions\SyntaxErrorException

CupOfTea\TwoStream\Exceptions\TwoStreamException

 1 <?php namespace CupOfTea\TwoStream;
 2
 3 use Exception;
 4 use TwoStream as TwoStreamFacade;
 5
 6 use CupOfTea\TwoStream\Console\Output;
 7 use CupOfTea\TwoStream\Console\Command;
 8
 9 class Stop extends Command
10 {
11
12     /**
13      * The console command name.
14      *
15      * @var string
16      */
17     protected $name = 'twostream:stop';
18
19     /**
20      * Console Output
21      *
22      * @var \CupOfTea\TwoStream\Console\Output
23      */
24     protected $out;
25
26     /**
27      * The console command description.
28      *
29      * @var string
30      */
31     protected $description = 'Stop the TwoStream server.';
32
33     /**
34      * Create a new stop command instance.
35      *
36      * @return void
37      */
38     public function __construct()
39     {
40         parent::__construct();
41
42         $this->out = new Output();
43     }
44
45     /**
46      * Fire the command
47      *
48      * @return void
49      */
50     public function fire()
51     {
52         $this->line('Stopping TwoStream server.');
53
54         try {
55             TwoStreamFacade::stop();
56         } catch (Exception $e) {}
57     }
58
59 }
60

		 API documentation generated by ApiGen


text:
size_t CEF_CALLBACK read_handler_read(struct _cef_read_handler_t* self,
    void* ptr, size_t size, size_t n)
{
  // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING

  DCHECK(self);
  if (!self)
    return 0;
  // Verify param: ptr; type: simple_byaddr
  DCHECK(ptr);
  if (!ptr)
    return 0;

  // Execute
  size_t _retval = CefReadHandlerCppToC::Get(self)->Read(
      ptr,
      size,
      n);

  // Return type: simple
  return _retval;
}

int CEF_CALLBACK read_handler_seek(struct _cef_read_handler_t* self,
    long offset, int whence)
{
  // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING

  DCHECK(self);
  if (!self)
    return 0;

  // Execute
  int _retval = CefReadHandlerCppToC::Get(self)->Seek(
      offset,
      whence);

  // Return type: simple
  return _retval;
}

long CEF_CALLBACK read_handler_tell(struct _cef_read_handler_t* self)
{
  // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING

  DCHECK(self);
  if (!self)
    return 0;

  // Execute
  long _retval = CefReadHandlerCppToC::Get(self)->Tell();

  // Return type: simple
  return _retval;
}

int CEF_CALLBACK read_handler_eof(struct _cef_read_handler_t* self)
{
  // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING

  DCHECK(self);
  if (!self)
    return 0;

  // Execute
  int _retval = CefReadHandlerCppToC::Get(self)->Eof();

  // Return type: simple
  return _retval;
}

// CONSTRUCTOR - Do not edit by hand.

CefReadHandlerCppToC::CefReadHandlerCppToC(CefReadHandler* cls)
    : CefCppToC<CefReadHandlerCppToC, CefReadHandler, cef_read_handler_t>(cls)
{
  struct_.struct_.read = read_handler_read;
  struct_.struct_.seek = read_handler_seek;
  struct_.struct_.tell = read_handler_tell;
  struct_.struct_.eof = read_handler_eof;
}

#ifndef NDEBUG
template<> long CefCppToC<CefReadHandlerCppToC, CefReadHandler,
    cef_read_handler_t>::DebugObjCt = 0;
#endif


text:
#ifndef MAP_PLOTTER_H
#define MAP_PLOTTER_H

#include "MapPlotterConfig.h"
#include "MapPlotterTypes.h"

#include <vector>

class MC2Point;

namespace isab {

/**
 *   Abstract class representing a vector of coordinates.
 *   To be used as a base class for specialized classes used
 *   by the MapPlotter subclasses.
 *   Should be templated into the MapPlotter later for performance.
 */
class PointVector {
public:

   /**
    *   Virtual destructor.
    */
   virtual ~PointVector() {};

   /**
    *   Adds one coordinate to the vector.
    *   @param x The x coordinate.
    *   @param y The y coordinate.
    */
   virtual void addPoint( int x, int y ) = 0;

   /**
    *   Adds many points at once to the vector.
    *   Default implementation just calls the reset mehtod and then addPoint
    *   method for each point.
    */
   virtual void setPoints(const std::vector<MC2Point>& points);

   /**
    *   Returns the number of coordinates in the vector.
    */
   virtual int getSize() const = 0;

   /**
    *   Resets the addposition ( and size ) back to zero.
    */
   virtual void reset() = 0;

   /**
    *   Returns the number of allocated points.
    */
   virtual int getAllocatedSize() const = 0;

};

/**
 *   Abstract class representing a bitmap suitable for use
 *   in the drawing system. Nothing is defined here, but
 *   the pointers can be used for passing the BitmMaps in and
 *   out of the MapPlotter.
 */
class BitMap {
};

/**
 *   Abstract class that should be used to describe a device
 *   that is able to draw a map. See it as a driver.
 *

 *   NB! It should be possible to use this file in
 *              many environments so the default implementations
 *              must not use anything other than the functions in
 *              MapPlotter.
 */
class MapPlotter {
public:

   /**
    *   Virtual destructor.
    */
   virtual ~MapPlotter() {}

   // -- Functions that must be implemented ---------------

   /**
    *   Fills the screen with the background color.
    */
   virtual void clearScreen() = 0;

   /**
    *   Sets the background color.
    *

    *   NB! The server will not send impossible values once the
    *   description formats are done.
    *   @param red   Red value   0-255.
    *   @param green Green value 0-255.
    *   @param blue  Blue value  0-255.
    */
   virtual void setBackgroundColor( unsigned int red,
                                    unsigned int green,
                                    unsigned int blue ) = 0;

   /**
    *   Sets the color of the pen.
    *

    *   NB! The server will not send impossible values once the
    *   description formats are done.
    *   @param red   Red value   0-255.
    *   @param green Green value 0-255.
    *   @param blue  Blue value  0-255.
    */
   virtual void setPenColor( unsigned int red,
                             unsigned int green,
                             unsigned int blue ) = 0;

   /**
    *   Sets the color of the pen using one 24bit color value.
    *   @param rgb24bits Red in bits 23-16 etc.
    */
   inline void setPenColor(unsigned int  rgb24bits ) {
      setPenColor( ( rgb24bits >> 16) & 0xff,
                   ( rgb24bits >>  8) & 0xff,
                   ( rgb24bits >>  0) & 0xff );
   }

   /**
    *   Puts the dimensions of the displayed map in the
    *   variables.
    */
   virtual void getMapSizePixels(Rectangle& size) const = 0;

   /**
    *   Creates a pointvector of size size.
    */
   virtual PointVector* createPointVector(int size) = 0;

   /**
    *   Returns the pointvector to the MapPlotter.
    */
   virtual void deletePointVector(PointVector* vect) = 0;

   // Functions that should be re-implemented. ---------------------->

   virtual int nbrMaskedExtraBitmaps() const { return 0; }

   virtual int switchBitmap( int nbr, int mask ) {
      return nbr == 0 && mask == false;
   }

   // Text functions -------------------------------------------------

   /**
    *   Creates a text string for use with the other text methods.
    *   Default implementation returns NULL.
    */
   virtual STRING* createString(const char* text);

   /**
    *   Deletes a text string.
    *   Default implementation does nothing.
    */
   virtual void deleteString(STRING* text);

   /**
    *   @return The number of characters in the string.
    */
   virtual int getStringLength( const STRING& text );

   /**
    *   Sets font. The description format in the server
    *   and the MapPlotter must know what needs to be put
    *   here.
    *   @param fontName Name of the font in client-specific format.
    *   @param size     Size of the font in UNIT.
    */
   virtual void setFont( const STRING& fontName, int size );

   /**
    *   Returns the rotation step possible by the plotter.
    *
Default implementation returns 0.
    *   @return The minimum number of degrees that characters can
    *           be rotated.
    */
   virtual int getMinTextRotation();

   /**
    *    Draw straight text. The specified point is at the baseline,
    *    left of the text.
    */
   virtual void drawTextAtBaselineLeft( const STRING& text,
                                        const MC2Point& point );

   /**
    *   Draws text on the display using the pen color and transparent
    *   background.
    *   @param text      The start of the text to draw.
    *   @param points    The center point of the text.
    *   @param startIdx  The first character to draw.
    *   @param nbrChars  The number of characters to draw.
    */
   virtual void drawText( const STRING& text,
                          const MC2Point& point,
                          int startIdx =  0,
                          int nbrChars = -1,
                          float angle  =  0.0 );

   /**
    *   Puts the bounding boxes of each character in str
    *   into the vector boxes.
    *

    *   Default implementation does nothing and returns 0.
    *   @param boxes  Vector to add the boxes to.
    *   @see drawText
    *   @return Number of characters in str.
    */
   virtual Rectangle getStringAsRectangle( const STRING& text,
                                           const MC2Point& point,
                                           int startIdx =  0,
                                           int nbrChars = -1,
                                           float angle  = 0.0 );

   /**
    *   Puts the bounding boxes of each character in str
    *   into the vector boxes.
    *

    *   Default implementation does nothing and returns 0.
    *   @param boxes  Vector to add the boxes to.
    *   @see drawText
    *   @return Number of characters in str.
    */
   virtual int getStringAsRectangles( std::vector<Rectangle>& boxes,
                                      const STRING& text,
                                      const MC2Point& point,
                                      int startIdx =  0,
                                      int nbrChars = -1,
                                      float angle  = 0.0 );

   /**
    *   Get if the text rendering direction is left to right
    *   or not (arabic, hebrew is right to left) for the
    *   specified text.
    *   Default implementation returns true.
    */
   virtual bool textDirectionLeftToRight( const STRING& text ) {
      return true;
   }

   // Misc ----------------------------------------------------------

   /**
    *   True if the mapplotter looks at the mask of the images
    *   to create the visible boundingbox.
    */
   virtual bool returnsVisibleSizeOfBitmaps() const {
      return false;
   }

   /**
    *   Returns true if the drawing is double buffered.
    *   Default implementation returns false.
    *   @return True if the drawing is double buffered.
    */
   virtual bool doubleBuffered() const;

   /**
    *   Tells the MapPlotter that it is ok to change buffer
    *   if it is doubleBuffered. Default implementation does
    *   nothing.
    *   @return doubleBuffered().
    */
   virtual bool drawBuffer( const Rectangle& rect );

   /**
    *   If the MapPlotter needs to prepare the plotting in
    *   any way it should do it in this method which is called
    *   before drawing.
    *

    *   The default implementation does not do anything.
    */
   virtual void prepareDrawing();

   /**
    *   Must be called by the drawing engine everytime a drawing
    *   is completed. This is to be able to free up the resources
    *   that may have been used during the draw.
    *

    *   The default implementation does not do anything.
    */
   virtual void drawingCompleted();

   /**
    *   Converts the bytes into a bitmap that can be drawn by the
    *   MapPlotter.
    *   Default implementation returns NULL.
    *   FIXME: Should we add the type of image too, e.g. PNG etc.?
    */
   virtual BitMap* createBitMap(bitMapType type,
                                const uint8* bytes,
                                int nbrBytes,
                                bool shouldScale = false,
                                int dpiCorrectionFactor = 1 );

   /**
    *   Draws the bitmap at x and y.
    *   Default implementation draws a small rectangle.
    */
   virtual void drawBitMap( const MC2Point& center,
                            const BitMap* bitMap);

   /**
    *   Gets the size of the specified BitMap in pixels
    *   Has to be implemented in derived class.
    *   @param size Rectangle which the bitmap is inside.
    *   @param bmp  Bitmap to get the size from.
    *   @param centerXY The center of the bitmap (position where it is drawn).
    */
   virtual void getBitMapAsRectangle(Rectangle& size,
                                     const MC2Point& origCenter,
                                     const BitMap* bmp);

   /**
    *   Gets the size of the specified BitMap in pixels
    *   The other getBitMapAsRectangle has to be implemented in the subclasses.
    *   @param size Rectangle which the bitmap is inside.
    *   @param bmp  Bitmap to get the size from.
    *   @param centerXY The center of the bitmap (position where it is drawn).
    */
   Rectangle getBitMapAsRectangle( const MC2Point& origCenter,
                                   const BitMap* bmp) {
      Rectangle rect;
      getBitMapAsRectangle(rect, origCenter, bmp);
      return rect;
   }

   /**
    *   Deletes the supplied bitmap.
    */
   virtual void deleteBitMap( BitMap* bitMap );

   /**
    *   Returns the wanted bitmap extension.
    *   Default implementation returns png. Dot will be appended
    *   by TileMapHandler.
    */
   virtual const char* getBitMapExtension() const;

   /**
    *   Sets the fill color for polygons.
    *   Default implementation sets the pen color.
    *   @see setPenColor.
    */
   virtual void setFillColor( unsigned int red,
                              unsigned int green,
                              unsigned int blue );
   /**
    *   Sets the color of the pen using one 24bit color value.
    *   @param rgb24bits Red in bits 23-16 etc.
    */
   inline void setFillColor(unsigned int  rgb24bits ) {
      setFillColor( ( rgb24bits >> 16) & 0xff,
                   ( rgb24bits >>  8) & 0xff,
                   ( rgb24bits >>  0) & 0xff );
   }

   /**
    *   Draws a polygon filled with the fill color and with a border
    *   with set with setPenColor and linewith as set by setLineWidth
    *   and dashstyle set by setDashStyle.
    *   If borderColor == penColor or lineWidth == 0 no border should
    *   be drawn.
    *

    *   Default implementation draws a polyline using the fill color.
    */
   virtual void drawPolygon( std::vector<MC2Point>::const_iterator begin,
                             std::vector<MC2Point>::const_iterator end );

   /**
    *   Draws a filled polygon defined by the iterators to the screen coords
    *   and the supplied color and line width. Override this to
    *   reduce the number of virtual functions called by the
    *   TileMapHandler.
    *   @param begin     First point draw.
    *   @param end       Point after last point to draw.
    *   @param fillcolor Color to fill with in rrggbb format.
    */
   virtual void drawPolygonWithColor( std::vector<MC2Point>::const_iterator begin,
                                      std::vector<MC2Point>::const_iterator end,
                                      uint32 fillcolor ) = 0;

   /**
    *   Draws a polyline defined by the array of points.
    */
   virtual void drawPolyLine( std::vector<MC2Point>::const_iterator begin,
                              std::vector<MC2Point>::const_iterator end ) = 0;

   /**
    *   Draws a polyline defined by the iterators to the screen coords
    *   and the supplied color and line width. Override this to
    *   reduce the number of virtual functions called by the
    *   TileMapHandler.
    *   @param begin     First point draw.
    *   @param end       Point after last point to draw.
    *   @param color     Color in rrggbb format.
    *   @param lineWidth Line width in pixels.
    */
   virtual void drawPolyLineWithColor( std::vector<MC2Point>::const_iterator begin,
                                       std::vector<MC2Point>::const_iterator end,
                                       uint32 color,
                                       int lineWidth ) = 0;

   /**
    *   Default implementation draws a polyline using the fill color.
    */
   //virtual void drawPolyPolygon( const PointVectorVector& polygons );

   /**
    *   Draws a spline of some sort.
    *

    *   Default implementation draws a polyline if not filled else polygon.
    */
   virtual void drawSpline( bool filled,
                            std::vector<MC2Point>::const_iterator begin,
                            std::vector<MC2Point>::const_iterator end );

   /**
    *   Same as drawPolygons, but the polygons must be convex. Can be
    *   implemented to speed things up.
    *

    *   Default implementation calls drawPolygons.
    */
   virtual void drawConvexPolygon( std::vector<MC2Point>::const_iterator begin,
                                   std::vector<MC2Point>::const_iterator end );

   /**
    *   Draws an arc.
    *   Default implementation draws a line from one corner to the other
    *   in the rectangle.
    */
   virtual void drawArc( bool filled,
                         const Rectangle& rect,
                         int startAngle,
                         int stopAngle);

   /**
    *   Draws a rectangle.
    *   @param filled     If true the rectangle is filled.
    *   @param rect       Dimensions of the rectangle.
    *   @param cornerSize Radius of corners.
    *   Default implementation cannot draw rounded corners and uses
    *   drawPolyLine or drawConvexPolygon.
    */
   virtual void drawRect( bool filled,
                          const Rectangle& rect,
                          int cornerSize = 0);

   /**
    *   Sets the width of the lines.
    *   Default implementation does nothing.
    */
   virtual void setLineWidth( int width );

   /**
    *   Sets the cap style of the pen.
    *   Default implementation does nothing.
    */
   virtual void setCapStyle( enum capStyle );

   /**
    *   Sets the dash style of the pen.
    *   Default implementation does nothing.
    */
   virtual void setDashStyle( enum dashStyle );

   /**
    *   Puts the dimensions of the displayed map in the
    *   variables. Must be overridden if the drawing units
    *   of the map is not pixels.
    *

    *   Default implementation returns getMapSizePixels.
    */
   virtual void getMapSizeDrawingUnits(Rectangle& size) const;

   /**
    *   If the plotter can handle the screen as a bitmap snapshot, i.e.
    *   if makeScreenSnapshot(), moveScreenSnapshot() and
    *   zoomScreenSnapshot() are properly implemented.
    */
   virtual bool snapshotHandlingImplemented() const;

   /**
    *   Creates a bitmap screen snapshot and stores it.
    *   Default implementation does nothing.
    */
   virtual void makeScreenSnapshot();

   /**
    *   Moves the screen snapshot.
    */
   virtual void moveScreenSnapshot( const MC2Point& deltaPoint );

   /**
    *   Zooms the screen snapshot. Value larger than one means zoom in.
    */
   virtual void zoomScreenSnapshot(double factor, const MC2Point& zoomPoint);

   /**
    *   Locks the bitmap buffer, needed on at least the symbian
    *   platform when doing operations on the bitmaps data.
    */
   virtual void lockBitmapBuffer();

   /**
    *   Unlocks the bitmap buffer. Should only be done when the buffer
    *   has been locked.
    */
   virtual void unlockBitmapBuffer();

   /**
    *   Returns the data adress of the bitmap.
    */
   virtual uint32* getBitmapBuffer();

   /**
    *   Returns the colorDepth of a bitmap.
    */
   virtual int getColorDepth();

   /**
    *  Set the drawing mode to be low quality and fast.
    *  Such as disabling antialiasing, or other tricks.
    */
   virtual void enableLowQualityDrawing( bool on );

   /**
    *  Should be overridden to return true by platforms
    *  that support image scaling.
    */
   virtual bool supportsBitMapScaling() const {
      return false;
   }

   /**
    *  Should be overridden by platforms that support image
    *  scaling.
    */
   virtual bool updateBitmapDimensions(BitMap* image,
                                       int newWidth,
                                       int newHeight) {
      return false;
   }
};
} // namespace
#endif


text:
module Sudoku.Strategy.NakedSingle where

import Data.Char
import Data.List
import Prelude
import Sudoku
import Sudoku.Strategy

resolveAllCandidates :: Sudoku -> [[(Char, String)]]
resolveAllCandidates su = mapWithIndeces su (\i j -> (su !! i !! j, findCandidates su i j))


text:
bluesky
=======

[![Build Status](https://img.shields.io/github/workflow/status/bluesky/bluesky/Unit%20Tests)](https://github.com/bluesky/bluesky/actions?query=workflow%3A%22Unit+Tests%22+branch%3Amaster)

[**Documentation**](http://blueskyproject.io/bluesky).


text:
namespace base {
class TaskRunner;
}

namespace net {

struct DhcpAdapterNamesLoggingInfo;
class DhcpPacFileAdapterFetcher;
class URLRequestContext;

// Windows-specific implementation.
class NET_EXPORT_PRIVATE DhcpPacFileFetcherWin
    : public DhcpPacFileFetcher,
      public base::SupportsWeakPtr<DhcpPacFileFetcherWin> {
 public:
  // Creates a DhcpPacFileFetcherWin that issues requests through
  // |url_request_context|. |url_request_context| must remain valid for
  // the lifetime of DhcpPacFileFetcherWin.
  explicit DhcpPacFileFetcherWin(URLRequestContext* url_request_context);
  ~DhcpPacFileFetcherWin() override;

  // DhcpPacFileFetcher implementation.
  int Fetch(base::string16* utf16_text,
            CompletionOnceCallback callback,
            const NetLogWithSource& net_log,
            const NetworkTrafficAnnotationTag traffic_annotation) override;
  void Cancel() override;
  void OnShutdown() override;
  const GURL& GetPacURL() const override;
  std::string GetFetcherName() const override;

  // Sets |adapter_names| to contain the name of each network adapter on
  // this machine that has DHCP enabled and is not a loop-back adapter. May
  // optionally update |info| (if non-null) with information for logging.
  // Returns false on error.
  static bool GetCandidateAdapterNames(std::set<std::string>* adapter_names,
                                       DhcpAdapterNamesLoggingInfo* info);

 protected:
  int num_pending_fetchers() const;

  URLRequestContext* url_request_context() const;

  scoped_refptr<base::TaskRunner> GetTaskRunner();

  // This inner class encapsulate work done on a worker pool thread.
  // The class calls GetCandidateAdapterNames, which can take a couple of
  // hundred milliseconds.
  class NET_EXPORT_PRIVATE AdapterQuery
      : public base::RefCountedThreadSafe<AdapterQuery> {
   public:
    AdapterQuery();

    // This is the method that runs on the worker pool thread.
    void GetCandidateAdapterNames();

    // This set is valid after GetCandidateAdapterNames has
    // been run. Its lifetime is scoped by this object.
    const std::set<std::string>& adapter_names() const;

    DhcpAdapterNamesLoggingInfo* logging_info() { return logging_info_.get(); }

   protected:
    // Virtual method introduced to allow unit testing.
    virtual bool ImplGetCandidateAdapterNames(
        std::set<std::string>* adapter_names,
        DhcpAdapterNamesLoggingInfo* info);

    friend class base::RefCountedThreadSafe<AdapterQuery>;
    virtual ~AdapterQuery();

   private:
    // These are constructed on the originating thread, then used on the
    // worker thread, then used again on the originating thread only when
    // the task has completed on the worker thread. No locking required.
    std::set<std::string> adapter_names_;
    std::unique_ptr<DhcpAdapterNamesLoggingInfo> logging_info_;

    DISALLOW_COPY_AND_ASSIGN(AdapterQuery);
  };

  // Virtual methods introduced to allow unit testing.
  virtual DhcpPacFileAdapterFetcher* ImplCreateAdapterFetcher();
  virtual AdapterQuery* ImplCreateAdapterQuery();
  virtual base::TimeDelta ImplGetMaxWait();
  virtual void ImplOnGetCandidateAdapterNamesDone() {}

 private:
  // Event/state transition handlers
  void CancelImpl();
  void OnGetCandidateAdapterNamesDone(
      scoped_refptr<AdapterQuery> query,
      const NetworkTrafficAnnotationTag traffic_annotation);
  void OnFetcherDone(size_t fetcher_i, int result);
  void OnWaitTimer();
  void TransitionToDone();

  // This is the outer state machine for fetching PAC configuration from
  // DHCP.  It relies for sub-states on the state machine of the
  // DhcpPacFileAdapterFetcher class.
  //
  // The goal of the implementation is to the following work in parallel
  // for all network adapters that are using DHCP:
  // a) Try to get the PAC URL configured in DHCP;
  // b) If one is configured, try to fetch the PAC URL.
  // c) Once this is done for all adapters, or a timeout has passed after
  //    it has completed for the fastest adapter, return the PAC file
  //    available for the most preferred network adapter, if any.
  //
  // The state machine goes from START->WAIT_ADAPTERS when it starts a
  // worker thread to get the list of adapters with DHCP enabled.
  // It then goes from WAIT_ADAPTERS->NO_RESULTS when it creates
  // and starts an DhcpPacFileAdapterFetcher for each adapter.  It goes
  // from NO_RESULTS->SOME_RESULTS when it gets the first result; at this
  // point a wait timer is started.  It goes from SOME_RESULTS->DONE in
  // two cases: All results are known, or the wait timer expired.  A call
  // to Cancel() will also go straight to DONE from any state.  Any
  // way the DONE state is entered, we will at that point cancel any
  // outstanding work and return the best known PAC script or the empty
  // string.
  //
  // The state machine is reset for each Fetch(), a call to which is
  // only valid in states START and DONE, as only one Fetch() is
  // allowed to be outstanding at any given time.
  enum State {
    STATE_START,
    STATE_WAIT_ADAPTERS,
    STATE_NO_RESULTS,
    STATE_SOME_RESULTS,
    STATE_DONE,
  };

  // Vector, in Windows' network adapter preference order, of
  // DhcpPacFileAdapterFetcher objects that are or were attempting
  // to fetch a PAC file based on DHCP configuration.
  using FetcherVector = std::vector<std::unique_ptr<DhcpPacFileAdapterFetcher>>;
  FetcherVector fetchers_;

  // Current state of this state machine.
  State state_;

  // The following members are associated with the latest call to Fetch().

  // Number of fetchers we are waiting for.
  int num_pending_fetchers_;

  // Lets our client know we're done. Not valid in states START or DONE.
  CompletionOnceCallback callback_;

  // The NetLog to use for the current Fetch().
  NetLogWithSource net_log_;

  // Pointer to string we will write results to. Not valid in states
  // START and DONE.
  base::string16* destination_string_;

  // PAC URL retrieved from DHCP, if any. Valid only in state STATE_DONE.
  GURL pac_url_;

  base::OneShotTimer wait_timer_;

  // Set to nullptr on cancellation.
  URLRequestContext* url_request_context_;

  // NULL or the AdapterQuery currently in flight.
  scoped_refptr<AdapterQuery> last_query_;

  // TaskRunner used for all DHCP lookup tasks.
  const scoped_refptr<base::TaskRunner> task_runner_;

  THREAD_CHECKER(thread_checker_);

  DISALLOW_IMPLICIT_CONSTRUCTORS(DhcpPacFileFetcherWin);
};

}  // namespace net

#endif  // NET_PROXY_RESOLUTION_WIN_DHCP_PAC_FILE_FETCHER_WIN_H_


text:
#ifndef SILK_STRUCTS_FLP_H
#define SILK_STRUCTS_FLP_H

#include "typedef.h"
#include "main.h"
#include "structs.h"

#ifdef __cplusplus
extern "C"
{
#endif

/********************************/
/* Noise shaping analysis state */
/********************************/
typedef struct {
    opus_int8                   LastGainIndex;
    silk_float                  HarmShapeGain_smth;
    silk_float                  Tilt_smth;
} silk_shape_state_FLP;

/********************************/
/* Encoder state FLP            */
/********************************/
typedef struct {
    silk_encoder_state          sCmn;                               /* Common struct, shared with fixed-point code */
    silk_shape_state_FLP        sShape;                             /* Noise shaping state */

    /* Buffer for find pitch and noise shape analysis */
    silk_float                  x_buf[ 2 * MAX_FRAME_LENGTH + LA_SHAPE_MAX ];/* Buffer for find pitch and noise shape analysis */
    silk_float                  LTPCorr;                            /* Normalized correlation from pitch lag estimator */
} silk_encoder_state_FLP;

/************************/
/* Encoder control FLP  */
/************************/
typedef struct {
    /* Prediction and coding parameters */
    silk_float                  Gains[ MAX_NB_SUBFR ];
    silk_float                  PredCoef[ 2 ][ MAX_LPC_ORDER ];     /* holds interpolated and final coefficients */
    silk_float                  LTPCoef[LTP_ORDER * MAX_NB_SUBFR];
    silk_float                  LTP_scale;
    opus_int                    pitchL[ MAX_NB_SUBFR ];

    /* Noise shaping parameters */
    silk_float                  AR[ MAX_NB_SUBFR * MAX_SHAPE_LPC_ORDER ];
    silk_float                  LF_MA_shp[     MAX_NB_SUBFR ];
    silk_float                  LF_AR_shp[     MAX_NB_SUBFR ];
    silk_float                  Tilt[          MAX_NB_SUBFR ];
    silk_float                  HarmShapeGain[ MAX_NB_SUBFR ];
    silk_float                  Lambda;
    silk_float                  input_quality;
    silk_float                  coding_quality;

    /* Measures */
    silk_float                  predGain;
    silk_float                  LTPredCodGain;
    silk_float                  ResNrg[ MAX_NB_SUBFR ];             /* Residual energy per subframe */

    /* Parameters for CBR mode */
    opus_int32                  GainsUnq_Q16[ MAX_NB_SUBFR ];
    opus_int8                   lastGainIndexPrev;
} silk_encoder_control_FLP;

/************************/
/* Encoder Super Struct */
/************************/
typedef struct {
    silk_encoder_state_FLP      state_Fxx[ ENCODER_NUM_CHANNELS ];
    stereo_enc_state            sStereo;
    opus_int32                  nBitsUsedLBRR;
    opus_int32                  nBitsExceeded;
    opus_int                    nChannelsAPI;
    opus_int                    nChannelsInternal;
    opus_int                    nPrevChannelsInternal;
    opus_int                    timeSinceSwitchAllowed_ms;
    opus_int                    allowBandwidthSwitch;
    opus_int                    prev_decode_only_middle;
} silk_encoder;

#ifdef __cplusplus
}
#endif

#endif


text:
// Generated by xsd compiler for ios/objective-c
// DO NOT CHANGE!

#import <Foundation/Foundation.h>
#import "PicoClassSchema.h"
#import "PicoPropertySchema.h"
#import "PicoConstants.h"
#import "PicoBindable.h"

/**
 (public class)

*/
@interface PersonType : NSObject <PicoBindable> {

@private
    NSString *_firstName;
    NSString *_lastName;
    NSString *_address1;
    NSString *_address2;
    NSString *_postCode;
    NSString *_city;
    NSString *_country;
    NSNumber *_id;

}

/**
 (public property)

 type : NSString, wrapper for primitive string
*/
@property (nonatomic, retain) NSString *firstName;

/**
 (public property)

 type : NSString, wrapper for primitive string
*/
@property (nonatomic, retain) NSString *lastName;

/**
 (public property)

 type : NSString, wrapper for primitive string
*/
@property (nonatomic, retain) NSString *address1;

/**
 (public property)

 type : NSString, wrapper for primitive string
*/
@property (nonatomic, retain) NSString *address2;

/**
 (public property)

 type : NSString, wrapper for primitive string
*/
@property (nonatomic, retain) NSString *postCode;

/**
 (public property)

 type : NSString, wrapper for primitive string
*/
@property (nonatomic, retain) NSString *city;

/**
 (public property)

 type : NSString, wrapper for primitive string
*/
@property (nonatomic, retain) NSString *country;

/**
 (public property)

 type : NSNumber, wrapper for primitive int
*/
@property (nonatomic, retain) NSNumber *id;

@end


text:
package com.planet_ink.coffee_mud.Commands;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.Clan.Authority;
import com.planet_ink.coffee_mud.Common.interfaces.Clan.MemberRecord;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;

import java.util.*;

@SuppressWarnings({})
public class ClanAccept extends StdCommand
{
	public ClanAccept(){}

	private final String[] access=I(new String[]{"CLANACCEPT"});
	@Override public String[] getAccessWords(){return access;}
	@Override
	public boolean execute(MOB mob, List<String> commands, int metaFlags)
		throws java.io.IOException
	{
		String memberStr=(commands.size()>1)?(String)commands.get(commands.size()-1):"";
		final String clanName=(commands.size()>2)?CMParms.combine(commands,1,commands.size()-1):"";

		Clan C=null;
		final boolean skipChecks=mob.getClanRole(mob.Name())!=null;
		if(skipChecks)
			C=mob.getClanRole(mob.Name()).first;

		if(C==null)
		for(final Pair<Clan,Integer> c : mob.clans())
			if((clanName.length()==0)||(CMLib.english().containsString(c.first.getName(), clanName))
			&&(c.first.getAuthority(c.second.intValue(), Clan.Function.ACCEPT)!=Authority.CAN_NOT_DO))
			{	C=c.first; break; }

		commands.clear();
		commands.add(getAccessWords()[0]);
		commands.add(memberStr);
		final StringBuffer msg=new StringBuffer("");
		boolean found=false;
		if(memberStr.length()>0)
		{
			if(C==null)
			{
				mob.tell(L("You aren't allowed to accept anyone into @x1.",((clanName.length()==0)?"anything":clanName)));
				return false;
			}
			if(C.getGovernment().getAutoRole() == C.getGovernment().getAcceptPos())
			{
				mob.tell(L("Everyone is already accepted."));
				return false;
			}
			if(skipChecks||CMLib.clans().goForward(mob,C,commands,Clan.Function.ACCEPT,false))
			{
				final List<MemberRecord> apps=C.getMemberList(C.getGovernment().getAutoRole());
				if(apps.size()<1)
				{
					mob.tell(L("There are no applicants to your @x1.",C.getGovernmentName()));
					return false;
				}
				memberStr=CMStrings.capitalizeAndLower(memberStr);
				for(final MemberRecord member : apps)
				{
					if(member.name.equalsIgnoreCase(memberStr))
					{
						found=true;
					}
				}
				if(found)
				{
					final MOB M=CMLib.players().getLoadPlayer(memberStr);
					if(M==null)
					{
						mob.tell(L("@x1 was not found.  Could not add to @x2.",memberStr,C.getGovernmentName()));
						return false;
					}
					if(skipChecks||CMLib.clans().goForward(mob,C,commands,Clan.Function.ACCEPT,true))
					{
						C.addMember(M,C.getGovernment().getAcceptPos());
						if(C.getGovernment().getEntryScript().trim().length()>0)
						{
							final ScriptingEngine S=(ScriptingEngine)CMClass.getCommon("DefaultScriptingEngine");
							S.setSavable(false);
							S.setVarScope("*");
							S.setScript(C.getGovernment().getEntryScript());
							final CMMsg msg2=CMClass.getMsg(M,M,null,CMMsg.MSG_OK_VISUAL,null,null,L("CLANENTRY"));
							S.executeMsg(M, msg2);
							S.dequeResponses();
							S.tick(M,Tickable.TICKID_MOB);
						}
						CMLib.clans().clanAnnounce(mob,L("@x1 is now a new member of @x2 @x3.",M.Name(),C.getGovernmentName(),C.name()));
						mob.tell(L("@x1 has been accepted into @x2 '@x3'.",M.Name(),C.getGovernmentName(),C.clanID()));
						if((M.session()!=null)&&(M.session().mob()==M))
							M.tell(L("@x1 has accepted you as a member of @x2 '@x3'.",mob.Name(),C.getGovernmentName(),C.clanID()));
						return false;
					}
				}
				else
				{
					msg.append(L("@x1 isn't an applicant of your @x2.",memberStr,C.getGovernmentName()));
				}
			}
			else
			{
				msg.append(L("You aren't in the right position to accept members into your @x1.",C.getGovernmentName()));
			}
		}
		else
		{
			msg.append(L("You haven't specified which applicant you are accepting."));
		}
		mob.tell(msg.toString());
		return false;
	}

	@Override public boolean canBeOrdered(){return false;}

}


text:
namespace phosphor
{
namespace logging
{

StartupFunctions& Extensions::getStartupFunctions()
{
    static StartupFunctions startupFunctions{};
    return startupFunctions;
}

CreateFunctions& Extensions::getCreateFunctions()
{
    static CreateFunctions createFunctions{};
    return createFunctions;
}

DeleteFunctions& Extensions::getDeleteFunctions()
{
    static DeleteFunctions deleteFunctions{};
    return deleteFunctions;
}

DeleteProhibitedFunctions& Extensions::getDeleteProhibitedFunctions()
{
    static DeleteProhibitedFunctions deleteProhibitedFunctions{};
    return deleteProhibitedFunctions;
}

Extensions::DefaultErrorCaps& Extensions::getDefaultErrorCaps()
{
    static DefaultErrorCaps defaultErrorCaps = DefaultErrorCaps::enable;
    return defaultErrorCaps;
}

} // namespace logging
} // namespace phosphor


text:
<?php

namespace App\Providers;

use Illuminate\Pagination\Paginator;
use Illuminate\Support\Facades\Blade;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        //
        Paginator::useBootstrap();
        // Blade::withDoubleEncoding();
    }
}


text:
package org.spaceproservice.exception;

public class AuthenticationException extends SpaceproException{
    public AuthenticationException(String s) {
        super(s);
    }
}


text:
if [ ! -d "./assets" ]; then
	mkdir assets
fi

# Delete all existing shaders in assets
rm -rf ./assets/*.?sh;

# Copy all shaders to assets
# We assume that vertex shaders are named as **.vsh and fragment shaders as **.fsh
find ./jni -name "*.?sh" -exec cp "{}" ./assets/ \;


text:
setwebdevenv
============
copyright @2014 Emerson (http://github.com/mrzon)

Set your web development environment seamlessly.

This program will automate the tedious task in creating your own local web development. It includes simulate IP address, adding fake domain to /private/etc/hosts and adding vhost configuration.

This program tested in Mac OS and based on this guide: http://lifewithoutrolemodel.wordpress.com/2014/05/06/how-to-make-local-environment-for-your-project-website/

How to use:

1. Make sure you have a directory that contained all web development project, name it e.g. "WebProjects"
2. For each project, create a .ini file in this directory, name it:
     * web_env_project1.ini
     * web_env_project2.ini
     * …
     * web_env_projectN.ini
3. Each .ini file contains these fields:

	```
	ip = 152.118.32.2 ;the IP that you want to simulate
	domain = "test.local" ; local domain name of your website development
	apache = "/Applications/XAMPP/xamppfiles"	;location of your apache program
	www = "/Users/test"	; project source of your website development
	```

4. Extract all files from this repo into the folder "WebProjects"
5. Run the bash file with this syntax:

	*~/WebProjects* > sudo ./web_env_prepare.sh ./web_env_project1.ini

Credits to the maker of read_ini file (https://github.com/rudimeier/)


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using Infrastructure.Common;
using System;
using System.Security.Cryptography.X509Certificates;
using System.ServiceModel;
using System.ServiceModel.Security;
using System.Threading.Tasks;
using Xunit;

public partial class Tcp_ClientCredentialTypeTests : ConditionalWcfTest
{
    [WcfFact]
    [Issue(1945, OS = OSID.AnyOSX)]
    [Condition(nameof(Root_Certificate_Installed),
               nameof(Client_Certificate_Installed),
               nameof(Peer_Certificate_Installed),
               nameof(SSL_Available))]
    [OuterLoop]
    // Asking for PeerTrust alone should succeed
    // if the certificate is in the TrustedPeople store.  For this test
    // we use a certificate we know is in the TrustedPeople store.
    public static void NetTcp_SecModeTrans_CertValMode_PeerTrust_Succeeds_In_TrustedPeople()
    {
        EndpointAddress endpointAddress = null;
        string testString = "Hello";
        ChannelFactory<IWcfService> factory = null;
        IWcfService serviceProxy = null;

        try
        {
            // *** SETUP *** \\
            NetTcpBinding binding = new NetTcpBinding(SecurityMode.Transport);
            binding.Security.Transport.ClientCredentialType = TcpClientCredentialType.None;

            endpointAddress = new EndpointAddress(
                                new Uri(Endpoints.NetTcp_SecModeTrans_ClientCredTypeNone_ServerCertValModePeerTrust_Address));

            factory = new ChannelFactory<IWcfService>(binding, endpointAddress);
            factory.Credentials.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.PeerTrust;

            serviceProxy = factory.CreateChannel();

            // *** EXECUTE *** \\
            string result = serviceProxy.Echo(testString);

            // *** VALIDATE *** \\
            Assert.Equal(testString, result);

            // *** CLEANUP *** \\
            ((ICommunicationObject)serviceProxy).Close();
            factory.Close();
        }
        finally
        {
            // *** ENSURE CLEANUP *** \\
            ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
        }
    }

    [WcfFact]
    [Issue(1945, OS = OSID.AnyOSX)]
    [Condition(nameof(Root_Certificate_Installed),
               nameof(Client_Certificate_Installed),
               nameof(Peer_Certificate_Installed),
               nameof(SSL_Available))]
    [OuterLoop]
    // Asking for PeerTrust alone should throw SecurityNegotiationException
    // if the certificate is not in the TrustedPeople store.  For this test
    // we use a valid chain-trusted certificate that we know is not in the
    // TrustedPeople store.
    public static void NetTcp_SecModeTrans_CertValMode_PeerTrust_Fails_Not_In_TrustedPeople()
    {
        EndpointAddress endpointAddress = null;
        string testString = "Hello";
        ChannelFactory<IWcfService> factory = null;
        IWcfService serviceProxy = null;
        CommunicationException communicationException = null;

        try
        {
            // *** SETUP *** \\
            NetTcpBinding binding = new NetTcpBinding(SecurityMode.Transport);
            binding.Security.Transport.ClientCredentialType = TcpClientCredentialType.None;

            endpointAddress = new EndpointAddress(new Uri(
                                Endpoints.Tcp_CustomBinding_SslStreamSecurity_Address));

            factory = new ChannelFactory<IWcfService>(binding, endpointAddress);
            factory.Credentials.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.PeerTrust;

            serviceProxy = factory.CreateChannel();

            // *** EXECUTE *** \\
            try
            {
                serviceProxy.Echo(testString);
            }
            catch (CommunicationException ce)
            {
                communicationException = ce;
            }

            // *** VALIDATE *** \\
            Assert.True(communicationException != null, "Expected CommunicationException but no exception was thrown.");
            Assert.True(communicationException.GetType().Name == "SecurityNegotiationException",
                        String.Format("Expected SecurityNegotiationException but received {0}",
                                      communicationException.ToString()));

            // *** CLEANUP *** \\
            // objects are in faulted state and will throw, so only use finally style cleanup
        }
        finally
        {
            // *** ENSURE CLEANUP *** \\
            ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
        }
    }

    [WcfFact]
    [Issue(1945, OS = OSID.AnyOSX)]
    [Condition(nameof(Root_Certificate_Installed),
               nameof(Client_Certificate_Installed),
               nameof(SSL_Available))]
    [OuterLoop]
    // Asking for PeerOrChainTrust should succeed if the certificate is
    // chain-trusted, even though it is not in the TrustedPeople store.
    // So we ask for a known chain-trusted certificate that we also know
    // it not in TrustedPeople.
    public static void NetTcp_SecModeTrans_CertValMode_PeerOrChainTrust_Succeeds_ChainTrusted()
    {
        EndpointAddress endpointAddress = null;
        string testString = "Hello";
        ChannelFactory<IWcfService> factory = null;
        IWcfService serviceProxy = null;

        try
        {
            // *** SETUP *** \\
            NetTcpBinding binding = new NetTcpBinding(SecurityMode.Transport);
            binding.Security.Transport.ClientCredentialType = TcpClientCredentialType.None;

            endpointAddress = new EndpointAddress(new Uri(
                Endpoints.Tcp_CustomBinding_SslStreamSecurity_Address));

            factory = new ChannelFactory<IWcfService>(binding, endpointAddress);
            factory.Credentials.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.PeerOrChainTrust;

            serviceProxy = factory.CreateChannel();

            // *** EXECUTE *** \\
            string result = serviceProxy.Echo(testString);

            // *** VALIDATE *** \\
            Assert.Equal(testString, result);

            // *** CLEANUP *** \\
            ((ICommunicationObject)serviceProxy).Close();
            factory.Close();
        }
        finally
        {
            // *** ENSURE CLEANUP *** \\
            ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
        }
    }

    [WcfFact]
    [Condition(nameof(Root_Certificate_Installed),
               nameof(Client_Certificate_Installed),
               nameof(SSL_Available))]
    [OuterLoop]
    // Asking for ChainTrust only should succeed if the certificate is
    // chain-trusted.
    public static void NetTcp_SecModeTrans_CertValMode_ChainTrust_Succeeds_ChainTrusted()
    {
        EndpointAddress endpointAddress = null;
        string testString = "Hello";
        ChannelFactory<IWcfService> factory = null;
        IWcfService serviceProxy = null;

        try
        {
            // *** SETUP *** \\
            NetTcpBinding binding = new NetTcpBinding(SecurityMode.Transport);
            binding.Security.Transport.ClientCredentialType = TcpClientCredentialType.None;

            endpointAddress = new EndpointAddress(new Uri(
                Endpoints.Tcp_CustomBinding_SslStreamSecurity_Address));

            factory = new ChannelFactory<IWcfService>(binding, endpointAddress);
            factory.Credentials.ServiceCertificate.Authentication.RevocationMode = X509RevocationMode.NoCheck;
            factory.Credentials.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.ChainTrust;

            serviceProxy = factory.CreateChannel();

            // *** EXECUTE *** \\
            string result = serviceProxy.Echo(testString);

            // *** VALIDATE *** \\
            Assert.Equal(testString, result);

            // *** CLEANUP *** \\
            ((ICommunicationObject)serviceProxy).Close();
            factory.Close();
        }
        finally
        {
            // *** ENSURE CLEANUP *** \\
            ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
        }
    }

    [WcfFact]
    [Issue(1945, OS = OSID.AnyOSX)]
    [Condition(nameof(Root_Certificate_Installed),
               nameof(Client_Certificate_Installed),
               nameof(SSL_Available))]
    [OuterLoop]
    // Asking for ChainTrust only should succeed if the certificate is
    // chain-trusted.
    public static void NetTcp_SecModeTrans_Duplex_Callback_Succeeds()
    {
        string clientCertThumb = null;
        EndpointAddress endpointAddress = null;
        DuplexChannelFactory<IWcfDuplexService> factory = null;
        IWcfDuplexService serviceProxy = null;
        Guid guid = Guid.NewGuid();

        try
        {
            // *** SETUP *** \\
            NetTcpBinding binding = new NetTcpBinding(SecurityMode.Transport);
            binding.Security.Transport.ClientCredentialType = TcpClientCredentialType.Certificate;

            endpointAddress = new EndpointAddress(new Uri(
                Endpoints.Tcp_Certificate_Duplex_Address));
            clientCertThumb = ServiceUtilHelper.ClientCertificate.Thumbprint;

            WcfDuplexServiceCallback callbackService = new WcfDuplexServiceCallback();
            InstanceContext context = new InstanceContext(callbackService);

            factory = new DuplexChannelFactory<IWcfDuplexService>(context, binding, endpointAddress);
            factory.Credentials.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.ChainTrust;
            factory.Credentials.ClientCertificate.SetCertificate(
                StoreLocation.CurrentUser,
                StoreName.My,
                X509FindType.FindByThumbprint,
                clientCertThumb);

            serviceProxy = factory.CreateChannel();

            // *** EXECUTE *** \\
            // Ping on another thread.
            Task.Run(() => serviceProxy.Ping(guid));
            Guid returnedGuid = callbackService.CallbackGuid;

            // *** VALIDATE *** \\
            Assert.True(guid == returnedGuid,
                string.Format("The sent GUID does not match the returned GUID. Sent '{0}', Received: '{1}'", guid, returnedGuid));

            // *** CLEANUP *** \\
            ((ICommunicationObject)serviceProxy).Close();
            ((ICommunicationObject)factory).Close();
        }
        finally
        {
            // *** ENSURE CLEANUP *** \\
            ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
        }
    }
}


text:
layout: post # page | post
title: 30 Compartir arxius amb Python
date: 2017-06-26
description: Compartir arxius amb alçant un xicotet server amb Python # Argument
keywords: server python  # Paraules clau
coments: true    # Comentaris activats
---

Compartir arxius ja no es sols cosa de *Dropbox* o *Google Drive*, les quals són molt bones solucions. Podem fer-ho de manera senzilla amb Pyhton, així:

1. Creem una carpeta, per exemple, li posem de nom `share`
2. Dins d'aquesta carpeta podem posar arxius
3. Ens situem dins d'aquest directori, el directori que anomenat `share` i llancem aquest comandament `python -m http.server 8090`
4. Obrim el navegador amb l'adreça `localhost:8090`. Si l'obrim des d'un altre ordinador de la xarxa local cal cambiar `localhost`per la `ip` de l'ordinador que conté la carpeta `share`.

Font: [TECHBASICS](https://techpickup.wordpress.com/2017/06/25/how-to-share-files-in-network/)


text:
from darwinpush import Client, Listener
from darwinpush.messages.AssociationMessage import AssociationCategory

import os
import time

# Create a listener to process the messages.
class MyListener(Listener):
    def __init__(self, q, quit_event):
        # Any setup if needed.

        # Finally, call the Super Class initialiser.
        super().__init__(q, quit_event)

    def now(self):
        return time.strftime("%d/%m/%y %H:%M:%S")

    def on_schedule_message(self, message, source):
        print(self.now(), source, "Schedule")

    def on_deactivated_message(self, message, source):
        print(self.now(), source, "Deactivated message")

    def on_association_message(self, message, source):
        print(self.now(), source, "Association")

    def on_alarm_message(self, message, source):
        print(self.now(), source, "Alarm message")

    def on_station_message(self, message, source):
        print(self.now(), source, "Station message")

    def on_tracking_id_message(self, message, source):
        print(self.now(), source, "Tracking ID message")

    def on_train_alert_message(self, message, source):
        print(self.now(), source, "Train alert message")

    def on_train_order_message(self, message, source):
        print(self.now(), source, "Train order message")

    def on_train_status_message(self, message, source):
        print(self.now(), source, "Train status message")

if __name__ == "__main__":
    # Instantiate the Push Port client.
    client = Client(
        os.environ["STOMP_USER"],
        os.environ["STOMP_PASS"],
        os.environ["STOMP_QUEUE"],
        MyListener,
        ftp_user=os.environ["FTP_USER"],
        ftp_passwd=os.environ["FTP_PASSWD"]
    )

    # Do not connect to stomp, just download and parse the logs from FTP for
    # the last `downtime` seconds and quit.
    client.connect(downtime=600, stomp=False)
    print("All done. Bye :)")
    client.disconnect()


text:
'use strict';
const
  zmq = require('zmq'),
  filename = process.argv[2],
  requester = zmq.socket('req');

requester.on('message', function(data) {
  let response = JSON.parse(data);
  console.log('received response: ' + data);
});

requester.connect('tcp://localhost:5469');
console.log('sending request for ' + filename);
for(let i = 0; i < 3; i++) {
  requester.send(JSON.stringify({
    path: filename
  }));
}


text:
/*
 * 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.
 */
package com.facebook.presto.tests.functions;

import com.teradata.tempto.ProductTest;
import org.testng.annotations.Test;

import static com.facebook.presto.tests.TestGroups.JSON_FUNCTIONS;
import static com.teradata.tempto.assertions.QueryAssert.Row.row;
import static com.teradata.tempto.assertions.QueryAssert.assertThat;
import static com.teradata.tempto.query.QueryExecutor.query;

public class JsonFunctionsTests
        extends ProductTest
{
    @Test(groups = JSON_FUNCTIONS)
    public void testJsonArrayContainsExist()
    {
        assertThat(query("SELECT json_array_contains('[1, 2, 3]', 2)")).containsExactly(row(true));
        assertThat(query("SELECT json_array_contains(CAST('[1, 2, 3]' as JSON), 2)")).containsExactly(row(true));
    }

    @Test(groups = JSON_FUNCTIONS)
    public void testJsonArrayLengthExist()
    {
        assertThat(query("SELECT json_array_length('[1, 2, 3]')")).containsExactly(row(3L));
        assertThat(query("SELECT json_array_length(CAST('[1, 2, 3]' as JSON))")).containsExactly(row(3L));
    }

    @Test(groups = JSON_FUNCTIONS)
    public void testJsonExtractExist()
    {
        assertThat(query("SELECT CAST(json_extract('{\"book\" : {\"pages\":1}}', '$.book') as VARCHAR)")).containsExactly(row("{\"pages\":1}"));
    }

    @Test(groups = JSON_FUNCTIONS)
    public void testJsonExtractScalarExist()
    {
        assertThat(query("SELECT json_extract_scalar('{\"book\" : {\"pages\":1}}', '$.book.pages')")).containsExactly(row("1"));
    }

    @Test(groups = JSON_FUNCTIONS)
    public void testJsonArrayGetExist()
    {
        assertThat(query("SELECT CAST (json_array_get('[\"string1\", \"string2\", \"string3\"]', 0) AS VARCHAR)")).containsExactly(row("string1"));
    }

    @Test(groups = JSON_FUNCTIONS)
    public void testJsonSizeExist()
    {
        assertThat(query("SELECT json_size('{ \"x\": {\"a\": 1, \"b\": 2} }', '$.x')")).containsExactly(row(2));
    }
}


text:
<?php

namespace Itq\Dev\Service;

/**
 * @author itiQiti Dev Team <opensource@itiqiti.com>
 */
class PhpService
{
    /**
     * @return array
     */
    public function getConfig()
    {
        $data = [
            'date_timezone'           => ini_get('date.timezone'),
            'phar_readonly'           => (bool) ini_get('phar.readonly'),
            'os'                      => PHP_OS,
            'version'                 => PHP_VERSION,
            'version_id'              => PHP_VERSION_ID,
            'sapi'                    => PHP_SAPI,
            'non standard extensions' => $this->getNonStandardExtensions(),
            'zend_extensions'         => $this->getZendExtensions(),
            'ini_file'                => php_ini_loaded_file(),
        ];

        return $data;
    }
    /**
     * @return array
     */
    public function getExtensions()
    {
        $extensions = get_loaded_extensions();

        sort($extensions);

        return $extensions;
    }
    /**
     * @return array
     */
    public function getNonStandardExtensions()
    {
        $extensions = $this->getExtensions();

        return array_diff(
            $extensions,
            [
                'Core', 'PDO', 'PDO_ODBC', 'Phar', 'Reflection', 'SPL', 'SimpleXML', 'bcmath', 'bz2',
                'calendar', 'ctype', 'date', 'dba', 'dom', 'ereg', 'exif', 'fileinfo', 'filter',
                'ftp', 'gd', 'gettext', 'hash', 'ldap', 'libxml', 'mysql', 'mysqli', 'mysqlnd', 'odbc',
                'openssl', 'pcre', 'json', 'pdo_mysql', 'pdo_sqlite', 'readline', 'session', 'shmop', 'soap', 'sockets',
                'standard', 'sqlite3', 'tokenizer', 'wddx', 'xml', 'xmlreader', 'xmlrpc', 'xmlwriter', 'xsl', 'zip', 'zlib',
                'pcntl', 'posix', 'sysvmsg', 'sysvsem', 'sysvshm', 'mhash',
            ]
        );
    }
    /**
     * @return array
     */
    public function getZendExtensions()
    {
        $extensions = get_loaded_extensions(true);

        sort($extensions);

        return $extensions;
    }
}


text:
module Cybele
  module Helpers
    module AppFiles
      module HelperFiles
        def customize_helper_files
          # Helper files
          remove_file 'app/helpers/application_helper.rb', force: true
          template 'app_files/app/helpers/application_helper.rb.erb', 'app/helpers/application_helper.rb'
        end
      end
    end
  end
end


text:
class CSolidSetDefaults : public IVPhysicsKeyHandler
{
public:
	virtual void ParseKeyValue( void *pData, const char *pKey, const char *pValue ) {}
	virtual void SetDefaults( void *pData );
};

extern CSolidSetDefaults g_SolidSetup;

#endif // SOLIDSETDEFAULTS_H


text:
<?xml version="1.0" encoding="UTF-8"?>
<article id="469">
	<title>The Phenomena of Interest to Information Science	</title>
	<author>Wersig, GernotNeveling, Ulrich	</author>
	<text>
		   Discusses the various explicit and implicit definitions of information and
		information science, against a view of their historical development.. Shows how
		the various views of information science overlap with other disciplines, and
		concludes with a proposal for a definition of information science based on
		social need.. A schema of information sciences is put forward with the plea that
		any discussion of information and information science should first declare the
		definitions to be used..
	</text>
</article>


text:
""" Settings module for echidna

Use this module to store echidna-wide settings that can be set
according to the user's preference.

Attributes:
  user_profile (dict): Configure options to contol the behaviour of
    echidna for the user.

    .. note:: options include:

      * *mode* - Use the *cautious* mode to raise ``UserWarning`` as
        an exception. Otherwise default *normal* mode just logs these
        messages.
      * *log_level* - If logging is initiated with
        :func:`echidna.utilities.start_logging`, this controls the
        messages logged to the terminal. Select the level of messages
        to log to the terminal.

        * *debug* logs all messages
        * *info* (default) logs all messages of info-level and above.
        * *warning* only logs warning and error messages

"""
user_profile = {
    # Select the mode - "normal" or "cautious"
    "mode": "normal",
    # Select the logging level - "debug", "info" or "warning"
    "log_level": "info"
    }


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

package google.registry.util;

import com.google.common.collect.Iterables;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Handler;
import java.util.logging.LogRecord;
import javax.annotation.Nullable;

/** A log handler that captures logs. */
public final class CapturingLogHandler extends Handler {

  private final List<LogRecord> records = new ArrayList<>();

  @Override
  public void publish(@Nullable LogRecord record) {
    if (record != null) {
      records.add(record);
    }
  }

  @Override
  public void flush() {}

  @Override
  public void close() {}

  public Iterable<LogRecord> getRecords() {
    return Iterables.unmodifiableIterable(records);
  }
}


text:
require 'turntabler/playlist'
require 'turntabler/preferences'
require 'turntabler/user'
require 'turntabler/sticker_placement'

module Turntabler
  # Represents a user who has authorized with the Turntable service
  class AuthorizedUser < User
    # The authentication token required to connect to the API
    # @return [String]
    attribute :auth, :userauth

    # The current availability status of the user ("available", "unavailable", or "away")
    # @return [String]
    attribute :status

    # The user's unique identifier on Facebook
    # @return [String]
    attribute :facebook_id, :fbid

    # The user's unique identifier on Twitter
    # @return [String]
    attribute :twitter_id, :twitterid

    # The e-mail address the user registered with on Turntable.  This is
    # typically only set if the user didn't log in via Facebook or Twitter.
    # @return [String]
    attribute :email

    # The password associated with the e-mail address registered with on Turntable.
    # This is typically only set if the user didn't log in via Facebook or Twitter.
    # @return [String]
    attribute :password

    # The user's current Turntable preferences
    # @return [Turntabler::Preferences]
    attr_reader :preferences

    # @api private
    def initialize(client, *)
      @status = 'available'
      @playlists = {}
      @preferences = Preferences.new(client)
      super
    end

    # Gets the Turntable id associated with this user for use with API services.
    # This will log the user in via email / password if it's not already set.
    #
    # @return [String]
    # @raise [Turntabler::Error] if the command fails
    def id
      login unless @id
      @id
    end

    # Gets the authentication token associated with this user for use with API
    # services.  This will log the user in via email / password if it's not already
    # set.
    #
    # @return [String]
    # @raise [Turntabler::Error] if the command fails
    def auth
      login unless @auth
      @auth
    end

    # Logs the user in using the associated e-mail address / password.  This will
    # generate a user id / auth token for authentication with the API services.
    #
    # @api private
    # @return [true]
    # @raise [Turntabler::Error] if the command fails
    def login
      response = EventMachine::HttpRequest.new('https://turntable.fm/api/user.email_login').get(:query => {:email => email, :password => password, :client => client.id}).response
      data = JSON.parse(response)
      raise(Error, data[1]['err']) unless data[0]
      self.attributes = data[1]
      true
    end

    # Authenticates the current user with turntable.
    #
    # @api private
    # @return [true]
    # @raise [Turntabler::Error] if the command fails
    def authenticate
      api('user.authenticate')
      true
    end

    # Loads the attributes for this user.  Attributes will automatically load
    # when accessed, but this allows data to be forcefully loaded upfront.
    #
    # @return [true]
    # @raise [Turntabler::Error] if the command fails
    # @example
    #   user.load     # => true
    #   user.email    # => "john.doe@gmail.com"
    def load
      data = api('user.info')
      self.attributes = data
      super
    end

    # Updates this user's profile information.
    #
    # @param [Hash] attributes The attributes to update
    # @option attributes [String] :name
    # @option attributes [String] :status Valid values include "available", "unavailable", and "away"
    # @option attributes [String] :laptop_name Valid values include "mac", "pc", "linux", "chrome", "iphone", "cake", "intel", and "android"
    # @option attributes [String] :twitter_id
    # @option attributes [String] :facebook_url
    # @option attributes [String] :website
    # @option attributes [String] :about
    # @option attributes [String] :top_artists
    # @option attributes [String] :hangout
    # @return [true]
    # @raise [ArgumentError] if an invalid attribute or value is specified
    # @raise [Turntabler::Error] if the command fails
    # @example
    #   user.update(:status => "away")        # => true
    #   user.update(:laptop_name => "mac")    # => true
    #   user.update(:name => "...")           # => true
    def update(attributes = {})
      assert_valid_keys(attributes, :name, :status, :laptop_name, :twitter_id, :facebook_url, :website, :about, :top_artists, :hangout)

      # Update status
      status = attributes.delete(:status)
      update_status(status) if status

      # Update laptop
      laptop_name = attributes.delete(:laptop_name)
      update_laptop(laptop_name) if laptop_name

      # Update profile with remaining data
      update_profile(attributes) if attributes.any?

      true
    end

    # Loads the list of users that are connected to the current user through a
    # social network like Facebook or Twitter.
    #
    # @return [Array<Turntabler::User>]
    # @raise [Turntabler::Error] if the command fails
    # @example
    #   user.buddies    # => [#<Turntabler::User ...>, ...]
    def buddies
      data = api('user.get_buddies')
      data['buddies'].map {|id| User.new(client, :_id => id)}
    end

    # Loads the list of users that the current user is a fan of.
    #
    # @return [Array<Turntabler::User>]
    # @raise [Turntabler::Error] if the command fails
    # @example
    #   user.fan_of   # => [#<Turntabler::User ...>, ...]
    def fan_of
      data = api('user.get_fan_of')
      data['fanof'].map {|id| User.new(client, :_id => id)}
    end

    # Loads the list of users that are a fan of the current user.
    #
    # @return [Array<Turntabler::User>]
    # @raise [Turntabler::Error] if the command fails
    # @example
    #   user.fans   # => [#<Turntabler::User ...>, ...]
    def fans
      data = api('user.get_fans')
      data['fans'].map {|id| User.new(client, :_id => id)}
    end

    # Gets the avatars that can be set by this user.
    #
    # @note This may load the user's data in order to get the ACL if it's not available already
    # @return [Array<Turntabler::Avatar>]
    # @raise [Turntabler::Error] if the command fails
    # @example
    #   user.avatars    # => [#<Turntabler::Avatar ...>, ...]
    def avatars
      client.avatars.select {|avatar| avatar.available?}
    end

    # Gets the playlist with the given id.
    #
    # @param [String] id The unique identifier for the playlist
    # @return [Turntabler::Playlist]
    # @example
    #   user.playlist             # => #<Turntabler::Playlist id="default" ...>
    #   user.playlist("rock")     # => #<Turntabler::Playlist id="rock" ...>
    def playlist(id = 'default')
      @playlists[id] ||= Playlist.new(client, :_id => id)
    end

    # Gets the stickers that have been purchased by this user.
    #
    # @return [Array<Turntabler::Sticker>]
    # @raise [Turntabler::Error] if the command fails
    # @example
    #   user.stickers_purchased   # => [#<Turntabler::Sticker ...>, ...]
    def stickers_purchased
      data = api('sticker.get_purchased_stickers')
      data['stickers'].map {|sticker_id| Sticker.new(client, :_id => sticker_id)}
    end

    # Gets the users that have been blocked by this user.
    #
    # @return [Array<Turntabler::User>]
    # @raise [Turntabler::Error] if the command fails
    # @example
    #   user.blocks   # => [#<Turntabler::User ...>, ...]
    def blocks
      data = api('block.list_all')
      data['blocks'].map {|attrs| User.new(client, attrs['block']['blocked'])}
    end

    private
    # Updates the user's profile information
    def update_profile(attributes = {})
      assert_valid_keys(attributes, :name, :twitter_id, :facebook_url, :website, :about, :top_artists, :hangout)

      # Convert attribute names over to their Turntable equivalent
      {:twitter_id => :twitter, :facebook_url => :facebook, :top_artists => :topartists}.each do |from, to|
        attributes[to] = attributes.delete(from) if attributes[from]
      end

      api('user.modify_profile', attributes)
      self.attributes = attributes
      true
    end

    # Updates the laptop currently being used
    def update_laptop(name)
      assert_valid_values(name, *%w(mac pc linux chrome iphone cake intel android))

      api('user.modify', :laptop => name)
      self.attributes = {'laptop' => name}
      true
    end

    # Sets the user's current status
    def update_status(status = self.status)
      assert_valid_values(status, *%w(available unavailable away))

      api('presence.update', :status => status)
      self.attributes = {'status' => status}
      true
    end
  end
end


text:
#import "Com0x82WebserverModule.h"
#import "TiBase.h"
#import "TiHost.h"
#import "TiUtils.h"
#import "FilesystemModule.h"
#import "HTTPServer.h"
#import "MyHTTPConnection.h"
#import "Com0x82WebserverCallbackProxy.h"

#import "DDLog.h"
#import "DDTTYLogger.h"

// Log levels: off, error, warn, info, verbose
static const int ddLogLevel = LOG_LEVEL_VERBOSE;

@implementation Com0x82WebserverModule

#pragma mark Internal

// this is generated for your module, please do not change it
-(id)moduleGUID
{
	return @"fa7f492c-cd23-4832-ae51-ef9eb7ad2b7b";
}

// this is generated for your module, please do not change it
-(NSString*)moduleId
{
	return @"com.0x82.webserver";
}

#pragma mark Lifecycle

-(void)startup
{

	// this method is called when the module is first loaded
	// you *must* call the superclass
	[super startup];

	NSLog(@"[INFO] %@ loaded",self);

	self.disconnectsInBackground = @(YES);
	wasRunning = NO;

	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillResignActive:) name:UIApplicationWillResignActiveNotification object:nil];
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillComeToForeground:) name:UIApplicationDidBecomeActiveNotification object:nil];
}

-(void)shutdown:(id)sender
{
	// this method is called when the module is being unloaded
	// typically this is during shutdown. make sure you don't do too
	// much processing here or the app will be quit forceably

	// you *must* call the superclass
	[super shutdown:sender];
}

-(void)applicationWillResignActive:(id)notification {
	NSLog(@"-----> applicationWillResignActive. disconnectsInBackground is %@", self.disconnectsInBackground);
	if(![self.disconnectsInBackground boolValue]) return;

	if(httpServer.isRunning) {
		__block UIBackgroundTaskIdentifier disconnectID = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
			[[UIApplication sharedApplication] endBackgroundTask:disconnectID];
		}];

		wasRunning = YES;
		[httpServer stop];
	} else {
		wasRunning = NO;
	}
}

-(void)applicationWillComeToForeground:(id)notification {
	NSLog(@"-----> applicationWillComeToForeground. disconnectsInBackground is %@", self.disconnectsInBackground);
	if(![self.disconnectsInBackground boolValue]) return;

	if(httpServer && wasRunning) {
		NSError *error;
		if(![httpServer start:&error]) {
			DDLogError(@"Error starting HTTP Server: %@", error);
		}
	}
}

#pragma mark Cleanup

-(void)dealloc
{
    [super dealloc];
}

#pragma Public APIs

-(void)stopServer:(id)args {
    if(httpServer && httpServer.isRunning) {
        [httpServer stop];
    }
}

-(id)startServer:(id)args
{
  ENSURE_SINGLE_ARG(args,NSDictionary);

	NSUInteger port        = [TiUtils intValue:@"port" properties:args def:12345];
	BOOL bonjourEnabled    = [TiUtils boolValue:@"bonjour" properties:args def:YES];
    NSString *bonjourName  = [TiUtils stringValue:@"bonjourName" properties:args];
	NSString *documentRoot = [TiUtils stringValue:@"documentRoot" properties:args def:NSTemporaryDirectory()];

	Com0x82WebserverCallbackProxy *proxy = [[Com0x82WebserverCallbackProxy alloc] _initWithPageContext:[self executionContext]];
	[proxy _initWithProperties:args];

	// Configure our logging framework.
	// To keep things simple and fast, we're just going to log to the Xcode console.
	[DDLog addLogger:[DDTTYLogger sharedInstance]];

	// Create server using our custom MyHTTPServer class
	httpServer = [[HTTPServer alloc] init];
	proxy.server = httpServer;

	// Tell the server to broadcast its presence via Bonjour.
	// This allows browsers such as Safari to automatically discover our service.
	if(bonjourEnabled) {
        if(bonjourName)
            [httpServer setName:bonjourName];
		[httpServer setType:@"_http._tcp."];
    }

	// Normally there's no need to run our server on any specific port.
	// Technologies like Bonjour allow clients to dynamically discover the server's port at runtime.
	// However, for easy testing you may want force a certain port so you can just hit the refresh button.
	[httpServer setPort:port];

  DDLogVerbose(@"Server started on %@:%d", [proxy ipAddress:nil], httpServer.port);

  // We're going to extend the base HTTPConnection class with our MyHTTPConnection class.
	// This allows us to do all kinds of customizations.
	[httpServer setConnectionClass:[MyHTTPConnection class]];

	// Serve files from our embedded Web folder
	DDLogVerbose(@"Setting document root: %@", documentRoot);
	[httpServer setDocumentRoot:documentRoot];

	// Start the server (and check for problems)
	NSError *error;
	if(![httpServer start:&error]) {
		DDLogError(@"Error starting HTTP Server: %@", error);
	}

  return [proxy autorelease];
}

@end