text:
import {addParamsToUrl} from '../../../src/url';
import {applyFillContent, isLayoutSizeDefined} from '#core/dom/layout';
import {createElementWithAttributes, removeElement} from '#core/dom';
import {getData, listen} from '../../../src/event-helper';
import {measureIntersection} from '#core/dom/layout/intersection';
import {omit} from '#core/types/object';
import {setStyle} from '#core/dom/style';
import {tryParseJson} from '#core/types/object/json';
import {userAssert} from '../../../src/log';

/** @const {string} */
export const TAG = 'amp-iframely';

/**
 * Implementation of the amp-iframely component.
 *
 * See {@link ../amp-iframely.md} for the spec.
 */
export class AmpIframely extends AMP.BaseElement {
  /** @param {!AmpElement} element */
  constructor(element) {
    super(element);

    /**
     * Address of Iframely media (3rd party rich media or a summary card for the URL).
     * @private {string}
     */
    this.src_ = null;

    /**
     * The main iFrame element that loads Iframely media.
     * @private {?Element}
     */
    this.iframe_ = null;

    /**
     * ID of Iframely content, if available
     * @private {?string}
     */
    this.widgetId_ = null;

    /**
     * Domain of Iframely CDN
     * @private {?string}
     */
    this.base_ = null;

    /**
     * Alternatively, identify with Iframely CDN via `url` and `key` hash params
     * @private {?string}
     */
    this.url_ = null;
    /** @private {?string} */
    this.key_ = null;

    /**
     * other data- options that will be passed into iFrame src
     * @private {?Object}
     * */
    this.options_ = null;
  }

  /** @override */
  isLayoutSupported(layout) {
    return isLayoutSizeDefined(layout);
  }

  /** @override */
  buildCallback() {
    /** Populating parameters once */
    this.widgetId_ = this.element.getAttribute('data-id');
    this.url_ = this.element.getAttribute('data-url');
    this.key_ = this.element.getAttribute('data-key');
    this.options_ = this.parseOptions_();
    let domain = 'cdn.iframe.ly';
    const requestedDomain = this.element.getAttribute('data-domain');
    if (requestedDomain && this.isValidDomain_(requestedDomain)) {
      domain = requestedDomain;
    }
    this.base_ = `https://${domain}/`;
    this.parseAttributes_();
  }

  /**
   * @param {boolean=} opt_onLayout
   * @override
   */
  preconnectCallback(opt_onLayout) {
    if (this.preconnect && this.preconnect.url_) {
      this.preconnect.url(this.base_, opt_onLayout);
    }
  }

  /** @override */
  createPlaceholderCallback() {
    /**
     * Building placeholder for responsive layout without resizing
     * or when requested via `data-img` attribute
     */
    const layout = this.getLayout();
    if (
      this.element.hasAttribute('data-img') ||
      (layout === 'responsive' && !this.element.hasAttribute('resizable'))
    ) {
      /** using Iframely placeholder image */
      const src = addParamsToUrl(
        this.constructSrc_('/thumbnail'),
        this.options_
      );
      const element = createElementWithAttributes(
        this.element.ownerDocument,
        'img',
        {
          'src': src,
          'loading': 'lazy',
          'placeholder': '',
        }
      );
      applyFillContent(element);
      return element;
    }
    return null;
  }

  /** @override */
  layoutCallback() {
    /** attach iFrame */
    this.iframe_ = this.element.ownerDocument.createElement('iframe');
    setStyle(this.iframe_, 'border', '0px');
    this.iframe_.setAttribute(
      'sandbox',
      'allow-scripts allow-same-origin allow-popups allow-forms allow-presentation'
    );
    this.src_ = addParamsToUrl(this.src_, this.options_);
    this.iframe_.src = this.src_;
    applyFillContent(this.iframe_);
    this.element.appendChild(this.iframe_);

    this.unlistener_ = listen(this.win, 'message', (event) => {
      if (event.source === this.iframe_.contentWindow) {
        this.handleEvent_(event);
      }
    });
    return this.loadPromise(this.iframe_);
  }

  /**
   * Handles Iframely events: widget sizing, cancel, decorate cards
   * @param {window.event} event - Iframely message with a method to apply
   * */
  handleEvent_(event) {
    const data = tryParseJson(getData(event));
    if (!data) {
      return;
    }
    if (data.method === 'resize' && data.height > 50) {
      /** Set the size of the card according to the message from Iframely */
      this.attemptChangeHeight(data['height']).catch(() => {});
    } else if (data.method === 'setIframelyEmbedData') {
      /** apply Iframely card styles if present */
      const media = data['data']['media'] || null;
      if (media && media['aspect-ratio']) {
        const intersection = measureIntersection(this.element);
        intersection.then((box) => {
          if (media['padding-bottom']) {
            /** Apply height for media with updated "aspect-ratio" and "padding-bottom". */
            const height =
              box.boundingClientRect.width / media['aspect-ratio'] +
              media['padding-bottom'];
            this.attemptChangeHeight(Math.round(height)).catch(() => {});
          } else {
            const height = box.boundingClientRect.width / media['aspect-ratio'];
            if (Math.abs(box.boundingClientRect.height - height) > 1) {
              /** Apply new height for updated "aspect-ratio". */
              this.attemptChangeHeight(Math.round(height)).catch(() => {});
            }
          }
        });
      }
    }
    if (data.method === 'cancelWidget') {
      this.attemptCollapse().catch(() => {});
    }
  }

  /**
   * Constructing url SRC for api calls
   * @param {string} slug src or iframe src in case false
   * @return {string} url of the placeholder
   * @private
   * */
  constructSrc_(slug) {
    if (this.widgetId_) {
      return `${this.base_}${this.widgetId_}${
        slug !== '/iframe' ? slug : ''
      }?amp=1`;
    } else {
      return addParamsToUrl(`${this.base_}api${slug}`, {
        'url': this.url_,
        'key': this.key_,
        'amp': '1',
      });
    }
  }

  /**
   * Test component call for required params
   * @return {null}
   * @private
   * */
  parseAttributes_() {
    userAssert(
      this.element.getAttribute('data-id') ||
        this.element.getAttribute('data-url'),
      '<%s> requires either "data-id" or a pair of "data-url" and "data-key" attributes for %s',
      TAG,
      this.element
    );
    if (!this.widgetId_) {
      if (this.url_) {
        userAssert(
          this.key_,
          'Iframely data-key must also be set when you specify data-url parameter at <%s> %s',
          TAG,
          this.element
        );
      }
      if (this.key_) {
        userAssert(
          this.url_,
          'Iframely data-url must also be set when you specify data-key parameter at <%s> %s',
          TAG,
          this.element
        );
      }
      if (this.key_ || this.url_) {
        userAssert(
          !this.widgetId_,
          'Iframely data-id should not be set when there is already a pair of data-url and data-key for <%s> %s',
          TAG,
          this.element
        );
      }
    }
    if ((this.widgetId_ && this.url_) || (this.widgetId_ && this.key_)) {
      userAssert(
        !this.widgetId_,
        'Only one way of setting either data-id or data-url and data-key supported for <%s> %s',
        TAG,
        this.element
      );
    }
    this.src_ = this.constructSrc_('/iframe');
  }

  /**
   * Parse other data-* attributes and append them to API query url
   * @return {object} of Iframely options
   * @private
   * */
  parseOptions_() {
    return omit(this.element.dataset, ['id', 'domain', 'key', 'url', 'img']);
  }

  /** @override */
  unlayoutCallback() {
    if (this.iframe_) {
      removeElement(this.iframe_);
      this.iframe_ = null;
    }
    if (this.unlisten_) {
      this.unlisten_();
      this.unlisten_ = null;
    }
    return true; // Request layoutCallback again.
  }

  /**
   * Validates that requested domain is a valid Iframely domain
   * @param {string} domainName - optional CDN alias, if different from the default Iframely host and is allowed.
   * @return {boolean} if domain is valid
   * @private
   * */
  isValidDomain_(domainName) {
    const allowedDomains = [
      /^(?:[^\.\/]+\.)?iframe\.ly$/i,
      /^if\-cdn\.com$/i,
      /^iframely\.net$/i,
      /^oembed\.vice\.com$/i,
      /^iframe\.nbcnews\.com$/i,
    ];
    return allowedDomains.reduce(
      (allowed, re) => allowed || re.test(domainName),
      false
    );
  }
}

AMP.extension(TAG, '0.1', (AMP) => {
  AMP.registerElement(TAG, AmpIframely);
});


text:
#include "pch.hpp"

#include <core/NonLibraryTrackHelper.h>
#include <boost/bind.hpp>
#include <core/PluginFactory.h>
#include <core/Plugin/IMetaDataReader.h>
#include <core/filestreams/Factory.h>

//////////////////////////////////////////////////////////////////////////////

using namespace musik::core;

//////////////////////////////////////////////////////////////////////////////

NonLibraryTrackHelper NonLibraryTrackHelper::sInstance;

NonLibraryTrackHelper::NonLibraryTrackHelper(void)
 :threadIsRunning(false)
{
}

NonLibraryTrackHelper::~NonLibraryTrackHelper(void){
}

NonLibraryTrackHelper& NonLibraryTrackHelper::Instance(){
    return NonLibraryTrackHelper::sInstance;
}

boost::mutex& NonLibraryTrackHelper::TrackMutex(){
    return NonLibraryTrackHelper::sInstance.trackMutex;
}

void NonLibraryTrackHelper::ReadTrack(musik::core::TrackPtr track){
    bool threadRunning(false);
    {
        boost::mutex::scoped_lock lock(this->mutex);
        this->tracksToRead.push_back(TrackWeakPtr(track));
        threadRunning   = this->threadIsRunning;
    }

    if(!threadRunning){
        if(this->helperThread){
            this->helperThread->join();
        }
        this->helperThread.reset(new boost::thread(boost::bind(&NonLibraryTrackHelper::ThreadLoop,this)));

    }
}

void NonLibraryTrackHelper::ThreadLoop(){

    // Get the metadatareaders
    typedef Plugin::IMetaDataReader PluginType;
    typedef PluginFactory::DestroyDeleter<PluginType> Deleter;
    typedef std::vector<boost::shared_ptr<Plugin::IMetaDataReader> > MetadataReaderList;
    MetadataReaderList metadataReaders = PluginFactory::Instance().QueryInterface<PluginType, Deleter>("GetMetaDataReader");

    // pop a track, read the metadata, notify and continue
    bool moreTracks(true);
    while(moreTracks){
        moreTracks  = false;
        musik::core::TrackPtr track;
        {
            boost::mutex::scoped_lock lock(this->mutex);

            if(!this->tracksToRead.empty()){
                // is this a valid track
                track = this->tracksToRead.front().lock();
                this->tracksToRead.pop_front();
            }

            moreTracks  = !this->tracksToRead.empty();

            if(!moreTracks){
                // Set to "not running". No locking beyond this point.
                this->threadIsRunning   = false;
            }
        }
        if(track){
            // check if this is a local file
            if(musik::core::filestreams::Factory::IsLocalFileStream(track->URL())){
                utfstring url(track->URL());
                utfstring::size_type lastDot = url.find_last_of(UTF("."));
                if(lastDot!=utfstring::npos){
                    track->SetValue("extension",url.substr(lastDot+1).c_str());
                }
                // Read track metadata
                typedef MetadataReaderList::iterator Iterator;
                Iterator it = metadataReaders.begin();
                while (it != metadataReaders.end()) {
                    if((*it)->CanReadTag(track->GetValue("extension")) ){
                        // Should be able to read the tag
                        if( (*it)->ReadTag(track.get()) ){
                            // Successfully read the tag.
    //                        tagRead=true;
                        }
                    }

                    it++;
                }

                // Lets notify that tracks has been read
                this->TrackMetadataUpdated(track);
            }
        }
    }

}

redpajama_set_name: RedPajamaGithub


text:
package dk.itu.jglyph.neat;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.jgap.BulkFitnessFunction;
import org.jgap.Chromosome;

import com.anji.integration.Activator;
import com.anji.integration.ActivatorTranscriber;
import com.anji.integration.TranscriberException;
import com.anji.util.Configurable;
import com.anji.util.Properties;

import dk.itu.jglyph.Glyph;
import dk.itu.jglyph.features.FeatureExtractors;
import dk.itu.jglyph.neat.TrainingSet;
import dk.itu.jglyph.user.Model;
import dk.itu.jglyph.user.Node;

/**
 * Determines fitness based on if this network respects the relations in the user model
 * (Based on com.anji.integration.TargetFitnessFunction)
 */
