text:
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************

using SDKTemplate;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;

namespace SecondaryTiles
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class TilePinned : Page
    {
        // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
        // as NotifyUser()
        MainPage rootPage = MainPage.Current;
        AppBar appBar;

        public TilePinned()
        {
            this.InitializeComponent();
        }

        /// <summary>
        /// Invoked when this page is about to be displayed in a Frame.
        /// </summary>
        /// <param name="e">Event data that describes how this page was reached.  The Parameter
        /// property is typically used to configure the page.</param>
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            // Preserve the app bar
            appBar = rootPage.BottomAppBar;
            // this ensures the app bar is not shown in this scenario
            rootPage.BottomAppBar = null;
        }

        /// <summary>
        /// Invoked when this page is about to be navigated out in a Frame
        /// </summary>
        /// <param name="e">Event data that describes how this page was reached.  The Parameter
        /// property is typically used to configure the page.</param>
        protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
        {
            // Restore the app bar
            rootPage.BottomAppBar = appBar;
        }

        /// <summary>
        /// This is the click handler for the 'TileExists' button.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TileExists_Click(object sender, RoutedEventArgs e)
        {
            Button button = sender as Button;
            if (button != null)
            {
                if (Windows.UI.StartScreen.SecondaryTile.Exists(MainPage.logoSecondaryTileId))
                {
                    rootPage.NotifyUser(MainPage.logoSecondaryTileId + " is pinned.", NotifyType.StatusMessage);
                }
                else
                {
                    rootPage.NotifyUser(MainPage.logoSecondaryTileId + " not currently pinned.", NotifyType.ErrorMessage);
                }
            }
        }
    }
}


text:
FROM aarch64/ubuntu
MAINTAINER Roman Shaposhnik <rvs@apache.org>

COPY bigtop_toolchain /etc/puppet/modules/bigtop_toolchain
COPY gradle.home /usr/share/gradle.home

RUN /etc/puppet/modules/bigtop_toolchain/bin/puppetize.sh
RUN puppet apply -e "include bigtop_toolchain::installer"
RUN chown jenkins:jenkins /usr/share/gradle.home

ENV GRADLE_USER_HOME=/usr/share/gradle.home

redpajama_set_name: RedPajamaGithub


text:
module ActiveAdmin
  module ViewHelpers
    module SidebarHelper

      def skip_sidebar!
        @skip_sidebar = true
      end

      def view_sidebar!
        @skip_sidebar = false
      end

      def skip_sidebar?
        @skip_sidebar == true
      end

    end
  end
end


text:
@interface BSAppDelegate : NSObject <NSApplicationDelegate,BSRefreshableScrollViewDataSource,BSRefreshableScrollViewDelegate>

@property (assign) IBOutlet NSWindow *window;

@property (nonatomic,weak) IBOutlet BSRefreshableScrollView* refreshableScrollView;

- (IBAction)stopRefreshTop:(id)sender;
- (IBAction)stopRefreshBottom:(id)sender;

@end


text:
/* ViewProfiles Styles */

.viewProfilesContainer {
  display:flex;
  min-height:100vh;
  text-align: center;
  font-family: 'Play', sans-serif;
  background-image: url("../../IMAGES/Computer_5.jpg");
  background-size:cover;
  background-position:center top;
  background-repeat:no-repeat;
  background-attachment:fixed;
  z-index: 0;
  flex-direction: column;
}

.usersDisplay {

  display: flex;
  flex-direction: row;
}
.viewResult {
  text-decoration:none;
  color:#009999;
  font-size: 1.5em;
  text-align: center;
  padding-top: 15px;
  width: calc(25% - 40px);
  background:#EEEEEE;
  border-radius:5px;
  min-height:150px;
  margin:10px;
  padding:10px;
}
.userList {
display: flex;
flex-direction: row;
}


text:
using Windows.UI.Xaml;

namespace TheChan.Views.Controls {
    public sealed partial class TabHeader {
        public static readonly DependencyProperty GlyphProperty = DependencyProperty.Register("Glyph", typeof (string),
            typeof (TabHeader), null);

        public string Glyph {
            get { return GetValue(GlyphProperty) as string; }
            set { SetValue(GlyphProperty, value); }
        }

        public static readonly DependencyProperty LabelProperty = DependencyProperty.Register("Label", typeof (string),
            typeof (TabHeader), null);

        public string Label {
            get { return GetValue(LabelProperty) as string; }
            set { SetValue(LabelProperty, value); }
        }

        public TabHeader() {
            InitializeComponent();
        }
    }
}


text:
package iot.pood.storage.service

import com.outworkers.phantom.ResultSet

import scala.concurrent.Future

/**
  * Created by rafik on 9.8.2017.
  */
trait DataService[A] {

  def saveItem(record: A): Future[ResultSet]

  def saveItems(records: Set[A]): Future[Set[ResultSet]]

}


text:
package types

// DockerCompose represents the docker compose object
type DockerCompose struct {
	Version  string
	Services DockerConfigs
	Volumes  map[string]interface{}
}

// NewDockerCompose returns a docker compose object
func NewDockerCompose() *DockerCompose {
	return &DockerCompose{
		Version:  "3",
		Services: DockerConfigs{},
		Volumes:  map[string]interface{}{},
	}
}

// Merge joins the given docker compose objects into one
func (d *DockerCompose) Merge(objs ...*DockerCompose) *DockerCompose {
	result := NewDockerCompose()
	for _, obj := range append(objs, d) {
		result.Services = result.Services.Merge(obj.Services)
		for key, val := range obj.Volumes {
			result.Volumes[key] = val
		}
	}
	return result
}


text:
require 'spec_helper'
require 'mailgun'
require 'railgun'

describe 'extract_body' do

  let(:text_mail_option) {
    {
      from:        'bob@example.com',
      to:          'sally@example.com',
      subject:     'RAILGUN TEST SAMPLE',
      body:         text_content,
      content_type: 'text/plain',
    }
  }
  let(:text_content) { '[TEST] Hello, world.' }

  let(:html_mail_option) {
    {
      from:        'bob@example.com',
      to:          'sally@example.com',
      subject:     'RAILGUN TEST SAMPLE',
      body:         html_content,
      content_type: 'text/html',
    }
  }
  let(:html_content) { '<h3> [TEST] </h3> <br/> Hello, world!' }

  context 'with <Content-Type: text/plain>' do
    let(:sample_mail) { Mail.new(text_mail_option) }

    it 'should return body text' do
      expect(Railgun.extract_body_text(sample_mail)).to eq(text_content)
    end

    it 'should not return body html' do
      expect(Railgun.extract_body_html(sample_mail)).to be_nil
    end
  end

  context 'with <Content-Type: text/html>' do
    let(:sample_mail) { Mail.new(html_mail_option) }

    it 'should not return body text' do
      expect(Railgun.extract_body_text(sample_mail)).to be_nil
    end

    it 'should return body html' do
      expect(Railgun.extract_body_html(sample_mail)).to eq(html_content)
    end
  end

  context 'with <Content-Type: multipart/alternative>' do
    let(:text_mail) { Mail.new(text_mail_option) }
    let(:html_mail) { Mail.new(html_mail_option) }

    before do
      @sample_mail = Mail::Part.new(content_type: "multipart/alternative")
      @sample_mail.add_part text_mail
      @sample_mail.add_part html_mail
    end

    it 'should return body text' do
      expect(Railgun.extract_body_text(@sample_mail)).to eq(text_content)
    end

    it 'should return body html' do
      expect(Railgun.extract_body_html(@sample_mail)).to eq(html_content)
    end
  end
end


text:
using BooksLib.Models;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace BooksLib.Repositories
{
    public class BooksSampleRepository : IBooksRepository
    {
        private List<Book> _books;
        public BooksSampleRepository()
        {
            InitSampleBooks();
        }

        private void InitSampleBooks()
        {
            _books = new List<Book>()
            {
                new Book { BookId = 1, Title = "Professional C# 6 and .NET Core 1.0", Publisher = "Wrox Press" },
                new Book { BookId = 2, Title = "Professional C# 5.0 and .NET 4.5.1", Publisher = "Wrox Press" },
                new Book { BookId = 3, Title = "Enterprise Services with the .NET Framework", Publisher = "AWL" }
            };
        }

        public Task<bool> DeleteAsync(int id)
        {
            Book bookToDelete = _books.Find(b => b.BookId == id);
            if (bookToDelete != null)
            {
                return Task.FromResult<bool>(_books.Remove(bookToDelete));
            }
            return Task.FromResult<bool>(false);
        }

        public Task<Book> GetItemAsync(int id) =>
            Task.FromResult(_books.Find(b => b.BookId == id));

        public Task<IEnumerable<Book>> GetItemsAsync() =>
            Task.FromResult<IEnumerable<Book>>(_books);

        public Task<Book> UpdateAsync(Book item)
        {
            Book bookToUpdate = _books.Find(b => b.BookId == item.BookId);
            if (bookToUpdate == null) return null;
            int ix = _books.IndexOf(bookToUpdate);
            _books[ix] = item;
            return Task.FromResult(_books[ix]);
        }

        public Task<Book> AddAsync(Book item)
        {
            item.BookId = _books.Select(b => b.BookId).Max() + 1;
            _books.Add(item);
            return Task.FromResult(item);
        }
    }
}


text:
var fs = require('fs');
var glob = require('glob');

// fs.existsSync is marked as deprecated, so accessSync is used instead (if it's available in the running version of Node).
function doesFileExist(path) {
    var exists;
    if (fs.accessSync) {
        try {
            fs.accessSync(path);
            exists = true;
        } catch (ex) {
            exists = false;
        }
    } else {
        exists = fs.existsSync(path);
    }
    return exists;
}

var args = process.argv.splice(2);

console.log("=== concat [" + args[0] + "] into [" + args[1] + "] ...");
if (args[2]) console.log("Input encoding: " + args[2]);

if (doesFileExist(args[1])) {
    console.log("~~ delete: " + args[1]);
    fs.unlinkSync(args[1]);
}

glob.sync(args[0]).forEach(function(file) {
    console.log("-- append: " + file);
    var src = fs.readFileSync(file, args[2] ? args[2] : 'utf8');
    src = src.replace(/^\uFEFF/, ''); // BOM strip
    fs.appendFileSync(args[1], src, 'utf8');
});


