text:
#import "CTAssetsPageViewController.h"
#import "CTAssetItemViewController.h"
#import "CTAssetScrollView.h"
#import "NSNumberFormatter+CTAssetsPickerController.h"
#import "NSBundle+CTAssetsPickerController.h"
#import "UIImage+CTAssetsPickerController.h"
#import "PHAsset+CTAssetsPickerController.h"

@interface CTAssetsPageViewController ()
<UIPageViewControllerDataSource, UIPageViewControllerDelegate>

@property (nonatomic, assign, getter = isStatusBarHidden) BOOL statusBarHidden;

@property (nonatomic, copy) NSArray *assets;
//@property (nonatomic, strong) PHFetchResult *fetchResult;
@property (nonatomic, strong, readonly) PHAsset *asset;

@property (nonatomic, strong) UIBarButtonItem *playButton;
@property (nonatomic, strong) UIBarButtonItem *pauseButton;

@property (nonatomic, strong) UIColor * whiteColor;
@property (nonatomic, strong) UIColor * blackColor;

@end

@implementation CTAssetsPageViewController

- (instancetype)initWithFetchResult:(PHFetchResult *)fetchResult
{
    NSMutableArray *assets = [NSMutableArray new];

    for (PHAsset *asset in fetchResult)
        [assets addObject:asset];

    return [self initWithAssets:[NSArray arrayWithArray:assets]];
}

- (instancetype)initWithAssets:(NSArray *)assets
{
    self = [super initWithTransitionStyle:UIPageViewControllerTransitionStyleScroll
                    navigationOrientation:UIPageViewControllerNavigationOrientationHorizontal
                                  options:@{UIPageViewControllerOptionInterPageSpacingKey:@30.f}];

    if (self)
    {
        self.assets     = assets;
        self.dataSource = self;
        self.delegate   = self;
        self.automaticallyAdjustsScrollViewInsets = NO;
    }

    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self setupViews];
    [self addNotificationObserver];

    //  Changed for VHS
    self.navigationItem.rightBarButtonItem =
    [[UIBarButtonItem alloc] initWithTitle:CTAssetsPickerLocalizedString(@"Done", nil)
                                     style:UIBarButtonItemStyleDone
                                    target:self
                                    action:@selector(pickCurrentAsset:)];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.navigationController setToolbarHidden:YES animated:NO];
}

- (void)dealloc
{
    [self removeNotificationObserver];
}

- (BOOL)prefersStatusBarHidden
{
    if (self.traitCollection.verticalSizeClass == UIUserInterfaceSizeClassCompact)
        return YES;
    else
        return self.isStatusBarHidden;
}

#pragma mark - Actions

- (void)pickCurrentAsset:(id)sender{
    //  Changed for VHS
    CTAssetItemViewController *vc = (CTAssetItemViewController *)self.viewControllers[0];
    [vc pauseAsset:nil];
    [self.picker selectAsset:vc.asset];
}

#pragma mark - Setup

- (void)setupViews
{
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
        self.whiteColor = [UIColor whiteColor];
        self.blackColor = self.whiteColor;
    } else {
        self.whiteColor = [UIColor whiteColor];
        self.blackColor = [UIColor blackColor];
    }

    self.view.backgroundColor = self.whiteColor;
}

- (void)setupButtons
{
    if (!self.playButton)
    {
        UIImage *playImage = [UIImage ctassetsPickerImageNamed:@"PlayButton"];
        playImage = [playImage imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];

        UIBarButtonItem *playButton =
        [[UIBarButtonItem alloc] initWithImage:playImage style:UIBarButtonItemStyleDone target:self action:@selector(playAsset:)];

        self.playButton = playButton;
    }

    if (!self.pauseButton)
    {
        UIImage *pasueImage = [UIImage ctassetsPickerImageNamed:@"PauseButton"];
        pasueImage = [pasueImage imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];

        UIBarButtonItem *pauseButton =
        [[UIBarButtonItem alloc] initWithImage:pasueImage style:UIBarButtonItemStylePlain target:self action:@selector(pauseAsset:)];

        self.pauseButton = pauseButton;
    }
}

#pragma mark - Update title

- (void)updateTitle:(NSInteger)index
{
    NSNumberFormatter *nf = [NSNumberFormatter new];

    NSInteger count = self.assets.count;
    self.title      = [NSString stringWithFormat:CTAssetsPickerLocalizedString(@"%@ of %@", nil),
                       [nf ctassetsPickerStringFromAssetsCount:index],
                       [nf ctassetsPickerStringFromAssetsCount:count]];
}

#pragma mark - Update toolbar

- (void)updateToolbar
{
    [self setupButtons];

    if ([self.asset ctassetsPickerIsVideo])
        self.toolbarItems = @[[self toolbarSpace], self.playButton, [self toolbarSpace]];
    else
        self.toolbarItems = nil;
}

- (void)replaceToolbarButton:(UIBarButtonItem *)button
{
    if (button)
    {
        UIBarButtonItem *space = [self toolbarSpace];
        self.toolbarItems = @[space, button, space];
    }
}

- (UIBarButtonItem *)toolbarSpace
{
    return [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
}

#pragma mark - Accessors

- (NSInteger)pageIndex
{
    return [self.assets indexOfObject:self.asset];
}

- (void)setPageIndex:(NSInteger)pageIndex
{
    NSInteger count = self.assets.count;

    if (pageIndex >= 0 && pageIndex < count)
    {
        PHAsset *asset = [self.assets objectAtIndex:pageIndex];

        CTAssetItemViewController *page = [CTAssetItemViewController assetItemViewControllerForAsset:asset];

        [self setViewControllers:@[page]
                       direction:UIPageViewControllerNavigationDirectionForward
                        animated:NO
                      completion:NULL];

        [self updateTitle:pageIndex + 1];
        [self updateToolbar];
    }
}

- (PHAsset *)asset
{
    return ((CTAssetItemViewController *)self.viewControllers[0]).asset;
}

#pragma mark - Page view controller data source

- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerBeforeViewController:(UIViewController *)viewController
{
    PHAsset *asset = ((CTAssetItemViewController *)viewController).asset;
    NSInteger index = [self.assets indexOfObject:asset];

    if (index > 0)
    {
        PHAsset *beforeAsset = [self.assets objectAtIndex:(index - 1)];
        return [CTAssetItemViewController assetItemViewControllerForAsset:beforeAsset];
    }

    return nil;
}

- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerAfterViewController:(UIViewController *)viewController
{
    PHAsset *asset  = ((CTAssetItemViewController *)viewController).asset;
    NSInteger index = [self.assets indexOfObject:asset];
    NSInteger count = self.assets.count;

    if (index < count - 1)
    {
        PHAsset *afterAsset = [self.assets objectAtIndex:(index + 1)];
        return [CTAssetItemViewController assetItemViewControllerForAsset:afterAsset];
    }

    return nil;
}

#pragma mark - Page view controller delegate

- (void)pageViewController:(UIPageViewController *)pageViewController didFinishAnimating:(BOOL)finished previousViewControllers:(NSArray *)previousViewControllers transitionCompleted:(BOOL)completed
{
    if (completed)
    {
        CTAssetItemViewController *vc = (CTAssetItemViewController *)pageViewController.viewControllers[0];
        NSInteger index = [self.assets indexOfObject:vc.asset] + 1;

        [self updateTitle:index];
        [self updateToolbar];
    }
}

- (void)pageViewController:(UIPageViewController *)pageViewController willTransitionToViewControllers:(NSArray *)pendingViewControllers
{
    [self.navigationController setToolbarHidden:YES animated:YES];
}

#pragma mark - Notification observer

- (void)addNotificationObserver
{
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];

    [center addObserver:self
               selector:@selector(assetScrollViewDidTap:)
                   name:CTAssetScrollViewDidTapNotification
                 object:nil];

    [center addObserver:self
               selector:@selector(assetScrollViewPlayerDidPlayToEnd:)
                   name:AVPlayerItemDidPlayToEndTimeNotification
                 object:nil];

    [center addObserver:self
               selector:@selector(assetScrollViewPlayerWillPlay:)
                   name:CTAssetScrollViewPlayerWillPlayNotification
                 object:nil];

    [center addObserver:self
               selector:@selector(assetScrollViewPlayerWillPause:)
                   name:CTAssetScrollViewPlayerWillPauseNotification
                 object:nil];
}

- (void)removeNotificationObserver
{
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];

    [center removeObserver:self name:CTAssetScrollViewDidTapNotification object:nil];
    [center removeObserver:self name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
    [center removeObserver:self name:CTAssetScrollViewPlayerWillPlayNotification object:nil];
    [center removeObserver:self name:CTAssetScrollViewPlayerWillPauseNotification object:nil];
}

#pragma mark - Notification events

- (void)assetScrollViewDidTap:(NSNotification *)notification
{
    UITapGestureRecognizer *gesture = (UITapGestureRecognizer *)notification.object;

    if (gesture.numberOfTapsRequired == 1)
    {
        [self toogleBackgroundColor:gesture];
        [self toogleControls:gesture];
    }
}

- (void)assetScrollViewPlayerDidPlayToEnd:(NSNotification *)notification
{
    [self replaceToolbarButton:self.playButton];

    [UIView animateWithDuration:0.2
                     animations:^{
                         self.view.backgroundColor = self.whiteColor;
                     }];

    [self fadeInControls:self.navigationController];
}

- (void)assetScrollViewPlayerWillPlay:(NSNotification *)notification
{
    [self replaceToolbarButton:self.pauseButton];

    [UIView animateWithDuration:0.2
                     animations:^{
                         self.view.backgroundColor = self.blackColor;
                     }];

    [self fadeAwayControls:self.navigationController];
}

- (void)assetScrollViewPlayerWillPause:(NSNotification *)notification
{
    [self replaceToolbarButton:self.playButton];
}

#pragma mark - Toogle background color

- (void)toogleBackgroundColor:(id)sender
{
    UIColor *color = ([self.view.backgroundColor isEqual: self.whiteColor]) ? self.blackColor : self.whiteColor;

    [UIView animateWithDuration:0.2
                     animations:^{
                         self.view.backgroundColor = color;
                     }];
}

#pragma mark - Toogle controls

- (void)toogleControls:(id)sender
{
    UINavigationController *nav = self.navigationController;

    if (self.isStatusBarHidden)
        [self fadeInControls:nav];
    else
        [self fadeAwayControls:nav];
}

- (void)fadeInControls:(UINavigationController *)nav
{
    self.statusBarHidden = NO;

    [nav setNavigationBarHidden:NO];
    [nav.navigationBar setAlpha:0.0f];

    if ([self.asset ctassetsPickerIsVideo])
    {
        [nav setToolbarHidden:NO];
        [nav.toolbar setAlpha:0.0f];
    }

    [UIView animateWithDuration:0.2
                     animations:^{
                         [self setNeedsStatusBarAppearanceUpdate];
                         [nav.navigationBar setAlpha:1.0f];

                         if ([self.asset ctassetsPickerIsVideo])
                             [nav.toolbar setAlpha:1.0f];
                     }];
}

- (void)fadeAwayControls:(UINavigationController *)nav
{
    self.statusBarHidden = YES;

    [UIView animateWithDuration:0.2
                     animations:^{
                         [self setNeedsStatusBarAppearanceUpdate];
                         [nav setNavigationBarHidden:YES animated:NO];
                         [nav setToolbarHidden:YES animated:NO];
                         [nav.navigationBar setAlpha:0.0f];
                         [nav.toolbar setAlpha:0.0f];
                     }];
}

#pragma mark - Playback

- (void)playAsset:(id)sender
{
    [((CTAssetItemViewController *)self.viewControllers[0]) playAsset:sender];
}

- (void)pauseAsset:(id)sender
{
    [((CTAssetItemViewController *)self.viewControllers[0]) pauseAsset:sender];
}

@end


text:
package com.javierdelgado.popularmovies_stage1.adapters;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.ActivityOptionsCompat;
import android.support.v4.util.Pair;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.javierdelgado.popularmovies_stage1.R;
import com.javierdelgado.popularmovies_stage1.activities.DetailActivity;
import com.javierdelgado.popularmovies_stage1.data.MovieContract;
import com.javierdelgado.popularmovies_stage1.model.Movie;
import com.squareup.picasso.Picasso;

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

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by Delga on 03/05/2017.
 */