public class ModelFitnessFunction implements BulkFitnessFunction, Configurable {
	/**
	 * Auto-generated serial version UID.
	 */
	private static final long serialVersionUID = -2295453770025929525L;

	/**
	 * The highest possible fitness value.
	 */
	private final static int MAX_FITNESS = 1000000;

	/**
	 * A utility object for logging.
	 */
	private static Logger logger = Logger.getLogger( ModelFitnessFunction.class );

	private final static String ADJUST_FOR_NETWORK_SIZE_FACTOR_KEY = "fitness.function.adjust.for.network.size.factor";
	private float adjustForNetworkSizeFactor = 0.0f;

	private final static String MINIMUM_DIFFERENCE_KEY = "glyph.fitness.minimum.difference";
	private double minimumDifference;

	/**
	 * The highest fitness value produced thus far.
	 */
	private int maxFitnessValue;

	/**
	 * The transcriber the produces neural networks from chromosomes.
	 */
	private ActivatorTranscriber activatorFactory;

	/**
	 * The user model.
	 */
	private Model model;

	/**
	 * The amount of stimuli.
	 */
	private int stimuliCount;

	/**
	 * The amount of responses.
	 */
	private int responseCount;

	/**
	 * See Parameter Details  for
	 * specific property settings.
	 *
	 * @param props configuration parameters
	 */
	public void init(Properties props)
	{
		try {
			activatorFactory = (ActivatorTranscriber) props
					.singletonObjectProperty( ActivatorTranscriber.class );

			adjustForNetworkSizeFactor = props.getFloatProperty( ADJUST_FOR_NETWORK_SIZE_FACTOR_KEY,
					0.0f );

			minimumDifference = props.getDoubleProperty( MINIMUM_DIFFERENCE_KEY,
					0.1 );

			// Figure out sizes for stimlui/response layers
			stimuliCount = props.getIntProperty("stimulus.size");
			responseCount = props.getIntProperty("response.size");

			// Read in model to grab relations from
			model = TrainingSet.model;

			setMaxFitnessValue(MAX_FITNESS);
		}
		catch ( Exception e ) {
			throw new IllegalArgumentException( "invalid properties: " + e.getClass().toString() + ": "
					+ e.getMessage() );
		}
	}

	/**
	 * @param aMaxFitnessValue maximum raw fitness this function will return
	 */
	protected void setMaxFitnessValue(int aMaxFitnessValue)
	{
		int minGenes = stimuliCount + responseCount;
		maxFitnessValue = aMaxFitnessValue - (int) ( adjustForNetworkSizeFactor * minGenes );
	}

	/**
	 * Iterates through chromosomes. For each, transcribe it to an Activator and
	 * present the stimuli to the activator. The stimuli are presented in random order to ensure the
	 * underlying network is not memorizing the sequence of inputs. Calculation of the fitness based
	 * on error is delegated to the subclass. This method adjusts fitness for network size, based on
	 * configuration.
	 *
	 * @param genotypes List contains Chromosome objects.
	 * @see ModelFitnessFunction#calculateErrorFitness(double[][], double, double)
	 */
	@SuppressWarnings("rawtypes")
	final public void evaluate(List genotypes)
	{
		// screw you, old java! :<
		@SuppressWarnings("unchecked")
		List<Chromosome> chromosomes = (List<Chromosome>) genotypes;

		for (Chromosome chromosome : chromosomes) {
			try {
				Activator activator = activatorFactory.newActivator( chromosome );

				// TODO grab all edges and end with an array of response-diffs and targets
				List<Double> diffs = new ArrayList<>();
				List<Double> scores = new ArrayList<>();

				for (Node parent : model.getNodes()) {
					for (Node child : parent.getChildren()) {
						diffs.add(getErrorDifference(activator, parent.glyph, child.glyph));
					}
					double[] parentStimulus = FeatureExtractors.getInstance().extractFeatures(parent.glyph);
					scores.add(activator.next(parentStimulus)[0]);
				}

				double minResponse = Double.POSITIVE_INFINITY, maxResponse = Double.NEGATIVE_INFINITY;

				for (Double d : scores) {
					minResponse = Math.min(minResponse, d);
					maxResponse = Math.max(maxResponse, d);
				}

				int fitness = calculateErrorFitness( diffs, minResponse,
						maxResponse )
						- (int) ( adjustForNetworkSizeFactor * chromosome.size() );

				chromosome.setFitnessValue( fitness );
			}
			catch ( TranscriberException e ) {
				logger.warn( "transcriber error: " + e.getMessage() );
				chromosome.setFitnessValue( 1 );
			}
		}
	}

	/**
	 * Calculates the error produced by the neural network, when evaluating a parent and child.
	 * @param activator The neural network.
	 * @param parent The parent.
	 * @param child The child.
	 * @return The error.
	 */
	private double getErrorDifference(Activator activator, Glyph parent, Glyph child) {
		double[] parentStimulus = FeatureExtractors.getInstance().extractFeatures(parent);
		double[] childStimulus = FeatureExtractors.getInstance().extractFeatures(child);

		double parentScore = activator.next(parentStimulus)[0];
		double childScore = activator.next(childStimulus)[0];

		double difference = (childScore + minimumDifference) - parentScore; // Add epsilon to make sure they aren't equal

		return Math.max(difference, 0.0);
	}

	/**
	 * Sum all differences, subtract from max
	 * fitness, and square result.
	 *
	 * @param differences between a response and the ideal response (0 = response was good)
	 * @param minResponse
	 * @param maxResponse
	 * @return result of calculation
	 */
	private int calculateErrorFitness( List<Double> diffs, double minResponse, double maxResponse ) {

		double maxSumDiff = getMaxError(
				diffs.size(),
				( maxResponse - minResponse + minimumDifference ),
				false );
		double maxRawFitnessValue = Math.pow( maxSumDiff, 2 );

		double sumDiff = 0;
		for (double d : diffs) {
			sumDiff += d;
		}

		if ( sumDiff > maxSumDiff + .00000001 )
			throw new IllegalStateException( "sum diff > max sum diff" );

		double rawFitnessValue = Math.pow( maxSumDiff - sumDiff, 2 );
		double skewedFitness = ( rawFitnessValue / maxRawFitnessValue ) * MAX_FITNESS;
		int result = (int) skewedFitness;
		return result;
	}

	/**
	 * @param responseCount
	 * @param minMaxRange
	 * @param sumOfSquares
	 * @return maximum error given the number and range of responses
	 */
	private double getMaxError( int responseCount, double minMaxRange, boolean sumOfSquares) {
		double maxDiffPerResponse = minMaxRange;
		if ( sumOfSquares )
			maxDiffPerResponse *= maxDiffPerResponse;
		return maxDiffPerResponse * responseCount;
	}

	/**
	 * @return maximum possible fitness value for this function
	 */
	public int getMaxFitnessValue() {
		return maxFitnessValue;
	}

}


text:
var config         = require('../../config.js');
var amdefinitions  = require('../../appmodules');

var factory=
{
  create:function(appmoduleName,_callback)
  {
    global.__zn__dbcp__.getConnection(function(err,dbc)
    {
      if (err)
      {
        _callback(err,null);
        return;
      }

      var appmodule=factory.applicationModules[appmoduleName](dbc);
      _callback(null,appmodule);

    });
  },

  release:function(appmodule)
  {
    appmodule.dbc.release();
  },

  get:function(appmoduleName,dbc)
  {
    return factory[appmoduleName](dbc);
  },

  createAms:function(amNames,$)
  {
    if(amNames==null || amNames.length==0)
    {
      $(null,null);
      return;
    };

    global.__zn__dbcp__.getConnection(function(err,dbc)
    {
      if (err)
      {
        $(err,null);
        return;
      }

      var ams=[];
      for(var i=0;i<amNames.length;i++)
      {
        var appmodule=factory.applicationModules[amNames[i]](dbc);
        ams[ams.length]=appmodule;
      }
      $(null,{dbc: dbc, ams: ams});
    });
  },

  releaseAms:function(obj)
  {
    obj && obj.dbc && obj.dbc.release();
  }
};

factory.applicationModules={};

factory.applicationModules.entity=require('./entity');
factory.applicationModules.attachment=require('./attachment');
factory.applicationModules.auth=require('./auth');

for(var appmodule in amdefinitions)
{
  if(amdefinitions.hasOwnProperty(appmodule)) factory.applicationModules[appmodule]=amdefinitions[appmodule];
}

module.exports=factory;


text:
/////////////////////////////////////////////////////////////////////////////
// CMySheet
#pragma once
class CMySheet : public CPropertySheet
{
protected:
//	void BuildPropPageArray();
	RECT m_rctPage;
	CFont m_fntPage;

	DECLARE_DYNAMIC(CMySheet)

// Construction
public:
	CMySheet(UINT nIDCaption, CWnd* pParentWnd = NULL, UINT iSelectPage = 0);
	CMySheet(LPCTSTR pszCaption, CWnd* pParentWnd = NULL, UINT iSelectPage = 0);

// Attributes
public:

// Operations
public:

// Overrides
	// ClassWizard generated virtual function overrides
	//{{AFX_VIRTUAL(CMySheet)
	public:
	virtual BOOL OnInitDialog();
	protected:
	virtual BOOL OnNotify(WPARAM wParam, LPARAM lParam, LRESULT* pResult);
	virtual BOOL OnCommand(WPARAM wParam, LPARAM lParam);
	//}}AFX_VIRTUAL

// Implementation
public:
	virtual ~CMySheet();

	// Generated message map functions
protected:
	virtual void BuildPropPageArray ();
	//{{AFX_MSG(CMySheet)
	//}}AFX_MSG
	afx_msg LONG OnResizePage (UINT, LONG);
	afx_msg void OnHelp();
	DECLARE_MESSAGE_MAP()

	bool m_KeepCancelButton;
public:
	afx_msg HBRUSH OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor);
	afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);
};

/////////////////////////////////////////////////////////////////////////////


text:
package paiso.model;

import java.io.Serializable;

/**
 * Base class to represent model entities.
 */
public abstract class BaseEntity implements Serializable {

}


text:
'use strict';

/**
 * @ngdoc function
 * @name uiApp.controller:TaskviewCtrl
 * @description
 * # TaskviewCtrl
 * Controller of the uiApp
 */
angular.module('uiApp')
  .controller('TaskviewCtrl', ['TaskService', 'ReplyErrorHandler', 'ConfirmModal', 'notifications', '$scope', '$stateParams', '$state', 'LastViewed', function(TaskService, ReplyErrorHandler, ConfirmModal, notifications, $scope, $stateParams, $state, LastViewed) {
    $scope.task = {};

    $scope.loadTask =function() {
        TaskService.id.get({id: $stateParams.id}, function(data) { //, status, headers, config
            $scope.task = data;
            var item = {'name': $scope.task.name, 'type': 'Task', 'id': $scope.task.id};
            LastViewed.add(item);
        }, ReplyErrorHandler);
    };
    $scope.loadTask();

    $scope.deleteTask = function (id) {
        ConfirmModal.showModal({}, {headerText: 'Confirm', bodyText: 'Are you sure you want to delete this Task?'}).then(function () {//result
            TaskService.id.delete({id: id},function() { //data, status, headers, config
                $state.go('root.taskbrowser');
                notifications.showSuccess('Task has been deleted.');
            }, ReplyErrorHandler);
        }, function() {notifications.showInfo('Delete canceled.');});
    };
}]);