text:
layout: post
title: "Stack & Queues"
description: "Introduction"
date: 2016-12-22
tags: [algorithm, stack, queues, data structures]
comments: true
share: true
---
## Contents
- [Stack](#stack)
- [Queue](#queue)

## Stack

Stack is data structure which follows **LIFO** (Last in first out) property. Stack supports two operations namely:

* **```push(element)```** - put the element in Queue
* **```pop()```** - remove the element from the Queue and return the element

Lets us understand these operations (Push, Pop) through the following example:

Say a woman is making chappatis and after each of the chappatis are finished, she is keeping them in a container. So how would this look like -

First the container is empty
* When the first chappati is finished making, it is placed in the container (Push)
* When the second chappati is finished, it is placed in the container on the top of the first chappati (again a Push)

Similarly it happens for all the n chappatis she makes - it means that **nth** chappati is at the top and the 1st chappati is at bottom of the container

Now suppose you sat for having dinner, and you asked for a chappati
So she will bring you the nth  chappati first (Pop), now **(n-1)th** is at top in the container
And if you asked for another chappati, she will bring you the **(n-1)th** one (again Pop)

What happened here?

Your container behaved liked a stack. Initially your stack was empty (when there were no chappatis in the container). Once she starts putting chappatis in the container (Push operation), the stack started to fill - the last chappati put into the container represents the top of the stack. When you started having dinner, the Pop operation began. Pop only allows the top of the stack to be removed and once its removed, the new element which is on the top of the stack becomes the top element.

We will now see how to implement stack in C++ (There is also an inbuilt stack in C++, its better to use that but here we will see how to implement stack if you don't want to use inbuilt stack):

[StackCode](https://github.com/dummybyte/CodeBlog/blob/master/Stack.cpp)

#### Time Complexity

As you can see there are no loops and only insertion and deletion operation over vector which is O(1) for each **push** and **pop** operation.

Note: The stack can be implemented by arrays as well and as well by linked list.
For arrays, we will have constraint of the size of the stack which will be equal to size of the array declared. We need to just maintain the index of the top element of the stack - the variable top will point to top most element of the stack. In case of pop(), just decrement the top variable and in case of push(int x), just overwrite the next index of the array and increment top.

If you are implementing by linked list, we need to maintain two pointers one will be head and the other will be top. In case of pop(), just need to change the previous node pointer to null and free the current node. And incase of push(), create a node and point the previous top to current node and update top to current node.

## Queue
Queue is a data structure which follows **FIFO** (First in First out) property. Lets understand from this example:

Suppose you need to buy a railway ticket counter. You go to a ticket-counter and stand in line(queue). Now the person standing at first gets the ticket first (since he has come first) and the person standing at last gets the ticket at last. Basically who came first gets the ticket first - in the order in which they came, they are served in the same order.

The same happens in a Queue. The element which is inserted in queue first gets popped out first (FIFO architecture). Queue also serves two operation -
* **```push/enQueue(element)```** - put the element in Queue
* **```pop()```** - remove the element from the Queue and return the element

We will see the queue implementation in C++:

[Queue Implementation](https://github.com/dummybyte/CodeBlog/blob/master/Queue.cpp)

#### Time Complexity
The time complexity for each ```push()``` and ```pop()``` is O(1).

Note: There are many ways by which you can implement Queue e.g. using Linked Lists, Arrays etc.

Here is a Linked List Implementation of Queue:
[Queue Linked List Implementaion](https://github.com/dummybyte/CodeBlog/blob/master/QueueLinkedListImplementation.cpp)


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- $Revision: 330543 $ -->
<refentry xmlns="http://docbook.org/ns/docbook" xml:id="pharfileinfo.getcompressedsize">
 <refnamediv>
  <refname>PharFileInfo::getCompressedSize</refname>
  <refpurpose>Returns the actual size of the file (with compression) inside the Phar archive</refpurpose>
 </refnamediv>
 <refsect1 role="description">
  &reftitle.description;
  <methodsynopsis>
   <modifier>public</modifier> <type>int</type><methodname>PharFileInfo::getCompressedSize</methodname>
   <void/>
  </methodsynopsis>

  <para>
   This returns the size of the file within the Phar archive.  Uncompressed files will return
   the same value for getCompressedSize as they will with <function>filesize</function>
  </para>
 </refsect1>

 <refsect1 role="returnvalues">
  &reftitle.returnvalues;
  <para>
   The size in bytes of the file within the Phar archive on disk.
  </para>
 </refsect1>

 <refsect1 role="examples">
  &reftitle.examples;
  <para>
   <example>
    <title>A <function>PharFileInfo::getCompressedSize</function> example</title>
    <programlisting role="php">
<![CDATA[
<?php
try {
    $p = new Phar('/path/to/my.phar', 0, 'my.phar');
    $p['myfile.txt'] = 'hi';
    $file = $p['myfile.txt'];
    echo $file->getCompressedSize();
} catch (Exception $e) {
    echo 'Write operations failed on my.phar: ', $e;
}
?>
]]>
    </programlisting>
    &example.outputs;
    <screen>
<![CDATA[
2
]]>
    </screen>
   </example>
  </para>
 </refsect1>

 <refsect1 role="seealso">
  &reftitle.seealso;
  <para>
   <simplelist>
    <member><function>PharFileInfo::isCompressed</function></member>
    <member><function>PharFileInfo::decompress</function></member>
    <member><function>PharFileInfo::compress</function></member>
    <member><function>Phar::canCompress</function></member>
    <member><function>Phar::isCompressed</function></member>
    <member><function>Phar::compress</function></member>
    <member><function>Phar::decompress</function></member>
    <member><function>Phar::getSupportedCompression</function></member>
    <member><function>Phar::decompressFiles</function></member>
    <member><function>Phar::compressFiles</function></member>
   </simplelist>
  </para>
 </refsect1>

</refentry>

<!-- Keep this comment at the end of the file
Local variables:
mode: sgml
sgml-omittag:t
sgml-shorttag:t
sgml-minimize-attributes:nil
sgml-always-quote-attributes:t
sgml-indent-step:1
sgml-indent-data:t
indent-tabs-mode:nil
sgml-parent-document:nil
sgml-default-dtd-file:"~/.phpdoc/manual.ced"
sgml-exposed-tags:nil
sgml-local-catalogs:nil
sgml-local-ecat-files:nil
End:
vim600: syn=xml fen fdm=syntax fdl=2 si
vim: et tw=78 syn=sgml
vi: ts=1 sw=1
-->


text:
@protocol getPassWord <NSObject>

- (void)getName:(NSString *)name andCount:(NSString *)count andPassWord:(NSString *)passWord;

@end

@interface RegisterViewController : UIViewController

@property(nonatomic, assign) id<getPassWord>delegate;

@end


text:
package projects.lcr.nodes.messages;

import sinalgo.nodes.messages.Message;

public class ColorMessage extends Message {

	private int uidoriginal = 0;
	private int colorID = 0 ;
	private int rootRenvoi = 0; //pour identifier si le root renvoie le message ?
	                              // si oui 1; sinon 0

	private int fois = 1;

	//constructeur
	public ColorMessage(int uid, int colorID){
		this.uidoriginal = uid;
		this.colorID = colorID;
	}

	public void setFois(){
		this.fois --;
	}

	public int getFois(){
		return this.fois;
	}

	public void setUidOriginal(int id){
		this.uidoriginal = id;
	}
	public void setColorID(int cid){
		this.colorID = cid;
	}
	public void setRootRenvoi(int i){
		this.rootRenvoi = i;
	}

	public int getUidOriginal(){
		return this.uidoriginal;
	}

	public int getColorID(){
		return this.colorID;
	}
	public int getRootRenvoi(){
		return this.rootRenvoi;
	}
	@Override
	public Message clone() {
		// TODO Auto-generated method stub
		return null;
	}

}


text:
Rails.application.routes.draw do

  namespace :admin do
  namespace :store do
    get 'manifests/index'
    end
  end

  get 'cart/remove/:id' => 'cart#remove'
  post 'cart/update'
  get 'cart/add_deal'
  get 'cart/add'
  post 'cart/applycode'
  get 'cart/apply_fb_discount'
  get 'cart/personalize'
  post 'cart/upload_picture'
  get 'cart/checkout'
  get 'cart/review'
  post 'cart/review' => 'cart#submit'
  post 'cart/checkout' => 'cart#checkout_update'
  get 'cart/submitted'
  get 'cart' => 'cart#index'
  get 'planding/:slug' => 'products#product_landing'
  get "products/:slug" => 'products#show'
  get 'resize' => 'images#resize'
  get 'images/resize'
  get "paypal_express/checkout"
  get "paypal_express/review"
  get 'barcode' => 'barcode#generate'

  # daily deals
  get '/deals/email' =>'daily_deals#email'
  get '/deals/:slug' => 'daily_deals#show'
  get '/deals' => 'daily_deals#index'

  # affiliate products
  get '/ap/:affiliate_slug/:product_slug' => 'affiliate_products#show'
  get '/ap/:affiliate_slug' => 'affiliate_products#index'

  # easypost webhook (callback)
  post '/easypost' => 'easypost#webhook'

  namespace :account do
    resources :orders
    resources :vouchers
    resources :auto_ship_items
  end

  namespace :admin do

    namespace :system do
      resources :affiliates do
        member do
          get 'products' => 'affiliates#products'
          post 'products_remove' => 'affiliates#remove_products'
          post 'products' => 'affiliates#create_products'
        end
      end
    end

    namespace :inventory do
      get 'reports/quantities_in_stock'
      get 'reports/item_demand'
      get 'reports' => 'reports#index'
      post 'purchase_orders_update_status' => 'purchase_orders#update_status'
      post 'purchase_orders_print_batch' => 'purchase_orders#print_batch'

      resources :purchase_orders do
        member do
          get 'items' => 'purchase_orders#items'
          post 'items' => 'purchase_orders#update_items'
          get 'receiving' => 'purchase_orders#receiving'
          post 'items' => 'purchase_orders#update_items'
          post 'receiving' => 'purchase_orders#update_receiving'
          get 'print'
          get 'set_status'
        end
      end
      resources :purchase_order_items
      resources :inventory_items
      resources :inventory_locations
      resources :inventory_transactions
    end

    # Store Routes
    namespace :store do

      get 'reports/product_sales_by_sku'
      get 'reports/product_sales_by_affiliate'
      get 'reports/product_sales_by_user'
      get 'reports/product_sales'
      get 'reports/daily_sales'
      get 'reports/monthly_sales'
      get 'reports/delayed_shipments'
      get 'reports/dropshipper_performance'
			get 'reports/shipments'
      get 'reports/sales_trend'
      get 'reports/pending_fulfillment'
      get 'reports/current_stock'
      get 'reports/inventory_required'
      get 'reports/user_leaderboard'
      get 'reports/purchase_frequency'
      get 'reports' => 'reports#index'

      get 'shipments_batch' => 'shipments#batch'
      get 'shipments_auto_batch' => 'shipments#auto_batch'
      get 'shipments/choose_order'
      post 'shipments_update_status' => 'shipments#update_status'
      post 'shipments_packing_slip_batch' => 'shipments#packing_slip_batch'
      post 'shipments_shipping_label_batch' => 'shipments#shipping_label_batch'
      post 'shipments_invoice_batch' => 'shipments#invoice_batch'
      get 'shipments/product_labels_pending'
      get 'shipments/product_labels'
      post 'shipments/product_labels' => 'shipments#label_print'

      get 'products/adjust_prices'
      post 'products/adjust_prices' => 'products#update_prices'

      post 'easy_post/batch'
      get 'easy_post/batch_status'
			get 'easy_post' => 'easy_post#index'
      patch 'easy_post' => 'easy_post#rates'
      post 'easy_post_buy' => 'easy_post#buy'

      post 'orders_batch_ship' => 'orders#batch_ship'
      post 'orders_update_status' => 'orders#update_status'
      post 'orders_print_receipts' => 'orders#print_receipts'
      post 'orders_address_label' => 'orders#address_label'
      post 'orders_send_confirmation' => 'orders#send_confirmation'
      post 'orders_create_shipment' => 'orders#create_shipment'

      get 'products/item_info' => 'products#item_info'

      post 'upc/allocate_batch' => 'upc#allocate_batch'

      resources :auto_ship_items
      resources :brands
      resources :catalogs
      resources :coupons
      resources :products do
        member do
          get 'pictures'
          get 'categories'
          get 'extra_properties'
          get 'label_elements'
          get 'coupons'
          get 'clone'
          post 'categories' => 'products#create_categories'
					get 'template'
					post 'template' => 'products#apply_template'
					get 'shipping_rates'
          get 'catalogs'
          post 'catalogs' => 'products#create_catalogs'
        end
      end
      resources :orders do
        member do
          resources :items
          resources :deal_items
          get 'resend_email'
          get 'product_labels'
          get 'print_shipping_label'
          get 'receipt'
          get 'clone'
        end
      end
      resources :shipments do
        member do
          get 'label_image'
          get 'label'
          get 'print'
          get 'packing_slip'
          get 'email_invoice'
          get 'invoice'
          get 'void_label'
          get 'email_confirmation'
          get 'scan'
          post 'scan' => 'shipments#verify_scan'
          get 'create_inventory_transaction'
        end
      end
      resources :manifests do
        member do
          post 'request_pickup'
        end
      end
      resources :tax_rates
      resources :vouchers do
        member do
         get 'issue'
        end
      end
      resources :voucher_groups do
        post 'vouchers' => 'voucher_groups#create_vouchers'
      end
      resources :invoice_images
      resources :shipping_options
      resources :product_shipping_rates
      resources :upc
      resources :affiliate_products
      resources :label_sheets
      resources :label_areas
      resources :label_elements

      resources :daily_deals do
        member do
          get 'orders'
          get 'pictures'
          get 'categories'
          get 'coupons'
          get 'items'
          post 'items' => 'daily_deals#update_items'
          get 'locations'
          get 'external_coupons'
          post 'categories' => 'daily_deals#create_categories'
          post 'coupons' => 'daily_deals#create_coupon'
          post 'create_external_coupons' => 'daily_deals#create_external_coupons'
          post 'import_external_coupons' => 'daily_deals#import_external_coupons'
          get 'delete_external_coupon' => 'daily_deals#delete_external_coupon'
          get 'delete_all_external_coupons' => 'daily_deals#delete_all_external_coupons'
          get 'export_external_coupons' => 'daily_deals#export_external_coupons'
        end
      end

    end

  end

end


text:
import { EventEmitter } from "events";

type fn = (...args: any[]) => void;

class BaseStore extends EventEmitter {
  public addChangeListener(eventName: string, callback: fn) {
    this.on(eventName, callback);
  }

  public removeChangeListener(eventName: string, callback: fn) {
    this.removeListener(eventName, callback);
  }
}

export default BaseStore;


text:
using System;
using System.Linq;
using Microsoft.Azure.Management.StreamAnalytics.Models;

namespace Microsoft.Azure.Management.StreamAnalytics.Models
{
    /// <summary>
    /// The definition of the IoT Hub data source as stream input.
    /// </summary>
    public partial class IoTHubStreamInputDataSource : StreamInputDataSource
    {
        private IoTHubStreamInputDataSourceProperties _properties;

        /// <summary>
        /// Optional. Gets or sets the properties of the IoT Hub data source as
        /// stream input.
        /// </summary>
        public IoTHubStreamInputDataSourceProperties Properties
        {
            get { return this._properties; }
            set { this._properties = value; }
        }

        /// <summary>
        /// Initializes a new instance of the IoTHubStreamInputDataSource class.
        /// </summary>
        public IoTHubStreamInputDataSource()
        {
        }
    }
}


text:
<?php

declare(strict_types=1);

namespace OpenCFP\Domain\Services\TalkRating;

use Illuminate\Database\Eloquent\Model;
use OpenCFP\Domain\Model\TalkMeta;
use OpenCFP\Domain\Services\Authentication;

abstract class TalkRating implements TalkRatingStrategy
{
    /**
     * @var int
     */
    protected $adminId;

    /**
     * @var TalkMeta
     */
    protected $meta;

    public function __construct(TalkMeta $meta, Authentication $auth)
    {
        $this->adminId = $auth->user()->getId();
        $this->meta    = $meta;
    }

    final public function rate(int $talkId, int $rating)
    {
        if (!$this->isValidRating($rating)) {
            throw TalkRatingException::invalidRating($rating);
        }
        $this->saveRating($talkId, $rating);
    }

    private function saveRating(int $talkId, int $rating)
    {
        $meta         = $this->fetchMetaInfo($talkId);
        $meta->rating = $rating;
        $meta->save();
    }

    private function fetchMetaInfo(int $talkId): Model
    {
        return $this->meta->firstOrCreate([
            'admin_user_id' => $this->adminId,
            'talk_id'       => $talkId,
        ]);
    }
}


text:
package spec

import (
	"io"

	v1 "github.com/google/go-containerregistry/pkg/v1"
	imagespec "github.com/opencontainers/image-spec/specs-go/v1"
)

// ImageSource interface to an image. It can have its config read, and a its containers
// can be read via an io.ReadCloser tar stream.
type ImageSource interface {
	// Config get the config for the image
	Config() (imagespec.ImageConfig, error)
	// TarReader get the flattened filesystem of the image as a tar stream
	TarReader() (io.ReadCloser, error)
	// Descriptor get the v1.Descriptor of the image
	Descriptor() *v1.Descriptor
	// V1TarReader get the image as v1 tarball, also compatible with `docker load`. If name arg is not "", override name of image in tarfile from default of image.
	V1TarReader(overrideName string) (io.ReadCloser, error)
}


text:
require 'oj'
require 'avro'

module Vert

  extend self

  InputError = Class.new(StandardError)
  ValidationError = Class.new(StandardError)

  #error messages for hash validation
  NOT_A_HASH_ERROR = "Not a hash."
  NOT_A_HASH_ERROR_KEY = :not_a_hash

  EMPTY_ERROR = "The hash is empty."
  EMPTY_ERROR_KEY = :empty

  ABSENT_KEY_ERROR = "The data does not contain one or more required keys."
  ABSENT_KEY_ERROR_KEY = :absent_key

  ARRAY_TYPE_ERROR = "The following key/s do not have Array type values."
  ARRAY_TYPE_ERROR_KEY = :array_type

  HASH_TYPE_ERROR = "The following key/s do not have Hash type values."
  HASH_TYPE_ERROR_KEY = :hash_type

  ARRAY_EMPTY_ERROR = "The following array key/s are empty."
  ARRAY_EMPTY_ERROR_KEY = :array_empty

  HASH_EMPTY_ERROR = "The following hash key/s are empty."
  HASH_EMPTY_ERROR_KEY = :hash_empty

  #error messages for JSON validation
  NOT_A_STRING_ERROR = "Not a JSON string."
  NOT_A_STRING_ERROR_KEY = :not_a_string

  EMPTY_JSON_ERROR = "The JSON string is empty."
  EMPTY_JSON_ERROR_KEY = :empty_json

  EMPTY_JSON_OBJECT_ERROR = "The JSON object is empty."
  EMPTY_JSON_OBJECT_ERROR_KEY = :empty_json_object

  MALFORMED_JSON_ERROR = "The JSON string is malformed"
  MALFORMED_JSON_ERROR_KEY = :malformed_json

  #error messages for avro verification
  INVALID_AVRO_SCHEMA_ERROR = "The avro schema is invalid"
  INVALID_AVRO_SCHEMA_ERROR_KEY = :invalid_avro_schema

  INVALID_AVRO_DATUM_ERROR = "The JSON provided is not an instance of the schema."
  INVALID_AVRO_DATUM_ERROR_KEY = :invalid_avro_datum

  #Enums
  TYPE_ENUM = {array_keys: Array, hash_keys: Hash}
  OPTIONS_HASH_ENUM = [:keys, :custom_errors]
  OPTIONS_JSON_HASH_ENUM = [:schema, :custom_errors]
  KEYS_ENUM = [:required_keys, :array_keys, :hash_keys]
  ERROR_KEY_ENUM = {
    NOT_A_HASH_ERROR_KEY => NOT_A_HASH_ERROR,
    EMPTY_ERROR_KEY => EMPTY_ERROR,
    ABSENT_KEY_ERROR_KEY =>  ABSENT_KEY_ERROR,
    ARRAY_TYPE_ERROR_KEY =>  ARRAY_TYPE_ERROR,
    HASH_TYPE_ERROR_KEY => HASH_TYPE_ERROR,
    ARRAY_EMPTY_ERROR_KEY => ARRAY_EMPTY_ERROR,
    HASH_EMPTY_ERROR_KEY => HASH_EMPTY_ERROR,
    NOT_A_STRING_ERROR_KEY => NOT_A_STRING_ERROR,
    EMPTY_JSON_ERROR_KEY => EMPTY_JSON_ERROR,
    EMPTY_JSON_OBJECT_ERROR_KEY => EMPTY_JSON_OBJECT_ERROR,
    MALFORMED_JSON_ERROR_KEY => MALFORMED_JSON_ERROR,
    INVALID_AVRO_SCHEMA_ERROR_KEY => INVALID_AVRO_SCHEMA_ERROR,
    INVALID_AVRO_DATUM_ERROR_KEY => INVALID_AVRO_DATUM_ERROR
  }

  #input validation
  OPTIONS_HASH_EMPTY = "The options hash must contain keys"
  OPTIONS_NOT_A_HASH = "The options parameter must be a hash"
  OPTIONS_HASH_FORMAT = "{:keys => {}, :custom_errors => {}}"
  OPTIONS_JSON_HASH_FORMAT = "{:schema => \"avro shcema\", :custom_errors => {}}"
  OPTIONS_HASH_MISSING_VALID_KEYS = "The options hash contains no valid keys. The valid symbol keys are - "
  KEYS_HASH_MISSING_VALID_KEYS = "The options hash contains no valid keys for the :keys hash. The valid symbol keys are - "
  CUSTOM_ERRORS_HASH_MISSING_VALID_KEYS = "The options hash contains no valid keys for the :custom_errors hash. The valid symbol keys are - "
  SCHEMA_NOT_A_STRING = "The options hash contains a :schema value which is not a string."
  SCHEMA_NOT_JSON = "The options hash contains a :schema value which is not a JSON string"

  def validate(hash, options = nil)
    unless options.nil?
      check_options_format(options, OPTIONS_HASH_FORMAT)
      check_options(options)
    end
    test_validations(hash, options)
  rescue InputError => exception
    build_error_output(exception)
  end

  def validate?(hash, options = nil)
    check_options(options) unless options.nil?
    test_validations(hash, options).nil? ? true : false
  rescue InputError => exception
    false
  end

  def validate_json?(json, options = nil)
    check_json_options(options) unless options.nil?
    validate_json(json, options).nil? ? true : false
  rescue InputError => exception
    false
  end

  def validate_json(json, options = nil)
    unless options.nil?
      check_options_format(options, OPTIONS_JSON_HASH_FORMAT)
      check_json_options(options)
    end
    test_validations_json(json, options)
  rescue InputError => exception
    build_error_output(exception)
  end

  def get_error_keys
    pp ERROR_KEY_ENUM
  end

  private

  def check_options(options)
    raise_when_all_keys_missing(options, OPTIONS_HASH_MISSING_VALID_KEYS, OPTIONS_HASH_ENUM)
    if options.keys.include?(:keys)
      raise_when_all_keys_missing(options[:keys], KEYS_HASH_MISSING_VALID_KEYS, KEYS_ENUM)
    end
  end

  def raise_when_all_keys_missing(hash, message, key_enum_array)
    test_result = any_keys_present?(hash, key_enum_array)
    raise InputError, "#{message}#{key_enum_array*", "}" unless test_result
  end

  def any_keys_present?(hash, key_array)
    test_result = key_array.inject(false) do |memo, entry|
      memo || hash.keys.include?(entry)
    end
  end

  def check_options_format(options, options_format)
    raise InputError, "#{OPTIONS_NOT_A_HASH}. The options hash has the following format:- #{options_format}" unless options.is_a?(Hash)
    raise InputError, OPTIONS_HASH_EMPTY if options.empty?
    if options.keys.include?(:custom_errors)
      raise_when_all_keys_missing(options[:custom_errors], CUSTOM_ERRORS_HASH_MISSING_VALID_KEYS, ERROR_KEY_ENUM.keys)
    end
  end

  def test_validations(hash, options)
    test_for_default_hash_errors(hash, options)
    if options_key_types_present?(options, :required_keys)
      raise_when_keys_absent(hash, options, :required_keys)
    elsif options_key_types_present?(options, :array_keys)
      test_for_array_key_errors(hash, options)
    elsif options_key_types_present?(options, :hash_keys)
      test_for_hash_key_errors(hash, options)
    end
  rescue ValidationError => exception
    build_error_output(exception)
  else
    nil
  end

  def check_json_options(options)
    raise_when_all_keys_missing(options, OPTIONS_HASH_MISSING_VALID_KEYS, OPTIONS_JSON_HASH_ENUM)
    if options.keys.include?(:schema)
      test_options = {custom_errors: {not_a_string: SCHEMA_NOT_A_STRING, malformed_json: SCHEMA_NOT_JSON}}
      unless Vert.validate_json?(options[:schema], test_options)
        test =  Vert.validate_json(options[:schema], test_options)
        raise InputError, test if test.include?(SCHEMA_NOT_JSON)
        raise InputError, test if test.include?(SCHEMA_NOT_A_STRING)
      end
    end
  end

  def test_validations_json(json, options)
    test_for_default_json_errors(json, options)
    if options_schema_present?(options)
      validate_with_avro(json, options)
    end
  rescue ValidationError => exception
    build_error_output(exception)
  else
    nil
  end

  def test_for_default_hash_errors(hash, options)
    raise_when_not_hash(hash, options)
    raise_when_empty(hash, options)
  end

  def raise_when_not_hash(hash, options)
    raise_custom_error(hash, options, NOT_A_HASH_ERROR_KEY) {|hash| !hash.is_a?(Hash)}
  end

  def raise_custom_error(data, options, error_key)
    test = yield data
    message = options_errors_present?(options, error_key) ? get_options_custom_error(options, error_key) : ERROR_KEY_ENUM[error_key]
    raise ValidationError, message if test
  end

  def options_errors_present?(options, error_key)
    if options.nil?
      false
    elsif options.include?(:custom_errors)
      options[:custom_errors].include?(error_key) ? true : false
    else
      false
    end
  end

  def get_options_custom_error(options, error_key)
    options[:custom_errors][error_key]
  end

  def raise_when_empty(hash, options)
    raise_custom_error(hash, options, EMPTY_ERROR_KEY) {|hash| hash.empty?}
  end

  def options_key_types_present?(options, key_type)
    if options.nil?
      false
    elsif options.include?(:keys)
      options[:keys].include?(key_type) ? true : false
    else
      false
    end
  end

  def test_for_array_key_errors(hash, options)
    test_for_collection_key_errors(hash, options, :array_keys)
  end

  def test_for_hash_key_errors(hash, options)
    test_for_collection_key_errors(hash, options, :hash_keys)
  end

  def test_for_collection_key_errors(hash, options, key_type)
    raise_when_keys_absent(hash, options, key_type)
    raise_when_keys_do_not_match_type(hash, options, key_type)
    raise_when_collection_keys_empty(hash, options, key_type)
  end

  def raise_when_keys_absent(hash, options, key_type)
    missing_keys = get_missing_keys(hash, options, key_type)
    raise_error(nil, options, build_missing_key_error(options, missing_keys)) {!missing_keys.empty?}
  end

  def get_missing_keys(hash, options, key_type)
    get_options_keys_array(options, key_type) - hash.keys
  end

  def raise_error(data, options, message)
    test = yield data
    raise ValidationError, message if test
  end

  def build_missing_key_error(options, missing_keys_array)
    "#{build_error_message(options, ABSENT_KEY_ERROR_KEY)}\nMissing key/s: #{missing_keys_array*", "}"
  end

  def build_error_message(options, error_key)
    options_errors_present?(options, error_key) ? get_options_custom_error(options, error_key) : ERROR_KEY_ENUM[error_key]
  end

   def test_criteria_met?(key_array)
    key_array.empty?
  end

  def raise_when_keys_do_not_match_type(hash, options, key_type)
    non_matched_type_keys = get_non_matched_type_keys(hash, options, key_type)
    raise_error(nil, options, build_non_matched_type_error_message(options, non_matched_type_keys, key_type)) {!test_criteria_met?(non_matched_type_keys)}
  end

  def get_non_matched_type_keys(hash, options, key_type)
    missing_keys = get_missing_keys(hash, options, key_type)
    non_matched_type_keys = (get_options_keys_array(options, key_type) - missing_keys).find_all do
      |key| hash[key].is_a?(TYPE_ENUM[key_type]) == false
    end
  end

  def get_options_keys_array(options, key_type)
    options[:keys][key_type]
  end

  def build_non_matched_type_error_message(options, non_matched_type_keys_array, key_type)
    case key_type
    when :array_keys
      "#{build_error_message(options, ARRAY_TYPE_ERROR_KEY)} Not Array type keys:- #{non_matched_type_keys_array*","}"
    when :hash_keys
      "#{build_error_message(options, HASH_TYPE_ERROR_KEY)} Not Hash type keys:- #{non_matched_type_keys_array*","}"
    end
  end

  def raise_when_collection_keys_empty(hash, options, key_type)
    if get_non_matched_type_keys(hash, options, key_type).empty?
      empty_collection_keys = get_empty_collection_keys(hash, options, key_type)
      raise_error(nil, options, build_empty_collection_error_message(options, empty_collection_keys, key_type)) {!test_criteria_met?(empty_collection_keys)}
    end
  end

  def get_empty_collection_keys(hash, options, key_type)
    get_options_keys_array(options, key_type).find_all do |item|
      hash[item].empty?
    end
  end

  def build_empty_collection_error_message(options, empty_collection_keys_array, key_type)
    case key_type
    when :array_keys
      "#{build_error_message(options, ARRAY_EMPTY_ERROR_KEY)} Empty array keys:- #{empty_collection_keys_array*","}"
    when :hash_keys
      "#{build_error_message(options, HASH_EMPTY_ERROR_KEY)} Empty hash keys:- #{empty_collection_keys_array*","}"
    end
  end

  def build_error_output(custom_exception)
    custom_exception.message
  end

  def test_for_default_json_errors(json, options)
    raise_when_not_string(json, options)
    hash = try_parse_json(json, options)
  end

  def options_schema_present?(options)
    if options.nil?
      false
    elsif options.include?(:schema)
      true
    else
      false
    end
  end

  def get_options_schema(options)
    options[:schema]
  end

  def raise_when_not_string(json, options)
    raise_custom_error(json, options, NOT_A_STRING_ERROR_KEY){|json| !json.is_a?(String)}
  end

  def try_parse_json(json, options)
    hash = Oj.load(json)
    raise_custom_error(hash, options, EMPTY_JSON_ERROR_KEY){|hash| hash.nil?}
    raise_custom_error(hash, options, EMPTY_JSON_OBJECT_ERROR_KEY){|hash| hash.empty?}
  rescue Oj::ParseError => exception
    detail = "#{exception.message.gsub( /\[.+\]/, "").rstrip}."
    raise ValidationError, "#{build_error_message(options, MALFORMED_JSON_ERROR_KEY)}, #{detail}"
  else
    hash
  end

  def validate_with_avro(json, options)
    schema_object = parse_avro_schema(options)
    message = build_error_message(options, INVALID_AVRO_DATUM_ERROR_KEY)
    raise_error(json, options, message){|json| !Avro::Schema.validate(schema_object, Oj.load(json))}
  end

  def parse_avro_schema(options)
    schema = Avro::Schema.parse(get_options_schema(options))
  rescue Avro::SchemaParseError => exception
    raise ValidationError, "#{build_error_message(options, INVALID_AVRO_SCHEMA_ERROR_KEY)}. #{exception.to_s}"
  else
    schema
  end

end


text:
package tp2.tpalt.upmc.quizzforfriend;

import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageButton;

import java.util.Random;

/**
 * Created by macbookpro on 17/10/2016.
 */

public class ThemeActivity extends AppCompatActivity {

    //Les bouttons qui me redirige soit vers un layout_choix_theme, soit qui charge un theme au hasard
    private Button themeAleatoire;
    private Button themeChoisis;

    /**
     * Some older devices needs a small delay between UI widget updates
     * and a change of the status and navigation bar.
     */
    private static final int UI_ANIMATION_DELAY = 5;
    private final Handler mHideHandler = new Handler();
    private View mContentView;
    private final Runnable mHidePart2Runnable = new Runnable() {
        @SuppressLint("InlinedApi")
        @Override
        public void run() {
            // Delayed removal of status and navigation bar

            // Note that some of these constants are new as of API 16 (Jelly Bean)
            // and API 19 (KitKat). It is safe to use them, as they are inlined
            // at compile-time and do nothing on earlier devices.
            mContentView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE
                    | View.SYSTEM_UI_FLAG_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
        }
    };
    private final Runnable mHideRunnable = new Runnable() {
        @Override
        public void run() {
            hide();
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);

        setContentView(R.layout.choisir_theme_layout);
        getSupportActionBar().hide();
        mContentView = findViewById(R.id.themeChoice);

        themeAleatoire = (Button)findViewById(R.id.themeAleatoire);
        themeChoisis   = (Button)findViewById(R.id.themeChoisis);
        QuizzForFriend.playLoadingActivity(getApplicationContext());
    }

    //On redirige en fonction du bouton sur lequel on appuie
    public void themeDirection(View v){
        QuizzForFriend.playSelectTheme(getApplicationContext());
        final View currentView = v;
        AlertDialog.Builder builderSingle = new AlertDialog.Builder(ThemeActivity.this, R.style.MyAlertDialogStyle);
        //builderSingle.setIcon(R.drawable.);
        builderSingle.setTitle("Quel type de partie ?");
        //builderSingle.setTI

        final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
                ThemeActivity.this,
                android.R.layout.select_dialog_singlechoice);
        arrayAdapter.add("Contre la montre");
        arrayAdapter.add("Normal");

        builderSingle.setNegativeButton(
                "Annuler",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        QuizzForFriend.playSelectPartySound(getApplicationContext());
                    }
                });

        builderSingle.setAdapter(
                arrayAdapter,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        QuizzForFriend.playSelectPartySound(getApplicationContext());
                        String strName = arrayAdapter.getItem(which);
                        AlertDialog.Builder builderInner = new AlertDialog.Builder(ThemeActivity.this , R.style.MyAlertDialogStyle);
                        builderInner.setMessage(strName);
                        QuizzForFriend.gameMode = strName;
                        builderInner.setTitle("Vous avez choisis le mode :");
                        builderInner.setPositiveButton(
                                "Ok",
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(
                                            DialogInterface dialog,
                                            int which) {
                                        dialog.dismiss();
                                        QuizzForFriend.playSelectPartySound(getApplicationContext());
                                        startActivity(intentForId(currentView));
                                    }
                                });
                        builderInner.show();
                    }
                });
        builderSingle.show();
    }

    private Intent intentForId(View v){
        Intent intent;
        if (v.getId() == R.id.themeChoisis){
            intent = new Intent(this, ListThemeActivity.class);}
        else {
            Random random = new Random();
            int position = random.nextInt(QuizzForFriend.quizes.length - 0);
            intent = new Intent();
            intent.setClass(this, ListItemDetailActivity.class);
            intent.putExtra("position", position);
        }
        return intent;
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        //muteSoundBtn.setText(R.string.MUTE_SOUND);
        super.onPostCreate(savedInstanceState);
        delayedHide(0);
    }

    private void toggle() {
        hide();
    }

    private void hide() {
        // Hide UI first
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.hide();
        }
        mHideHandler.postDelayed(mHidePart2Runnable, UI_ANIMATION_DELAY);
    }

    /**
     * Schedules a call to hide() in [delay] milliseconds, canceling any
     * previously scheduled calls.
     */
    private void delayedHide(int delayMillis) {
        mHideHandler.removeCallbacks(mHideRunnable);
        mHideHandler.postDelayed(mHideRunnable, delayMillis);
    }
    public void toogleSound(View v){
        ImageButton muteSoundBtn = (ImageButton) findViewById(R.id.muteSound);
        QuizzForFriend.toogleThemeSound(muteSoundBtn);
        QuizzForFriend.playToggleSound(getBaseContext());
    }
}