public class MoviesAdapter extends RecyclerView.Adapter<MoviesAdapter.MoviesViewHolder> {

    private List<Movie> mMoviesList = null;
    private Context mContext;

    public MoviesAdapter(Context context) {
        mContext = context;
    }

    @Override
    public MoviesViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.movie_item, parent, false);
        return new MoviesViewHolder(mContext, view);
    }

    @Override
    public void onBindViewHolder(MoviesViewHolder holder, int position) {
        holder.bind(position);
    }

    @Override
    public int getItemCount() {
        return mMoviesList == null ? 0 : mMoviesList.size();
    }

    public void setData(List<Movie> movies){
        mMoviesList = movies;
        notifyDataSetChanged();
    }

    public void setData(Cursor movies) {
        List<Movie> list = new ArrayList<>();
        while (movies.moveToNext()) {
            int id = movies.getInt(movies.getColumnIndex(MovieContract.MovieEntry.COLUMN_MOVIE_ID));
            String title = movies.getString(movies.getColumnIndex(MovieContract.MovieEntry.COLUMN_TITLE));
            String cover = movies.getString(movies.getColumnIndex(MovieContract.MovieEntry.COLUMN_POSTER));
            String backdrop = movies.getString(movies.getColumnIndex(MovieContract.MovieEntry.COLUMN_BACKDROP));
            String releaseDate = movies.getString(movies.getColumnIndex(MovieContract.MovieEntry.COLUMN_RELEASE_DATE));
            double rating = movies.getDouble(movies.getColumnIndex(MovieContract.MovieEntry.COLUMN_RATING));
            String description = movies.getString(movies.getColumnIndex(MovieContract.MovieEntry.COLUMN_SYNOPOSIS));
            // Create movie
            Movie movie = new  Movie(id, title, cover, backdrop, releaseDate, rating, description);
            movie.setFavorite(true);
            list.add(movie);
        }
        mMoviesList = list;
        notifyDataSetChanged();
    }

    class MoviesViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

        Context context;
        @BindView(R.id.item_moviecover) ImageView movieCover;

        public MoviesViewHolder(Context context, View itemView) {
            super(itemView);

            this.context = context;
            ButterKnife.bind(this,itemView);
            itemView.setOnClickListener(this);
        }

        void bind(int position) {
            Picasso.with(itemView.getContext())
                    .load(context.getResources().getString(R.string.base_cover_url) + mMoviesList.get(position).getCover())
                    .error(R.drawable.sad_icon)
                    .into(movieCover);
        }

        @Override
        public void onClick(View view) {
            Intent detailIntent = new Intent(mContext, DetailActivity.class);

            // If the movie is in database, then it is favorite
            Movie movie = mMoviesList.get(getAdapterPosition());
            String selection = MovieContract.MovieEntry.COLUMN_MOVIE_ID + "=?";
            String[] selectionArgs = new String[]{Integer.toString(movie.getId())};
            Cursor query = mContext.getContentResolver().query(MovieContract.MovieEntry.CONTENT_URI,
                    null,
                    selection,
                    selectionArgs,
                    null);
            if (query.getCount() == 1) {
                movie.setFavorite(true);
            }
            detailIntent.putExtra(DetailActivity.KEY_MOVIE_ID,movie);

            //Set up transition
            Pair<View, String> pair_cover = Pair.create((View) movieCover, mContext.getString(R.string.transition_movie_image));

            //Animation
            ActivityOptionsCompat options = ActivityOptionsCompat.
                    makeSceneTransitionAnimation((Activity) mContext, pair_cover);

            //Start activity
            ActivityCompat.startActivity(mContext, detailIntent, options.toBundle());
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
(function () {
  'use strict';

  angular
    .module('photos')
    .controller('PhotosListController', PhotosListController);
  PhotosListController.$inject = ['PhotosService','$scope', 'Authentication', 'FileUploader', '$state', '$timeout', '$window', '$http'];
  function PhotosListController(PhotosService, $scope, Authentication, FileUploader, photo, $state, $timeout, $window, $http) {
    var vm = this;
    vm.authentication = Authentication;
    vm.photos = PhotosService.query();
    $scope.src = 'https://s3-us-west-2.amazonaws.com/photobucketsoftwareproject/';
  }
})();


text:
using CineSphere.Common;
using CineSphere.Model;
using System;
using System.Diagnostics;
using System.IO;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Activation;
using Windows.Storage.AccessCache;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Imaging;

namespace CineSphere
{

    sealed partial class App : Application
    {
        public static string DBPath = string.Empty;

        public App()
        {
            this.InitializeComponent();
            this.Suspending += OnSuspending;
        }

        protected override async void OnLaunched(LaunchActivatedEventArgs args)
        {
            Frame rootFrame = Window.Current.Content as Frame;

            if (rootFrame == null)
            {
                rootFrame = new Frame();

                SuspensionManager.RegisterFrame(rootFrame, "AppFrame");

                if (args.PreviousExecutionState == ApplicationExecutionState.Terminated)
                {
                    // Restore the saved session state only when appropriate
                    try
                    {
                        await SuspensionManager.RestoreAsync();
                    }
                    catch (SuspensionManagerException)
                    {
                        //Something went wrong restoring state.
                        //Assume there is no state and continue
                    }
                }
                // Get a reference to the SQLite database
                DBPath = Path.Combine(
                    Windows.Storage.ApplicationData.Current.LocalFolder.Path, "video.s3db");

                using (var db = new SQLiteConnection(DBPath))
                {
                    db.CreateTable<Video>();
                }
                ResetData();

                // Place the frame in the current Window
                Window.Current.Content = rootFrame;
            }
            if (rootFrame.Content == null)
            {
                // When the navigation stack isn't restored navigate to the first page,
                // configuring the new page by passing required information as a navigation
                // parameter
                if (!rootFrame.Navigate(typeof(MainPage)))
                {
                    throw new Exception("Failed to create initial page");
                }
            }
            // Ensure the current window is active
          //  Window.Current.Activate();
        }

        private void ResetData()
        {
            using (var db = new SQLiteConnection(DBPath))
            {

                //db.DeleteAll<Video>();
                //StorageApplicationPermissions.FutureAccessList.Clear();
            }
        }

        private async void OnSuspending(object sender, SuspendingEventArgs e)
        {
            var deferral = e.SuspendingOperation.GetDeferral();
            await SuspensionManager.SaveAsync();
            deferral.Complete();
        }
    }
}


text:
<!DOCTYPE html>

    <meta http-equiv="refresh" content="0;URL=constant.MAP_GROWSDOWN.html">

Redirecting to constant.MAP_GROWSDOWN.html...


text:
.class Lcom/google/android/gms/drive/internal/h$3;
.super Lcom/google/android/gms/drive/internal/h$b;

# annotations
.annotation system Ldalvik/annotation/EnclosingMethod;
    value = Lcom/google/android/gms/drive/internal/h;->discardContents(Lcom/google/android/gms/common/api/GoogleApiClient;Lcom/google/android/gms/drive/Contents;)Lcom/google/android/gms/common/api/PendingResult;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x0
    name = null
.end annotation

# instance fields
.field final synthetic rc:Lcom/google/android/gms/drive/internal/h;

.field final synthetic rd:Lcom/google/android/gms/drive/Contents;

# direct methods
.method constructor <init>(Lcom/google/android/gms/drive/internal/h;Lcom/google/android/gms/drive/Contents;)V
    .locals 0

    iput-object p1, p0, Lcom/google/android/gms/drive/internal/h$3;->rc:Lcom/google/android/gms/drive/internal/h;

    iput-object p2, p0, Lcom/google/android/gms/drive/internal/h$3;->rd:Lcom/google/android/gms/drive/Contents;

    invoke-direct {p0, p1}, Lcom/google/android/gms/drive/internal/h$b;-><init>(Lcom/google/android/gms/drive/internal/h;)V

    return-void
.end method

# virtual methods
.method protected bridge synthetic a(Lcom/google/android/gms/common/api/Api$a;)V
    .locals 1

    move-object v0, p1

    check-cast v0, Lcom/google/android/gms/drive/internal/j;

    invoke-virtual {p0, v0}, Lcom/google/android/gms/drive/internal/h$3;->a(Lcom/google/android/gms/drive/internal/j;)V

    return-void
.end method

.method protected a(Lcom/google/android/gms/drive/internal/j;)V
    .locals 4

    :try_start_0
    invoke-virtual {p1}, Lcom/google/android/gms/drive/internal/j;->cN()Lcom/google/android/gms/drive/internal/o;

    move-result-object v0

    new-instance v1, Lcom/google/android/gms/drive/internal/CloseContentsRequest;

    iget-object v2, p0, Lcom/google/android/gms/drive/internal/h$3;->rd:Lcom/google/android/gms/drive/Contents;

    const/4 v3, 0x0

    invoke-direct {v1, v2, v3}, Lcom/google/android/gms/drive/internal/CloseContentsRequest;-><init>(Lcom/google/android/gms/drive/Contents;Z)V

    new-instance v2, Lcom/google/android/gms/drive/internal/z;

    invoke-direct {v2, p0}, Lcom/google/android/gms/drive/internal/z;-><init>(Lcom/google/android/gms/common/api/a$c;)V

    invoke-interface {v0, v1, v2}, Lcom/google/android/gms/drive/internal/o;->a(Lcom/google/android/gms/drive/internal/CloseContentsRequest;Lcom/google/android/gms/drive/internal/p;)V
    :try_end_0
    .catch Landroid/os/RemoteException; {:try_start_0 .. :try_end_0} :catch_0

    return-void

    :catch_0
    move-exception p1

    new-instance v0, Lcom/google/android/gms/common/api/Status;

    invoke-virtual {p1}, Landroid/os/RemoteException;->getLocalizedMessage()Ljava/lang/String;

    move-result-object v1

    const/16 v2, 0x8

    const/4 v3, 0x0

    invoke-direct {v0, v2, v1, v3}, Lcom/google/android/gms/common/api/Status;-><init>(ILjava/lang/String;Landroid/app/PendingIntent;)V

    invoke-virtual {p0, v0}, Lcom/google/android/gms/drive/internal/h$3;->a(Lcom/google/android/gms/common/api/Result;)V

    return-void
.end method


text:
<?xml version="1.0" encoding="utf-8"?>

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:bottom="0px" android:left="0px" android:right="0px" android:top="0px">
        <shape android:shape="rectangle">
            <stroke android:color="@color/colorWarning" android:width="2dp"/>
        </shape>
    </item>
    <item android:bottom="0px" android:left="0px" android:right="0px" android:top="0px">
        <shape android:shape="rectangle">
            <stroke android:color="@color/buttonDisableOverlay" android:width="2dp"/>
        </shape>
    </item>
</layer-list>


text:
import { Component } from '@angular/core';

import { HeroService } from './hero.service';

@Component({
  selector: 'part2-heroes1',
  providers: [HeroService],
  template: `

part2/heroes1: Heroes 1

    <part2-heroes1-list></part2-heroes1-list>

  `
})
export class HeroesComponent { }


text:
package fi.csc.chipster.tools.common;

import java.io.File;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;

import org.apache.commons.io.FileUtils;

import fi.csc.chipster.comp.Exceptions;
import fi.csc.chipster.comp.JobState;
import fi.csc.chipster.comp.ToolUtils;
import fi.csc.chipster.comp.java.JavaCompJobBase;

public class DownloadFile extends JavaCompJobBase {

	public static final int CONNECTION_TIMEOUT = 15 * 1000; // ms
	public static final int READ_TIMEOUT = 7 * 24 * 60 * 60 * 1000; // ms

	/*
	 * We definitely don't wan't to enable 'file' protocol. Other protocols might be
	 * fine as long as the isLocalhost() check below is sufficient for it.
	 */
	public static final List<String> allowedProtocols = Arrays.asList(new String[] { "http", "https", "ftp" });

	public static final String CURRENT = "current";
	public static final String YES = "yes";
	public static final String NO = "no";

	@Override
	public String getSADL() {
		return "TOOL fi.csc.chipster.tools.common.DownloadFile.java: \"Download file from URL directly to server\" (Download a file from a URL address to the Chipster server. The URL must be visible to Chipster server. If it's not, use client's 'Import from URL' functionality instead.)"
				+ "\n" + "OUTPUT downloaded_file: \"Downloaded file\"\n"
				+ "PARAMETER paramUrl: \"URL\" TYPE UNCHECKED_STRING (URL to download)\n"
				+ "PARAMETER OPTIONAL paramFileExtension: \"Add a file extension\" TYPE [" + CURRENT
				+ ": \"Keep current\", bam: \"BAM\", fa: \"FASTA\", fastq: \"FASTQ\", gtf: \"GTF\"] DEFAULT " + CURRENT
				+ " (The output file is named according to the last part of the URL. If it doesn't contain a correct file extension, select it here so that the file type is recognized correctly.)\n"
				+ "PARAMETER OPTIONAL paramCheckCerts: \"Require valid SSL certificate\" TYPE [" + YES + ": \"Yes\", "
				+ NO + ": \"No\"] DEFAULT " + YES
				+ " (Disable if the https server has a self-signed ssl certificate which you trust.)\n";
	}

	@Override
	protected void execute() {
		updateState(JobState.RUNNING, "downloading");

		try {
			// file
			File outputFile = new File(jobDataDir, toolDescription.getOutputFiles().get(0).getFileName().getID());

			// parameters
			List<String> parameters = inputMessage.getParameters(JAVA_PARAMETER_SECURITY_POLICY, toolDescription);
			String urlString = parameters.get(0);
			String fileExtension = parameters.get(1);
			boolean checkCerts = true;
			if (NO.equals(parameters.get(2))) {
				checkCerts = false;
			}

			URL url = new URL(urlString);

			if (!allowedProtocols.contains(url.getProtocol())) {

				getResultMessage().setErrorMessage("Unsupported protocol: " + url.getProtocol());
				updateState(JobState.FAILED_USER_ERROR, "");
				return;
			}

			if (UrlTransferUtil.isLocalhost(url.getHost())) {

				getResultMessage().setErrorMessage("Not allowed to connect localhost: " + url.getHost());
				updateState(JobState.FAILED_USER_ERROR, "");
				return;
			}

			String datasetName = UrlTransferUtil.parseFilename(url);

			if (!CURRENT.equals(fileExtension)) {
				datasetName += "." + fileExtension;
			}

			URLConnection connection = url.openConnection();
			if (checkCerts) {
				// needed for old chipster which configures socket factory
				// doesn't do anything in the new chipster
				// can be removed when old not in use anymore
//				KeyAndTrustManager.configureForCACertificates(connection);
			} else {
				KeyAndTrustManager.configureForTrustAllCertificates(connection);
			}
			connection.setConnectTimeout(CONNECTION_TIMEOUT);
			connection.setReadTimeout(READ_TIMEOUT);
			InputStream stream = connection.getInputStream();
			FileUtils.copyInputStreamToFile(stream, outputFile);

			LinkedHashMap<String, String> nameMap = new LinkedHashMap<>();
			nameMap.put(outputFile.getName(), datasetName);

			ToolUtils.writeOutputDescription(jobDataDir, nameMap);

		} catch (Exception e) {
			getResultMessage().setErrorMessage(Exceptions.getStackTrace(e));
			updateState(JobState.FAILED, "");
			return;
		}

		updateState(JobState.RUNNING, "download finished");
	}
}


text:
package client.serverconnection.functionality;

import java.io.BufferedReader;
import java.io.IOException;

import messages.MessageType;
import client.serverconnection.ServerConnectionNotifier;
import client.serverconnection.functionality.YTJBLowLevelServerConnection.AliveChecker;
import client.serverconnection.functionality.handler.NotificationHandler;
import client.serverconnection.functionality.handler.ResponseHandler;

public class InputListener implements Runnable {

	private boolean running = true;
	private BufferedReader input;
	private ServerConnectionNotifier notifyWrapper;
	private ResponseController responses;
	private AliveChecker checker;

	public InputListener(BufferedReader input, ServerConnectionNotifier notifyWrapper,ResponseController responses, AliveChecker checker) {
		this.input = input;
		this.notifyWrapper = notifyWrapper;
		this.responses = responses;
		this.checker = checker;
	}

	@Override
	public void run() {
		try {
			while (running){
				String line = input.readLine();
				if (!line.equals("")){
					checker.setLastResponse();
					if (Thread.interrupted())
						break;
					String[] params = line.split(MessageType.SEPERATOR);
					int messageType = Integer.parseInt(params[0]);
					if (messageType == MessageType.RESPONSENOTIFY){
						Thread t = new Thread(new ResponseHandler(responses,params));
						t.start();
					}else{
						Thread t = new Thread(new NotificationHandler(notifyWrapper,messageType,params));
						t.start();
					}
				}
			}
		} catch (IOException | NullPointerException e) {
			notifyWrapper.onNotify(MessageType.DISCONNECT,null);
		}
	}

}


text:
<!DOCTYPE html>

		<title>Some interesting facts</title>
		<link rel="stylesheet" type="text/css" href="styles/styles.css" />

G52APR Web Resources

Some interesting facts

Fact 1

The first alarm clock could only ring at 4 a.m.

Fact 2

The winter of 1932 in the US was so cold that Niagara falls froze completely solid!

Fact 3

To have your picture taken by the very first camera you would have had to sit still for 8 hours!


text:
Rails.application.routes.draw do

  resources :tags

  # omniauth callback
  get "/auth/:provider/callback", to: "sessions#create"
  get "/sessions/logout", to: "sessions#logout"

  post "/minutes/preview", to: "minutes#preview"
  get "/minutes/search_by_tag", to: "minutes#search_by_tag"

  resources :minutes do
    member do
      get 'reuse'
    end
  end
 # resources :users

  # The priority is based upon order of creation: first created -> highest priority.
  # See how all your routes lay out with "rake routes".

  # You can have the root of your site routed with "root"
  root 'welcome#index'

#  match "users/repositories/" => "users#repositories", :via => [:get]
  resources :users do
    collection do
      get 'repositories'
    end
  end

  namespace :incoming_webhook do
    post 'github'
  end

  # Example of regular route:
  #   get 'products/:id' => 'catalog#view'

  # Example of named route that can be invoked with purchase_url(id: product.id)
  #   get 'products/:id/purchase' => 'catalog#purchase', as: :purchase

  # Example resource route (maps HTTP verbs to controller actions automatically):
  #   resources :products

  # Example resource route with options:
  #   resources :products do
  #     member do
  #       get 'short'
  #       post 'toggle'
  #     end
  #
  #     collection do
  #       get 'sold'
  #     end
  #   end

  # Example resource route with sub-resources:
  #   resources :products do
  #     resources :comments, :sales
  #     resource :seller
  #   end

  # Example resource route with more complex sub-resources:
  #   resources :products do
  #     resources :comments
  #     resources :sales do
  #       get 'recent', on: :collection
  #     end
  #   end

  # Example resource route with concerns:
  #   concern :toggleable do
  #     post 'toggle'
  #   end
  #   resources :posts, concerns: :toggleable
  #   resources :photos, concerns: :toggleable

  # Example resource route within a namespace:
  #   namespace :admin do
  #     # Directs /admin/products/* to Admin::ProductsController
  #     # (app/controllers/admin/products_controller.rb)
  #     resources :products
  #   end
end


text:
layout: "default"
isPage: true
---

# FAQ

### Difference between ESDoc and JSDoc
JSDoc is most popular JavaScript API Documentation tool.
ESDoc is inspired by JSDoc.

- ESDoc
  - supports ES6
  - targets at ES6 ``class`` and ``import/export`` style
  - generates detailed document
  - measures document coverage
  - associates test code to document.
  - is slower than JSDoc(I want to improve it)
- JSDoc
  - supports ES3/ES5 (JSDoc 3.3.0 will support ES6)
  - targets Class-base OOP and Prototype-base OOP
  - has many flexible document tags

### Supported Languages
ESDoc supports ES6(ECMAScript-262 6th, ES2015).

The languages below are not supported.
- ES3, ES5: Use [JSDoc](https://github.com/jsdoc3/jsdoc)
- ES7: Because ES7 is not stable.
- Alt-JS(TypeScript, CoffeeScript, Dart, etc...): Because supporting them is too hard.

### Supported Environment
ESDoc supports Node.js(v0.12) and io.js


text:
/*Problem 9. Trapezoids

Write an expression that calculates trapezoid's area by given sides a and b and height h.
Examples:

a	       b	    h	    area
5	       7	    12	    72
2	       1        33	    49.5
8.5	      4.3	    2.7	    17.28
100	      200	    300	    45000
0.222	  0.333	    0.555	0.1540125*/

using System;

class Trapezoids
{
    static void Main()
    {
        Console.Write("Please enter side A= ");
        double sideA = double.Parse(Console.ReadLine());
        Console.Write("Please enter side B= ");
        double sideB = double.Parse(Console.ReadLine());
        Console.Write("Please enter height H= ");
        double height = double.Parse(Console.ReadLine());
        double area = (((sideA + sideB) / 2) * height);
        Console.WriteLine("Trapezoid with sides A={0}, B={1} and height={2} have area={3}", sideA, sideB, height, area);
    }
}


text:
---
layout: doc_page
title: "Apache Druid (incubating) Quickstart"
---

<!--
  ~ Licensed to the Apache Software Foundation (ASF) under one
  ~ or more contributor license agreements.  See the NOTICE file
  ~ distributed with this work for additional information
  ~ regarding copyright ownership.  The ASF licenses this file
  ~ to you under the Apache License, Version 2.0 (the
  ~ "License"); you may not use this file except in compliance
  ~ with the License.  You may obtain a copy of the License at
  ~
  ~   http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing,
  ~ software distributed under the License is distributed on an
  ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  ~ KIND, either express or implied.  See the License for the
  ~ specific language governing permissions and limitations
  ~ under the License.
  -->

# Apache Druid (incubating) Quickstart

In this quickstart, we will download Druid and set it up on a single machine. The cluster will be ready to load data
after completing this initial setup.

Before beginning the quickstart, it is helpful to read the [general Druid overview](../design/index.html) and the
[ingestion overview](../ingestion/index.html), as the tutorials will refer to concepts discussed on those pages.

## Prerequisites

### Software

You will need:
  * Java 8 (8u92+)
  * Linux, Mac OS X, or other Unix-like OS (Windows is not supported)
  * 8G of RAM
  * 2 vCPUs

## Getting started

[Download](https://www.apache.org/dyn/closer.cgi?path=/incubator/druid/#{DRUIDVERSION}/apache-druid-#{DRUIDVERSION}-bin.tar.gz)
the #{DRUIDVERSION} release.

Extract Druid by running the following commands in your terminal:

```bash
tar -xzf apache-druid-#{DRUIDVERSION}-bin.tar.gz
cd apache-druid-#{DRUIDVERSION}
```

In the package, you should find:

* `DISCLAIMER`, `LICENSE`, and `NOTICE` files
* `bin/*` - scripts useful for this quickstart
* `conf/*` - template configurations for a clustered setup
* `extensions/*` - core Druid extensions
* `hadoop-dependencies/*` - Druid Hadoop dependencies
* `lib/*` - libraries and dependencies for core Druid
* `quickstart/*` - configuration files, sample data, and other files for the quickstart tutorials

## Download Zookeeper

Druid has a dependency on [Apache ZooKeeper](http://zookeeper.apache.org/) for distributed coordination. You'll
need to download and run Zookeeper.

In the package root, run the following commands:

```bash
curl https://archive.apache.org/dist/zookeeper/zookeeper-3.4.11/zookeeper-3.4.11.tar.gz -o zookeeper-3.4.11.tar.gz
tar -xzf zookeeper-3.4.11.tar.gz
mv zookeeper-3.4.11 zk
```

The startup scripts for the tutorial will expect the contents of the Zookeeper tarball to be located at `zk` under the apache-druid-#{DRUIDVERSION} package root.

## Start up Druid services

From the apache-druid-#{DRUIDVERSION} package root, run the following command:

```bash
bin/supervise -c quickstart/tutorial/conf/tutorial-cluster.conf
```

This will bring up instances of Zookeeper and the Druid services, all running on the local machine, e.g.:

```bash
bin/supervise -c quickstart/tutorial/conf/tutorial-cluster.conf
[Wed Feb 27 12:46:13 2019] Running command[zk], logging to[/apache-druid-#{DRUIDVERSION}/var/sv/zk.log]: bin/run-zk quickstart/tutorial/conf
[Wed Feb 27 12:46:13 2019] Running command[coordinator], logging to[/apache-druid-#{DRUIDVERSION}/var/sv/coordinator.log]: bin/run-druid coordinator quickstart/tutorial/conf
[Wed Feb 27 12:46:13 2019] Running command[broker], logging to[/apache-druid-#{DRUIDVERSION}/var/sv/broker.log]: bin/run-druid broker quickstart/tutorial/conf
[Wed Feb 27 12:46:13 2019] Running command[router], logging to[/apache-druid-#{DRUIDVERSION}/var/sv/router.log]: bin/run-druid router quickstart/tutorial/conf
[Wed Feb 27 12:46:13 2019] Running command[historical], logging to[/apache-druid-#{DRUIDVERSION}/var/sv/historical.log]: bin/run-druid historical quickstart/tutorial/conf
[Wed Feb 27 12:46:13 2019] Running command[overlord], logging to[/apache-druid-#{DRUIDVERSION}/var/sv/overlord.log]: bin/run-druid overlord quickstart/tutorial/conf
[Wed Feb 27 12:46:13 2019] Running command[middleManager], logging to[/apache-druid-#{DRUIDVERSION}/var/sv/middleManager.log]: bin/run-druid middleManager quickstart/tutorial/conf
```

All persistent state such as the cluster metadata store and segments for the services will be kept in the `var` directory under the apache-druid-#{DRUIDVERSION} package root. Logs for the services are located at `var/sv`.

Later on, if you'd like to stop the services, CTRL-C to exit the `bin/supervise` script, which will terminate the Druid processes.

### Resetting cluster state

If you want a clean start after stopping the services, delete the `var` directory and run the `bin/supervise` script again.

Once every service has started, you are now ready to load data.

#### Resetting Kafka

If you completed [Tutorial: Loading stream data from Kafka](./tutorial-kafka.html) and wish to reset the cluster state, you should additionally clear out any Kafka state.

Shut down the Kafka broker with CTRL-C before stopping Zookeeper and the Druid services, and then delete the Kafka log directory at `/tmp/kafka-logs`:

```bash
rm -rf /tmp/kafka-logs
```

## Loading Data

### Tutorial Dataset

For the following data loading tutorials, we have included a sample data file containing Wikipedia page edit events that occurred on 2015-09-12.

This sample data is located at `quickstart/tutorial/wikiticker-2015-09-12-sampled.json.gz` from the Druid package root. The page edit events are stored as JSON objects in a text file.

The sample data has the following columns, and an example event is shown below:

  * added
  * channel
  * cityName
  * comment
  * countryIsoCode
  * countryName
  * deleted
  * delta
  * isAnonymous
  * isMinor
  * isNew
  * isRobot
  * isUnpatrolled
  * metroCode
  * namespace
  * page
  * regionIsoCode
  * regionName
  * user

```json
{
  "timestamp":"2015-09-12T20:03:45.018Z",
  "channel":"#en.wikipedia",
  "namespace":"Main",
  "page":"Spider-Man's powers and equipment",
  "user":"foobar",
  "comment":"/* Artificial web-shooters */",
  "cityName":"New York",
  "regionName":"New York",
  "regionIsoCode":"NY",
  "countryName":"United States",
  "countryIsoCode":"US",
  "isAnonymous":false,
  "isNew":false,
  "isMinor":false,
  "isRobot":false,
  "isUnpatrolled":false,
  "added":99,
  "delta":99,
  "deleted":0,
}
```

The following tutorials demonstrate various methods of loading data into Druid, including both batch and streaming use cases.

### [Tutorial: Loading a file](./tutorial-batch.html)

This tutorial demonstrates how to perform a batch file load, using Druid's native batch ingestion.

### [Tutorial: Loading stream data from Apache Kafka](./tutorial-kafka.html)

This tutorial demonstrates how to load streaming data from a Kafka topic.

### [Tutorial: Loading a file using Apache Hadoop](./tutorial-batch-hadoop.html)

This tutorial demonstrates how to perform a batch file load, using a remote Hadoop cluster.

### [Tutorial: Loading data using Tranquility](./tutorial-tranquility.html)

This tutorial demonstrates how to load streaming data by pushing events to Druid using the Tranquility service.

### [Tutorial: Writing your own ingestion spec](./tutorial-ingestion-spec.html)

This tutorial demonstrates how to write a new ingestion spec and use it to load data.


text:
export state_tomo, cal_seqs

function tomo_blocks(qubits::Tuple{Vararg{Qubit}}; num_pulses::Int=4)
    if num_pulses == 4
        tomo_set = [Id, X90, Y90, X]
    elseif num_pulses == 6
        tomo_set = [Id, X90, X90m, Y90, Y90m, X]
    else
        error("Only able to handle num_pulses=4 or 6")
    end
    # TODO: replace with lexproduct when https://github.com/JuliaLang/julia/pull/18825 is merged
    pulse_combos = map(reverse, Base.product( fill(tomo_set, length(qubits))... ))
    return [ reduce(⊗, p(q) for (p,q) in zip(pulses, qubits)) for pulses in vec(pulse_combos) ]
end

"""
  state_tomo(sequence, qubits; num_pulses=4)

Applies state tomography after the `sequence` on the `qubits` using either the
4-pulse [Id, X90, Y90, X] or 6-pulse [Id, X90, X90m, Y90, Y90m, X] set of
tomographic readout pulses.
"""
function state_tomo{T<:QGL.SequenceEntry}(seq::Vector{T}, qubits::Tuple{Vararg{Qubit}}; num_pulses::Int=4)
    meas_block = reduce(⊗, MEAS(q) for q in qubits)
    return [[seq; tomo_block; meas_block] for tomo_block in tomo_blocks(qubits; num_pulses=num_pulses)]
end

"""
  cal_seqs(qubits; num_repeats=2)

Returns an array of "calibration sequences" - all combinations in
lexicographical order of Id and X pulses for the `qubits` followed by the
measurement block. To enhance the visuals or estimate noise the sequences can be
inner repeated by `num_repeats`.

# Example
```julia
julia> cal_seqs((q1,q2); num_repeats=2)
8-element Array{Array{QGL.PulseBlock,1},1}:
 QGL.PulseBlock[(Id(q1))⊗(Id(q2)),(MEAS(M-q1))⊗(MEAS(M-q2))⊗(TRIG(digitizerTrig))]
 QGL.PulseBlock[(Id(q1))⊗(Id(q2)),(MEAS(M-q1))⊗(MEAS(M-q2))⊗(TRIG(digitizerTrig))]
 QGL.PulseBlock[(Id(q1))⊗(X(q2)),(MEAS(M-q1))⊗(MEAS(M-q2))⊗(TRIG(digitizerTrig))]
 QGL.PulseBlock[(Id(q1))⊗(X(q2)),(MEAS(M-q1))⊗(MEAS(M-q2))⊗(TRIG(digitizerTrig))]
 QGL.PulseBlock[(X(q1))⊗(Id(q2)),(MEAS(M-q1))⊗(MEAS(M-q2))⊗(TRIG(digitizerTrig))]
 QGL.PulseBlock[(X(q1))⊗(Id(q2)),(MEAS(M-q1))⊗(MEAS(M-q2))⊗(TRIG(digitizerTrig))]
 QGL.PulseBlock[(X(q1))⊗(X(q2)),(MEAS(M-q1))⊗(MEAS(M-q2))⊗(TRIG(digitizerTrig))]
 QGL.PulseBlock[(X(q1))⊗(X(q2)),(MEAS(M-q1))⊗(MEAS(M-q2))⊗(TRIG(digitizerTrig))]
```
"""
function cal_seqs(qubits::Tuple{Vararg{Qubit}}; num_repeats::Int=2)
    cal_set = [Id, X]
    meas_block = reduce(⊗, MEAS(q) for q in qubits)
    # TODO: replace with lexproduct when https://github.com/JuliaLang/julia/pull/18825 is merged
    pulse_combos = map(reverse, Base.product( fill(cal_set, length(qubits))... ))
    pulse_combos = repeat(vec(pulse_combos), inner=num_repeats)
    return [ [reduce(⊗, p(q) for (p,q) in zip(pulses, qubits)), meas_block] for pulses in pulse_combos]
end

"""
Create and optionally compile a RabiWidth experiment for a single qubit assuming
a tanh pulse shape and a piAmp amplitude

RabiWidth(qubit, pulseSpacings; compile=true)

Parameters
-------
qubit           : qubit in scope
pulseSpacings   : iterable of experiment time steps in seconds
compile         : if true, compile the sequence to .h5 files

Returns
-------
seqs            : Array of sequences

Ex: RabiWidth(q, 1e-9*linspace(10, 2010, 201))
"""
function RabiWidth(qubit, pulseSpacings; compile::Bool=true)
    qubit.shape_params[:shape_function] = QGL.PulseShapes.tanh;
	seqs = [[Uθ(qubit, len, qubit.shape_params[:piAmp], 0., qubit.frequency, qubit.shape_params),
        MEAS(qubit)] for len in pulseSpacings]
    if compile
	   compile_to_hardware(seqs, "Rabi");
    end
    return seqs
end

"""
Create and optionally compile a RabiAmp experiment for a single qubit

RabiWidth(qubit, amps; compile=true)

Parameters
-------
qubit           : qubit in scope
amps            : iterable of experiment amplitudes [-1,1]
compile         : if true, compile the sequence to .h5 files

Returns
-------
seqs            : Array of sequences

Ex: RabiAmp(q, linspace(-1, 1, 101))
"""

function RabiAmp(qubit, amps; compile::Bool=true)
	seqs = [[Uθ(qubit, qubit.shape_params[:length], amp, 0.),
        MEAS(qubit)] for amp in amps]
    if compile
        compile_to_hardware(seqs, "Rabi");
    end
    return seqs
end

"""
Create and optionally compile a T1 experiment for a single qubit

InversionRecovery(qubit, amps; compile=true)

qubit           : qubit in scope
pulseSpacings   : iterable of experiment time steps in seconds
compile         : if true, compile the sequence to .h5 files

returns         : Array of sequences

Ex: InversionRecovery(q, 1e-9*linspace(10, 2010, 201))
"""

function InversionRecovery(qubit, pulseSpacings; num_repeats::Int=2, compile::Bool=true)
	seqs = [[X(qubit), Id(qubit,len), MEAS(qubit)] for len in pulseSpacings];
    cals = cal_seqs((qubit,), num_repeats = num_repeats);
    seqs = append!(seqs, cals);
    if compile
        compile_to_hardware(seqs, "T1");
    end
    return seqs
end

"""
Create and optionally compile a Ramsey experiment for a single qubit

Ramsey(qubit, pulseSpacings; TPPIFreq::Float64=0.0, num_repeats::Int=2, compile=true)

Parameters
-------
qubit           : qubit in scope
pulseSpacings   : iterable of experiment time steps in seconds
TPPIFreq        : time-proportinal phase increment frequency in Hz
num_repeats     : number of calibration repeats
compile         : if true, compile the sequence to .h5 files

Returns
-------
seqs            : Array of sequences

Ex: Ramsey(q, 1e-9*linspace(10, 2010, 201))

"""
function Ramsey(qubit, pulseSpacings; TPPIFreq::Float64=0.0, num_repeats::Int=2, compile::Bool=true)
    phases = TPPIFreq * pulseSpacings

    seqs = [[X90(qubit), Id(qubit, l), Uθ(qubit, qubit.shape_params[:length],
        qubit.shape_params[:pi2Amp], phase), MEAS(qubit)] for (l, phase) in zip(pulseSpacings, phases)];
    cals = cal_seqs((qubit,), num_repeats = num_repeats);
    seqs = append!(seqs, cals);
    if compile
        compile_to_hardware(seqs, "Ramsey");
    end
    return seqs
end


text:
package com.gentics.mesh.core.endpoint.node;

import static com.gentics.mesh.http.HttpConstants.ETAG;
import static com.gentics.mesh.util.MimeTypeUtils.DEFAULT_BINARY_MIME_TYPE;
import static io.netty.handler.codec.http.HttpResponseStatus.NOT_MODIFIED;

import javax.inject.Inject;
import javax.inject.Singleton;

import com.gentics.mesh.context.InternalActionContext;
import com.gentics.mesh.context.impl.InternalRoutingActionContextImpl;
import com.gentics.mesh.core.data.binary.HibBinary;
import com.gentics.mesh.core.data.dao.BinaryDao;
import com.gentics.mesh.core.data.node.field.HibBinaryField;
import com.gentics.mesh.core.db.Tx;
import com.gentics.mesh.core.image.ImageManipulator;
import com.gentics.mesh.core.rest.node.field.image.FocalPoint;
import com.gentics.mesh.handler.RangeRequestHandler;
import com.gentics.mesh.http.MeshHeaders;
import com.gentics.mesh.parameter.ImageManipulationParameters;
import com.gentics.mesh.core.data.storage.BinaryStorage;
import com.gentics.mesh.util.ETag;
import com.gentics.mesh.util.EncodeUtil;
import com.gentics.mesh.util.MimeTypeUtils;

import io.vertx.core.http.HttpHeaders;
import io.vertx.core.http.HttpServerResponse;
import io.vertx.core.http.impl.MimeMapping;
import io.vertx.ext.web.RoutingContext;
import io.vertx.reactivex.core.Vertx;

/**
 * Handler which will accept {@link HibBinaryField} elements and return the binary data using the given context.
 */
@Singleton
public class BinaryFieldResponseHandler {

	private final ImageManipulator imageManipulator;

	private final BinaryStorage storage;

	private final Vertx rxVertx;

	private final RangeRequestHandler rangeRequestHandler;

	@Inject
	public BinaryFieldResponseHandler(ImageManipulator imageManipulator, BinaryStorage storage, Vertx rxVertx, RangeRequestHandler rangeRequestHandler) {
		this.imageManipulator = imageManipulator;
		this.storage = storage;
		this.rxVertx = rxVertx;
		this.rangeRequestHandler = rangeRequestHandler;
	}

	/**
	 * Handle the binary field response.
	 *
	 * @param rc
	 * @param binaryField
	 */
	public void handle(RoutingContext rc, HibBinaryField binaryField) {
		rc.response().putHeader(HttpHeaders.ACCEPT_RANGES, "bytes");
		if (checkETag(rc, binaryField)) {
			return;
		}
		InternalActionContext ac = new InternalRoutingActionContextImpl(rc);
		ImageManipulationParameters imageParams = ac.getImageParameters();
		if (binaryField.hasProcessableImage() && imageParams.hasResizeParams()) {
			resizeAndRespond(rc, binaryField, imageParams);
		} else {
			respond(rc, binaryField);
		}
	}

	private boolean checkETag(RoutingContext rc, HibBinaryField binaryField) {
		InternalActionContext ac = new InternalRoutingActionContextImpl(rc);
		String sha512sum = binaryField.getBinary().getSHA512Sum();
		String etagKey = sha512sum;
		if (binaryField.hasProcessableImage()) {
			etagKey += ac.getImageParameters().getQueryParameters();
		}

		String etagHeaderValue = ETag.prepareHeader(ETag.hash(etagKey), false);
		HttpServerResponse response = rc.response();
		response.putHeader(ETAG, etagHeaderValue);
		String requestETag = rc.request().getHeader(HttpHeaders.IF_NONE_MATCH);
		if (requestETag != null && requestETag.equals(etagHeaderValue)) {
			response.setStatusCode(NOT_MODIFIED.code()).end();
			return true;
		}
		return false;
	}

	private void respond(RoutingContext rc, HibBinaryField binaryField) {
		BinaryDao binaryDao = Tx.get().binaryDao();
		HttpServerResponse response = rc.response();

		HibBinary binary = binaryField.getBinary();
		String fileName = binaryField.getFileName();
		String contentType = binaryField.getMimeType();
		// Try to guess the contenttype via the filename
		if (contentType == null) {
			contentType = MimeMapping.getMimeTypeForFilename(fileName);
		}

		response.putHeader(MeshHeaders.WEBROOT_RESPONSE_TYPE, "binary");

		addContentDispositionHeader(response, fileName, "attachment");

		// Set to IDENTITY to avoid gzip compression
		response.putHeader(HttpHeaders.CONTENT_ENCODING, HttpHeaders.IDENTITY);

		String localPath = storage.getLocalPath(binary.getUuid());
		if (localPath != null) {
			rangeRequestHandler.handle(rc, localPath, contentType);
		} else {
			String contentLength = String.valueOf(binary.getSize());
			if (contentType != null) {
				response.putHeader(HttpHeaders.CONTENT_TYPE, contentType);
			}
			response.putHeader(HttpHeaders.CACHE_CONTROL, "must-revalidate");
			response.putHeader(HttpHeaders.CONTENT_LENGTH, contentLength);
			binaryDao.getStream(binary).subscribe(response::write, rc::fail, response::end);
		}

	}

	private void resizeAndRespond(RoutingContext rc, HibBinaryField binaryField, ImageManipulationParameters imageParams) {
		HttpServerResponse response = rc.response();
		// We can maybe enhance the parameters using stored parameters.
		if (!imageParams.hasFocalPoint()) {
			FocalPoint fp = binaryField.getImageFocalPoint();
			if (fp != null) {
				imageParams.setFocalPoint(fp);
			}
		}
		Integer originalHeight = binaryField.getBinary().getImageHeight();
		Integer originalWidth = binaryField.getBinary().getImageWidth();

		if ("auto".equals(imageParams.getHeight())) {
			imageParams.setHeight(originalHeight);
		}
		if ("auto".equals(imageParams.getWidth())) {
			imageParams.setWidth(originalWidth);
		}
		String fileName = binaryField.getFileName();
		imageManipulator.handleResize(binaryField.getBinary(), imageParams)
			.flatMap(cachedFilePath -> rxVertx.fileSystem().rxProps(cachedFilePath)
				.doOnSuccess(props -> {
					response.putHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(props.size()));
					response.putHeader(HttpHeaders.CONTENT_TYPE, MimeTypeUtils.getMimeTypeForFilename(cachedFilePath).orElse(DEFAULT_BINARY_MIME_TYPE));
					response.putHeader(HttpHeaders.CACHE_CONTROL, "must-revalidate");
					response.putHeader(MeshHeaders.WEBROOT_RESPONSE_TYPE, "binary");
					// Set to IDENTITY to avoid gzip compression
					response.putHeader(HttpHeaders.CONTENT_ENCODING, HttpHeaders.IDENTITY);

					addContentDispositionHeader(response, fileName, "inline");

					response.sendFile(cachedFilePath);
				}))
			.subscribe(ignore -> {}, rc::fail);
	}

	private void addContentDispositionHeader(HttpServerResponse response, String fileName, String type) {
		String encodedFileNameUTF8 = EncodeUtil.encodeForRFC5597(fileName);
		String encodedFileNameISO = EncodeUtil.toISO88591(fileName);

		StringBuilder value = new StringBuilder();
		value.append(type + ";");
		value.append(" filename=\"" + encodedFileNameISO + "\";");
		value.append(" filename*=" + encodedFileNameUTF8);
		response.putHeader("content-disposition", value.toString());
	}

}


text:
package system_chaincode

import (
	//import system chain codes here
	"github.com/hyperledger/fabric/core/system_chaincode/api"
	"github.com/hyperledger/fabric/core/system_chaincode/sample_syscc"
)

//RegisterSysCCs is the hook for system chaincodes where system chaincodes are registered with the fabric
//note the chaincode must still be deployed and launched like a user chaincode will be
func RegisterSysCCs() {
	api.RegisterSysCC("github.com/hyperledger/fabric/core/system_chaincode/sample_syscc", &sample_syscc.SampleSysCC{})
}


text:
import React from 'react';
import PropTypes from 'prop-types';
import get from 'lodash.get';
import pure from 'recompose/pure';

const hasNumberFormat = !!(
    typeof Intl === 'object' &&
    Intl &&
    typeof Intl.NumberFormat === 'function'
);

/**
 * Display a numeric value as a locale string.
 *
 * Uses Intl.NumberFormat() if available, passing the locales and options props as arguments.
 * If Intl is not available, it outputs number as is (and ignores the locales and options props).
 *
 * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString
 * @example
 * <NumberField source="score" />
 * // renders the record { id: 1234, score: 567 } as
 * 567
 *
 * <NumberField source="score" elStyle={{ color: 'red' }} />
 * // renders the record { id: 1234, score: 567 } as
 * 567
 *
 * <NumberField source="share" options={{ style: 'percent' }} />
 * // renders the record { id: 1234, share: 0.2545 } as
 * 25%
 *
 * <NumberField source="price" options={{ style: 'currency', currency: 'USD' }} />
 * // renders the record { id: 1234, price: 25.99 } as
 * $25.99
 *
 * <NumberField source="price" locales="fr-FR" options={{ style: 'currency', currency: 'USD' }} />
 * // renders the record { id: 1234, price: 25.99 } as
 * 25,99 $US
 */
export const NumberField = ({ record, source, locales, options, elStyle }) => {
    if (!record) return null;
    const value = get(record, source);
    if (value == null) return null;
    if (!hasNumberFormat) return {value};
    return (
        {value.toLocaleString(locales, options)}
    );
};

NumberField.propTypes = {
    addLabel: PropTypes.bool,
    elStyle: PropTypes.object,
    label: PropTypes.string,
    locales: PropTypes.oneOfType([
        PropTypes.string,
        PropTypes.arrayOf(PropTypes.string),
    ]),
    options: PropTypes.object,
    record: PropTypes.object,
    source: PropTypes.string.isRequired,
};

const PureNumberField = pure(NumberField);

PureNumberField.defaultProps = {
    addLabel: true,
    style: { textAlign: 'right' },
    headerStyle: { textAlign: 'right' },
};

export default PureNumberField;


text:
%
% Licensed to the Apache Software Foundation (ASF) under one
% or more contributor license agreements.  See the NOTICE file
% distributed with this work for additional information
% regarding copyright ownership.  The ASF licenses this file
% to you under the Apache License, Version 2.0 (the
% "License"); you may not use this file except in compliance
% with the License.  You may obtain a copy of the License at
%
%   http://www.apache.org/licenses/LICENSE-2.0
%
% Unless required by applicable law or agreed to in writing,
% software distributed under the License is distributed on an
% "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
% KIND, either express or implied.  See the License for the
% specific language governing permissions and limitations
% under the License.
%
\documentclass[convert={density=300,size=500x500,outext=.png}]{standalone}
\usepackage{tikz}
\usepackage{pgf}
\usetikzlibrary{arrows,positioning}
\usepackage{graphicx}
\tikzset{
    procs/.style={
           rectangle,
           rounded corners,
           draw=black, thick,
           text width=13em,
           minimum height=.5em,
           text centered},
    % Define arrow style
    msgs/.style={
           ->,
           thick,
           shorten <=2pt,
           shorten >=2pt,}
}
\begin{document}
\begin{tikzpicture}[node distance=1cm, auto,]
	\node[procs] (nc) {\large Node Controller (NC)};
	\node[procs,above=of nc] (ncservice) {\large NC Service};
	\node[procs, above= of ncservice] (cc) {\large Cluster Controller (CC)};

	\path [draw, -latex'] (ncservice) -- node {\scriptsize 2. NC startup}(nc);
	\path [draw, -latex'] (cc) --  node {\scriptsize 1. NC parameters }(ncservice);
	\draw [->] (nc.east) -- ++(1em,0) node[near end, rotate=-90,xshift=-4em] {\scriptsize 3. NC registration} |- (cc.east);
\end{tikzpicture} \\*

\end{document}


text:
package org.springframework.boot.context.embedded.jetty;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.HandlerCollection;
import org.eclipse.jetty.server.handler.HandlerWrapper;
import org.springframework.boot.context.embedded.EmbeddedServletContainer;
import org.springframework.boot.context.embedded.EmbeddedServletContainerException;
import org.springframework.util.Assert;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.StringUtils;

/**
 * {@link EmbeddedServletContainer} that can be used to control an embedded Jetty server.
 * Usually this class should be created using the
 * {@link JettyEmbeddedServletContainerFactory} and not directly.
 *
 * @author Phillip Webb
 * @author Dave Syer
 * @author David Liu
 * @see JettyEmbeddedServletContainerFactory
 */
public class JettyEmbeddedServletContainer implements EmbeddedServletContainer {

	private static final Log logger = LogFactory
			.getLog(JettyEmbeddedServletContainer.class);

	private final Server server;

	private final boolean autoStart;

	private Connector[] connectors;

	/**
	 * Create a new {@link JettyEmbeddedServletContainer} instance.
	 * @param server the underlying Jetty server
	 */
	public JettyEmbeddedServletContainer(Server server) {
		this(server, true);
	}

	/**
	 * Create a new {@link JettyEmbeddedServletContainer} instance.
	 * @param server the underlying Jetty server
	 * @param autoStart if auto-starting the container
	 */
	public JettyEmbeddedServletContainer(Server server, boolean autoStart) {
		this.autoStart = autoStart;
		Assert.notNull(server, "Jetty Server must not be null");
		this.server = server;
		initialize();
	}

	private synchronized void initialize() {
		try {
			// Cache and clear the connectors to prevent requests being handled before
			// the application context is ready
			this.connectors = this.server.getConnectors();
			this.server.setConnectors(null);

			// Start the server so that the ServletContext is available
			this.server.start();
		}
		catch (Exception ex) {
			// Ensure process isn't left running
			stopSilently();
			throw new EmbeddedServletContainerException(
					"Unable to start embedded Jetty servlet container", ex);
		}
	}

	private void stopSilently() {
		try {
			this.server.stop();
		}
		catch (Exception ex) {
		}
	}

	@Override
	public void start() throws EmbeddedServletContainerException {
		this.server.setConnectors(this.connectors);
		if (!this.autoStart) {
			return;
		}
		try {
			this.server.start();
			for (Handler handler : this.server.getHandlers()) {
				handleDeferredInitialize(handler);
			}
			Connector[] connectors = this.server.getConnectors();
			for (Connector connector : connectors) {
				connector.start();
			}
			JettyEmbeddedServletContainer.logger.info("Jetty started on port(s) "
					+ getActualPortsDescription());
		}
		catch (Exception ex) {
			throw new EmbeddedServletContainerException(
					"Unable to start embedded Jetty servlet container", ex);
		}
	}

	private String getActualPortsDescription() {
		StringBuilder ports = new StringBuilder();
		for (Connector connector : this.server.getConnectors()) {
			ports.append(ports.length() == 0 ? "" : ", ");
			ports.append(getLocalPort(connector) + getProtocols(connector));
		}
		return ports.toString();
	}

	private Integer getLocalPort(Connector connector) {
		try {
			// Jetty 9 internals are different, but the method name is the same
			return (Integer) ReflectionUtils.invokeMethod(
					ReflectionUtils.findMethod(connector.getClass(), "getLocalPort"),
					connector);
		}
		catch (Exception ex) {
			JettyEmbeddedServletContainer.logger.info("could not determine port ( "
					+ ex.getMessage() + ")");
			return 0;
		}
	}

	private String getProtocols(Connector connector) {
		try {
			List<String> protocols = connector.getProtocols();
			return " (" + StringUtils.collectionToDelimitedString(protocols, ", ") + ")";
		}
		catch (NoSuchMethodError ex) {
			// Not available with Jetty 8
			return "";
		}

	}

	private void handleDeferredInitialize(Handler... handlers) throws Exception {
		for (Handler handler : handlers) {
			if (handler instanceof JettyEmbeddedWebAppContext) {
				((JettyEmbeddedWebAppContext) handler).deferredInitialize();
			}
			else if (handler instanceof HandlerWrapper) {
				handleDeferredInitialize(((HandlerWrapper) handler).getHandler());
			}
			else if (handler instanceof HandlerCollection) {
				handleDeferredInitialize(((HandlerCollection) handler).getHandlers());
			}
		}
	}

	@Override
	public synchronized void stop() {
		try {
			this.server.stop();
		}
		catch (InterruptedException ex) {
			Thread.currentThread().interrupt();
		}
		catch (Exception ex) {
			throw new EmbeddedServletContainerException(
					"Unable to stop embedded Jetty servlet container", ex);
		}
	}

	@Override
	public int getPort() {
		Connector[] connectors = this.server.getConnectors();
		for (Connector connector : connectors) {
			// Probably only one...
			return getLocalPort(connector);
		}
		return 0;
	}

	/**
	 * Returns access to the underlying Jetty Server.
	 * @return the Jetty server
	 */
	public Server getServer() {
		return this.server;
	}

}


text:
var basename = require('path').basename;
var utils = require('cli-util');
var merge = utils.merge, walk = utils.walk;
var native = require('cli-native');
var camelcase = utils.camelcase;
var delimited = utils.delimited;

var defaults = {
  prefix: basename(process.argv[1]),
  delimiter: '_',
  initialize: false,
  match: null,
  transform: {
    key: null,
    value: null,
    name: null
  },
  expand: {
    delimiter: null,
    transform: function(key) {
      return key.toLowerCase();
    }
  },
  native: null
}

/**
 *  Helper class for accessing environment variables
 *  using a defined prefix.
 *
 *  @param conf The configuration object.
 */
var Environment = function(conf) {
  Object.defineProperty(this, 'conf',
    {
      enumerable: false,
      configurable: false,
      writable: false,
      value: conf || {}
    }
  );
  if(this.conf.initialize) {
    this.load();
  }
}

/**
 *  Retrieve a suitable key for setting an environment
 *  variable.
 *
 *  @api private
 *
 *  @param key The candidate key.
 *
 *  @return A converted key.
 */
function getKey(key) {
  if(this.conf.transform) {
    if(typeof(this.conf.transform.key) == 'function') {
      return this.conf.transform.key.call(this, key);
    }
  }
  key = delimited(key, this.conf.delimiter);
  key = key.replace(/- /, this.conf.delimiter);
  key = key.replace(/[^a-zA-Z0-9_]/, '');
  if(this.conf.prefix) {
    return this.conf.prefix + this.conf.delimiter + key.toLowerCase()
  }
  return key.toLowerCase();
}

/**
 *  Retrieve the value of a variable from the environment.
 *
 *  @api private
 *
 *  @param key The key that has already been passed through
 *  the key transformation function.
 *  @param property The name of a property corresponding to the key.
 *  @param raw The raw untouched key.
 *
 *  @return The value of the environment variable.
 */
function getValue (key, name, raw) {
  if(this.conf.transform) {
    if(typeof(this.conf.transform.value) == 'function') {
      return this.conf.transform.value.call(this, key, name, raw);
    }
  }
  var value = process.env[raw] || this[name];
  if(this.conf.native && typeof(value) == 'string') {
    value = native.to(
      value, this.conf.native.delimiter, this.conf.native.json);
  }
  return value;
}

/**
 *  Convert a key into a property name.
 *
 *  @param key The property key.
 *
 *  @return A camel case property name.
 */
function getName(key) {
  if(key == '_') return key;
  if(this.conf.transform) {
    if(typeof(this.conf.transform.name) == 'function') {
      return this.conf.transform.name.call(this, key);
    }
  }
  if(this.conf.prefix) {
    key = key.replace(this.conf.prefix + '_', '');
  }
  // guard against silly variables such as npm_config_cache____foo
  key = key.replace(
    new RegExp(this.conf.delimiter + '+', 'g'), this.conf.delimiter);

  return camelcase(key, this.conf.delimiter)
}

/**
 *  Set an environment variable using the transform
 *  set function.
 *
 *  @param key The variable key.
 *  @param value The variable value.
 */
function set(key, value) {
  var k = this.getKey(key);
  var name = this.getName(key);
  if(this.conf.native && typeof(value) == 'string') {
    try {
      value = native.to(
        value, this.conf.native.delimiter, this.conf.native.json);
    }catch(e){}
  }
  this[name] = process.env[k] = value;
}

/**
 *  Get an environment variable using the transform
 *  get function.
 *
 *  @param key The variable key.
 *
 *  @return The variable value.
 */
function get(key) {
  var k = this.getKey(key);
  var name = this.getName(key);
  var value = this.getValue(k, name, key);
  return value;
}

/**
 *  Load variables from the environment into this
 *  instance.
 *
 *  @param match A regular expression test determining
 *  which variables to load.
 */
function load(match) {
  match = match || this.conf.match;
  for(var z in process.env) {
    if(match instanceof RegExp) {
      if(match.test(z)) {
        this.set(z.toLowerCase(), process.env[z]);
      }
    }else{
      this.set(z.toLowerCase(), process.env[z]);
    }
  }

  // expand out camel case strings using another delimiter
  if(this.conf.expand && this.conf.expand.delimiter) {
    var o = {}, k, v, val;
    for(k in this) {
      val = this[k];
      v = delimited(k, this.conf.expand.delimiter);
      if(typeof this.conf.expand.transform === 'function') {
        v = this.conf.expand.transform(v);
      }

      this.set(v, val);
      delete this[k];
    }
  }
}

/**
 *  Performs substitution of environment variables within
 *  strings. The substitution format is:
 *
 *    $variable or ${variable}
 *
 *  @param str The target string value.
 *  @param env An object containing environment variables
 *  default is process.env.
 *  @param escaping Whether escaped dollars indicate replacement
 *  should be ignored.
 *  @param convert A conversion function used to convert the value
 *  to a string value before replacement.
 *  @param strict Throw an error if a replacement does not match an
 *  environment variable.
 */
function replace(str, env, escaping, convert, strict) {
  if(!str) return str;
  var re = /(\\?)(\$\{?)(\w+)(\}?)/g;
  if(!re.test(str)) return str;
  env = env || process.env;
  escaping = escaping === undefined ? true : escaping;
  if(!convert) {
    convert = function(value){return value};
  }
  str = str.replace(re, function(
    match, backslash, prefix, name, suffix, offset, string) {
    if(backslash && env[name]) {
      if(escaping) {
        return prefix + name + suffix;
      }
    }
    if(!env[name] && backslash && escaping) {
      return prefix + name + suffix;
    }
    if(env[name]) {
      if(!escaping && backslash) {
        return backslash + convert(env[name]);
      }
      return convert(env[name]);
    }else if(strict) {
      throw new Error(
        'environment variable replace could not locate variable: ' + name)
    }
    return match;
  })
  return str;
}

/**
 *  Performs recursive substitution of environment variables within
 *  complex objects.
 *
 *  @param root The root object.
 *  @param env An object containing environment variables
 *  default is process.env.
 *  @param escaping Whether escaped dollars indicate replacement
 *  should be ignored.
 */
function env(root, env, escaping) {
  walk(root, function visit(props) {
    return (props.value instanceof String) || typeof props.value === 'string';
  }, function transform(props) {
    props.parent[props.name] = replace(props.value, env, escaping);
  })
}

var methods = {
  getKey: getKey,
  getValue: getValue,
  getName: getName,
  get: get,
  set: set,
  load: load
}

for(var z in methods) {
  Object.defineProperty(Environment.prototype, z,
    {
      enumerable: false,
      configurable: false,
      writable: false,
      value: methods[z]
    }
  )
}

module.exports = function(conf) {
  var c = merge(defaults, {}, {copy: true});
  var env = new Environment(merge(conf, c));
  return env;
}

module.exports.Environment = Environment;
module.exports.replace = replace;
module.exports.env = env;


text:
<!DOCTYPE html>

<title>OffscreenCanvas test: 2d.path.closePath.empty</title>

2d.path.closePath.empty


text:
package org.globsframework.streams.accessors.utils;

import org.globsframework.streams.accessors.BooleanAccessor;

public class ValueBooleanAccessor implements BooleanAccessor {
    private Boolean value;

    public ValueBooleanAccessor() {
    }

    public ValueBooleanAccessor(Boolean value) {
        this.value = value;
    }

    public void setValue(Boolean value) {
        this.value = value;
    }

    public Object getObjectValue() {
        return value;
    }

    public Boolean getBoolean() {
        return value;
    }

    public boolean getValue(boolean valueIfNull) {
        return value;
    }
}


text:
for d in $fpath; do
	if [[ -e "$d/url-quote-magic" ]]; then
		autoload -U url-quote-magic
		zle -N self-insert url-quote-magic
	fi
done

## jobs
setopt long_list_jobs

## pager
export PAGER="less"
export LESS="-R"

# only define LC_CTYPE if undefined
if [[ -z "$LC_CTYPE" && -z "$LC_ALL" ]]; then
	export LC_CTYPE=${LANG%%:*} # pick the first entry from LANG
fi

# recognize comments
setopt interactivecomments

# rerun previous command. For when I try to Ctrl-p <enter> and forget to press Ctrl.
alias p='$(fc -ln -1)'

alias tails="tail -n 75 -f"
alias rpsec="rspec" # I can't spell rspec

alias frs="foreman run rails server -b 0.0.0.0"


text:
package com.eaglesakura.andriders.plugin.data;

import com.eaglesakura.andriders.AceSdkUtil;
import com.eaglesakura.andriders.plugin.connection.PluginConnection;
import com.eaglesakura.andriders.plugin.internal.CentralDataCommand;
import com.eaglesakura.andriders.plugin.internal.PluginServerImpl;
import com.eaglesakura.andriders.sensor.SensorType;
import com.eaglesakura.andriders.serialize.PluginProtocol;
import com.eaglesakura.android.service.data.Payload;

import android.location.Location;
import android.support.annotation.FloatRange;
import android.support.annotation.IntRange;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;

/**
 * ACEの持つデータを送受信する。
 */
public class CentralEngineSessionData {

    final PluginServerImpl mServerImpl;

    final PluginConnection mConnection;

    public CentralEngineSessionData(@NonNull PluginConnection connection, @NonNull PluginServerImpl serverImpl) {
        mConnection = connection;
        mServerImpl = serverImpl;
    }

    /**
     * 接続先のMACアドレスを取得する
     * <p/>
     * このアドレスにしたがってデータを得る
     */
    @Nullable
    public String getGadgetAddress(@NonNull SensorType type) {
        try {
            return mServerImpl.postToClientAsString(CentralDataCommand.CMD_setBleGadgetAddress, type.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * ホイールの外周サイズ(mm)を取得する。
     *
     * デフォルトは700x23cに合わせ、 2096.0 となる。
     */
    @FloatRange(from = 0.0)
    public float getWheelOuterLength() {
        try {
            return Float.parseFloat(mServerImpl.postToClientAsString(CentralDataCommand.CMD_getWheelOuterLength, null));
        } catch (Exception e) {
            return 2096;
        }
    }

    /**
     * ユーザーのGPS座標を更新する
     */
    public void setLocation(@NonNull Location loc) {
        mServerImpl.validAcesSession();

        try {
            PluginProtocol.SrcLocation idl = new PluginProtocol.SrcLocation(loc);
            Payload payload = new Payload(AceSdkUtil.serializeToByteArray(idl));
            mServerImpl.postToClient(CentralDataCommand.CMD_setLocation, payload);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 心拍を更新する
     */
    public void setHeartrate(@IntRange(from = 1) int bpm) {
        mServerImpl.validAcesSession();

        try {
            PluginProtocol.SrcHeartrate idl = new PluginProtocol.SrcHeartrate((short) bpm);
            Payload payload = new Payload(AceSdkUtil.serializeToByteArray(idl));
            mServerImpl.postToClient(CentralDataCommand.CMD_setHeartrate, payload);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * S&Cセンサーの情報を更新する
     */
    public void setSpeedAndCadence(@FloatRange(from = 0) float crankRpm, @IntRange(from = 0) int crankRevolution, @FloatRange(from = 0) float wheelRpm, @IntRange(from = 0) int wheelRevolution) {
        mServerImpl.validAcesSession();

        try {
            PluginProtocol.SrcSpeedAndCadence idl = new PluginProtocol.SrcSpeedAndCadence();
            idl.crankRpm = crankRpm;
            idl.crankRevolution = crankRevolution;
            idl.wheelRpm = wheelRpm;
            idl.wheelRevolution = wheelRevolution;

            Payload payload = new Payload(AceSdkUtil.serializeToByteArray(idl));
            mServerImpl.postToClient(CentralDataCommand.CMD_setSpeedAndCadence, payload);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


text:
import { NotificationController } from './notification-controller';

export interface RendererNotifyStatic {
    new (): Renderer;
}

/**
 * An abstract base class for implementors of the basic Renderer API.
 */
export class Renderer {
    /**
     * Gets an anchor for the ViewSlot to insert a view into.
     * @returns A DOM element.
     */
    public getNotificationContainer(): Element {
        throw new Error('NotificationRenderer must implement getNotificationContainer().');
    }

    /**
     * Displays the notification.
     * @returns Promise A promise that resolves when the notification has been displayed.
     */
    public showNotification(_notificationController: NotificationController): Promise<any> {
        throw new Error('NotificationRenderer must implement showNotification().');
    }

    /**
     * Hides the notification.
     * @returns Promise A promise that resolves when the notification has been hidden.
     */
    public hideNotification(_notificationController: NotificationController): Promise<any> {
        throw new Error('NotificationRenderer must implement hideNotification().');
    }
}


text:
package simplifier

import "github.com/twtiger/gosecco/tree"

// AcceptBinaryNegation implements Visitor
func (s *binaryNegationSimplifier) AcceptBinaryNegation(v tree.BinaryNegation) {
	val := s.Transform(v.Operand)
	s.Result = tree.Arithmetic{Op: tree.BINXOR, Left: val, Right: tree.NumericLiteral{uint64(0xFFFFFFFFFFFFFFFF)}}
}

// binaryNegationSimplifier simplifies binary complement by removing it and replacing it with an xor instruction
type binaryNegationSimplifier struct {
	tree.EmptyTransformer
}

func createBinaryNegationSimplifier() tree.Transformer {
	s := &binaryNegationSimplifier{}
	s.RealSelf = s
	return s
}


text:
---
title: "Separation of Web and App"
layout: "post"
permalink: "/2008/06/firefox-with-gmail-and-google-calendar.html"
uuid: "4766216136616838981"
guid: "tag:blogger.com,1999:blog-32090046.post-4766216136616838981"
date: "2008-07-01 02:46:00"
updated: "2008-07-01 14:11:49"
description:
blogger:
    siteid: "32090046"
    postid: "4766216136616838981"
    comments: "0"
categories: [firefox, gmail]
author:
    name: "rectalogic"
    url: "undefined?rel=author"
    image: "http://img2.blogblog.com/img/b16-rounded.gif"
---

I need to run Gmail and Google Calendar in a separate browser instance from my working browser so they are isolated from crashes/hangs. I tried the Firefox 3 [Prism plugin](https://addons.mozilla.org/en-US/firefox/addon/6665) along with [gmail.webapp](http://starkravingfinkle.org/projects/webrunner/gmail.webapp) and [gcalendar.webapp](http://starkravingfinkle.org/projects/webrunner/gcalendar.webapp) but wasn't happy with this - mainly because I don't want a separate instance for gmail and calendar. I want my browser and one other instance hosting both gmail and calendar.

You can run multiple Firefox instances by directly launching `/Applications/Firefox.app/Contents/MacOS/firefox` - but risk corrupting shared profile database files.

So I ended up creating a simple profile just for these webapps - launching the [Profile Manager](http://kb.mozillazine.org/Opening_a_new_instance_of_Firefox_with_another_profile) with
`/Applications/Firefox.app/Contents/MacOS/firefox -P -no-remote` and creating a new profile named google.

Now I can launch gmail and calendar using this new profile in a separate Firefox instance like this: `/Applications/Firefox.app/Contents/MacOS/firefox-bin -P google -no-remote https://mail.google.com/mail https://www.google.com/calendar/render`. I packaged this shell script in a bundle as Google.app and gave it the icon borrowed from `Google Notifier.app`.  You can download it [here](http://www.rectalogic.com/downloads/GoogleFirefox.dmg).

Also, if you prefer monospace fonts when viewing and composing plain text emails in Gmail, create a user CSS file in the google profile you created above (e.g. `~/Library/Application Support/Firefox/Profiles/*.google/chrome/userContent.css`) with the following contents:

```css
@-moz-document domain(mail.google.com)
{
    /* GMail messages and textarea should use fixed-width font */
    .ArwC7c, .iE5Yyc {
        font-family: MonoSpace !important;
        font-size: 9pt !important;
    }
}
```


text:
package org.statmantis;

import org.junit.BeforeClass;
import org.statmantis.mport.park.RetrosheetParkReaderTest;
import org.statmantis.mport.person.RetrosheetPersonReaderTest;
import org.statmantis.mport.retro.RetrosheetContext;
import org.statmantis.mport.team.RetrosheetTeamReaderTest;

/**
 * Base test class for tests that need a retrosheet context
 *
 * @author Chad Retz
 */
public abstract class RetrosheetContextAwareTestBase {

    protected static RetrosheetContext retroContext;

    @BeforeClass
    public static void oneTimeSetUp() throws Exception {
        //build the context
        retroContext = new RetrosheetContext();
        retroContext.getParks().putAll(RetrosheetParkReaderTest.getParks());
        retroContext.getPersons().putAll(RetrosheetPersonReaderTest.getPersons());
        retroContext.getTeams().putAll(RetrosheetTeamReaderTest.getTeams(retroContext));
    }
}


text: <?php include('../analyticstracking.php') ?>


text: @start %LOCAL%\etc\motd.txt


text:
name "sphinx"
version "1.1.3"

dependency "pip"
dependency "pygments"

build do
  command "#{install_dir}/embedded/bin/pip install -I --build #{project_dir} #{name}==#{version}"
end


text:
	<title>Change Password</title>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta name="generator" content="HelpNDoc">
	<link type="text/css" rel="stylesheet" media="all" href="css/reset.css" />
	<link type="text/css" rel="stylesheet" media="all" href="css/base.css" />
	<link type="text/css" rel="stylesheet" media="all" href="css/hnd.css" />

Change Password

					Getting Started ››

Change password allows User to reset their password in case User cannot login or forgets the password.  If there is failure to login, User can reset their password.

Created with the Personal Edition of HelpNDoc: Free Web Help generator

				Copyright © <Dates> by <Authors>. All Rights Reserved.


text:
from os.path import dirname, realpath, exists
from setuptools import setup
import sys

author = "Paul Müller"
authors = [author]
description = 'Algorithms for diffraction tomography'
name = 'odtbrain'
year = "2015"

sys.path.insert(0, realpath(dirname(__file__))+"/"+name)
from _version import version  # noqa: E402

if __name__ == "__main__":  # required by Windows/pytest (multiprocessing)
    setup(
        name=name,
        author=author,
        author_email='dev@craban.de',
        url='https://github.com/RI-imaging/ODTbrain',
        version=version,
        packages=[name],
        package_dir={name: name},
        license="BSD (3 clause)",
        description=description,
        long_description=open('README.rst').read()
            if exists('README.rst') else '',
        install_requires=["numexpr",  # 3D backpropagation
                          "numpy>=1.7.0",
                          "pyfftw>=0.9.2",  # 3D backpropagation
                          "scikit-image>=0.11.0",  # phase-unwrapping
                          "scipy>=1.4.0",  # Updated QHull in griddata
                          ],
        python_requires='>=3.5, <4',
        keywords=["odt", "opt", "diffraction", "born", "rytov", "radon",
                  "backprojection", "backpropagation", "inverse problem",
                  "Fourier diffraction theorem", "Fourier slice theorem"],
        classifiers=[
            'Operating System :: OS Independent',
            'Programming Language :: Python :: 3',
            'Topic :: Scientific/Engineering :: Visualization',
            'Intended Audience :: Science/Research'
                     ],
        platforms=['ALL'],
        )


text:
namespace PBQP {

  /// \brief Abstract base class for heuristic implementations.
  ///
  /// This class provides a handy base for heuristic implementations with common
  /// solver behaviour implemented for a number of methods.
  ///
  /// To implement your own heuristic using this class as a base you'll have to
  /// implement, as a minimum, the following methods:
  ///

  ///
 void addToHeuristicList(Graph::NodeItr) : Add a node to the
  ///        heuristic reduction list.
  ///
 void heuristicReduce() : Perform a single heuristic reduction.
  ///
 void preUpdateEdgeCosts(Graph::EdgeItr) : Handle the (imminent)
  ///        change to the cost matrix on the given edge (by R2).
  ///
 void postUpdateEdgeCostts(Graph::EdgeItr) : Handle the new
  ///        costs on the given edge.
  ///
 void handleAddEdge(Graph::EdgeItr) : Handle the addition of a new
  ///        edge into the PBQP graph (by R2).
  ///
 void handleRemoveEdge(Graph::EdgeItr, Graph::NodeItr) : Handle the
  ///        disconnection of the given edge from the given node.
  ///
 A constructor for your derived class : to pass back a reference to
  ///        the solver which is using this heuristic.
  ///

  ///
  /// These methods are implemented in this class for documentation purposes,
  /// but will assert if called.
  ///
  /// Note that this class uses the curiously recursive template idiom to
  /// forward calls to the derived class. These methods need not be made
  /// virtual, and indeed probably shouldn't for performance reasons.
  ///
  /// You'll also need to provide NodeData and EdgeData structs in your class.
  /// These can be used to attach data relevant to your heuristic to each
  /// node/edge in the PBQP graph.

  template <typename HImpl>
  class HeuristicBase {
  private:

    typedef std::list<Graph::NodeItr> OptimalList;

    HeuristicSolverImpl<HImpl> &s;
    Graph &g;
    OptimalList optimalList;

    // Return a reference to the derived heuristic.
    HImpl& impl() { return static_cast<HImpl&>(*this); }

    // Add the given node to the optimal reductions list. Keep an iterator to
    // its location for fast removal.
    void addToOptimalReductionList(Graph::NodeItr nItr) {
      optimalList.insert(optimalList.end(), nItr);
    }

  public:

    /// \brief Construct an instance with a reference to the given solver.
    /// @param solver The solver which is using this heuristic instance.
    HeuristicBase(HeuristicSolverImpl<HImpl> &solver)
      : s(solver), g(s.getGraph()) { }

    /// \brief Get the solver which is using this heuristic instance.
    /// @return The solver which is using this heuristic instance.
    ///
    /// You can use this method to get access to the solver in your derived
    /// heuristic implementation.
    HeuristicSolverImpl<HImpl>& getSolver() { return s; }

    /// \brief Get the graph representing the problem to be solved.
    /// @return The graph representing the problem to be solved.
    Graph& getGraph() { return g; }

    /// \brief Tell the solver to simplify the graph before the reduction phase.
    /// @return Whether or not the solver should run a simplification phase
    ///         prior to the main setup and reduction.
    ///
    /// HeuristicBase returns true from this method as it's a sensible default,
    /// however you can over-ride it in your derived class if you want different
    /// behaviour.
    bool solverRunSimplify() const { return true; }

    /// \brief Decide whether a node should be optimally or heuristically
    ///        reduced.
    /// @return Whether or not the given node should be listed for optimal
    ///         reduction (via R0, R1 or R2).
    ///
    /// HeuristicBase returns true for any node with degree less than 3. This is
    /// sane and sensible for many situations, but not all. You can over-ride
    /// this method in your derived class if you want a different selection
    /// criteria. Note however that your criteria for selecting optimal nodes
    /// should be at least as strong as this. I.e. Nodes of degree 3 or
    /// higher should not be selected under any circumstances.
    bool shouldOptimallyReduce(Graph::NodeItr nItr) {
      if (g.getNodeDegree(nItr) < 3)
        return true;
      // else
      return false;
    }

    /// \brief Add the given node to the list of nodes to be optimally reduced.
    /// @param nItr Node iterator to be added.
    ///
    /// You probably don't want to over-ride this, except perhaps to record
    /// statistics before calling this implementation. HeuristicBase relies on
    /// its behaviour.
    void addToOptimalReduceList(Graph::NodeItr nItr) {
      optimalList.push_back(nItr);
    }

    /// \brief Initialise the heuristic.
    ///
    /// HeuristicBase iterates over all nodes in the problem and adds them to
    /// the appropriate list using addToOptimalReduceList or
    /// addToHeuristicReduceList based on the result of shouldOptimallyReduce.
    ///
    /// This behaviour should be fine for most situations.
    void setup() {
      for (Graph::NodeItr nItr = g.nodesBegin(), nEnd = g.nodesEnd();
           nItr != nEnd; ++nItr) {
        if (impl().shouldOptimallyReduce(nItr)) {
          addToOptimalReduceList(nItr);
        } else {
          impl().addToHeuristicReduceList(nItr);
        }
      }
    }

    /// \brief Optimally reduce one of the nodes in the optimal reduce list.
    /// @return True if a reduction takes place, false if the optimal reduce
    ///         list is empty.
    ///
    /// Selects a node from the optimal reduce list and removes it, applying
    /// R0, R1 or R2 as appropriate based on the selected node's degree.
    bool optimalReduce() {
      if (optimalList.empty())
        return false;

      Graph::NodeItr nItr = optimalList.front();
      optimalList.pop_front();

      switch (s.getSolverDegree(nItr)) {
        case 0: s.applyR0(nItr); break;
        case 1: s.applyR1(nItr); break;
        case 2: s.applyR2(nItr); break;
        default: llvm_unreachable(
                        "Optimal reductions of degree > 2 nodes is invalid.");
      }

      return true;
    }

    /// \brief Perform the PBQP reduction process.
    ///
    /// Reduces the problem to the empty graph by repeated application of the
    /// reduction rules R0, R1, R2 and RN.
    /// R0, R1 or R2 are always applied if possible before RN is used.
    void reduce() {
      bool finished = false;

      while (!finished) {
        if (!optimalReduce()) {
          if (impl().heuristicReduce()) {
            getSolver().recordRN();
          } else {
            finished = true;
          }
        }
      }
    }

    /// \brief Add a node to the heuristic reduce list.
    /// @param nItr Node iterator to add to the heuristic reduce list.
    void addToHeuristicList(Graph::NodeItr nItr) {
      llvm_unreachable("Must be implemented in derived class.");
    }

    /// \brief Heuristically reduce one of the nodes in the heuristic
    ///        reduce list.
    /// @return True if a reduction takes place, false if the heuristic reduce
    ///         list is empty.
    bool heuristicReduce() {
      llvm_unreachable("Must be implemented in derived class.");
      return false;
    }

    /// \brief Prepare a change in the costs on the given edge.
    /// @param eItr Edge iterator.
    void preUpdateEdgeCosts(Graph::EdgeItr eItr) {
      llvm_unreachable("Must be implemented in derived class.");
    }

    /// \brief Handle the change in the costs on the given edge.
    /// @param eItr Edge iterator.
    void postUpdateEdgeCostts(Graph::EdgeItr eItr) {
      llvm_unreachable("Must be implemented in derived class.");
    }

    /// \brief Handle the addition of a new edge into the PBQP graph.
    /// @param eItr Edge iterator for the added edge.
    void handleAddEdge(Graph::EdgeItr eItr) {
      llvm_unreachable("Must be implemented in derived class.");
    }

    /// \brief Handle disconnection of an edge from a node.
    /// @param eItr Edge iterator for edge being disconnected.
    /// @param nItr Node iterator for the node being disconnected from.
    ///
    /// Edges are frequently removed due to the removal of a node. This
    /// method allows for the effect to be computed only for the remaining
    /// node in the graph.
    void handleRemoveEdge(Graph::EdgeItr eItr, Graph::NodeItr nItr) {
      llvm_unreachable("Must be implemented in derived class.");
    }

    /// \brief Clean up any structures used by HeuristicBase.
    ///
    /// At present this just performs a sanity check: that the optimal reduce
    /// list is empty now that reduction has completed.
    ///
    /// If your derived class has more complex structures which need tearing
    /// down you should over-ride this method but include a call back to this
    /// implementation.
    void cleanup() {
      assert(optimalList.empty() && "Nodes left over in optimal reduce list?");
    }

  };

}

#endif // LLVM_CODEGEN_PBQP_HEURISTICBASE_H


text:
package org.elasticsearch.index.codec.postingsformat;

import org.apache.lucene.codecs.PostingsFormat;
import org.apache.lucene.codecs.blocktree.BlockTreeTermsWriter;
import org.apache.lucene.codecs.lucene50.Lucene50PostingsFormat;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.inject.assistedinject.Assisted;
import org.elasticsearch.common.settings.Settings;

/**
 * The default postingsformat, maps to {@link Lucene50PostingsFormat}.
 *

 *
<tt>min_block_size</tt>: the minimum block size the default Lucene term
 * dictionary uses to encode on-disk blocks.

 *
 *
<tt>max_block_size</tt>: the maximum block size the default Lucene term
 * dictionary uses to encode on-disk blocks.

 *

 */
// LUCENE UPGRADE: Check if type of field postingsFormat needs to be updated!
public class DefaultPostingsFormatProvider extends AbstractPostingsFormatProvider {

    private final int minBlockSize;
    private final int maxBlockSize;
    private final Lucene50PostingsFormat postingsFormat;

    @Inject
    public DefaultPostingsFormatProvider(@Assisted String name, @Assisted Settings postingsFormatSettings) {
        super(name);
        this.minBlockSize = postingsFormatSettings.getAsInt("min_block_size", BlockTreeTermsWriter.DEFAULT_MIN_BLOCK_SIZE);
        this.maxBlockSize = postingsFormatSettings.getAsInt("max_block_size", BlockTreeTermsWriter.DEFAULT_MAX_BLOCK_SIZE);
        this.postingsFormat = new Lucene50PostingsFormat(minBlockSize, maxBlockSize);
    }

    public int minBlockSize() {
        return minBlockSize;
    }

    public int maxBlockSize() {
        return maxBlockSize;
    }

    @Override
    public PostingsFormat get() {
        return postingsFormat;
    }
}


text:
package com.kotikan.hack.picture.heartbeat;

import com.kotikan.hack.picture.imageServer.Images;
import com.kotikan.hack.picture.model.Session;

/**
 * Created by roberthewitt on 29/09/2014.
 */
public class Beats {

    public static HeartBeats instance() {

        return new HeartBeats() {
            @Override
            public BeatInfo pulse(Session session) {
                if (Images.instance().isNewImageRequired(session)) {
                    return BeatInfo.CHANGED;
                } else {
                    return BeatInfo.UNCHANGED;
                }
            }
        };
    }

}


text:
<?php

namespace AppBundle\Controller;
use FOS\RestBundle\Controller\Annotations\Delete;
use FOS\RestBundle\Controller\Annotations\Post;
use FOS\RestBundle\Controller\Annotations\Get;
use FOS\RestBundle\Controller\Annotations\Put;
use FOS\RestBundle\Controller\FOSRestController;
use Symfony\Component\HttpFoundation\Request;
use AppBundle\Entity\WhiteListCategories;
use AppBundle\Form\WhiteListCategoriesType;
use Doctrine\Common\Util\Inflector;

class WhiteListCategoriesRestController extends FOSRestController
{
    /**
     *
     * @Get("/whitelistcategories/{id}")
     */
    public function getWhiteListCategoriesAction($id){
        $whitelist = $this->getDoctrine()->getRepository('AppBundle:WhiteListCategories')->find($id);

        if(!is_object($whitelist)){
            throw $this->createNotFoundException();
        }

        return $whitelist;
    }

    /**
     *
     * @Get("/whitelistcategories")
     */
    public function getAllWhiteListCategoriesAction(){
        $whitelist = $this->getDoctrine()->getRepository('AppBundle:WhiteListCategories')->findAll();

        if(count($whitelist) == 0){
            throw $this->createNotFoundException();
        }

        return $whitelist;
    }

    /**
     *
     * @Post("/whitelistcategories")
     */
    public function postWhiteListCategoriesAction(Request $request){
        $json = $request->request->all();

        $whitelist = new WhiteListCategories();

        $form = $this->createForm(WhiteListCategoriesType::class, $whitelist);

        $form->handleRequest($request);
        $form->submit($request);

        if ($form->isValid()) {
            foreach($json as $field=> $value)
            {
                $setter = sprintf('set%s', ucfirst(Inflector::camelize($field)));
                if(preg_match('/\d{4}-\d{2}-\d{2}/',$value)){
                    $value = new \DateTime($value);
                }
                $whitelist->$setter($value);
            }
            $em = $this->getDoctrine()->getManager();
            $em->persist($whitelist);
            $em->flush();
        }
        return $whitelist;
    }

    /**
     *
     * @Put("/whitelistcategories/{id}")
     */
    public function putWhiteListCategoriesAction(Request $request, $id){
        $putItems = json_decode($request->getContent() ,true);

        $whitelist = $this->getDoctrine()->getRepository('AppBundle:WhiteListCategories')->find($id);

        if(!is_object($whitelist)){
            throw $this->createNotFoundException();
        }

        foreach($putItems as $field=> $value)
        {
            $setter = sprintf('set%s', ucfirst(Inflector::camelize($field)));
            if(preg_match('/\d{4}-\d{2}-\d{2}/',$value)){
                $value = new \DateTime($value);
            }
            $whitelist->$setter($value);
        }

        $form = $this->createForm(new WhiteListCategoriesType(),$whitelist);

        $form->handleRequest($request);
        $form->submit($request->getContent());

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($whitelist);
            $em->flush();
        }

        return $whitelist;
    }

    /**
     *
     * @Delete("/whitelistcategories/{id}")
     */
    public function deleteWhiteListCategoriesAction($id){

    }
}