text:
<?php
/*
Title: Vendor MIME
Tagline: custom media type for versioning
Tags: versioning,mime,mediatype,vendor,custom
Requires: PHP >= 5.3
Description:
This example shows how to use vendor specific media types for versioning

###Vendor-Specific Media Types

> Media types use the subtype prefix `vnd` to indicate that they are owned and
> controlled by a `vendor`. Vendor-specific media types convey a clear description
> of a message's content to the programs that understand their meaning.
- [REST API Design Rulebook](http://books.google.com.sg/books?id=eABpzyTcJNIC&lpg=PA40&ots=vxTC21e8JB&dq=vendor%20specific%20media%20types&pg=PA40#v=onepage&q=vendor%20specific%20media%20types&f=false)

Important steps are

```php
Defaults::$apiVendor = "SomeVendor";
Defaults::$useVendorMIMEVersioning = true;

$r = new Restler();
$r->setAPIVersion(2);
//...
```

Content:

Here is how you will consume different versions of the api using cURL.

**Version 1**

```bash
curl 'http://restler3.luracast.com/examples/_012_vendor_mime/index.php/bmi?height=162.6&weight=84' -H 'Accept: application/vnd.somevendor-v1+json' -i

HTTP/1.1 200 OK
Date: Sun, 06 Jan 2013 10:46:40 GMT
Server: Apache/2.2.22 (Unix) DAV/2 PHP/5.3.14 mod_ssl/2.2.22 OpenSSL/0.9.8o
X-Powered-By: Luracast Restler v3.0.0rc3
Set-Cookie: ZDEDebuggerPresent=php,phtml,php3; path=/
Vary: Accept
Cache-Control: no-cache, must-revalidate
Expires: 0
Content-Language: en
Content-Length: 209
Content-Type: application/vnd.SomeVendor-v1+json; charset=utf-8

{
  "bmi": 31.77,
  "message": "Obesity",
  "metric": {
    "height": "162.6 centimeters",
    "weight": "84 kilograms"
  },
  "imperial": {
    "height": "5 feet 4 inches",
    "weight": "185.19 pounds"
  }
}

```
**Version 2 without unit**
```bash
curl 'http://restler3.luracast.com/examples/_012_vendor_mime/index.php/bmi?height=162.6&weight=84' -H 'Accept: application/vnd.somevendor-v2+json' -i

HTTP/1.1 400 Bad Request
Date: Sun, 06 Jan 2013 10:48:19 GMT
Server: Apache/2.2.22 (Unix) DAV/2 PHP/5.3.14 mod_ssl/2.2.22 OpenSSL/0.9.8o
X-Powered-By: Luracast Restler v3.0.0rc3
Set-Cookie: ZDEDebuggerPresent=php,phtml,php3; path=/
Vary: Accept
Cache-Control: no-cache, must-revalidate
Expires: 0
Content-Language: en
Content-Length: 87
Connection: close
Content-Type: application/vnd.SomeVendor-v2+json; charset=utf-8

{
  "error": {
    "code": 400,
    "message": "Bad Request: invalid height unit"
  }
}

```
**Version 2 with unit**
```bash
curl 'http://restler3.luracast.com/examples/_012_vendor_mime/index.php/bmi?height=1.626meters&weight=84kilograms' -H 'Accept: application/vnd.somevendor-v2+json' -i

HTTP/1.1 200 OK
Date: Sun, 06 Jan 2013 11:05:26 GMT
Server: Apache/2.2.22 (Unix) DAV/2 PHP/5.3.14 mod_ssl/2.2.22 OpenSSL/0.9.8o
X-Powered-By: Luracast Restler v3.0.0rc3
Set-Cookie: ZDEDebuggerPresent=php,phtml,php3; path=/
Vary: Accept
Cache-Control: no-cache, must-revalidate
Expires: 0
Content-Language: en
Content-Length: 209
Content-Type: application/vnd.SomeVendor-v2+json; charset=utf-8

{
  "bmi": 31.77,
  "message": "Obesity",
  "metric": {
    "height": "162.6 centimeters",
    "weight": "84 kilograms"
  },
  "imperial": {
    "height": "5 feet 4 inches",
    "weight": "185.19 pounds"
  }
}

```

*/
require_once '../../../vendor/restler.php';
use Luracast\Restler\Defaults;
use Luracast\Restler\Restler;

Defaults::$apiVendor = "SomeVendor";
Defaults::$useVendorMIMEVersioning = true;

$r = new Restler();
$r->setAPIVersion(2);
$r->addAPIClass('SomeVendor\\BMI');
$r->addAPIClass('Resources');
$r->handle();


text:
module.exports = {
    "extends": "standard"
};


text:
<?php

namespace PWE\Lib\Doctrine;

use Doctrine\DBAL\Driver\Statement;
use PDO;

class StatementEmulator implements \IteratorAggregate, Statement
{

    public function bindValue($param, $value, $type = null)
    {

    }

    public function closeCursor()
    {

    }

    public function columnCount()
    {

    }

    public function errorCode()
    {

    }

    public function errorInfo()
    {

    }

    public function execute($params = null)
    {

    }

    public function fetch($fetchMode = null, $cursorOrientation = PDO::FETCH_ORI_NEXT, $cursorOffset = 0)
    {

    }

    public function fetchAll($fetchMode = null, $fetchArgument = null, $ctorArgs = null)
    {

    }

    public function fetchColumn($columnIndex = 0)
    {

    }

    public function rowCount()
    {

    }

    public function current()
    {

    }

    public function key()
    {

    }

    public function next()
    {

    }

    public function rewind()
    {

    }

    public function valid()
    {

    }

    public function getIterator()
    {

    }

    public function bindParam($column, &$variable, $type = null, $length = null)
    {

    }

    public function setFetchMode($fetchMode, $arg2 = null, $arg3 = null)
    {

    }

}


text:
import { ISubtitle } from '../interfaces/ISubtitle';

export class LurnPlayerOptions {
    source: string;
    width: string;
    height: string;
    subtitles: Array<ISubtitle>;

    constructor(_source: string,
                _width: string = 'auto',
                _height: string = 'auto',
                _subtitles: Array<ISubtitle> = new Array<ISubtitle>()) {
        this.source = _source;
        this.width = _width;
        this.height = _height;
        this.subtitles = _subtitles;
    }
}


text:
package org.springframework.boot.autoconfigure.jdbc;

import javax.annotation.PreDestroy;

import org.springframework.beans.factory.BeanClassLoaderAware;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.jdbc.EmbeddedDatabaseConnection;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabase;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;

/**
 * Configuration for embedded data sources.
 *
 * @author Phillip Webb
 * @author Stephane Nicoll
 * @see DataSourceAutoConfiguration
 */
@Configuration
@EnableConfigurationProperties(DataSourceProperties.class)
public class EmbeddedDataSourceConfiguration implements BeanClassLoaderAware {

	private EmbeddedDatabase database;

	private ClassLoader classLoader;

	private final DataSourceProperties properties;

	public EmbeddedDataSourceConfiguration(DataSourceProperties properties) {
		this.properties = properties;
	}

	@Override
	public void setBeanClassLoader(ClassLoader classLoader) {
		this.classLoader = classLoader;
	}

	@Bean
	public EmbeddedDatabase dataSource() {
		EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder()
				.setType(EmbeddedDatabaseConnection.get(this.classLoader).getType());
		this.database = builder.setName(this.properties.getName())
				.generateUniqueName(this.properties.isGenerateUniqueName()).build();
		return this.database;
	}

	@PreDestroy
	public void close() {
		if (this.database != null) {
			this.database.shutdown();
		}
	}

}


text:
#include <flickcurl.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <glib.h>
#include <pthread.h>

#include "cache.h"
#include "conf.h"

#define DEFAULT_CACHE_TIMEOUT   14400 /* In seconds. */

/* Valid sizes: http://librdf.org/flickcurl/api/flickcurl-section-photo.html#flickcurl-photo-as-source-uri */
#define GET_PHOTO_SIZE      'o'
#define PHOTOS_PER_API_CALL 100
#define PHOTO_EXTRAS        "date_taken,url_o,original_format"

/* Photo parameters */
#define SAFETY_LEVEL    1
#define CONTENT_TYPE    1

#define CACHE_UNSET     0
#define CACHE_SET       1

typedef struct {
    cached_information ci;
    unsigned short set;
    GHashTable *photo_ht;
} cached_photoset;

typedef struct {
    cached_information ci;
} cached_photo;

static GHashTable *photoset_ht;             /* The photoset cache */
static pthread_rwlock_t cache_lock;         /* To make thread safe */
static time_t last_cleaned;                 /* To age/invalidate the cache */

static flickcurl *fc;

static inline cached_photo *create_cached_photo() {
    return (cached_photo *)calloc(1, sizeof(cached_photo));
}

static inline cached_photoset *create_cached_photoset() {
    return (cached_photoset *)calloc(1, sizeof(cached_photoset));
}

static inline GHashTable *create_cache() {
    return g_hash_table_new(g_str_hash, g_str_equal);
}

/*
 * Initialize the flickcurl connection
*/
static int flickr_init() {
    char *conf_path;
    char *login;

    flickcurl_init();
    fc = flickcurl_new();

    conf_path = get_conf_path();
    if(!conf_path)
        return FAIL;

    if(check_conf_file(conf_path, fc))
        return FAIL;

    /* Read from the config file, ~/.flickcurl.conf */
    if(flickcurl_config_read_ini(fc, conf_path, "flickr", fc, flickcurl_config_var_handler))
        return FAIL;

    login = flickcurl_test_login(fc);
    if(!login)
        return FAIL;

    free(login);
    free(conf_path);
    return SUCCESS;
}

static void flickr_kill() {
    flickcurl_free(fc);
    flickcurl_finish();
}

/**
 * ===Cache Methods===
**/

/* Creates a new cached_photoset using the photoset or a blank one if NULL is passed in */
static int new_cached_photoset(cached_photoset **cps, flickcurl_photoset *fps) {
    unsigned int i;
    cached_information *ci;

    *cps = create_cached_photoset();
    if(!cps)
        return FAIL;

    ci = &((*cps)->ci);
    ci->name = strdup(fps ? fps->title : "");
    ci->id = strdup(fps ? fps->id : "");
    ci->time = 0;
    ci->size = fps ? (unsigned int)fps->photos_count : 0;
    ci->dirty = CLEAN;
    (*cps)->set = CACHE_UNSET;
    (*cps)->photo_ht = g_hash_table_new(g_str_hash, g_str_equal);

    /* Replace backslashes with spaces */
    for(i = 0; i < strlen(ci->name); i++) {
        if(ci->name[i] == '/')
            ci->name[i] = ' ';
    }
    return SUCCESS;
}

static cached_information *copy_cached_info(const cached_information *ci) {
    cached_information *newci = ci?(cached_information *)malloc(sizeof(cached_information)):NULL;
    if(!newci)
        return NULL;
    *newci = *ci;
    if(ci->name)
        newci->name = strdup(ci->name);
    if(ci->id)
        newci->id = strdup(ci->id);
    return newci;
}

void free_cached_info(cached_information *ci) {
    if(ci) {
        free(ci->name);
        free(ci->id);
        free(ci);
    }
}

/* All of our keys and values will be dynamic so we will want to free them. */
static gboolean free_photo_ht(gpointer key, gpointer value, gpointer user_data) {
    (void)user_data;
    cached_photo *cp = value;

    if(cp->ci.dirty == CLEAN) {
        free(cp->ci.uri);
        free(cp->ci.name);
        free(cp->ci.id);
        free(key);
        free(value);
        return TRUE;
    }
    else {
        return FALSE;
    }
}

/* All of our keys and values will be dynamic so we will want to free them. */
static gboolean free_photoset_ht(gpointer key, gpointer value, gpointer user_data) {
    GHashTable *photo_ht;
    (void)user_data;

    cached_photoset *cps = value;
    photo_ht = cps->photo_ht;

    g_hash_table_foreach_remove(photo_ht, free_photo_ht, NULL);

    if(cps->ci.dirty == CLEAN && g_hash_table_size(photo_ht) == 0) {
        g_hash_table_destroy(photo_ht);

        free(key);
        free(cps->ci.name);
        free(cps->ci.id);
        free(value);
        return TRUE;
    }
    else {
        cps->set = (cps->ci.dirty == CLEAN) ? CACHE_UNSET : CACHE_SET;
        return FALSE;
    }
}

/*
 * Checks whether the cache should be cleaned. Time can be changed in
 * DEFAULT_CACHE_TIMEOUT define.
 * Assumes there is a lock initiated
*/
static int check_cache() {
    flickcurl_photoset **fps;
    cached_photoset *cps;
    int i;

    if((time(NULL) - last_cleaned) < DEFAULT_CACHE_TIMEOUT)
        return SUCCESS;

    pthread_rwlock_unlock(&cache_lock); /* Release the read lock and lock for writting */
    pthread_rwlock_wrlock(&cache_lock);

    if((time(NULL) - last_cleaned) < DEFAULT_CACHE_TIMEOUT)
        return SUCCESS;

    /* Wipe clean entries from the cache. */
    g_hash_table_foreach_remove(photoset_ht, free_photoset_ht, NULL);

    if(g_hash_table_size(photoset_ht) == 0) {
        g_hash_table_destroy(photoset_ht);
        photoset_ht = create_cache();
    }

    if(!g_hash_table_lookup(photoset_ht, "")) {
        /* Create an empty photoset container for the photos not in a photoset */
        if(new_cached_photoset(&cps, NULL))
            return FAIL;

        g_hash_table_insert(photoset_ht, strdup(""), cps);
    }

    if(!(fps = flickcurl_photosets_getList(fc, NULL)))
        return FAIL;

    /* Add the photosets to the cache */
    for(i = 0; fps[i]; i++) {
        if(!g_hash_table_lookup(photoset_ht, fps[i]->title)) {
            if(new_cached_photoset(&cps, fps[i]))
                return FAIL;
            g_hash_table_insert(photoset_ht, strdup(cps->ci.name), cps);
        }
    }
    flickcurl_free_photosets(fps);

    last_cleaned = time(NULL);

    return SUCCESS;
}