text:
package stresso.trie;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
import java.util.TreeSet;

import com.google.common.base.Strings;
import org.apache.accumulo.core.client.AccumuloException;
import org.apache.accumulo.core.client.AccumuloSecurityException;
import org.apache.accumulo.core.client.Connector;
import org.apache.fluo.api.client.FluoClient;
import org.apache.fluo.api.client.FluoFactory;
import org.apache.fluo.api.config.FluoConfiguration;
import org.apache.fluo.core.util.AccumuloUtil;
import org.apache.hadoop.io.Text;

public class Split {

  private static final String RGB_CLASS =
      "org.apache.accumulo.server.master.balancer.RegexGroupBalancer";
  private static final String RGB_PATTERN_PROP = "table.custom.balancer.group.regex.pattern";
  private static final String RGB_DEFAULT_PROP = "table.custom.balancer.group.regex.default";
  private static final String TABLE_BALANCER_PROP = "table.balancer";

  public static void main(String[] args) throws Exception {
    if (args.length != 3) {
      System.err.println("Usage: " + Split.class.getSimpleName()
          + " <fluo props> <table props> <tablets per level>");
      System.exit(-1);
    }

    FluoConfiguration config = new FluoConfiguration(new File(args[0]));

    int maxTablets = Integer.parseInt(args[2]);

    int nodeSize;
    int stopLevel;
    try (FluoClient client = FluoFactory.newClient(config)) {
      nodeSize = client.getAppConfiguration().getInt(Constants.NODE_SIZE_PROP);
      stopLevel = client.getAppConfiguration().getInt(Constants.STOP_LEVEL_PROP);
    }

    setupBalancer(config);

    int level = 64 / nodeSize;

    while (level >= stopLevel) {
      int numTablets = maxTablets;
      if (numTablets == 0)
        break;

      TreeSet<Text> splits = genSplits(level, numTablets);
      addSplits(config, splits);
      System.out.printf("Added %d tablets for level %d\n", numTablets, level);

      level--;
    }

    optimizeAccumulo(config, args[1]);
  }

  private static void optimizeAccumulo(FluoConfiguration config, String tableProps)
      throws Exception {
    Connector conn = AccumuloUtil.getConnector(config);

    Properties tprops = new Properties();
    tprops.load(new ByteArrayInputStream(tableProps.getBytes(StandardCharsets.UTF_8)));

    Set<Entry<Object, Object>> es = tprops.entrySet();
    for (Entry<Object, Object> e : es) {
      conn.tableOperations().setProperty(config.getAccumuloTable(), e.getKey().toString(),
          e.getValue().toString());
    }
    try {
      conn.instanceOperations().setProperty("table.durability", "flush");
      conn.tableOperations().removeProperty("accumulo.metadata", "table.durability");
      conn.tableOperations().removeProperty("accumulo.root", "table.durability");
    } catch (AccumuloException e) {
      System.err.println(
          "Unable to set durability settings (error expected in Accumulo 1.6) : " + e.getMessage());
    }
  }

  private static void setupBalancer(FluoConfiguration config) throws AccumuloSecurityException {
    Connector conn = AccumuloUtil.getConnector(config);

    try {
      // setting this prop first intentionally because it should fail in 1.6
      conn.tableOperations().setProperty(config.getAccumuloTable(), RGB_PATTERN_PROP, "(\\d\\d).*");
      conn.tableOperations().setProperty(config.getAccumuloTable(), RGB_DEFAULT_PROP, "none");
      conn.tableOperations().setProperty(config.getAccumuloTable(), TABLE_BALANCER_PROP, RGB_CLASS);
      System.out.println("Setup tablet group balancer");
    } catch (AccumuloException e) {
      System.err.println(
          "Unable to setup tablet balancer (error expected in Accumulo 1.6) : " + e.getMessage());
    }
  }