static int populate_photoset_cache(cached_photoset *cps, flickcurl_photo **fp) {
    int j = 0;

    if(!fp)
        return FAIL;

    /* Add photos to photoset cache */
    for(; fp[j]; j++) {
        cached_photo *cp;
        struct tm tm = {0};
        char *title;
        char *id;

        title = fp[j]->fields[PHOTO_FIELD_title].string;
        id    = fp[j]->id;

        /* Check if dirty version already exists in the database. */
        if((cp = g_hash_table_lookup(cps->photo_ht, title))) {
            if(!strcmp(cp->ci.id, id))
                continue;
        }
        else if((cp = g_hash_table_lookup(cps->photo_ht, id))) {
            if(!strcmp(cp->ci.id, id))
                continue;
            else
                continue;              /* TODO: Need to figure out what to do here. */
        }

        if(!(cp = create_cached_photo())) {
            return FAIL;
        }

        cp->ci.uri = flickcurl_photo_as_source_uri(fp[j], GET_PHOTO_SIZE);
        cp->ci.name = strdup(title);
        cp->ci.id = strdup(id);
        cp->ci.size = PHOTO_SIZE_UNSET;
        cp->ci.dirty = CLEAN;

        sscanf(fp[j]->fields[PHOTO_FIELD_dates_taken].string, "%4d-%2d-%2d %2d:%2d:%2d",
          &(tm.tm_year), &(tm.tm_mon), &(tm.tm_mday), &(tm.tm_hour), &(tm.tm_min), &(tm.tm_sec));
        tm.tm_year = tm.tm_year - 1900;     /* Years since 1900 */
        tm.tm_mon--;                        /* Programmers start with 0... */
        tm.tm_sec--;
        tm.tm_min--;
        tm.tm_hour--;
        cp->ci.time = mktime(&tm);

        /* Can't place empty or duplicate names into the hash table. If this is the case, use the photo id instead. */
        if(cp->ci.name[0] == '\0' || g_hash_table_lookup(cps->photo_ht, cp->ci.name))
            g_hash_table_insert(cps->photo_ht, strdup(cp->ci.id), cp);
        else
            g_hash_table_insert(cps->photo_ht, strdup(cp->ci.name), cp);
    }

    return j;
}

static inline flickcurl_photo **get_photoset_photos(cached_photoset *cps, int page) {
    flickcurl_photo **fp;

    /* Are we searching for photos in a photoset or not? */
    if(!strcmp(cps->ci.id, "")) {   /* Get photos NOT in a photoset */
        if(!(fp = flickcurl_photos_getNotInSet(fc, 0, 0, NULL, NULL, 0, PHOTO_EXTRAS, PHOTOS_PER_API_CALL, page)))
            return NULL;
    }
    else {                          /* Add the photos of the photoset into the cache */
        if(!(fp = flickcurl_photosets_getPhotos(fc, cps->ci.id, PHOTO_EXTRAS, 0, PHOTOS_PER_API_CALL, page)))
            return NULL;
    }

    return fp;
}

/*
 * The photosets are filled dynamically based on which photosets are loaded
 * (it would be a waste to load all flickr info if not needed).
 * This method needs to be called in order to fill the photoset cache
 * with photo information.
 * Assumes there is a lock initiated
 */
static int check_photoset_cache(cached_photoset *cps) {
    flickcurl_photo **fp;
    unsigned int total_size = 0;
    int processed = 0;
    int page = 0;

    if(!cps)
        return FAIL;
    if(!(cps->photo_ht))
        return FAIL;
    if(cps->set)
        return SUCCESS;

    pthread_rwlock_unlock(&cache_lock); /* Release the read lock and lock for writting */
    pthread_rwlock_wrlock(&cache_lock);

    if(cps->set)
        return SUCCESS;

    while((fp = get_photoset_photos(cps, page++))) {
        processed = populate_photoset_cache(cps, fp);
        flickcurl_free_photos(fp);
        if(processed < 0)
            return FAIL;

        total_size += (unsigned int)processed;

        if(processed < PHOTOS_PER_API_CALL)
            break;
    }

    cps->ci.time = time(NULL);
    cps->ci.size = total_size;
    cps->set = CACHE_SET;

    return SUCCESS;
}

/*
 * Initiates a new flickcurl connection and creates the caching
 * mechanism.
*/
int flickr_cache_init() {
    if(flickr_init())
        return FAIL;
    photoset_ht = create_cache();
    last_cleaned = 0;
    pthread_rwlock_init(&cache_lock, NULL);
    return SUCCESS;
}

/*
 * Destroys the caches and the flickcurl connection
*/
void flickr_cache_kill() {
    /* Wipe existing cache */
    pthread_rwlock_wrlock(&cache_lock);
    pthread_rwlock_destroy(&cache_lock);
    g_hash_table_foreach_remove(photoset_ht, free_photoset_ht, NULL);
    g_hash_table_destroy(photoset_ht);
    flickr_kill();
}

/**
* ===Accessing Data Methods===
**/

/* Creates an array of strings cooresponding to the users photosets.
 * Returns the number of photosets or negative for an error.
 *
 * IMPORTANT: Make sure you free(names) after you are done!
 */
unsigned int get_photoset_names(char ***names) {
    GHashTableIter iter;
    char *key;
    unsigned int size, i;

    if(!names)
        return 0;

    pthread_rwlock_rdlock(&cache_lock);
    if(check_cache()) {
        pthread_rwlock_unlock(&cache_lock);
        return 0;
    }

    /* We dont want to add the "" photoset (used for photos without a photoset) into this list */
    size = g_hash_table_size(photoset_ht) - 1;

    if(!(*names = (char **)malloc(sizeof(*names) * size))) {
        pthread_rwlock_unlock(&cache_lock);
        return 0;
    }

    /* Add each photoset to the list. We add the keys since the names may be duplicates/NULL */
    g_hash_table_iter_init(&iter, photoset_ht);
    i = 0;
    while(g_hash_table_iter_next(&iter, (gpointer)&key, NULL)) {
        if(key && strcmp(key, "")) {
            (*names)[i] = strdup(key);
            i++;
        }
    }
    pthread_rwlock_unlock(&cache_lock);
    return i;
}

/* Creates an array of strings cooresponding to  the users photos
 * of a certain photoset. Returns the number of photos in the
 * photoset or negative signaling an error.
 *
 * IMPORTANT: Make sure you free(names) (but not the strings within)
 * after you are done!
 */
unsigned int get_photo_names(const char *photoset, char ***names) {
    GHashTableIter iter;
    char *key;
    cached_photoset *cps;
    cached_photo *cp;
    unsigned int i, size;

    if(!names || !photoset)
        return 0;

    pthread_rwlock_rdlock(&cache_lock);
    if(check_cache())
        goto fail;

    /* If the photoset is not found in the cache, return */
    if(!(cps = g_hash_table_lookup(photoset_ht, photoset)))
        goto fail;

    if(check_photoset_cache(cps))
        goto fail;

    size = g_hash_table_size(cps->photo_ht);

    if(!(*names = (char **)malloc(sizeof(*names) * size)))
        goto fail;

    /* Add each photo to the list. We add the keys since the names may be duplicates/NULL */
    g_hash_table_iter_init(&iter, cps->photo_ht);
    for(i = 0; g_hash_table_iter_next(&iter, (gpointer)&key, (gpointer)&cp); i++)
    {
        (*names)[i] = strdup(key);
    }

    pthread_rwlock_unlock(&cache_lock);
    return size;

fail:   pthread_rwlock_unlock(&cache_lock);
    return 0;
}

/* Looks for the photoset specified in the argument.
 * Returns pointer to the stored cached_information
 * or 0 if not found.
 */
cached_information *photoset_lookup(const char *photoset) {
    cached_photoset *cps;
    cached_information *ci_copy = NULL;

    pthread_rwlock_rdlock(&cache_lock);
    if(check_cache())
        goto fail;

    cps = g_hash_table_lookup(photoset_ht, photoset);
    if(cps)
        ci_copy = copy_cached_info(&(cps->ci));

fail: pthread_rwlock_unlock(&cache_lock);
    return ci_copy;
}

/*
 * Internal method to get the cached_photo of
 * a particular photo.
 * Assumes there is a lock initiated
 */
static cached_photo *get_photo(const char *photoset, const char *photo) {
    cached_photoset *cps;

    if(check_cache())
        return NULL;

    if(!(cps = g_hash_table_lookup(photoset_ht, photoset)))
        return NULL;

    if(check_photoset_cache(cps))
        return NULL;

    return g_hash_table_lookup(cps->photo_ht, photo);
}

/* Looks for the photo specified in the arguments.
 * Returns pointer to the stored cached_information
 * or 0 if not found.
 */
cached_information *photo_lookup(const char *photoset, const char *photo) {
    cached_photo *cp;
    cached_information *ci_copy = NULL;

    pthread_rwlock_rdlock(&cache_lock);
    if((cp = get_photo(photoset, photo)))
        ci_copy = copy_cached_info(&(cp->ci));
    pthread_rwlock_unlock(&cache_lock);

    return ci_copy;
}

/* Returns the URI used to get the actual image of
 * picture.
 */
char *get_photo_uri(const char *photoset, const char *photo) {
    cached_photo *cp;
    char *uri_copy = NULL;

    pthread_rwlock_rdlock(&cache_lock);
    if((cp = get_photo(photoset, photo))) {
        if(cp->ci.uri) {
            uri_copy = strdup(cp->ci.uri);
        }
    }
    pthread_rwlock_unlock(&cache_lock);

    return uri_copy;
}

/* Renames the photo specified in the args to the
 * new name.
 */
int set_photo_name(const char *photoset, const char *photo, const char *newname) {
    cached_photo *cp;

    pthread_rwlock_wrlock(&cache_lock);
    if(!(cp = get_photo(photoset, photo))) {
        pthread_rwlock_unlock(&cache_lock);
        return FAIL;
    }

    flickcurl_photos_setMeta(fc, cp->ci.id, newname, "");
    last_cleaned = 0;
    pthread_rwlock_unlock(&cache_lock);
    return SUCCESS;
}

/* Renames the photoset */
int set_photoset_name(const char *photoset, const char *newname) {
    void *key, *value;
    cached_photoset *cps;
    int retval = FAIL;

    pthread_rwlock_wrlock(&cache_lock);

    if(g_hash_table_lookup_extended(photoset_ht, photoset, &key, &value)) {
        cps = value;

        if(cps->ci.dirty == CLEAN)
            if(flickcurl_photosets_editMeta(fc, cps->ci.id, newname, NULL))
                goto fail;

        free(cps->ci.name);
        cps->ci.name = strdup(newname);

        g_hash_table_remove(photoset_ht, photoset);
        g_hash_table_insert(photoset_ht, strdup(newname), cps);

        free(key);
        retval = SUCCESS;
    }

fail: pthread_rwlock_unlock(&cache_lock);

    return retval;
}

/* Sets the photos size */
int set_photo_size(const char *photoset, const char *photo, unsigned int newsize) {
    cached_photo *cp;

    pthread_rwlock_wrlock(&cache_lock);
    if(!(cp = get_photo(photoset, photo))) {
        pthread_rwlock_unlock(&cache_lock);
        return FAIL;
    }

    cp->ci.size = newsize;
    pthread_rwlock_unlock(&cache_lock);

    return SUCCESS;
}

int set_photo_dirty(const char *photoset, const char *photo, unsigned short dirty) {
    cached_photo *cp;

    pthread_rwlock_wrlock(&cache_lock);
    if(!(cp = get_photo(photoset, photo))) {
        pthread_rwlock_unlock(&cache_lock);
        return FAIL;
    }

    cp->ci.dirty = dirty;
    pthread_rwlock_unlock(&cache_lock);

    return SUCCESS;
}

int get_photo_dirty(const char *photoset, const char *photo) {
    cached_photo *cp;
    unsigned short dirty;

    pthread_rwlock_rdlock(&cache_lock);
    if(!(cp = get_photo(photoset, photo))) {
        pthread_rwlock_unlock(&cache_lock);
        return FAIL;
    }
    dirty = cp->ci.dirty;
    pthread_rwlock_unlock(&cache_lock);

    return dirty;
}