  private static TreeSet<Text> genSplits(int level, int numTablets) {

    TreeSet<Text> splits = new TreeSet<>();

    String ls = String.format("%02d:", level);

    int numSplits = numTablets - 1;
    int distance = (((int) Math.pow(Character.MAX_RADIX, Node.HASH_LEN) - 1) / numTablets) + 1;
    int split = distance;
    for (int i = 0; i < numSplits; i++) {
      splits.add(new Text(
          ls + Strings.padStart(Integer.toString(split, Character.MAX_RADIX), Node.HASH_LEN, '0')));
      split += distance;
    }

    splits.add(new Text(ls + "~"));

    return splits;
  }

  private static void addSplits(FluoConfiguration config, TreeSet<Text> splits) throws Exception {
    Connector conn = AccumuloUtil.getConnector(config);
    conn.tableOperations().addSplits(config.getAccumuloTable(), splits);
  }
}


text:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Go Cart</title>

<link href="<?php echo base_url('assets/css/bootstrap.min.css');?>" rel="stylesheet" type="text/css" />
<link href="<?php echo base_url('assets/css/bootstrap-responsive.min.css');?>" rel="stylesheet" type="text/css" />
<link type="text/css" href="<?php echo base_url('assets/css/jquery-ui.css');?>" rel="stylesheet" />

<script type="text/javascript" src="<?php echo base_url('assets/js/jquery.js');?>"></script>
<script type="text/javascript" src="<?php echo base_url('assets/js/jquery-ui.js');?>"></script>
<script type="text/javascript" src="<?php echo base_url('assets/js/bootstrap.min.js');?>"></script>

<style type="text/css">

/* fix some bootstrap problems */
.btn-mini [class^="icon-"] {
	margin-top: -1px;
}
.navbar-form .input-append .btn {
	margin-top:0px;
	padding-left:2px;
	padding-right:5px;
}

</style>

<body>

	<div class="container-fluid">


text:
set -euo pipefail
if [[ ! -d "${RUNFILES_DIR:-/dev/null}" && ! -f "${RUNFILES_MANIFEST_FILE:-/dev/null}" ]]; then
  if [[ -f "$0.runfiles_manifest" ]]; then
    export RUNFILES_MANIFEST_FILE="$0.runfiles_manifest"
  elif [[ -f "$0.runfiles/MANIFEST" ]]; then
    export RUNFILES_MANIFEST_FILE="$0.runfiles/MANIFEST"
  elif [[ -f "$TEST_SRCDIR/bazel_tools/tools/bash/runfiles/runfiles.bash" ]]; then
    export RUNFILES_DIR="$0.runfiles"
  fi
fi
if [[ -f "${RUNFILES_DIR:-/dev/null}/bazel_tools/tools/bash/runfiles/runfiles.bash" ]]; then
  source "${RUNFILES_DIR}/bazel_tools/tools/bash/runfiles/runfiles.bash"
elif [[ -f "${RUNFILES_MANIFEST_FILE:-/dev/null}" ]]; then
  source "$(grep -m1 "^bazel_tools/tools/bash/runfiles/runfiles.bash " \
            "$RUNFILES_MANIFEST_FILE" | cut -d ' ' -f 2-)"
else
  echo >&2 "ERROR: cannot find @bazel_tools//tools/bash/runfiles:runfiles.bash"
  exit 1
fi
# --- end runfiles.bash initialization ---

export BAZEL_SUFFIX="_jdk_minimal"
source "$(rlocation "io_bazel/src/test/shell/integration_test_setup.sh")" \
  || { echo "integration_test_setup.sh not found!" >&2; exit 1; }

# Bazel's install base is < 320MB with minimal JDK and > 320MB with an all
# modules JDK.
function test_size_less_than_320MB() {
  bazel info
  ib=$(bazel info install_base)
  size=$(du -s "$ib" | cut -d\	 -f1)
  maxsize=$((1024*320))
  if [ $size -gt $maxsize ]; then
    echo "$ib was too big:" 1>&2
    du -a "$ib" 1>&2
    fail "Size of install_base is $size kB, expected it to be less than $maxsize kB."
  fi
}

function test_cc() {
  local -r pkg=$FUNCNAME
  mkdir -p "$pkg" || fail "Couldn't create $pkg."
  cat > "$pkg/BUILD" <<EOF
cc_binary(
    name = "foo",
    srcs = ["foo.cc"],
)
EOF
  cat > "$pkg/foo.cc" <<EOF
int main() {
  return 42;
}
EOF

  bazel build "//$pkg:foo" || fail "Expected success."
}

function test_java() {
  local -r pkg=$FUNCNAME
  mkdir -p "$pkg" || fail "Couldn't create $pkg."
  cat > "$pkg/BUILD" <<EOF
java_binary(
    name = "foo",
    srcs = ["foo.java"],
    main_class = "foo",
)
EOF
  cat > "$pkg/foo.java" <<EOF
public class foo {
  public static void main(String[] args) {
    System.out.println("Hello Bazel!");
  }
}
EOF

  bazel build "//$pkg:foo" || fail "Expected success."
}

run_suite "Test bazel with minimal embedded JDK."


text:
package com.wamdy.dpp.datascrapt;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Workbook;

import com.wamdy.com.datascrapt.rule.MappingRule;
import com.wamdy.com.datascrapt.rule.Rule;
import com.wamdy.com.datascrapt.rule.impl.CollectionReadRule;
import com.wamdy.com.datascrapt.rule.impl.ObjectReadRule;

public class ExcelImportTester {
    public static void main(String[] args) throws IOException {
        File file = new File("test.xls");
        POIFSFileSystem ins = new POIFSFileSystem(file);
        Workbook workbook = new HSSFWorkbook(ins);
        CollectionReadRule<ArrayList, SimpleObject> rule = getCollectionRule();
        WorkbookReader<SimpleObject> workbookReader = new WorkbookReader<SimpleObject>(workbook, rule, null);
        // List<Function> functions = workbookReader.readAll();
        int start = 1;
        int end = 100;
        List<SimpleObject> functions = workbookReader.readRange(start, end);
    }

    private static CollectionReadRule<ArrayList, SimpleObject> getCollectionRule() {
        CollectionReadRule<ArrayList, SimpleObject> collectionRule = new CollectionReadRule<>();
        collectionRule.setCollectionClass(ArrayList.class);
        collectionRule.setObjectClass(SimpleObject.class);

        Collection<Rule> rules = new ArrayList<Rule>();
        ObjectReadRule<SimpleObject> rule = new ObjectReadRule<SimpleObject>();
        rule.setObjectClass(SimpleObject.class);
        Map<String, Rule> attributes = new HashMap<String, Rule>();
        MappingRule<String> ruleAttra = new MappingRule<String>();
        ruleAttra.setSimpleAttributeType(String.class);
        ruleAttra.setMappingRule("Sheet1!A2*+");
        attributes.put("a", ruleAttra);
        MappingRule<String> ruleAttrb = new MappingRule<String>();
        ruleAttrb.setSimpleAttributeType(String.class);
        ruleAttrb.setMappingRule("Sheet1!B2*+");
        attributes.put("b", ruleAttrb);
        rule.setAttribute(attributes);
        rules.add(rule);

        collectionRule.setRules(rules);
        return collectionRule;
    }
}


text:
package com.blinkboxbooks.android.ui.library;

import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;

import com.blinkboxbooks.android.R;
import com.blinkboxbooks.android.controller.BookDownloadController;
import com.blinkboxbooks.android.controller.LibraryController;
import com.blinkboxbooks.android.model.BookItem;
import com.blinkboxbooks.android.provider.BBBContract;
import com.blinkboxbooks.android.ui.BaseActivity;
import com.blinkboxbooks.android.ui.shop.ShopActivity;
import com.blinkboxbooks.android.util.AnalyticsHelper;
import com.blinkboxbooks.android.util.BBBUIUtils;
import com.blinkboxbooks.android.widget.BookCover;

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

/**
 * Custom adapter for displaying a list of book items with a RecyclerView
 */
public class LibraryBooksAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private static final int VIEW_TYPE_FIND_EBOOKS = 0;
    private static final int VIEW_TYPE_BOOK = 1;

    private List<BookItem> mItems = new ArrayList<>();
    private int mColumns;
    private BaseActivity mActivity;
    private LibraryBookOptionsHelper mOptionsHelper;
    private int mBookPaddingSide;
    private int mFilterType;

    final Comparator<BookItem> mComparator = new Comparator<BookItem>() {
        @Override
        public int compare(BookItem lhs, BookItem rhs) {
            long rhsId = rhs.book == null ? 0L : rhs.book.id;
            long lhsId = lhs.book == null ? 0L : lhs.book.id;

            return (int) (lhsId - rhsId);
        }
    };

    public LibraryBooksAdapter(BaseActivity activity, List<BookItem> items, int columns, int filterType, LibraryBookOptionsHelper optionsHelper) {
        mItems = items;
        mActivity = activity;
        mColumns = columns;
        mOptionsHelper = optionsHelper;
        mBookPaddingSide = activity.getResources().getDimensionPixelOffset(R.dimen.gap_medium);
        mFilterType = filterType;
        setHasStableIds(true);
    }

    /**
     * Set the item at the specified index, and notify the recycler view that this index has changed
     *
     * @param index the index to udpate
     * @param item  the item to set
     */
    public void setItem(int index, BookItem item) {
        mItems.set(index, item);
        notifyItemChanged(index);
    }

    /**
     * If a BookItem with the same id exists in the adapter, overwrite it's index with the given item & notify the recycler view
     *
     * @param item the item to set
     */
    public void updateItem(BookItem item) {
        for (int index = mItems.size(); --index >= 0; ) {
            final BookItem book = mItems.get(index);
            if (mComparator.compare(book, item) == 0) {
                mItems.set(index, item);
                notifyItemChanged(index);
                break;
            }
        }
    }

    /**
     * Remove the given BookItem from teh adapter, and notify the recycler view.
     *
     * @param item the item to remove.
     * @return true if the item has been found & removed, false otherwise.
     */
    public boolean removeItem(BookItem item) {
        for (int index = mItems.size(); --index >= 0; ) {
            final BookItem book = mItems.get(index);
            if (mComparator.compare(book, item) == 0) {
                mItems.remove(index);
                notifyItemRemoved(index);
                return true;
            }
        }

        return false;
    }

    /**
     * Set the list of book items for the adapter to use
     *
     * @param items the list of BookItem objects that the adapter should use
     */
    public void setItems(List<BookItem> items) {
        mItems = items;
        notifyDataSetChanged();
    }

    @Override
    public long getItemId(int position) {
        final BookItem bookItem = mItems.get(position);
        return bookItem.book == null ? 0L : bookItem.book.id;
    }

    @Override
    public int getItemViewType(int position) {
        if (mItems.get(position) instanceof FindMoreEbooksBookItem) {
            return VIEW_TYPE_FIND_EBOOKS;
        } else {
            return VIEW_TYPE_BOOK;
        }
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        switch (viewType) {
            case VIEW_TYPE_FIND_EBOOKS:
                return new ViewHolderFindEbooks(LayoutInflater.from(parent.getContext()).inflate(R.layout.view_find_more_ebooks, parent, false));
            case VIEW_TYPE_BOOK:
            default:
                return new ViewHolderBook(LayoutInflater.from(parent.getContext()).inflate(R.layout.view_book_griditem, parent, false));
        }
    }

    @Override
    public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {

        // Special case handling for the find ebooks view type
        if (getItemViewType(position) == VIEW_TYPE_FIND_EBOOKS) {
            ViewHolderFindEbooks viewHolder = (ViewHolderFindEbooks) holder;
            calculateBookCoverSize(viewHolder.bookFrame);

            viewHolder.bookFrame.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    AnalyticsHelper.getInstance().sendEvent(AnalyticsHelper.CATEGORY_LIBRARY_ITEM_CLICK, AnalyticsHelper.GA_EVENT_FIND_MORE_BOOKS_CLICKED, "", null);
                    Intent intent = new Intent(mActivity, ShopActivity.class);
                    mActivity.startActivity(intent);
                }
            });

        } else {
            // Standard handling for a normal book item
            final BookItem item = mItems.get(position);
            final ViewHolderBook viewHolder = (ViewHolderBook) holder;

            viewHolder.bookCover.setBook(item.book);
            viewHolder.bookCover.setDownloadProgress(item.book.download_status, item.book.download_offset);

            if (item.lastPosition.position != null) {
                viewHolder.progressBar.setProgress(item.lastPosition.percentage);
                viewHolder.progressBar.setVisibility(View.VISIBLE);
            } else {
                viewHolder.progressBar.setVisibility(View.INVISIBLE);
            }

            calculateBookCoverSize(viewHolder.bookCover);

            viewHolder.bookCover.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // If the book is in the downloaded state we open it. It its not downloaded we the user will
                    // just remain in the library.
                    if (item.book.download_status == BBBContract.Books.DOWNLOADED) {
                        Intent intent = LibraryController.getOpenBookIntent(mActivity, item.book);
                        mActivity.startActivity(intent);
                    } else if (item.book.download_status == BBBContract.Books.DOWNLOADING) {
                        // If the book is currently downloading then we cancel the active download
                        BookDownloadController.getInstance(mActivity).cancelDownloadClicked(item.book);
                    } else {
                        BookDownloadController.getInstance(mActivity).startDownloadClicked(mActivity, item.book);
                    }
                }
            });

            viewHolder.optionsButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mOptionsHelper.displayOptionsForBook(mActivity, viewHolder.optionsButton, item, mFilterType);
                }
            });
        }
    }

    @Override
    public int getItemCount() {
        return mItems.size();
    }

    /**
     * ViewHolder class to store UI controls for a standard book
     */
    private static class ViewHolderBook extends RecyclerView.ViewHolder {
        private View optionsButton;
        private BookCover bookCover;
        private ProgressBar progressBar;

        public ViewHolderBook(View itemView) {
            super(itemView);
            bookCover = (BookCover) itemView.findViewById(R.id.bookcover);
            optionsButton = itemView.findViewById(R.id.btn_options);
            progressBar = (ProgressBar) itemView.findViewById(R.id.progressbar_read);
        }
    }

    /**
     * ViewHolder class to store UI conrols for find more ebooks
     */
    public static class ViewHolderFindEbooks extends RecyclerView.ViewHolder {

        public View bookFrame;

        public ViewHolderFindEbooks(View itemView) {
            super(itemView);
            bookFrame = itemView.findViewById(R.id.book_frame);
        }
    }

    /**
     * Calculate the size of the book cover based on the current screen dimensions
     *
     * @param bookCover the book cover whose size to set
     */
    private void calculateBookCoverSize(View bookCover) {
        final int width = ((BBBUIUtils.getScreenWidth(mActivity) - (mBookPaddingSide * (mColumns + 1)))) / mColumns;
        ViewGroup.LayoutParams params = bookCover.getLayoutParams();
        params.width = width;
        params.height = (int) (width * LibraryController.WIDTH_HEIGHT_RATIO);
        bookCover.setLayoutParams(params);
    }
}