int create_empty_photoset(const char *photoset) {
    cached_photoset *cps;
    int retval = FAIL;

    pthread_rwlock_wrlock(&cache_lock);

    if(g_hash_table_lookup(photoset_ht, photoset))
        goto fail;

    /* The new empty photoset */
    if(!(cps = create_cached_photoset()))
        goto fail;

    cps->ci.name = strdup(photoset);
    cps->ci.id = strdup("");
    cps->ci.dirty = DIRTY;
    cps->ci.time = time(NULL);
    cps->set = CACHE_SET;
    cps->photo_ht = create_cache();

    g_hash_table_insert(photoset_ht, strdup(cps->ci.name), cps);

    retval = SUCCESS;

fail: pthread_rwlock_unlock(&cache_lock);
    return retval;
}

int create_empty_photo(const char *photoset, const char *photo) {
    cached_photoset *cps;
    cached_photo *cp;
    int retval = FAIL;

    pthread_rwlock_wrlock(&cache_lock);

    cps = g_hash_table_lookup(photoset_ht, photoset);

    /* Check to see photoset exists. */
    if(!cps)
        goto fail;

   /* Check if photo already exists */
    if(g_hash_table_lookup(cps->photo_ht, photo))
        goto fail;

    /* The new empty photo */
    if(!(cp = create_cached_photo()))
        goto fail;

    cp->ci.name = strdup(photo);
    cp->ci.id = strdup("");
    cp->ci.dirty = DIRTY;
    cp->ci.time = time(NULL);
    cp->ci.size = PHOTO_SIZE_UNSET;

    g_hash_table_insert(cps->photo_ht, strdup(cp->ci.name), cp);

    retval = SUCCESS;

fail: pthread_rwlock_unlock(&cache_lock);
    return retval;
}

int upload_photo(const char *photoset, const char *photo, const char *path) {
    flickcurl_upload_status* status;
    flickcurl_upload_params params;
    cached_photoset *cps;
    cached_photo *cp;
    int retval = FAIL;

    pthread_rwlock_wrlock(&cache_lock);

    cps = g_hash_table_lookup(photoset_ht, photoset);

    if(!cps)
        goto fail;

    if(!(cp = g_hash_table_lookup(cps->photo_ht, photo)))
        goto fail;

    memset(&params, '\0', sizeof(flickcurl_upload_params));
    params.safety_level = SAFETY_LEVEL;    /* default safety */
    params.content_type = CONTENT_TYPE;    /* default photo */
    params.photo_file = path;
    params.title = cp->ci.name;

    status = flickcurl_photos_upload_params(fc, &params);

    if(status) {
        if(cps->ci.dirty == DIRTY) { // if photoset is dirty, create it
            char * photosetid = flickcurl_photosets_create(fc, cps->ci.name, NULL, status->photoid, NULL);

            if(photosetid) {
                cps->ci.id = photosetid;
                cps->ci.dirty = CLEAN;
            }
        }
        else if(strcmp(cps->ci.id, "")) { // if photoset has an id, add new photo to it
            flickcurl_photosets_addPhoto(fc, cps->ci.id, status->photoid);
        }

        flickcurl_free_upload_status(status);
    }

    cp->ci.dirty = CLEAN;

    cps->set = CACHE_UNSET;

    retval = SUCCESS;

fail: pthread_rwlock_unlock(&cache_lock);
    return retval;
}

int set_photo_photoset(const char *photoset, const char *photo, const char *new_photoset) {
    cached_photoset *cps;
    cached_photoset *new_cps;
    cached_photo *cp;
    int retval = FAIL;

    pthread_rwlock_wrlock(&cache_lock);

    cps = g_hash_table_lookup(photoset_ht, photoset);
    new_cps = g_hash_table_lookup(photoset_ht, new_photoset);

    if(!cps || !new_cps)
        goto fail;

    if(!(cp = g_hash_table_lookup(cps->photo_ht, photo)))
        goto fail;

    if(strcmp(cps->ci.id, "")) {
        flickcurl_photosets_removePhoto(fc, cps->ci.id, cp->ci.id);
    }

    if(strcmp(new_cps->ci.id, "")) {
        flickcurl_photosets_addPhoto(fc, new_cps->ci.id, cp->ci.id);
    }

    g_hash_table_foreach_remove(cps->photo_ht, free_photo_ht, NULL);
    g_hash_table_foreach_remove(new_cps->photo_ht, free_photo_ht, NULL);

    cps->set = CACHE_UNSET;
    new_cps->set = CACHE_UNSET;

    retval = SUCCESS;

fail: pthread_rwlock_unlock(&cache_lock);
    return retval;
}

int remove_photo_from_cache(const char *photoset, const char *photo) {
    void *key, *value;
    cached_photoset *cps;
    cached_photo *cp;
    int retval = FAIL;

    pthread_rwlock_wrlock(&cache_lock);

    if(!(cps = g_hash_table_lookup(photoset_ht, photoset)))
        goto fail;

    if(g_hash_table_lookup_extended(cps->photo_ht, photo, &key, &value)) {
        cp = value;

        if(cp->ci.dirty) {
            g_hash_table_remove(cps->photo_ht, photo);

            free(cp->ci.uri);
            free(cp->ci.name);
            free(cp->ci.id);
            free(key);
            free(value);

            retval = SUCCESS;
        }
    }

fail: pthread_rwlock_unlock(&cache_lock);
    return retval;
}

int photoDelete(char *photo_id) {
    return flickcurl_photos_delete(fc, photo_id);
}


text:
package db

import "gopkg.in/mgo.v2"

// Mongo contains the mongo connection info
type Mongo struct {
	URL            string
	Database       string
	CollectionName string
}

// Collection returns the goreportcard mongo collection
func (db *Mongo) Collection() (*mgo.Collection, error) {
	session, err := mgo.Dial(db.URL)
	if err != nil {
		return nil, err
	}
	c := session.DB(db.Database).C(db.CollectionName)

	return c, nil
}


text:
require('./bootstrap');

$('#login-dropdown').click(function(){
    //if navbar is collapsed need to scroll up the options
    if($('.navbar-toggle').attr('aria-expanded') == 'true'){
        //Do scroll
        //TODO
    }
});


text:
package com.lc.m;

public class SwapNodesInPairs {
    public ListNode swapPairs(ListNode head) {
        if(head == null) return null;

        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode prev = dummy;
        ListNode first = head;
        ListNode second = head.next;

        while(first != null && second != null) {
        	first.next = second.next;
        	second.next = first;
        	prev.next = second;

        	prev = first;
        	first = first.next;
        	if(first == null) break;
        	second = first.next;
        }
        return dummy.next;
    }
}


text:
TV Script Generation

In this project, you'll generate your own Simpsons TV scripts using RNNs.  You'll be using part of the Simpsons dataset of scripts from 27 seasons.  The Neural Network you'll build will generate a new TV script for a scene at Moe's Tavern.

Get the Data

The data is already provided for you.  You'll be using a subset of the original dataset.  It consists of only the scenes in Moe's Tavern.  This doesn't include other versions of the tavern, like "Moe's Cavern", "Flaming Moe's", "Uncle Moe's Family Feed-Bag", etc..

"""
DON'T MODIFY ANYTHING IN THIS CELL
"""
import helper

data_dir = './data/simpsons/moes_tavern_lines.txt'
text = helper.load_data(data_dir)
# Ignore notice, since we don't use it for analysing the data
text = text[81:]

Explore the Data

Play around with view_sentence_range to view different parts of the data.

view_sentence_range = (0, 10)

"""
DON'T MODIFY ANYTHING IN THIS CELL
"""
import numpy as np

print('Dataset Stats')
print('Roughly the number of unique words: {}'.format(len({word: None for word in text.split()})))
scenes = text.split('\n\n')
print('Number of scenes: {}'.format(len(scenes)))
sentence_count_scene = [scene.count('\n') for scene in scenes]
print('Average number of sentences in each scene: {}'.format(np.average(sentence_count_scene)))

sentences = [sentence for scene in scenes for sentence in scene.split('\n')]
print('Number of lines: {}'.format(len(sentences)))
word_count_sentence = [len(sentence.split()) for sentence in sentences]
print('Average number of words in each line: {}'.format(np.average(word_count_sentence)))

print()
print('The sentences {} to {}:'.format(*view_sentence_range))
print('\n'.join(text.split('\n')[view_sentence_range[0]:view_sentence_range[1]]))

Dataset Stats
Roughly the number of unique words: 11492
Number of scenes: 262
Average number of sentences in each scene: 15.251908396946565
Number of lines: 4258
Average number of words in each line: 11.50164396430249

The sentences 0 to 10:

Moe_Szyslak: (INTO PHONE) Moe's Tavern. Where the elite meet to drink.
Bart_Simpson: Eh, yeah, hello, is Mike there? Last name, Rotch.
Moe_Szyslak: (INTO PHONE) Hold on, I'll check. (TO BARFLIES) Mike Rotch. Mike Rotch. Hey, has anybody seen Mike Rotch, lately?
Moe_Szyslak: (INTO PHONE) Listen you little puke. One of these days I'm gonna catch you, and I'm gonna carve my name on your back with an ice pick.
Moe_Szyslak: What's the matter Homer? You're not your normal effervescent self.
Homer_Simpson: I got my problems, Moe. Give me another one.
Moe_Szyslak: Homer, hey, you should not drink to forget your problems.
Barney_Gumble: Yeah, you should only drink to enhance your social skills.

Implement Preprocessing Functions

The first thing to do to any dataset is preprocessing.  Implement the following preprocessing functions below:

Lookup Table

Tokenize Punctuation

Lookup Table

To create a word embedding, you first need to transform the words to ids.  In this function, create two dictionaries:

Dictionary to go from the words to an id, we'll call vocab_to_int

Dictionary to go from the id to word, we'll call int_to_vocab

Return these dictionaries in the following tuple (vocab_to_int, int_to_vocab)

import numpy as np
import problem_unittests as tests
from collections import Counter

def create_lookup_tables(text):
    """
    Create lookup tables for vocabulary
    :param text: The text of tv scripts split into words
    :return: A tuple of dicts (vocab_to_int, int_to_vocab)
    """
    # TODO: Implement Function
    counts = Counter(text)
    vocab = sorted(counts, key=counts.get, reverse=True)
    vocab_to_int = {word: ii for ii, word in enumerate(vocab, 1)}
    int_to_vocab = {ii: word for word, ii in vocab_to_int.items()}
    return vocab_to_int, int_to_vocab

"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
tests.test_create_lookup_tables(create_lookup_tables)

Tests Passed

Tokenize Punctuation

We'll be splitting the script into a word array using spaces as delimiters.  However, punctuations like periods and exclamation marks make it hard for the neural network to distinguish between the word "bye" and "bye!".

Implement the function token_lookup to return a dict that will be used to tokenize symbols like "!" into "||Exclamation_Mark||".  Create a dictionary for the following symbols where the symbol is the key and value is the token:

Period ( . )

Comma ( , )