text:
require 'rails_helper'
require 'auto_html'
require 'auto_html/filters/quote'

describe 'auto_html quote filter' do
  include AutoHtml
  it "convert > into quotes" do
    source = <<-SOURCE
> One
>two
three
four
SOURCE

    result = auto_html(source){ quote }
    result.should == <<-OUTPUT
<quote>> One</quote>
<quote>>two</quote>
three
four
OUTPUT
  end
end


text:
Danilo Benevides <danilobenevides01@gmail.com>
--FILE--
<?php

declare(strict_types=1);

require 'vendor/autoload.php';

use Respect\Validation\Exceptions\InstanceException;
use Respect\Validation\Exceptions\NestedValidationException;
use Respect\Validation\Validator as v;

try {
    v::instance(DateTime::class)->check('');
} catch (InstanceException $exception) {
    echo $exception->getMessage() . PHP_EOL;
}

try {
    v::not(v::instance(Traversable::class))->check(new ArrayObject());
} catch (InstanceException $exception) {
    echo $exception->getMessage() . PHP_EOL;
}

try {
    v::instance(ArrayIterator::class)->assert(new stdClass());
} catch (NestedValidationException $exception) {
    echo $exception->getFullMessage() . PHP_EOL;
}

try {
    v::not(v::instance(stdClass::class))->assert(new stdClass());
} catch (NestedValidationException $exception) {
    echo $exception->getFullMessage() . PHP_EOL;
}
?>
--EXPECT--
"" must be an instance of "DateTime"
`[traversable] (ArrayObject: { })` must not be an instance of "Traversable"
- `[object] (stdClass: { })` must be an instance of "ArrayIterator"
- `[object] (stdClass: { })` must not be an instance of "stdClass"


text:
import logging

from harvester.ext.crawler.base import CrawlerPluginBase

from ckan_api_client.high_level import CkanHighlevelClient

class CkanCrawler(CrawlerPluginBase):
    logger = logging.getLogger(__name__)

    def fetch_data(self, storage):
        self.logger.info("Fetching data from Ckan at {0}".format(self.url))
        client = CkanHighlevelClient(
            self.url, api_key=self.conf.get('api_key'))

        for dataset in client.iter_datasets():
            self.logger.info("Dataset: {0}".format(dataset.id))
            storage.set_object('dataset', dataset.id, dataset.serialize())

        for group in client.iter_groups():
            self.logger.info("Group: {0}".format(group.name))
            storage.set_object('group', group.name, group.serialize())

        for organization in client.iter_organizations():
            self.logger.info("Organization: {0}".format(organization.name))
            storage.set_object('organization', organization.name,
                               organization.serialize())


text:
trackIt.js
----------

Introduction
------------

trackIt.js is an extra lightweight and basic router meant to work with [x-tag](https://x-tag.github.io/), a library to handle web components.

How it works
------------

1. link "trackIt.js" with `script` tags in your html.
```html
<script src='trackIt.js'></script>
```

2. inititalize trackIt
```js
var tracker = track({
  content: 'main',
  root: 'home'
});
```

  * options

    * `content`: a placeholder where your pages will be inserted

    * `root`: the default `x-tag` custom element generally linked to '/', here the 'x-home' custom element.

3. route
```js
tracker.jump('/hello');
```

Will change the url, and insert the `x-hello` element in the `content` element you specified in the options.

Example explanations
--------------------

For the example, I created some x-tag components:

* `nav-bar` - which contains `nav-link` component
* `x-something` - where "something" is the name of the page

Inside each component folder there is:

* a `.js` file named after the component, where I registered my custom element.
* a `.scss` file which rules exclusively applying to this component. For convenience, I grouped pages components, and wrote general css rules for all pages.

Finally with *gulp* I concatenate all the components in one file under the `js` folders in a `components.js` file.
And I do the same thing with my styles.

Last, I initialize my tracker inside `js/tracker.js`.
```js
var tracker = track({
  content: 'main',
  root: 'home'
});
```

###The glue between our links and the tracker

In order to properly route pages, we have to pass the path specified in the `href` attribute as a parameter for our `tracker.jump()` function.

So in our `navLink.js` we simply define a *click* handler for its link.

```js
xtag.register('nav-link', {
  // ...
  events: {
    'click:delegate(a)': function (event) {
      tracker.jump(event.target);
    };
  }
  // ...
});
```

For convenience we can just pass the `a` element, here referenced by `event.target` and trackIt will use the `href` attribute itself. But you can pass an explicit path too.


text:
"""===========================
Geneset analysis
===========================

:Author: Andreas Heger
:Release: $Id$
:Date: |today|
:Tags: Python

Overview
========

This pipeline performs gene set analysis of one or more
genesets.

Input data are two collections of files, genelists and pathways.

Genelists are tabular data with a gene for each row and associated
attributes in additional columns such as expression level, probability
of being called differentially expressed, etc.

Pathways are tabular data linking genes to pathways that they exist
in.

Generally, it performs the following tasks:

1. The pipeline merges separately prepared gene lists into
   a single gene list matrix. There is a continuous scale
   version (P-Values, expression values, ...) and a thresholded
   version (0 and 1 for genelist membership).

2. The pipeline builds a matrix of gene list annotations to
   test against. To this end, it collects:

   ENSEMBL GO annotations
   KEGG Pathways
   User supplied pathways
   GSEA database signatures

3. The pipeline performs various gene set enrichment analyses.
   These are:

   1. Hypergeometric GO analysis
   2. Gene set enrichment analysis

4. The pipeline creates various QC metrics. To this end it looks
   for biases in any of the gene lists supplied. Biases the pipeline
   looks at are:

   1. Gene length
   2. Nucleotide composition
   3. Gene intron/exon structure
   4. User supplied table with biases.

Usage
=====

See :ref:`PipelineSettingUp` and :ref:`PipelineRunning` on general
information how to use CGAT pipelines.

Configuration
-------------

The pipeline requires a configured :file:`pipeline.ini` file.

The sphinxreport report requires a :file:`conf.py` and
:file:`sphinxreport.ini` file (see :ref:`PipelineReporting`). To start
with, use the files supplied with the Example_ data.

Input
-----

Optional inputs
+++++++++++++++

Requirements
------------

The pipeline requires the results from
:doc:`pipeline_annotations`. Set the configuration variable
:py:data:`annotations_database` and :py:data:`annotations_dir`.

On top of the default CGAT setup, the pipeline requires the following
software to be in the path:

+----------+-----------+---------------------------+
|*Program* |*Version*  |*Purpose*                  |
+----------+-----------+---------------------------+
|          |           |                           |
+----------+-----------+---------------------------+

Pipeline output
===============

The major output is in the database file :file:`csvdb`.

Glossary
========

.. glossary::

Code
====

"""
from ruffus import *

import sys
import os
import sqlite3
import pandas

import CGAT.Experiment as E
import CGAT.IOTools as IOTools
import CGAT.Database as Database
import CGAT.SetTools as SetTools
import CGATPipelines.PipelineGO as PipelineGO

###################################################
###################################################
###################################################
# Pipeline configuration
###################################################

# load options from the config file
import CGATPipelines.Pipeline as P
PARAMS = P.getParameters(
    ["%s/pipeline.ini" % os.path.splitext(__file__)[0],
     "../pipeline.ini",
     "pipeline.ini"])

PARAMS.update(P.peekParameters(
    PARAMS["annotations_dir"],
    "pipeline_annotations.py",
    prefix="annotations_",
    update_interface=True))

# Update the PARAMS dictionary in any PipelineModules
# e.g.:
# import CGATPipelines.PipelineGeneset as PipelineGeneset
# PipelineGeneset.PARAMS = PARAMS

def connect():
    '''connect to database.

    Use this method to connect to additional databases.

    Returns a database connection.
    '''

    dbh = sqlite3.connect(PARAMS["database_name"])
    statement = '''ATTACH DATABASE '%s' as annotations''' % (
        PARAMS["annotations_database"])
    cc = dbh.cursor()
    cc.execute(statement)
    cc.close()

    return dbh

@transform('genelists.dir/*.tsv.gz',
           suffix(".tsv.gz"),
           ".load")
def loadGeneLists(infile, outfile):
    '''load gene list data into database.'''
    P.load(infile, outfile,
           tablename="genelist_%s" % P.toTable(outfile))

@merge('genelists.dir/*.tsv.gz', 'genelists.tsv.gz')
def buildGeneListMatrix(infiles, outfile):
    '''build a gene list matrix for simple pathway analysis
    based on hypergeometric test.

    A gene list is derived from a gene set by
    applying thresholds to the input data set. The
    thresholds are defined in the configuration file.
    '''

    genesets = []
    backgrounds = []
    headers = []
    for infile in infiles:
        genelist = pandas.read_csv(
            IOTools.openFile(infile),
            index_col=0,
            sep='\t')

        track = P.snip(os.path.basename(infile), ".tsv.gz")
        headers.append(track)

        field = PARAMS[P.matchParameter("%s_foreground_field" % track)]
        min_threshold = PARAMS[P.matchParameter(
            "%s_foreground_min_threshold" % track)]
        max_threshold = PARAMS[P.matchParameter(
            "%s_foreground_max_threshold" % track)]
        genesets.append(set(genelist[
            (genelist[field] >= min_threshold) &
            (genelist[field] <= max_threshold)].index))

        E.info('%s: foreground: %f <= %s <= %f' % (track,
                                                   min_threshold,
                                                   field,
                                                   max_threshold))

        field = PARAMS[P.matchParameter("%s_background_field" % track)]
        min_threshold = PARAMS[P.matchParameter(
            "%s_background_min_threshold" % track)]
        max_threshold = PARAMS[P.matchParameter(
            "%s_background_max_threshold" % track)]

        E.info('%s: background: %f <= %s <= %f' % (track,
                                                   min_threshold,
                                                   field,
                                                   max_threshold))
        backgrounds.append(set(genelist[
            (genelist[field] >= min_threshold) &
            (genelist[field] <= max_threshold)].index))

        E.info("%s: fg=%i, bg=%i" % (track,
                                     len(genesets[-1]),
                                     len(backgrounds[-1])))

    E.info("writing gene list matrix")
    with IOTools.openFile(outfile, "w") as outf:
        SetTools.writeSets(outf, genesets, labels=headers)
    with IOTools.openFile(outfile + ".bg.tsv.gz", "w") as outf:
        SetTools.writeSets(outf, backgrounds, labels=headers)

    E.info("writing intersection/union matrix")
    # build set intersection matrix
    matrix = SetTools.unionIntersectionMatrix(genesets)
    with IOTools.openFile(outfile + ".matrix.gz", "w") as outf:
        IOTools.writeMatrix(outf, matrix, headers, headers)
    matrix = SetTools.unionIntersectionMatrix(backgrounds)
    with IOTools.openFile(outfile + ".bg.matrix.gz", "w") as outf:
        IOTools.writeMatrix(outf, matrix, headers, headers)

@transform(buildGeneListMatrix,
           suffix(".tsv.gz"),
           ".load")
def loadGeneListMatrix(infile, outfile):
    '''load fgene list matrix into table.'''
    track = P.snip(infile, ".tsv.gz")
    P.load(infile, outfile, tablename="%s_foreground" % track)
    P.load(infile + ".bg.tsv.gz", outfile, tablename="%s_background" % track)

@transform('pathways.dir/*.tsv.gz',
           regex('.*/(.*).tsv.gz'),
           r"pathways_\1.load")
def loadPathways(infile, outfile):
    '''load pathway information into database.'''
    P.load(infile, outfile, "--add-index=gene_id --add-index=go_id")

@follows(mkdir('hypergeometric.dir'))
@transform('pathways.dir/*.tsv.gz',
           regex('.*/(.*).tsv.gz'),
           add_inputs(buildGeneListMatrix),
           r'hypergeometric.dir/\1.tsv')
def runHypergeometricAnalysis(infiles, outfile):
    '''run pathway analysis on pathway files in
    the directory pathways.dir.
    '''
    infile_pathways, infile_genelist = infiles
    infile_background = infile_genelist + ".bg.tsv.gz"

    # TODO:
    # gene annotations
    # category annotations
    #
    # os.path.join(
    #        PARAMS["annotations_dir"],
    #        PARAMS_ANNOTATIONS["interface_go_obo"]),

    PipelineGO.runGOFromFiles(
        outfile=outfile,
        outdir=outfile + ".dir",
        fg_file=infile_genelist,
        bg_file=infile_background,
        go_file=infile_pathways,
        ontology_file=None,
        minimum_counts=PARAMS["hypergeometric_minimum_counts"],
        pairs=False,
        gene2name=None)

def computePathwayBiases(infile, outfile):
    pass

@transform(runHypergeometricAnalysis,
           suffix(".tsv"),
           r"\1.load")
def loadHypergeometricAnalysis(infile, outfile):
    '''load GO results.'''

    track = P.toTable(outfile)
    tablename = 'hypergeometric_%s_summary' % track
    P.load(infile, outfile, tablename=tablename)

    dbh = connect()
    ontologies = [x[0] for x in Database.executewait(
        dbh,
        '''SELECT DISTINCT ontology FROM %s''' % tablename).fetchall()]

    genelists = [x[0] for x in Database.executewait(
        dbh,
        '''SELECT DISTINCT genelist FROM %s''' % tablename).fetchall()]

    # output files from runGO.py
    sections = ('results', 'parameters', 'withgenes')

    for section in sections:
        tablename = 'hypergeometric_%s_%s' % (track, section)
        load_statement = P.build_load_statement(
            tablename=tablename)

        statement = '''
        cgat combine_tables
        --cat=track
        --regex-filename="hypergeometric.dir/%(track)s.tsv.dir/(\S+).%(section)s"
        hypergeometric.dir/%(track)s.tsv.dir/*.%(section)s
        | %(load_statement)s
        >> %(outfile)s'''
        P.run()

    for ontology in ontologies:

        fn = os.path.join(infile + ".dir", "all_alldesc.%s.l2fold" % ontology)

        if not os.path.exists(fn):
            E.warn("file %s does not exist" % fn)
            continue

        P.load(fn,
               outfile,
               tablename='hypergeometric_%s_%s_l2fold' % (track, ontology),
               options='--allow-empty-file')

        fn = os.path.join(
            infile + ".dir", "all_alldesc.%s.l10pvalue" % ontology)

        P.load(fn,
               outfile,
               tablename='hypergeometric_%s_%s_l10pvalue' % (track, ontology),
               options='--allow-empty-file')

        fn = os.path.join(
            infile + ".dir", "all_alldesc.%s.l10qvalue" % ontology)

        P.load(fn,
               outfile,
               tablename='hypergeometric_%s_%s_l10qvalue' % (track, ontology),
               options='--allow-empty-file')

@merge(runHypergeometricAnalysis,
       "hypergeometric_summary.load")
def loadHypergeometricResultsSummary(infiles, outfile):
    '''load GO summary results.'''
    infiles = glob.glob("hypergeometric.dir/*/*.parameters")
    P.mergeAndLoad(infiles, outfile)

@collate("hypergeometric.dir/go.tsv.dir/*.results",
         regex(r"hypergeometric.dir/go.tsv.dir/(.*)\.(.*).results"),
         r"hypergeometric.go.dir/go.tsv.dir/\1.revigo")
def plotGOResults(infiles, outfile):
    '''.'''

    infiles = " ".join(infiles)

    track = P.snip(outfile, ".revigo")

    statement = '''
    cat %(infiles)s
    | cgat revigo
      --go-tsv-file=%(annotations_filename_go)s
      --output-filename-pattern=%(track)s.%%s
      --ontology=all
      --max-similarity=0.5
      --reverse-palette
      --force-output
      -v 2
    > %(outfile)s
    '''

    P.run()

@follows(loadPathways,
         loadGeneLists,
         loadGeneListMatrix,
         loadHypergeometricAnalysis)
def full():
    pass

@follows(mkdir("report"))
def build_report():
    '''build report from scratch.'''

    E.info("starting report build process from scratch")
    P.run_report(clean=True)

@follows(mkdir("report"))
def update_report():
    '''update report.'''

    E.info("updating report")
    P.run_report(clean=False)

@follows(update_report)
def publish_report():
    '''publish report.'''

    E.info("publishing report")
    P.publish_report()

if __name__ == "__main__":

    # P.checkFiles( ("genome.fasta", "genome.idx" ) )
    sys.exit(P.main(sys.argv))


text:
test(() => {
    const params = new URLSearchParams();
    const id = token();
    params.set("resource-url", SAME_ORIGIN_RESOURCES_URL + "/delayed-js.h2.py?id=" + id);
    params.set("resource-id", id);
    const test_url = "resources/preload-in-flight-when-consumed.h2.py?" + params.toString();
    window.location.replace(new URL(test_url, window.location));
});


text:
// -*-Mode: C++;-*-

// * BeginRiceCopyright *****************************************************
//
// $HeadURL$
// $Id$
//
// --------------------------------------------------------------------------
// Part of HPCToolkit (hpctoolkit.org)
//
// Information about sources of support for research and development of
// HPCToolkit is at 'hpctoolkit.org' and in 'README.Acknowledgments'.
// --------------------------------------------------------------------------
//
// Copyright ((c)) 2002-2022, Rice University
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
//   notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
//   notice, this list of conditions and the following disclaimer in the
//   documentation and/or other materials provided with the distribution.
//
// * Neither the name of Rice University (RICE) nor the names of its
//   contributors may be used to endorse or promote products derived from
//   this software without specific prior written permission.
//
// This software is provided by RICE and contributors "as is" and any
// express or implied warranties, including, but not limited to, the
// implied warranties of merchantability and fitness for a particular
// purpose are disclaimed. In no event shall RICE or contributors be
// liable for any direct, indirect, incidental, special, exemplary, or
// consequential damages (including, but not limited to, procurement of
// substitute goods or services; loss of use, data, or profits; or
// business interruption) however caused and on any theory of liability,
// whether in contract, strict liability, or tort (including negligence
// or otherwise) arising in any way out of the use of this software, even
// if advised of the possibility of such damage.
//
// ******************************************************* EndRiceCopyright *

//***************************************************************************
//
// File:
//   $HeadURL$
//
// Purpose:
//   [The purpose of this file]
//
// Description:
//   [The set of functions, macros, etc. defined in the file]
//
//***************************************************************************

//************************* System Include Files ****************************

#include <iostream>
using std::cerr;
using std::endl;

#include <string>
using std::string;

//*************************** User Include Files ****************************

#include "Args.hpp"

//*************************** Forward Declarations **************************

// Cf. DIAG_Die.
#define ARG_ERROR(streamArgs)                                        \
  { std::ostringstream WeIrDnAmE;                                    \
    WeIrDnAmE << streamArgs /*<< std::ends*/;                        \
    printError(std::cerr, WeIrDnAmE.str());                          \
    exit(1); }

//***************************************************************************

//***************************************************************************
// Args
//***************************************************************************

Args::Args()
{
}

Args::~Args()
{
}

const std::string
Args::getCmd() const
{
  // avoid error messages with: <path>/hpcprof-mpi
  static string cmd = "hpcprof-mpi";
  return cmd; // parser.getCmd();
}


text:
namespace xrtl {

namespace {

class Win32Semaphore : public Win32WaitHandle<Semaphore> {
 public:
  Win32Semaphore(HANDLE handle, int maximum_count)
      : Win32WaitHandle(handle, maximum_count) {}

  bool Release(int release_count, int* out_previous_count) override {
    return ::ReleaseSemaphore(handle_, release_count,
                              reinterpret_cast<LPLONG>(out_previous_count)) !=
           0;
  }
};

}  // namespace

ref_ptr<Semaphore> Semaphore::Create(int initial_count, int maximum_count) {
  return make_ref<Win32Semaphore>(
      ::CreateSemaphore(nullptr, initial_count, maximum_count, nullptr),
      maximum_count);
}

}  // namespace xrtl


text:
package org.thriftee.core;

import javax.xml.transform.stream.StreamSource;

import org.thriftee.thrift.schema.IdlSchemaBuilder;
import org.thriftee.thrift.schema.SchemaBuilderException;
import org.thriftee.thrift.schema.ThriftSchema;

public interface SchemaBuilder {

  public abstract ThriftSchema buildSchema(SchemaBuilderConfig config)
      throws SchemaBuilderException;

  public static class FromXML implements SchemaBuilder {

    @Override
    public ThriftSchema buildSchema(SchemaBuilderConfig config)
        throws SchemaBuilderException {
      final IdlSchemaBuilder bldr = new IdlSchemaBuilder();
      return bldr.buildFromXml(new StreamSource(config.globalXmlFile()));
    }

  }

}


text:
class Company < ActiveRecord::Base
  has_many :employees, dependent: :destroy
  has_many :users, dependent: :destroy
end


text:
%%
%% Qt5xHb - Bindings libraries for Harbour/xHarbour and Qt Framework 5
%%
%% Copyright (C) 2020 Marcos Antonio Gambeta <marcosgambeta AT outlook DOT com>
%%

$project=Qt5xHb
$module=QtCore

$header

$includes

$beginSlotsClass
$signal=|finished()
$signal=|frameChanged( int frame )
$signal=|stateChanged( QTimeLine::State newState )
$signal=|valueChanged( qreal value )
$endSlotsClass