Quotation Mark ( " )

Semicolon ( ; )

Exclamation mark ( ! )

Question mark ( ? )

Left Parentheses ( ( )

Right Parentheses ( ) )

Dash ( – )

Return ( \n )

      This dictionary will be used to token the symbols and add the delimiter (space) around it.  This separates the symbols as it's own word, making it easier for the neural network to predict on the next word. Make sure you don't use a token that could be confused as a word. Instead of using the token "dash", try using something like "

      dash

      ".

def token_lookup():
    """
    Generate a dict to turn punctuation into a token.
    :return: Tokenize dictionary where the key is the punctuation and the value is the token
    """
    # TODO: Implement Function
    punct_dist ={
        '.': 'period', ',': 'comma', '"': 'quotationmark',';': 'semicolon', '!': 'exclamation_mark', '?': 'question_mark', '(': 'left_parentheses', ')': 'right_parentheses',
        '--': 'dash', '\n': 'return'}
    return punct_dist

"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
tests.test_tokenize(token_lookup)

Tests Passed

Preprocess all the data and save it

Running the code cell below will preprocess all the data and save it to file.

"""
DON'T MODIFY ANYTHING IN THIS CELL
"""
# Preprocess Training, Validation, and Testing Data
helper.preprocess_and_save_data(data_dir, token_lookup, create_lookup_tables)

Check Point

This is your first checkpoint. If you ever decide to come back to this notebook or have to restart the notebook, you can start from here. The preprocessed data has been saved to disk.

"""
DON'T MODIFY ANYTHING IN THIS CELL
"""
import helper
import numpy as np
import problem_unittests as tests

int_text, vocab_to_int, int_to_vocab, token_dict = helper.load_preprocess()

Build the Neural Network

You'll build the components necessary to build a RNN by implementing the following functions below:

get_inputs

get_init_cell

get_embed

build_rnn

build_nn

get_batches

Check the Version of TensorFlow and Access to GPU

"""
DON'T MODIFY ANYTHING IN THIS CELL
"""
from distutils.version import LooseVersion
import warnings
import tensorflow as tf

# Check TensorFlow Version
assert LooseVersion(tf.__version__) >= LooseVersion('1.0'), 'Please use TensorFlow version 1.0 or newer'
print('TensorFlow Version: {}'.format(tf.__version__))

# Check for a GPU
if not tf.test.gpu_device_name():
    warnings.warn('No GPU found. Please use a GPU to train your neural network.')
else:
    print('Default GPU Device: {}'.format(tf.test.gpu_device_name()))

TensorFlow Version: 1.0.1
Default GPU Device: /gpu:0

Input

Implement the get_inputs() function to create TF Placeholders for the Neural Network.  It should create the following placeholders:

Input text placeholder named "input" using the TF Placeholder name parameter.

Targets placeholder

Learning Rate placeholder

Return the placeholders in the following the tuple (Input, Targets, LearingRate)

def get_inputs():
    """
    Create TF Placeholders for input, targets, and learning rate.
    :return: Tuple (input, targets, learning rate)
    """
    # TODO: Implement Function
    inputs = tf.placeholder(tf.int32, shape=(None, None), name= 'input')
    targets = tf.placeholder(tf.int32, shape=(None, None), name= 'targets')
    learning_rate = tf.placeholder(tf.float32, name= 'learning_rate')
    return (inputs, targets, learning_rate)

"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
tests.test_get_inputs(get_inputs)

Tests Passed

Build RNN Cell and Initialize

Stack one or more BasicLSTMCells in a MultiRNNCell.

The Rnn size should be set using rnn_size

Initalize Cell State using the MultiRNNCell's zero_state() function

Apply the name "initial_state" to the initial state using tf.identity()

Return the cell and initial state in the following tuple (Cell, InitialState)

def get_init_cell(batch_size, rnn_size):
    """
    Create an RNN Cell and initialize it.
    :param batch_size: Size of batches
    :param rnn_size: Size of RNNs
    :return: Tuple (cell, initialize state)
    """
    # TODO: Implement Function
    lstm_layers = 2
    lstm = tf.contrib.rnn.BasicLSTMCell(rnn_size)
    # Add dropout to the cell
    drop = tf.contrib.rnn.DropoutWrapper(lstm, output_keep_prob=0.5)
    cell = tf.contrib.rnn.MultiRNNCell([drop] * lstm_layers)
    #cell = tf.contrib.rnn.MultiRNNCell([lstm] * lstm_layers)
    initial_state = cell.zero_state(batch_size, tf.float32)
    initial_state = tf.identity(initial_state, name='initial_state')
    return (cell, initial_state)

"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
tests.test_get_init_cell(get_init_cell)

Tests Passed

Word Embedding

Apply embedding to input_data using TensorFlow.  Return the embedded sequence.

def get_embed(input_data, vocab_size, embed_dim):
    """
    Create embedding for <input_data>.
    :param input_data: TF placeholder for text input.
    :param vocab_size: Number of words in vocabulary.
    :param embed_dim: Number of embedding dimensions
    :return: Embedded input.
    """
    # TODO: Implement Function
    embedding = tf.Variable(tf.random_uniform((vocab_size, embed_dim), -1, 1))
    embed = tf.nn.embedding_lookup(embedding, input_data)
    return embed

"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
tests.test_get_embed(get_embed)

Tests Passed

Build RNN

You created a RNN Cell in the get_init_cell() function.  Time to use the cell to create a RNN.

Build the RNN using the tf.nn.dynamic_rnn()

Apply the name "final_state" to the final state using tf.identity()

Return the outputs and final_state state in the following tuple (Outputs, FinalState)

def build_rnn(cell, inputs):
    """
    Create a RNN using a RNN Cell
    :param cell: RNN Cell
    :param inputs: Input text data
    :return: Tuple (Outputs, Final State)
    """
    # TODO: Implement Function
    outputs, final_state = tf.nn.dynamic_rnn(cell, inputs, dtype=tf.float32)
    final_state = tf.identity(final_state, name="final_state")
    return outputs, final_state

"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
tests.test_build_rnn(build_rnn)

Tests Passed

Build the Neural Network

Apply the functions you implemented above to:

Apply embedding to input_data using your get_embed(input_data, vocab_size, embed_dim) function.

Build RNN using cell and your build_rnn(cell, inputs) function.

Apply a fully connected layer with a linear activation and vocab_size as the number of outputs.

Return the logits and final state in the following tuple (Logits, FinalState)

def build_nn(cell, rnn_size, input_data, vocab_size):
    """
    Build part of the neural network
    :param cell: RNN cell
    :param rnn_size: Size of rnns
    :param input_data: Input data
    :param vocab_size: Vocabulary size
    :return: Tuple (Logits, FinalState)
    """
    # TODO: Implement Function
    embedding = get_embed(input_data, vocab_size, rnn_size)
    outputs, final_state = build_rnn(cell, embedding)
    weight = tf.truncated_normal_initializer(stddev = 0.01)
    bias= tf.zeros_initializer()
    predictions = tf.contrib.layers.fully_connected(outputs,
                                                        vocab_size,
                                                        weights_initializer = weight,
                                                        biases_initializer=bias,
                                                        activation_fn=None)
    #predictions = tf.contrib.layers.fully_connected(outputs, vocab_size, activation_fn=None)
    return predictions, final_state

"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
tests.test_build_nn(build_nn)

Tests Passed

Batches

Implement get_batches to create batches of input and targets using int_text.  The batches should be a Numpy array with the shape (number of batches, 2, batch size, sequence length). Each batch contains two elements:

The first element is a single batch of input with the shape [batch size, sequence length]

The second element is a single batch of targets with the shape [batch size, sequence length]

If you can't fill the last batch with enough data, drop the last batch.

For exmple, get_batches([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], 2, 3) would return a Numpy array of the following:

[
  # First Batch
  [
    # Batch of Input
    [[ 1  2  3], [ 7  8  9]],
    # Batch of targets
    [[ 2  3  4], [ 8  9 10]]
  ],

  # Second Batch
  [
    # Batch of Input
    [[ 4  5  6], [10 11 12]],
    # Batch of targets
    [[ 5  6  7], [11 12 13]]
  ]
]

def get_batches(int_text, batch_size, seq_length):
    """
    Return batches of input and target
    :param int_text: Text with the words replaced by their ids
    :param batch_size: The size of batch
    :param seq_length: The length of sequence
    :return: Batches as a Numpy array
    """
    # TODO: Implement Function
    num_batch = len(int_text) // ( seq_length *batch_size)
    batches = np.empty((num_batch ,2, batch_size, seq_length))
    for i in range(len(batches)):
        for j in range(batch_size):
            start_idx = (i * seq_length)+j
            end_idx = start_idx + seq_length
            if end_idx <= (len(int_text) -1):
                batches[i][0][j] = int_text[ start_idx: end_idx]
            start_idx = start_idx + seq_length*2
            end_idx = end_idx +  seq_length+ seq_length
            if end_idx <= (len(int_text) -1):
                batches[i][1][j] = int_text[ start_idx: end_idx]
    return batches

"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
tests.test_get_batches(get_batches)

Tests Passed

Neural Network Training

Hyperparameters

Tune the following parameters:

Set num_epochs to the number of epochs.

Set batch_size to the batch size.

Set rnn_size to the size of the RNNs.

Set seq_length to the length of sequence.

Set learning_rate to the learning rate.

Set show_every_n_batches to the number of batches the neural network should print progress.

# Number of Epochs
num_epochs = 50
# Batch Size
batch_size = 256
# RNN Size
rnn_size = 512
# Sequence Length
seq_length = 15
# Learning Rate
learning_rate = 0.01
# Show stats for every n number of batches
show_every_n_batches = 100

"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
save_dir = './save'

Build the Graph

Build the graph using the neural network you implemented.

"""
DON'T MODIFY ANYTHING IN THIS CELL
"""
from tensorflow.contrib import seq2seq

train_graph = tf.Graph()
with train_graph.as_default():
    vocab_size = len(int_to_vocab)
    input_text, targets, lr = get_inputs()
    input_data_shape = tf.shape(input_text)
    cell, initial_state = get_init_cell(input_data_shape[0], rnn_size)
    logits, final_state = build_nn(cell, rnn_size, input_text, vocab_size)

    # Probabilities for generating words
    probs = tf.nn.softmax(logits, name='probs')

    # Loss function
    cost = seq2seq.sequence_loss(
        logits,
        targets,
        tf.ones([input_data_shape[0], input_data_shape[1]]))

    # Optimizer
    optimizer = tf.train.AdamOptimizer(lr)

    # Gradient Clipping
    gradients = optimizer.compute_gradients(cost)
    capped_gradients = [(tf.clip_by_value(grad, -1., 1.), var) for grad, var in gradients]
    train_op = optimizer.apply_gradients(capped_gradients)

Train

Train the neural network on the preprocessed data.  If you have a hard time getting a good loss, check the forms to see if anyone is having the same problem.

"""
DON'T MODIFY ANYTHING IN THIS CELL
"""
batches = get_batches(int_text, batch_size, seq_length)

with tf.Session(graph=train_graph) as sess:
    sess.run(tf.global_variables_initializer())

    for epoch_i in range(num_epochs):
        state = sess.run(initial_state, {input_text: batches[0][0]})

        for batch_i, (x, y) in enumerate(batches):
            feed = {
                input_text: x,
                targets: y,
                initial_state: state,
                lr: learning_rate}
            train_loss, state, _ = sess.run([cost, final_state, train_op], feed)

            # Show every <show_every_n_batches> batches
            if (epoch_i * len(batches) + batch_i) % show_every_n_batches == 0:
                print('Epoch {:>3} Batch {:>4}/{}   train_loss = {:.3f}'.format(
                    epoch_i,
                    batch_i,
                    len(batches),
                    train_loss))

    # Save Model
    saver = tf.train.Saver()
    saver.save(sess, save_dir)
    print('Model Trained and Saved')

Epoch   0 Batch    0/17   train_loss = 8.821
Epoch   5 Batch   15/17   train_loss = 1.469
Epoch  11 Batch   13/17   train_loss = 0.182
Epoch  17 Batch   11/17   train_loss = 0.149
Epoch  23 Batch    9/17   train_loss = 0.134
Epoch  29 Batch    7/17   train_loss = 0.129
Epoch  35 Batch    5/17   train_loss = 0.136
Epoch  41 Batch    3/17   train_loss = 0.155
Epoch  47 Batch    1/17   train_loss = 0.167
Model Trained and Saved

Save Parameters

Save seq_length and save_dir for generating a new TV script.

"""
DON'T MODIFY ANYTHING IN THIS CELL
"""
# Save parameters for checkpoint
helper.save_params((seq_length, save_dir))

Checkpoint

"""
DON'T MODIFY ANYTHING IN THIS CELL
"""
import tensorflow as tf
import numpy as np
import helper
import problem_unittests as tests

_, vocab_to_int, int_to_vocab, token_dict = helper.load_preprocess()
seq_length, load_dir = helper.load_params()

Implement Generate Functions

Get Tensors

Get tensors from loaded_graph using the function get_tensor_by_name().  Get the tensors using the following names:

"input:0"

"initial_state:0"

"final_state:0"

"probs:0"

Return the tensors in the following tuple (InputTensor, InitialStateTensor, FinalStateTensor, ProbsTensor)

def get_tensors(loaded_graph):
    """
    Get input, initial state, final state, and probabilities tensor from <loaded_graph>
    :param loaded_graph: TensorFlow graph loaded from file
    :return: Tuple (InputTensor, InitialStateTensor, FinalStateTensor, ProbsTensor)
    """
    # TODO: Implement Function
    input_tensor = loaded_graph.get_tensor_by_name('input:0')
    initial_state_tensor = loaded_graph.get_tensor_by_name('initial_state:0')
    final_state_tensor = loaded_graph.get_tensor_by_name('final_state:0')
    probs_tensor = loaded_graph.get_tensor_by_name('probs:0')
    return input_tensor, initial_state_tensor, final_state_tensor, probs_tensor

"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
tests.test_get_tensors(get_tensors)

Tests Passed

Choose Word

Implement the pick_word() function to select the next word using probabilities.

def pick_word(probabilities, int_to_vocab):
    """
    Pick the next word in the generated text
    :param probabilities: Probabilites of the next word
    :param int_to_vocab: Dictionary of word ids as the keys and words as the values
    :return: String of the predicted word
    """
    # TODO: Implement Function
    word_id = np.random.choice(len(probabilities), p=probabilities)
    return int_to_vocab[word_id]

"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
tests.test_pick_word(pick_word)

Tests Passed

Generate TV Script

This will generate the TV script for you.  Set gen_length to the length of TV script you want to generate.

gen_length = 200
# homer_simpson, moe_szyslak, or Barney_Gumble
prime_word = 'moe_szyslak'

"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
loaded_graph = tf.Graph()
with tf.Session(graph=loaded_graph) as sess:
    # Load saved model
    loader = tf.train.import_meta_graph(load_dir + '.meta')
    loader.restore(sess, load_dir)

    # Get Tensors from loaded model
    input_text, initial_state, final_state, probs = get_tensors(loaded_graph)

    # Sentences generation setup
    gen_sentences = [prime_word + ':']
    prev_state = sess.run(initial_state, {input_text: np.array([[1]])})

    # Generate sentences
    for n in range(gen_length):
        # Dynamic Input
        dyn_input = [[vocab_to_int[word] for word in gen_sentences[-seq_length:]]]
        dyn_seq_length = len(dyn_input[0])

        # Get Prediction
        probabilities, prev_state = sess.run(
            [probs, final_state],
            {input_text: dyn_input, initial_state: prev_state})

        pred_word = pick_word(probabilities[dyn_seq_length-1], int_to_vocab)

        gen_sentences.append(pred_word)

    # Remove tokens
    tv_script = ' '.join(gen_sentences)
    for key, token in token_dict.items():
        ending = ' ' if key in ['\n', '(', '"'] else ''
        tv_script = tv_script.replace(' ' + token.lower(), key)
    tv_script = tv_script.replace('\n ', '\n')
    tv_script = tv_script.replace('( ', '(')

    print(tv_script)

moe_szyslak:, couldn't for for be. a belch job, how's chuckles matter what i so i total sits right-handed lisa_simpson: follow neat follow around.

belch oh one county me another skills just end i sits! this end my, chocolate he's tomorrow i. a homer_simpson: yeah.

barney_gumble:. moe_szyslak:
homer_simpson: pretty i all mike excuse milk just a too.
belch oh one depressin' on)

didn't the has you next to had excuse tick. i follow around me! what's hey, right milk i him have me be.((
((
barney_gumble:. homer moe_szyslak: moe_szyslak: moe_szyslak: moe_szyslak: moe_szyslak: moe_szyslak: moe_szyslak:) moe_szyslak: moe_szyslak: i into moe_szyslak: moe_szyslak: i just corkscrews! this are good profiling to, mike hey, i'm chuckles matter you that he end you the, ah.
barney_gumble:)
moe_szyslak: moe_szyslak: moe_szyslak: moe_szyslak: i so i dunno the tomorrow you the,, the has, carve problems a your forget, my, how's chuckles skills for would just. a belch job, isn't

belch oh.(

The TV Script is Nonsensical

It's ok if the TV script doesn't make any sense.  We trained on less than a megabyte of text.  In order to get good results, you'll have to use a smaller vocabulary or get more data.  Luckly there's more data!  As we mentioned in the begging of this project, this is a subset of another dataset.  We didn't have you train on all the data, because that would take too long.  However, you are free to train your neural network on all the data.  After you complete the project, of course.

Submitting This Project

When submitting this project, make sure to run all the cells before saving the notebook. Save the notebook file as "dlnd_tv_script_generation.ipynb" and save it as a HTML file under "File" -> "Download as". Include the "helper.py" and "problem_unittests.py" files in your submission.


text:
package org.apache.hadoop.hbase.client;

import java.io.IOException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseTestingUtility;
import org.apache.hadoop.hbase.MediumTests;
import org.apache.hadoop.hbase.MultithreadedTestUtil;
import org.apache.hadoop.hbase.MultithreadedTestUtil.RepeatingTestThread;
import org.apache.hadoop.hbase.ZooKeeperConnectionException;
import org.apache.hadoop.hbase.client.HConnectionManager.HConnectionImplementation;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.zookeeper.ZooKeeperWatcher;
import org.apache.zookeeper.KeeperException;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.experimental.categories.Category;

/**
 * Various tests of using HConnection
 */
@Category(MediumTests.class)
public class TestHConnection {
  final Log LOG = LogFactory.getLog(getClass());
  private final static HBaseTestingUtility TEST_UTIL = new HBaseTestingUtility();
  private final long MILLIS_TO_WAIT_FOR_RACE = 1000;

  /**
   * @throws java.lang.Exception
   */
  @BeforeClass
  public static void setUpBeforeClass() throws Exception {
    TEST_UTIL.startMiniCluster();
  }

  /**
   * @throws java.lang.Exception
   */
  @AfterClass
  public static void tearDownAfterClass() throws Exception {
    TEST_UTIL.shutdownMiniCluster();
  }

  /**
   * Thread that periodically aborts the connection
   */
  class AbortThread extends RepeatingTestThread {
    final HConnection connection;

    public AbortThread(MultithreadedTestUtil.TestContext ctx, HConnection connection) {
      super(ctx);
      this.connection = connection;
    }

    @Override
    public void doAnAction() throws IOException {
      connection.abort("test session expired", new KeeperException.SessionExpiredException());
    }
  };

  class HConnectionRaceTester extends HConnectionImplementation {
    public HConnectionRaceTester(Configuration configuration, boolean managed) throws ZooKeeperConnectionException {
      super(configuration, managed, null);
    }

    /**
     * Sleep after calling getZookeeperWatcher to attempt to trigger a race condition.
     * If the HConnection retrieves the ZooKeeperWatcher but does not cache the value,
     * by the time the new watcher is used, it could be null if the connection was aborted.
     * This sleep will increase the time between when the watcher is retrieved and when it is used.
     */
    public ZooKeeperWatcher getZooKeeperWatcher() throws ZooKeeperConnectionException {
      ZooKeeperWatcher zkw = super.getZooKeeperWatcher();
      try {
        Thread.sleep(10);
      } catch (InterruptedException ie) {
        // Ignore
      }
      return zkw;
    }
  }

  /**
   * Test that a connection that is aborted while calling isTableDisabled doesn't NPE
   */
  @Test
  public void testTableDisabledRace() throws Exception {
    final HConnection connection = new HConnectionRaceTester(TEST_UTIL.getConfiguration(), true);
    MultithreadedTestUtil.TestContext ctx =
      new MultithreadedTestUtil.TestContext(TEST_UTIL.getConfiguration());
    RepeatingTestThread disabledChecker = new RepeatingTestThread(ctx) {
      @Override
      public void doAnAction() throws IOException {
        try {
          connection.isTableDisabled(Bytes.toBytes("tableToCheck"));
        } catch (IOException ioe) {
          // Ignore.  ZK can legitimately fail, only care if we get a NullPointerException
        }
      }
    };
    AbortThread abortThread = new AbortThread(ctx, connection);

    ctx.addThread(disabledChecker);
    ctx.addThread(abortThread);
    ctx.startThreads();
    ctx.waitFor(MILLIS_TO_WAIT_FOR_RACE);
    ctx.stop();
  }

  /**
   * Test that a connection that is aborted while calling getCurrentNrNRS doesn't NPE
   */
  @Test
  public void testGetCurrentNrHRSRace() throws Exception {
    final HConnection connection = new HConnectionRaceTester(TEST_UTIL.getConfiguration(), true);
    MultithreadedTestUtil.TestContext ctx =
      new MultithreadedTestUtil.TestContext(TEST_UTIL.getConfiguration());
    RepeatingTestThread getCurrentNrHRSCaller = new RepeatingTestThread(ctx) {
      @Override
      public void doAnAction() throws IOException {
        try {
          connection.getCurrentNrHRS();
        } catch (IOException ioe) {
          // Ignore.  ZK can legitimately fail, only care if we get a NullPointerException
        }
      }
    };
    AbortThread abortThread = new AbortThread(ctx, connection);

    ctx.addThread(getCurrentNrHRSCaller);
    ctx.addThread(abortThread);
    ctx.startThreads();
    ctx.waitFor(MILLIS_TO_WAIT_FOR_RACE);
    ctx.stop();
  }

  @org.junit.Rule
  public org.apache.hadoop.hbase.ResourceCheckerJUnitRule cu =
    new org.apache.hadoop.hbase.ResourceCheckerJUnitRule();
}


text:
require File.expand_path(File.join(File.dirname(__FILE__), 'spec_helper'))

describe DataObjects::Connection do
  before do
    @connection = DataObjects::Connection.new('mock://localhost')
  end

  after do
    @connection.release
  end

  %w{dispose create_command}.each do |meth|
    it "should respond to ##{meth}" do
      @connection.should.respond_to(meth.intern)
    end
  end

  it "should have #to_s that returns the connection uri string" do
    @connection.to_s.should == 'mock://localhost'
  end

  describe "initialization" do

    it "should accept a connection uri as a Addressable::URI" do
      c = DataObjects::Connection.new(Addressable::URI::parse('mock://localhost/database'))
      # relying on the fact that mock connection sets @uri
      c.to_s.should == 'mock://localhost/database'
    end

    it "should return the Connection specified by the scheme" do
      c = DataObjects::Connection.new(Addressable::URI.parse('mock://localhost/database'))
      c.should.be.kind_of(DataObjects::Mock::Connection)
      c.should.be.kind_of(DataObjects::Pooling)
    end

    it "should return the Connection specified by the scheme without pooling" do
      c = DataObjects::Connection.new(Addressable::URI.parse('java://jdbc/database?scheme=mock2'))
      c.should.not.be.kind_of(DataObjects::Pooling)
    end
  end
end


text:
package edu.towson.cis.cosc603.project2.monopoly.gui;

import java.awt.GridLayout;

import javax.swing.JPanel;

import edu.towson.cis.cosc603.project2.monopoly.GameMaster;

// TODO: Auto-generated Javadoc
/**
 * The Class InfoPanel.
 */
public class InfoPanel extends JPanel {

	/** The Constant serialVersionUID. */
	private static final long serialVersionUID = 1L;

	/**
	 * Display info.
	 */
	public void displayInfo() {
		GameMaster master = GameMaster.instance();
		setLayout(new GridLayout(1, master.getNumberOfPlayers()));
		for (int i = 0; i< master.getNumberOfPlayers(); i++){
			PlayerPanel panel = new PlayerPanel(master.getPlayer(i));
			add(panel);
			panel.displayInfo();
		}
	}
}


text:
<?php
if (isset($_GET['i'])){ //Thumbs
	$filename = $_GET['i'];
	$size = $_GET['size'];
	//Path info
	$path = explode(".", $_GET['i']); //Array of the Path + Extension
	$ext = array_pop($path); // File Extension
	$thumb = '../../' . implode($path); //Path minus extension - Ends in /
	if(!file_exists($thumb."_tn_".$size.".".$ext)) {
		// Set a maximum height and width
		$width  = $size;
		$height = $size;
		// Get new dimensions
		list($width_orig, $height_orig) = getimagesize($filename);
		if ($width && ($width_orig < $height_orig)) {
			$width = ($height / $height_orig) * $width_orig;
		} else {
			$height = ($width / $width_orig) * $height_orig;
		}
		// Resample
		$image_p = imagecreatetruecolor($width, $height);
		$image   = imagecreatefromjpeg($filename);
		imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
		// Output
		imagejpeg($image_p, $thumb."_tn_".$size.".".$ext);
		imagedestroy($image);
		imageDestroy($image_p);
	}
	// Content type
	header('Content-type: image/jpeg');
	$fp = fopen($thumb."_tn_".$size.".".$ext, "r");
	echo fread($fp, filesize($thumb."_tn_".$size.".".$ext));
	fclose($fp);
}elseif (isset($_GET['path'])){ //Stripes
	$path = '../../' . $_GET['path'];
	$width = $_GET['width'];
	$height = $_GET['height'];
	//Look for images in directory
	$images = array();
	$dir = dir($path);
	while($file = $dir->read()) {
		if($file != "." && $file != ".." && $file != ".svn" && !preg_match('/_tn_/', $file)) {
			array_push($images, $file);
	  	}
	}
	$dir->close();
	$cachename = $path.'/cache_tn_'.md5(join('', $images))."_".$width."_".$height.".jpg";
	if(!file_exists($cachename)) {
		$stripe = imagecreatetruecolor($width * count($images), $height);

		$i = 0;
		foreach($images as $filename) {
			$image   = imagecreatefromjpeg($path."/".$filename);
			imagecopyresampled($stripe, $image, $i++ * $width, 0, 0, 0, $width, $height, imagesx($image), imagesy($image));
		}

		imagejpeg($stripe, $cachename);
		imagedestroy($stripe);
	}
	// Content type
	header('Content-type: image/jpeg');
	readfile($cachename);
}
?>


text:
import datetime
import os
import pprint
import re
import time
import urllib2

from   bs4 import BeautifulSoup

def make_soup(url):
    try:
        output = urllib2.urlopen(url)
        html   = ''.join(output.readlines())
    except urllib2.HTTPError as ex:
        html = ''
        print 'x ',
    return BeautifulSoup(html)

def available_tickets(paralympics=False):
    result = []
    sports = {
        'olympics' : {
                'Athletics'             : 8194,
                'Basketball'            : 8198,
                'Canoe slalom'          : 8202,
                'Cycling - track'       : 8209,
                'Diving'                : 8210,
                'Gymnastics - artistic' : 8216,
                'Gymnastics - rhythmic' : 8217,
                'Hockey'                : 8219,
                'Olympic park'          : 8269,
                'Swimming'              : 8225,
                'Volleyball'            : 8232,
                'Waterpolo'             : 8233,
            },
        'paralympics' : {
                'Athletics'             : 8247,
                'Closing ceremony'      : 8267,
                'Opening ceremony'      : 8266,
            }
        }

    summary_template_url = 'http://www.tickets.london2012.com/browse?' + \
            'form=search&tab=%s&sport=%d&event=&venue=&fromDate=&' + \
            'toDate=&morning=1&afternoon=1&evening=1&' + \
            'show_available_events=1'
    details_template_url = 'http://www.tickets.london2012.com/' + \
            'eventdetails?id=%s'
    lookup = 'paralympics' if paralympics else 'olympics'
    now = datetime.datetime.now()
    tab = 'para' if paralympics else 'oly'

    for sport, code in sports[lookup].iteritems():
        url    = summary_template_url % (tab, code)
        soup   = make_soup(url)
        if soup.find('h2') and soup.find('h2').text == 'Search results':
            table = soup.find('table')
            if table:
                for elem in table.find_all('input', {'value':'Select'}):
                    row = elem.parent.parent.parent.parent
                    event_id  = row.find('input', {'name':'id'}).attrs['value']
                    details_url = details_template_url % event_id
                    details_soup = make_soup(details_url)
                    event_info = details_soup.find('table', {'title':'Ticket Summary'})
                    date_tag = details_soup.find('td', text='Date')
                    date = date_tag.nextSibling.nextSibling.text if date_tag else None
                    time_tag = details_soup.find('td', text='Time')
                    time = time_tag.nextSibling.nextSibling.text if time_tag else None
                    option_tags = details_soup.find_all('option', {'price':True})
                    if option_tags:
                        cost_texts = map(lambda x : x.text, option_tags)
                        costs = map(lambda x : re.findall('[0-9.]+', x)[0], cost_texts)
                        min_cost = min(map(lambda x : float(x), costs))
                        result.append({
                                'sport' : sport,
                                'date'  : date,
                                'time'  : time,
                                'url'   : details_url,
                                'cost'  : min_cost
                            })
    return result

if __name__ == "__main__":
    while True:
        time.sleep(2)
        print datetime.datetime.now().time()
        result = available_tickets()
        if result:
            break
        break
    pprint.pprint(result) if result else None
    os.system('cvlc /usr/share/sounds/gnome/default/alerts/glass.ogg vlc://quit')


text:
#ifndef _ncvtestsourceprovider_hpp_
#define _ncvtestsourceprovider_hpp_

#include <memory>

#include BOSS_OPENCV_U_opencv2__highgui_hpp //original-code:"opencv2/highgui.hpp"
#include "opencv2/cudalegacy.hpp"

template <class T>
class NCVTestSourceProvider
{
public:

    NCVTestSourceProvider(Ncv32u seed, T rangeLow, T rangeHigh, Ncv32u maxWidth, Ncv32u maxHeight)
        :
        bInit(false)
    {
        ncvAssertPrintReturn(rangeLow < rangeHigh, "NCVTestSourceProvider ctor:: Invalid range", );

        int devId;
        cudaDeviceProp devProp;
        ncvAssertPrintReturn(cudaSuccess == cudaGetDevice(&devId), "Error returned from cudaGetDevice", );
        ncvAssertPrintReturn(cudaSuccess == cudaGetDeviceProperties(&devProp, devId), "Error returned from cudaGetDeviceProperties", );

        //Ncv32u maxWpitch = alignUp(maxWidth * sizeof(T), devProp.textureAlignment);

        allocatorCPU.reset(new NCVMemNativeAllocator(NCVMemoryTypeHostPinned, static_cast<Ncv32u>(devProp.textureAlignment)));
        data.reset(new NCVMatrixAlloc<T>(*this->allocatorCPU.get(), maxWidth, maxHeight));
        ncvAssertPrintReturn(data.get()->isMemAllocated(), "NCVTestSourceProvider ctor:: Matrix not allocated", );

        this->dataWidth = maxWidth;
        this->dataHeight = maxHeight;

        srand(seed);

        for (Ncv32u i=0; i<maxHeight; i++)
        {
            for (Ncv32u j=0; j<data.get()->stride(); j++)
            {
                data.get()->ptr()[i * data.get()->stride() + j] =
                    (T)(((1.0 * rand()) / RAND_MAX) * (rangeHigh - rangeLow) + rangeLow);
            }
        }

        this->bInit = true;
    }

    NCVTestSourceProvider(std::string pgmFilename)
        :
        bInit(false)
    {
        ncvAssertPrintReturn(sizeof(T) == 1, "NCVTestSourceProvider ctor:: PGM constructor complies only with 8bit types", );

        cv::Mat image = cv::imread(pgmFilename);
        ncvAssertPrintReturn(!image.empty(), "NCVTestSourceProvider ctor:: PGM file error", );

        int devId;
        cudaDeviceProp devProp;
        ncvAssertPrintReturn(cudaSuccess == cudaGetDevice(&devId), "Error returned from cudaGetDevice", );
        ncvAssertPrintReturn(cudaSuccess == cudaGetDeviceProperties(&devProp, devId), "Error returned from cudaGetDeviceProperties", );

        allocatorCPU.reset(new NCVMemNativeAllocator(NCVMemoryTypeHostPinned, static_cast<Ncv32u>(devProp.textureAlignment)));
        data.reset(new NCVMatrixAlloc<T>(*this->allocatorCPU.get(), image.cols, image.rows));
        ncvAssertPrintReturn(data.get()->isMemAllocated(), "NCVTestSourceProvider ctor:: Matrix not allocated", );

        this->dataWidth = image.cols;
        this->dataHeight = image.rows;

        cv::Mat hdr(image.size(), CV_8UC1, data.get()->ptr(), data.get()->pitch());
        image.copyTo(hdr);

        this->bInit = true;
    }

    NcvBool fill(NCVMatrix<T> &dst)
    {
        ncvAssertReturn(this->isInit() &&
                        dst.memType() == allocatorCPU.get()->memType(), false);

        if (dst.width() == 0 || dst.height() == 0)
        {
            return true;
        }

        for (Ncv32u i=0; i<dst.height(); i++)
        {
            Ncv32u srcLine = i % this->dataHeight;

            Ncv32u srcFullChunks = dst.width() / this->dataWidth;
            for (Ncv32u j=0; j<srcFullChunks; j++)
            {
                memcpy(dst.ptr() + i * dst.stride() + j * this->dataWidth,
                    this->data.get()->ptr() + this->data.get()->stride() * srcLine,
                    this->dataWidth * sizeof(T));
            }

            Ncv32u srcLastChunk = dst.width() % this->dataWidth;
            memcpy(dst.ptr() + i * dst.stride() + srcFullChunks * this->dataWidth,
                this->data.get()->ptr() + this->data.get()->stride() * srcLine,
                srcLastChunk * sizeof(T));
        }

        return true;
    }

    NcvBool fill(NCVVector<T> &dst)
    {
        ncvAssertReturn(this->isInit() &&
                        dst.memType() == allocatorCPU.get()->memType(), false);

        if (dst.length() == 0)
        {
            return true;
        }

        Ncv32u srcLen = this->dataWidth * this->dataHeight;

        Ncv32u srcFullChunks = (Ncv32u)dst.length() / srcLen;
        for (Ncv32u j=0; j<srcFullChunks; j++)
        {
            memcpy(dst.ptr() + j * srcLen, this->data.get()->ptr(), srcLen * sizeof(T));
        }

        Ncv32u srcLastChunk = dst.length() % srcLen;
        memcpy(dst.ptr() + srcFullChunks * srcLen, this->data.get()->ptr(), srcLastChunk * sizeof(T));

        return true;
    }

    ~NCVTestSourceProvider()
    {
        data.reset();
        allocatorCPU.reset();
    }

private:

    NcvBool isInit(void)
    {
        return this->bInit;
    }

    NcvBool bInit;
    std::auto_ptr< INCVMemAllocator > allocatorCPU;
    std::auto_ptr< NCVMatrixAlloc<T> > data;
    Ncv32u dataWidth;
    Ncv32u dataHeight;
};

#endif // _ncvtestsourceprovider_hpp_


text:
From within the `docs` folder run the following:

To autogenerate the packages and modules documentation from their docstrings:
```bash
sphinx-apidoc ../qsr_lib/src/ -o rsts/api/ -e
```
*NOTE:* `sphinx-apidoc` does not overwrite any files, so if you want to regenerate the documentation for a package or a
module then delete first its rst file in the `docs/rsts/api` folder.

Then simply run:
```bash
make html
```

## `qsrs.rst`
The table in `qsrs.rst` is generated from `qsrs_table.md` as writing tables in RsT is a pain.
md files can be converted to rst ones using  `pandoc`.
The actual command run from within the `docs/rsts/handwritten/qsrs` folder is:

```bash
pandoc --from=markdown --to=rst --output=qsrs_table.rst qsrs_table.md
```

If pandoc converts "\`" to "\`\`" then do two string replacements:

1. "\`\`" to "\`"
2. "\`  " to "\`     ", i.e 'backtilt+2 spaces' to 'backtilt+6 spaces'


text:
NetworKit::Partition NetworKit::PartitionIntersection::calculate(const Partition &zeta, const NetworKit::Partition &eta) {
	Partition result(std::max(zeta.numberOfElements(), eta.numberOfElements()));
	result.setUpperBound(zeta.upperBound()*eta.upperBound());
	zeta.parallelForEntries([&](node u, index s) {
		if (zeta.contains(u) && eta.contains(u)) {
			result[u] = s * eta.upperBound() + eta[u];
		}
	});
	result.compact();
	return result;
}


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="@dimen/y144"
    android:background="@color/w0"
    android:orientation="vertical">

    <!--搜索-->
    <RelativeLayout
        android:id="@+id/serch_layout"
        android:layout_width="match_parent"
        android:layout_height="@dimen/y90"
        android:layout_centerVertical="true"
        android:layout_marginEnd="@dimen/width_48"
        android:layout_marginStart="@dimen/width_48"
        android:background="@drawable/et_circular_4_white">

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_centerInParent="true"
            android:orientation="horizontal">

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_vertical"
                android:src="@mipmap/serch" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_vertical"
                android:layout_marginStart="@dimen/x18"
                android:text="@string/serch"
                android:textColor="@color/gray_login" />
        </LinearLayout>

    </RelativeLayout>
</RelativeLayout>


text:
<?php

namespace Oro\Bundle\AddressBundle\Tests\Unit\Form\DataTransformer;

use Oro\Bundle\AddressBundle\Entity\Address;

class MultiAddressMock
{
    /** @var Address */
    private $billingAddress;

    /** @var Address */
    private $shippingAddress;

    /**
     * @return Address
     */
    public function getBillingAddress()
    {
        return $this->billingAddress;
    }

    /**
     * @param Address $billingAddress
     */
    public function setBillingAddress($billingAddress)
    {
        $this->billingAddress = $billingAddress;
    }

    /**
     * @return Address
     */
    public function getShippingAddress()
    {
        return $this->shippingAddress;
    }

    /**
     * @param Address $shippingAddress
     */
    public function setShippingAddress($shippingAddress)
    {
        $this->shippingAddress = $shippingAddress;
    }
}