text:
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using CsvHelper;
using CsvHelper.Configuration;

namespace Hidari0415.UstdCsv2Ju
{
	public static class UstdCsvReader
	{
		/// <summary>
		/// Read Metric data from CSV file.
		/// </summary>
		/// <param name="path">a CSV file path</param>
		/// <returns>All data that read from CSV file</returns>
		public static List<MetricRecord> ReadMetricRecords(string path)
		{
			List<MetricRecord> records;

			using (var reader = new CsvReader(new StreamReader(path, Encoding.Default)))
			{
				reader.Configuration.RegisterClassMap<MetricRecordMap>();

				records = reader.GetRecords<MetricRecord>().ToList();
			}

			return records;
		}
	}

	internal sealed class MetricRecordMap : CsvClassMap<MetricRecord>
	{
		public MetricRecordMap()
		{
			Map(m => m.Kind).Index(0);
			Map(m => m.Name).Index(1);
			Map(m => m.File).Index(2);
			Map(m => m.Value).Index(3);
		}
	}
}


text:
/* $This file is distributed under the terms of the license in LICENSE$ */

package edu.cornell.mannlib.vitro.webapp.reasoner.plugin;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.apache.jena.ontology.OntModel;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.Statement;

import edu.cornell.mannlib.vitro.webapp.reasoner.ReasonerPlugin;
import edu.cornell.mannlib.vitro.webapp.reasoner.SimpleReasoner;

/**
 * Disables sameAs in associated SimpleReasoner.
 */
public class DisableSameAs implements ReasonerPlugin {

    private static final Log log = LogFactory.getLog(DisableSameAs.class);

	private SimpleReasoner simpleReasoner;

    public void setSimpleReasoner(SimpleReasoner simpleReasoner) {
    	this.simpleReasoner = simpleReasoner;
        this.simpleReasoner.setSameAsEnabled( false );
        log.info("owl:sameAs disabled in SimpleReasoner.");
    }

    public boolean isConfigurationOnlyPlugin() {
        return true;
    }

    public SimpleReasoner getSimpleReasoner() {
    	return this.simpleReasoner;
    }

	public boolean isInterestedInAddedStatement(Statement stmt) {
		return false;
	}

	public boolean isInterestedInRemovedStatement(Statement stmt) {
		return false;
	}

	public void addedABoxStatement(Statement stmt,
            Model aboxAssertionsModel,
            Model aboxInferencesModel,
            OntModel TBoxInferencesModel) {
    }

    public void removedABoxStatement(Statement stmt,
            Model aboxAssertionsModel,
            Model aboxInferencesModel,
            OntModel TBoxInferencesModel) {
    }

}

redpajama_set_name: RedPajamaGithub


text:
package net.rachel030219.hashchecker.activities;

import android.os.Build;
import android.os.Bundle;
import android.net.Uri;
import android.view.View;
import android.view.MenuItem;
import android.view.WindowManager;
import android.widget.TextView;
import android.content.Intent;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import net.rachel030219.hashchecker.R;

public class AboutActivity extends AppCompatActivity{

	TextView mAboutMe;

	@Override
	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		setContentView(R.layout.about);

		Toolbar mToolbar = findViewById(R.id.about_toolbar);
		mToolbar.setTitle(getTitle());
		setSupportActionBar(mToolbar);

		ActionBar mActionBar = getSupportActionBar();
		mActionBar.setHomeButtonEnabled(true);
		mActionBar.setDisplayHomeAsUpEnabled(true);

		if (Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT) {
			WindowManager.LayoutParams localLayoutParams = getWindow().getAttributes();
			localLayoutParams.flags = (WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS | localLayoutParams.flags);
		}

		bindViews();
	}

	private void bindViews(){
		mAboutMe = findViewById(R.id.about_me);
		mAboutMe.setOnClickListener(new View.OnClickListener(){
			@Override
			public void onClick(View v){
				Intent intent = new Intent(Intent.ACTION_VIEW);
				intent.setData(Uri.parse("https://me.stfw.info"));
				startActivity(intent);
			}
		});
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item){
		if (item.getItemId() == android.R.id.home)
			finish();
		return true;
	}
}


text:
alias fl="flutter"
alias flattach="flutter attach"
alias flb="flutter build"
alias flchnl="flutter channel"
alias flc="flutter clean"
alias fldvcs="flutter devices"
alias fldoc="flutter doctor"
alias flpub="flutter pub"
alias flget="flutter pub get"
alias flr="flutter run"
alias flrd="flutter run --debug"
alias flrp="flutter run --profile"
alias flrr="flutter run --release"
alias flupgrd="flutter upgrade"

# COMPLETION FUNCTION
if (( ! $+commands[flutter] )); then
  return
fi

# If the completion file doesn't exist yet, we need to autoload it and
# bind it to `flutter`. Otherwise, compinit will have already done that.
if [[ ! -f "$ZSH_CACHE_DIR/completions/_flutter" ]]; then
  typeset -g -A _comps
  autoload -Uz _flutter
  _comps[flutter]=_flutter
fi

flutter zsh-completion >| "$ZSH_CACHE_DIR/completions/_flutter" &|


text:
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.diagnostic;

import com.intellij.diagnostic.IdeaReportingEvent.TextBasedThrowable;
import com.intellij.openapi.diagnostic.Attachment;
import com.intellij.openapi.diagnostic.IdeaLoggingEvent;
import com.intellij.openapi.diagnostic.Logger;
import org.jetbrains.annotations.NotNull;

import java.util.Collection;
import java.util.Collections;
import java.util.List;

/** @deprecated use {@link LogMessage} (to be removed in IDEA 2020) */
@Deprecated
@SuppressWarnings({"DeprecatedIsStillUsed", "unused"})
public class LogMessageEx extends LogMessage {
  /** @deprecated use {@link Logger#error(String, Throwable, Attachment...)} or {@link LogMessage} (to be removed in IDEA 2020) */
  @Deprecated
  public LogMessageEx(IdeaLoggingEvent event, String title, String notificationText) {
    super(event.getThrowable(), event.getMessage(), attachments(event));
  }

  // needed for compatibility - some reporters expect/check for instances of this class
  LogMessageEx(Throwable throwable, String message, List<Attachment> attachments, String notificationText) {
    super(throwable, message, attachments);
  }

  private static List<Attachment> attachments(IdeaLoggingEvent event) {
    Object data = event.getData();
    return data instanceof AbstractMessage ? ((AbstractMessage)data).getAllAttachments() : Collections.emptyList();
  }

  /** @deprecated use {@link Logger#error(String, Throwable, Attachment...)} (to be removed in IDEA 2020) */
  @Deprecated
  public static IdeaLoggingEvent createEvent(String message, String details, Attachment... attachments) {
    return createEvent(new TextBasedThrowable(details), message, attachments);
  }

  /** @deprecated use {@link Logger#error(String, Throwable, Attachment...)} (to be removed in IDEA 2020) */
  @Deprecated
  public static IdeaLoggingEvent createEvent(String message, String details, String title, String notificationText, Attachment attachment) {
    return createEvent(new TextBasedThrowable(details), message, attachment);
  }

  /** @deprecated use {@link Logger#error(String, Throwable, Attachment...)} (to be removed in IDEA 2020) */
  @Deprecated
  public static IdeaLoggingEvent createEvent(String message, String details, String title, String notificationText, Collection<Attachment> attachments) {
    Attachment[] array = attachments != null ? attachments.toArray(Attachment.EMPTY_ARRAY) : Attachment.EMPTY_ARRAY;
    return createEvent(new TextBasedThrowable(details), message, array);
  }

  /** @deprecated use {@link Logger#error(String, Throwable, Attachment...)} and {@link AttachmentFactory#createContext} (to be removed in IDEA 2020) */
  @Deprecated
  public static void error(@NotNull Logger logger, @NotNull String message, @NotNull String... attachmentText) {
    error(logger, message, new Throwable(), attachmentText);
  }

  /** @deprecated use {@link Logger#error(String, Throwable, Attachment...)} and {@link AttachmentFactory#createContext} (to be removed in IDEA 2020) */
  @Deprecated
  public static void error(Logger logger, String message, Throwable cause, String... attachmentText) {
    StringBuilder detailsBuffer = new StringBuilder();
    for (String detail : attachmentText) {
      detailsBuffer.append(detail).append(",");
    }
    if (attachmentText.length > 0 && detailsBuffer.length() > 0) {
      detailsBuffer.setLength(detailsBuffer.length() - 1);
    }
    if (detailsBuffer.length() > 0) {
      logger.error(message, cause, AttachmentFactory.createContext(detailsBuffer));
    }
    else {
      logger.error(message, cause);
    }
  }
}


text:
require 'active_record/connection_adapters/abstract_adapter'

module TransactionIsolation
  module ActiveRecord
    module ConnectionAdapters # :nodoc:
      module AbstractAdapter

        VALID_ISOLATION_LEVELS = [:read_uncommitted, :read_committed, :repeatable_read, :serializable]

        # If true, #isolation_level(level) method is available
        def supports_isolation_levels?
          false
        end

        def isolation_level( level )
          raise NotImplementedError
        end

        private

          def validate_isolation_level( isolation_level )
            unless VALID_ISOLATION_LEVELS.include?( isolation_level )
              raise ArgumentError, "Invalid isolation level '#{isolation_level}'. Supported levels include #{VALID_ISOLATION_LEVELS.join( ', ' )}."
            end
          end

      end
    end
  end
end

ActiveRecord::ConnectionAdapters::AbstractAdapter.send( :include, TransactionIsolation::ActiveRecord::ConnectionAdapters::AbstractAdapter )


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.google.noop</groupId>
  <artifactId>noop-repo</artifactId>
  <version>1.0</version>
  <properties>
    <mavenVersion>2.1</mavenVersion>
  </properties>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.7</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>com.google.collections</groupId>
      <artifactId>google-collections</artifactId>
      <version>0.9</version>
    </dependency>
    <dependency>
      <groupId>commons-lang</groupId>
      <artifactId>commons-lang</artifactId>
      <version>2.4</version>
    </dependency>
  </dependencies>
  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>${mavenVersion}</version>
        <configuration>
          <source>1.6</source>
          <target>1.6</target>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>


text:
<!DOCTYPE html>

Creates a new LLVM TD file. You can edit the file in the IDE's Source Editor.


text:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.LinkedList;
import java.util.ListIterator;

//
// Decompiled by Procyon v0.5.30
//

public class MonitorDevice
{
    private static final Word MONITOR_READY;
    private static final Word MONITOR_NOTREADY;
    private OutputStreamWriter dout;
    private LinkedList<ActionListener> mlist;

    public MonitorDevice() {
        if (!PennSim.GRAPHICAL_MODE) {
            this.dout = new OutputStreamWriter(System.out);
        }
        else {
            this.mlist = new LinkedList<ActionListener>();
        }
    }

    public MonitorDevice(final OutputStream outputStream) {
        this.dout = new OutputStreamWriter(outputStream);
    }

    public void addActionListener(final ActionListener actionListener) {
        this.mlist.add(actionListener);
    }

    public Word status() {
        if (this.ready()) {
            return MonitorDevice.MONITOR_READY;
        }
        return MonitorDevice.MONITOR_NOTREADY;
    }

    public boolean ready() {
        if (PennSim.GRAPHICAL_MODE) {
            return true;
        }
        try {
            this.dout.flush();
            return true;
        }
        catch (IOException ex) {
            ErrorLog.logError(ex);
            return false;
        }
    }

    public void reset() {
        if (PennSim.GRAPHICAL_MODE) {
            final ListIterator<ActionListener> listIterator = this.mlist.listIterator();
            while (listIterator.hasNext()) {
                listIterator.next().actionPerformed(new ActionEvent(new Integer(1), 0, null));
            }
        }
    }

    public void write(final char c) {
        if (PennSim.GRAPHICAL_MODE) {
            final ListIterator<ActionListener> listIterator = this.mlist.listIterator();
            while (listIterator.hasNext()) {
                listIterator.next().actionPerformed(new ActionEvent(c + "", 0, null));
            }
        }
        else {
            try {
                this.dout.write(c);
                this.dout.flush();
            }
            catch (IOException ex) {
                ErrorLog.logError(ex);
            }
        }
    }

    static {
        MONITOR_READY = new Word(32768);
        MONITOR_NOTREADY = new Word(0);
    }
}


text:
import {Location, LocationStrategy, PathLocationStrategy} from '@angular/common';
import {AppModule, AppModuleFactoryLoader, ApplicationRef, ComponentResolver, Injector, OpaqueToken, SystemJsAppModuleLoader} from '@angular/core';

import {ROUTER_CONFIGURATION, setupRouter} from './common_router_providers';
import {RouterLink, RouterLinkWithHref} from './directives/router_link';
import {RouterLinkActive} from './directives/router_link_active';
import {RouterOutlet} from './directives/router_outlet';
import {Router} from './router';
import {ROUTES} from './router_config_loader';
import {RouterOutletMap} from './router_outlet_map';
import {ActivatedRoute} from './router_state';
import {DefaultUrlSerializer, UrlSerializer} from './url_tree';

/**
 * @stable
 */
export const ROUTER_DIRECTIVES = [RouterOutlet, RouterLink, RouterLinkWithHref, RouterLinkActive];

export const ROUTER_PROVIDERS: any[] = [
  Location, {provide: LocationStrategy, useClass: PathLocationStrategy},
  {provide: UrlSerializer, useClass: DefaultUrlSerializer}, {
    provide: Router,
    useFactory: setupRouter,
    deps: [
      ApplicationRef, ComponentResolver, UrlSerializer, RouterOutletMap, Location, Injector,
      AppModuleFactoryLoader, ROUTES, ROUTER_CONFIGURATION
    ]
  },
  RouterOutletMap,
  {provide: ActivatedRoute, useFactory: (r: Router) => r.routerState.root, deps: [Router]},
  {provide: AppModuleFactoryLoader, useClass: SystemJsAppModuleLoader},
  {provide: ROUTER_CONFIGURATION, useValue: {enableTracing: false}}
];

/**
 * Router module.
 *
 * ### Example
 *
 * ```
 * bootstrap(AppCmp, {modules: [RouterModule]});
 * ```
 *
 * @experimental
 */
@AppModule({directives: ROUTER_DIRECTIVES, providers: ROUTER_PROVIDERS})
export class RouterModule {
  constructor(private injector: Injector) {
    setTimeout(() => {
      const appRef = injector.get(ApplicationRef);
      if (appRef.componentTypes.length == 0) {
        appRef.registerBootstrapListener(() => { injector.get(Router).initialNavigation(); });
      } else {
        injector.get(Router).initialNavigation();
      }
    }, 0);
  }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Bridge.Translator
{
    public interface ISourceMapRecorder
    {
        /// <summary>
        /// Record a source location. If the <paramref name="sourcePath"/> is null and <paramref name="sourceLine"/> and <paramref name="sourceCol"/> are both 0 it means that no source information is available.
        /// </summary>
        /// <param name="scriptLine">1-based line number in the generated script.</param>
        /// <param name="scriptCol">1-based column in the generated script.</param>
        /// <param name="sourcePath">Path to the source file.</param>
        /// <param name="sourceLine">1-base line number in the source file.</param>
        /// <param name="sourceCol">1-based column number in the source file</param>
        void RecordLocation(int scriptLine, int scriptCol, string sourcePath, int sourceLine, int sourceCol);
    }
}


text:
module Backend
  class ContactsController < BaseController
    before_action :set_active_nav

    # get: /backend/contacts
    def index
      @contacts = Contact.all
                         .order("#{sort_column} #{sort_direction}")
                         .page(params.fetch(:page, nil))
                         .per(20)
    end

    def sort_column
      Contact.column_names.include?(params[:sort]) ? params[:sort] : "id"
    end
    helper_method :sort_column

    private

    def set_active_nav
      @active_nav = 'backend_contacts'
    end
  end
end


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

	$.noConflict();
	jQuery( document ).ready(function( $ ) {
	  // Code that uses jQuery's $ can follow here.
	});

	var $inputMessage = jQuery('.inputMessage');
	var typing = false;
	var socket = io();

	angular.module('2Chat', ['ngRoute'])
		.run(function($http, $rootScope, $location) {
			$rootScope.authenticated = false;
			$rootScope.current_user = 'Guest';
			$rootScope.current_chat_user = '';

			$rootScope.signout = function(){
				$http.get('auth/signout');
				$rootScope.authenticated = false;
				$rootScope.current_user = 'Guest';
				$location.path('/');
			};

			$rootScope.newChat = function(recieverName){
				$rootScope.current_chat_user = recieverName;
				$location.path('/newChat');
			}
		})
		.config(['$routeProvider', function($routeProvider) {
			$routeProvider
				.when('/', {
					templateUrl: 'welcomePage.html',
					controller: '2chatMainCtrl',
					controllerAs: 'mainCtrl'
				})
				.when('/login', {
					templateUrl: 'login.html',
					controller: 'authController',
					controllerAs: 'authCtrl'
				})
				.when('/register', {
					templateUrl: 'register.html',
					controller: 'authController',
					controllerAs: 'authCtrl'
				})
				.when('/contacts', {
					templateUrl: 'contacts.html',
					controller: 'contactsController',
					controllerAs: 'contactsCtrl'
				})
				.when('/chats', {
					templateUrl: 'chats.html',
					controller: 'chatsController',
					controllerAs: 'chatsCtrl'
				})
				.when('/newChat', {
					templateUrl: 'newChat.html',
					controller: 'newChatController',
					controllerAs: 'newChatCtrl'
				});

			//$locationProvider.html5Mode(true);
		}])
		.controller('2chatMainCtrl', ['$route', '$routeParams', '$location', function($route, $routeParams, $location) {
			this.$route = $route;
			this.$routeParams = $routeParams;
			this.$location = $location;
		}])
		.controller('authController', function($scope, $http, $rootScope, $location){
			$scope.user = {username: '', password: ''};
			$scope.error_message = '';

			$scope.login = function(){
				$http.post('/auth/login', $scope.user).success(function(data){
					if(data.state == 'success'){
						$rootScope.authenticated = true;
						$rootScope.current_user = data.user.name;
						$location.path('/contacts');
					}
					else{
						$scope.error_message = data.message;
					}
					socket.emit('login',{username: data.user.name});
				});
			};

			$scope.register = function(){
				$http.post('/auth/signup', $scope.user).success(function(data){
					if(data.state == 'success'){
						$rootScope.authenticated = true;
						$rootScope.current_user = data.user.name;
						$location.path('/');
					}
					else{
						$scope.error_message = data.message;
					}
				});
			};
		})
		.controller('contactsController', function($scope, $http, $location, $rootScope) {
			$scope.contacts = [];
			$scope.error_message = "";

			if($rootScope.authenticated){
				$http.get('/api/contacts?username=' + $rootScope.current_user)
					.success(function(data) {
						$scope.contacts = data;
					})
					.error(function(data) {
						$scope.error_message = data.statusText;
					});
			}
			else{
				$location.path('/');
			}

		})
		.controller('chatsController', function($scope, $rootScope, $http, $location) {
			$scope.chatters = [];
			$scope.error_message = "";

			if($rootScope.authenticated){
				$http.get('/api/contacts/chatters')
					.success(function(data) {
						$scope.contacts = data;
					})
					.error(function(data) {
						$scope.error_message = data.statusText;
					});
			}
			else{
				$location.path('/');
			}
		})
		.controller('newChatController', function($scope, $rootScope, $http, $location) {
			$scope.messages = [];

			$scope.postChat = function(){
				console.log(angular.element('[id="inputMessage"]').val());
				socket.emit('chat message', {sender: $rootScope.current_user, reciever: $rootScope.current_chat_user,message: jQuery('.inputMessage').val()});
				jQuery('.msg_push_old').html(jQuery('.msg_push_old').html() + '
' + '
' + jQuery('.inputMessage').val() + '
');
				jQuery('.inputMessage').val('');
			}

			if($rootScope.authenticated){

			}
			else{
				$location.path('/');
			}
		});
		console.log($inputMessage.html());
	$inputMessage.keypress(function(event) {
		if (event.which !== 13) {
			if (typing === false && $inputMessage.is(":focus")) {
				typing = true;
				socket.emit("typing", {
					isTyping: true,
					roomID: id,
					person: "Client"
				});
			} else {
				clearTimeout(timeout);
				timeout = setTimeout(timeoutFunction, 2000);
			}
		} else {
			sendMessage();
			clearTimeout(timeout);
			timeoutFunction();
		}
	})
	socket.on('typing', function(data) {
	console.log('typing');
	$inputMessage = jQuery('#' + data.roomID);
	var $parent = $inputMessage.parent();
	var $typing = $parent.children(".typing");
	if (data.isTyping)
		$typing.append("" + data.person + " is typing...");
	else
		$typing.text('');
})
jQuery('#inputForm').submit(function(){
	return false;
});
socket.on('chat message', function(data) {
	console.log('recieved');
	console.log(jQuery('.messages').html());
	jQuery('.messages').html(jQuery('.messages').html() + '
' + '
' + data.message + '
');
})
})(window.angular);


text:
package libgit

import (
	"io"

	lru "github.com/hashicorp/golang-lru"
	"github.com/pkg/errors"
	"gopkg.in/src-d/go-git.v4/plumbing"
	"gopkg.in/src-d/go-git.v4/plumbing/storer"
)

type onDemandObject struct {
	s           storer.EncodedObjectStorer
	hash        plumbing.Hash
	typeSet     bool
	objType     plumbing.ObjectType
	sizeSet     bool
	size        int64
	recentCache *lru.Cache
}

var _ plumbing.EncodedObject = (*onDemandObject)(nil)

func (odo *onDemandObject) cache() (o plumbing.EncodedObject, err error) {
	if tmp, ok := odo.recentCache.Get(odo.hash); ok {
		o = tmp.(plumbing.EncodedObject)
	} else {
		o, err = odo.s.EncodedObject(odo.objType, odo.hash)
		if err != nil {
			return nil, err
		}
		odo.recentCache.Add(odo.hash, o)
	}

	if !odo.sizeSet {
		odo.size = o.Size()
	}
	if !odo.typeSet {
		odo.objType = o.Type()
	}
	return o, nil
}

func (odo *onDemandObject) cacheIfNeeded() error {
	if odo.size >= 0 {
		return nil
	}
	// TODO: We should be able to read the type and size from the
	// object's header, without loading the entire object itself.
	_, err := odo.cache()
	return err
}

func (odo *onDemandObject) Hash() plumbing.Hash {
	return odo.hash
}

func (odo *onDemandObject) Type() plumbing.ObjectType {
	_ = odo.cacheIfNeeded()
	return odo.objType
}

func (odo *onDemandObject) SetType(ot plumbing.ObjectType) {
	odo.typeSet = true
	odo.objType = ot
}

func (odo *onDemandObject) Size() int64 {
	_ = odo.cacheIfNeeded()
	return odo.size
}

func (odo *onDemandObject) SetSize(s int64) {
	odo.sizeSet = true
	odo.size = s
}

func (odo *onDemandObject) Reader() (io.ReadCloser, error) {
	// Create a new object to stream data from the storer on-demand,
	// without caching the bytes to long-lived memory.  Let the block
	// cache do its job to keep recent data in memory and control
	// total memory usage.
	o, err := odo.cache()
	if err != nil {
		return nil, err
	}
	return o.Reader()
}

func (odo *onDemandObject) Writer() (io.WriteCloser, error) {
	return nil, errors.New("onDemandObject shouldn't be used for writes")
}


text:
import * as React from 'react';
import {createPortal} from 'react-dom';
import useLayoutEffect from 'use-isomorphic-layout-effect';
import {FocusGuard, HIDDEN_STYLES} from './utils/FocusGuard';

type ManagerRef = null | {
  handleBeforeOutside: () => void;
  handleAfterOutside: () => void;
};

const PortalContext = React.createContext<null | {
  preserveTabOrder: boolean;
  setModal: React.Dispatch<React.SetStateAction<boolean>>;
  beforeInsideRef: React.RefObject<HTMLSpanElement>;
  afterInsideRef: React.RefObject<HTMLSpanElement>;
  beforeOutsideRef: React.RefObject<HTMLSpanElement>;
  afterOutsideRef: React.RefObject<HTMLSpanElement>;
  managerRef: React.MutableRefObject<ManagerRef>;
}>(null);

const DEFAULT_ID = 'floating-ui-root';

export const useFloatingPortalNode = ({
  id = DEFAULT_ID,
  enabled = true,
}: {
  id?: string;
  enabled?: boolean;
} = {}) => {
  const [portalEl, setPortalEl] = React.useState<HTMLElement | null>(null);

  useLayoutEffect(() => {
    if (!enabled) {
      return;
    }

    const rootNode = document.getElementById(id);

    if (rootNode) {
      setPortalEl(rootNode);
    } else {
      const newPortalEl = document.createElement('div');
      newPortalEl.id = id;
      setPortalEl(newPortalEl);

      if (!document.body.contains(newPortalEl)) {
        document.body.appendChild(newPortalEl);
      }
    }
  }, [id, enabled]);

  return portalEl;
};

/**
 * Portals your floating element outside of the main app node.
 * @see https://floating-ui.com/docs/FloatingPortal
 */
export const FloatingPortal = ({
  children,
  id = DEFAULT_ID,
  root = null,
  preserveTabOrder = true,
}: {
  children?: React.ReactNode;
  id?: string;
  root?: HTMLElement | null;
  preserveTabOrder?: boolean;
}) => {
  const portalNode = useFloatingPortalNode({id, enabled: !root});
  const [modal, setModal] = React.useState(true);

  const beforeOutsideRef = React.useRef<HTMLSpanElement>(null);
  const afterOutsideRef = React.useRef<HTMLSpanElement>(null);
  const beforeInsideRef = React.useRef<HTMLSpanElement>(null);
  const afterInsideRef = React.useRef<HTMLSpanElement>(null);
  const managerRef = React.useRef<ManagerRef>(null);

  const renderGuards =
    !!children && !!(root || portalNode) && preserveTabOrder && !modal;

  return (
    <PortalContext.Provider
      value={React.useMemo(
        () => ({
          preserveTabOrder,
          beforeOutsideRef,
          afterOutsideRef,
          beforeInsideRef,
          afterInsideRef,
          managerRef,
          setModal,
        }),
        [preserveTabOrder]
      )}
    >
      {renderGuards && (
        <FocusGuard
          ref={beforeOutsideRef}
          onFocus={() => {
            managerRef.current?.handleBeforeOutside();
          }}
        />
      )}
      {renderGuards && (
        <span aria-owns={portalNode?.id} style={HIDDEN_STYLES} />
      )}
      {root
        ? createPortal(children, root)
        : portalNode
        ? createPortal(children, portalNode)
        : null}
      {renderGuards && (
        <FocusGuard
          ref={afterOutsideRef}
          onFocus={() => {
            managerRef.current?.handleAfterOutside();
          }}
        />
      )}
    </PortalContext.Provider>
  );
};

export const usePortalContext = () => React.useContext(PortalContext);


text:
add_dependencies({
    muting: 'js/muting.js',
    people: 'js/people.js',
    unread: 'js/unread.js',
});

var stream_data = require('js/stream_data.js');

stream_data = {
    canonicalized_name: stream_data.canonicalized_name,
};
set_global('stream_data', stream_data);
set_global('blueslip', {});

var Dict = global.Dict;
var muting = global.muting;
var people = global.people;

var unread = require('js/unread.js');

var narrow_state = {};
global.narrow_state = narrow_state;

var current_msg_list = {};
global.current_msg_list = current_msg_list;

var home_msg_list = {};
global.home_msg_list = home_msg_list;

var me = {
    email: 'me@example.com',
    user_id: 30,
    full_name: 'Me Myself',
};
people.add(me);
people.initialize_current_user(me.user_id);

var zero_counts = {
    private_message_count: 0,
    home_unread_messages: 0,
    mentioned_message_count: 0,
    stream_count: new Dict(),
    subject_count: new Dict(),
    pm_count: new Dict(),
    unread_in_current_view: 0,
};

(function test_empty_counts_while_narrowed() {
    narrow_state.active = function () {
        return true;
    };
    current_msg_list.all_messages = function () {
        return [];
    };

    var counts = unread.get_counts();
    assert.deepEqual(counts, zero_counts);
}());

(function test_empty_counts_while_home() {
    narrow_state.active = function () {
        return false;
    };
    current_msg_list.all_messages = function () {
        return [];
    };

    var counts = unread.get_counts();
    assert.deepEqual(counts, zero_counts);
}());

(function test_changing_subjects() {
    // Summary: change the subject of a message from 'lunch'
    // to 'dinner' using update_unread_topics().
    var count = unread.num_unread_for_subject('social', 'lunch');
    assert.equal(count, 0);

    var stream_id = 100;
    var wrong_stream_id = 110;

    var message = {
        id: 15,
        type: 'stream',
        stream_id: stream_id,
        subject: 'lunch',
    };

    var other_message = {
        id: 16,
        type: 'stream',
        stream_id: stream_id,
        subject: 'lunch',
    };

    unread.process_loaded_messages([message, other_message]);

    count = unread.num_unread_for_subject(stream_id, 'lunch');
    assert.equal(count, 2);
    assert(unread.topic_has_any_unread(stream_id, 'lunch'));
    assert(!unread.topic_has_any_unread(wrong_stream_id, 'lunch'));

    var event = {
        subject: 'dinner',
    };

    unread.update_unread_topics(message, event);

    count = unread.num_unread_for_subject(stream_id, 'lunch');
    assert.equal(count, 1);

    count = unread.num_unread_for_subject(stream_id, 'dinner');
    assert.equal(count, 1);

    event = {
        subject: 'snack',
    };

    unread.update_unread_topics(other_message, event);

    count = unread.num_unread_for_subject(stream_id, 'lunch');
    assert.equal(count, 0);
    assert(!unread.topic_has_any_unread(stream_id, 'lunch'));
    assert(!unread.topic_has_any_unread(wrong_stream_id, 'lunch'));

    count = unread.num_unread_for_subject(stream_id, 'snack');
    assert.equal(count, 1);
    assert(unread.topic_has_any_unread(stream_id, 'snack'));
    assert(!unread.topic_has_any_unread(wrong_stream_id, 'snack'));

    // Test defensive code.  Trying to update a message we don't know
    // about should be a no-op.
    event = {
        subject: 'brunch',
    };
    unread.update_unread_topics(other_message, event);

    // cleanup
    message.subject = 'dinner';
    unread.process_read_message(message);
    count = unread.num_unread_for_subject(stream_id, 'dinner');
    assert.equal(count, 0);

    other_message.subject = 'snack';
    unread.process_read_message(other_message);
    count = unread.num_unread_for_subject(stream_id, 'snack');
    assert.equal(count, 0);
}());

stream_data.get_stream_id = function () {
    return 999;
};

(function test_muting() {
    stream_data.is_subscribed = function () {
        return true;
    };

    stream_data.in_home_view = function () {
        return true;
    };

    unread.declare_bankruptcy();

    var stream_id = 101;
    var unknown_stream_id = 555;

    stream_data.get_sub_by_id = function (stream_id) {
        if (stream_id === 101) {
            return {name: 'social'};
        }
    };

    var message = {
        id: 15,
        type: 'stream',
        stream_id: stream_id,
        subject: 'test_muting',
    };

    unread.process_loaded_messages([message]);
    var counts = unread.get_counts();
    assert.equal(counts.stream_count.get(stream_id), 1);
    assert.equal(counts.home_unread_messages, 1);
    assert.equal(unread.num_unread_for_stream(stream_id), 1);

    muting.add_muted_topic('social', 'test_muting');
    counts = unread.get_counts();
    assert.equal(counts.stream_count.get(stream_id), 0);
    assert.equal(counts.home_unread_messages, 0);
    assert.equal(unread.num_unread_for_stream(stream_id), 0);

    assert.equal(unread.num_unread_for_stream(unknown_stream_id), 0);
}());

(function test_num_unread_for_subject() {
    // Test the num_unread_for_subject() function using many
    // messages.
    unread.declare_bankruptcy();

    var stream_id = 301;
    var count = unread.num_unread_for_subject(stream_id, 'lunch');
    assert.equal(count, 0);

    var message = {
        type: 'stream',
        stream_id: stream_id,
        subject: 'lunch',
    };

    var num_msgs = 500;
    var i;
    for (i = 0; i < num_msgs; i += 1) {
        message.id = i+1;
        unread.process_loaded_messages([message]);
    }

    count = unread.num_unread_for_subject(stream_id, 'lunch');
    assert.equal(count, num_msgs);

    for (i = 0; i < num_msgs; i += 1) {
        message.id = i+1;
        unread.process_read_message(message);
    }

    count = unread.num_unread_for_subject(stream_id, 'lunch');
    assert.equal(count, 0);
}());

(function test_home_messages() {
    narrow_state.active = function () {
        return false;
    };
    stream_data.is_subscribed = function () {
        return true;
    };
    stream_data.in_home_view = function () {
        return true;
    };

    var stream_id = 401;

    stream_data.get_sub_by_id = function () {
        return {
            name: 'whatever',
        };
    };

    var message = {
        id: 15,
        type: 'stream',
        stream_id: stream_id,
        subject: 'lunch',
    };

    home_msg_list.get = function (msg_id) {
        return (msg_id === '15') ? message : undefined;
    };

    var counts = unread.get_counts();
    assert.equal(counts.home_unread_messages, 0);

    unread.process_loaded_messages([message]);

    counts = unread.get_counts();
    assert.equal(counts.home_unread_messages, 1);
    assert.equal(counts.stream_count.get(stream_id), 1);
    unread.process_read_message(message);
    counts = unread.get_counts();
    assert.equal(counts.home_unread_messages, 0);

    unread.process_loaded_messages([message]);
    counts = unread.get_counts();
    assert.equal(counts.home_unread_messages, 1);

    // Now unsubscribe all our streams.
    stream_data.is_subscribed = function () {
        return false;
    };
    counts = unread.get_counts();
    assert.equal(counts.home_unread_messages, 0);

}());

(function test_phantom_messages() {
    var message = {
        id: 999,
        type: 'stream',
        stream_id: 555,
        subject: 'phantom',
    };

    stream_data.get_sub_by_id = function () { return; };

    unread.process_read_message(message);
    var counts = unread.get_counts();
    assert.equal(counts.home_unread_messages, 0);
}());

(function test_private_messages() {
    narrow_state.active = function () {
        return false;
    };
    stream_data.is_subscribed = function () {
        return true;
    };

    var counts = unread.get_counts();
    assert.equal(counts.private_message_count, 0);

    var anybody = {
        email: 'anybody@example.com',
        user_id: 999,
        full_name: 'Any Body',
    };
    people.add_in_realm(anybody);

    var message = {
        id: 15,
        type: 'private',
        display_recipient: [
            {user_id: anybody.user_id},
            {id: me.user_id},
        ],
    };

    unread.process_loaded_messages([message]);

    counts = unread.get_counts();
    assert.equal(counts.private_message_count, 1);
    assert.equal(counts.pm_count.get('999'), 1);
    unread.process_read_message(message);
    counts = unread.get_counts();
    assert.equal(counts.private_message_count, 0);
    assert.equal(counts.pm_count.get('999'), 0);
}());

(function test_num_unread_for_person() {
    var alice = {
        email: 'alice@example.com',
        user_id: 101,
        full_name: 'Alice',
    };
    people.add_in_realm(alice);

    var bob = {
        email: 'bob@example.com',
        user_id: 102,
        full_name: 'Bob',
    };
    people.add_in_realm(bob);

    assert.equal(unread.num_unread_for_person(alice.user_id), 0);
    assert.equal(unread.num_unread_for_person(bob.user_id), 0);

    var message = {
        id: 15,
        display_recipient: [{id: alice.user_id}],
        type: 'private',
    };

    var read_message = {
        flags: ['read'],
    };
    unread.process_loaded_messages([message, read_message]);
    assert.equal(unread.num_unread_for_person(alice.user_id), 1);

    assert.equal(unread.num_unread_for_person(''), 0);
}());

(function test_mentions() {
    narrow_state.active = function () {
        return false;
    };
    stream_data.is_subscribed = function () {
        return true;
    };

    var counts = unread.get_counts();
    assert.equal(counts.mentioned_message_count, 0);

    var message = {
        id: 15,
        type: 'stream',
        stream_id: 999,
        subject: 'lunch',
        mentioned: true,
    };

    unread.process_loaded_messages([message]);

    counts = unread.get_counts();
    assert.equal(counts.mentioned_message_count, 1);
    unread.process_read_message(message);
    counts = unread.get_counts();
    assert.equal(counts.mentioned_message_count, 0);
}());

(function test_declare_bankruptcy() {
    unread.declare_bankruptcy();

    var counts = unread.get_counts();
    assert.deepEqual(counts, zero_counts);
}());

(function test_num_unread_current_messages() {
    var count = unread.num_unread_current_messages();
    assert.equal(count, 0);

    var message = {
        id: 15,
    };
    current_msg_list.all_messages = function () {
        return [message];
    };

    // It's a little suspicious that num_unread_current_messages()
    // is using the pointer as a hint for filtering out unread
    // messages, but right now, it's impossible for unread messages
    // to be above the pointer in a narrowed view, so unread.js uses
    // this for optimization purposes.
    current_msg_list.selected_id = function () {
        return 11; // less than our message's id
    };

    count = unread.num_unread_current_messages();
    assert.equal(count, 1);
}());

(function test_message_unread() {
    // Test some code that might be overly defensive, for line coverage sake.
    assert(!unread.message_unread(undefined));
    assert(unread.message_unread({flags: []}));
    assert(!unread.message_unread({flags: ['read']}));
}());

(function test_errors() {
    global.blueslip.warn = function () {};

    // Test unknown message leads to zero count
    var message = {
        id: 9,
        type: 'private',
        display_recipient: [{id: 9999}],
    };

    unread.process_read_message(message);
    var counts = unread.get_counts();
    assert.equal(counts.private_message_count, 0);

    // Test undefined stream_id
    message = { type: 'stream' };

    global.blueslip.error = function (msg) {
        assert.equal(msg, 'No stream_id found for message undefined');
    };

    unread.process_read_message(message);
}());


text:
WSO2-MB 3.0.0 Template for the Configurator
-------------------------------------------------------------------------------------

###Creating MB Template Module for Private PaaS

(1) Build the template module zip file by running the following command.

```
mvn clean install
```

---
### Configuration parameters
Following are the configuration parameters that is used by the template.
You can configure following in the ***module.ini*** file.

#### Read from environment variables :

    READ_FROM_ENVIRONMENT = false

-------------------------------------------------------------------------------------

#### Set the path of product directory :

    CARBON_HOME = <MB_HOME>

---

#### Enable clustering :

    CONFIG_PARAM_CLUSTERING = true

* Used in - < MB_HOME >/repository/conf/axis2/axis2.xml

---

#### Set Membership Schema :

    CONFIG_PARAM_MEMBERSHIP_SCHEME = wka

* Used in - < MB_HOME >/repository/conf/axis2/axis2.xml

---

#### Set Domain :

    CONFIG_PARAM_DOMAIN = wso2.mb.domain

* Used in - < MB_HOME >/repository/conf/axis2/axis2.xml

---

#### Well known members declaration :

    CONFIG_PARAM_WKA_MEMBERS = "127.0.0.1:4000,127.0.1.1:4001"

* Format - "ip_address1:port1,ip_address2:port2"
* Used in - < MB_HOME >/repository/conf/axis2/axis2.xml

---

#### Set Local Member Hostname and port :

    CONFIG_PARAM_LOCAL_MEMBER_HOST = 127.0.0.1
    CONFIG_PARAM_LOCAL_MEMBER_PORT = 4000

* Used in - < MB_HOME >/repository/conf/axis2/axis2.xml

---

### Set Port offset :

    CONFIG_PARAM_PORT_OFFSET = 0

* Used in - < MB_HOME >/repository/conf/carbon.xml

---
#### Set proxy ports when using a load balancer :

    CONFIG_PARAM_HTTP_PROXY_PORT = 80
    CONFIG_PARAM_HTTPS_PROXY_PORT = 443

* Used in - < MB_HOME >/repository/conf/tomcat/catalina-server.xml

---
#### Set management console hostnames

    CONFIG_PARAM_MGT_HOST_NAME = mgt.am.cloud-test.wso2.com

* Used in - < MB_HOME >/repository/conf/carbon.xml

---

## Following are the config parameters used for setting up external database
#### Set URL for MB store DB

    CONFIG_PARAM_MB_STORE_DB_URL= jdbc:mysql://localhost:3306/mb_store_db

#### Set Username for MB store DB

    CONFIG_PARAM_MB_STORE_DB_USER_NAME=root

#### Set Password for MB store DB
```
    CONFIG_PARAM_MB_STORE_DB_PASSWORD=root
```
#### Set Driver class name for MB store DB

    CONFIG_PARAM_MB_STORE_DB_DRIVER=com.mysql.jdbc.Driver

#### Set URL for MB metrics DB

    CONFIG_PARAM_MB_METRICS_DB_URL= jdbc:mysql://localhost:3306/mb_metrics_db

#### Set Username for MB metrics DB

    CONFIG_PARAM_MB_METRICS_DB_USERNAME=root

#### Set Password for MB metrics DB
```
    CONFIG_PARAM_MB_METRICS_DB_PASSWORD=root
```
#### Set Driver class name for MB metrics DB

    CONFIG_PARAM_MB_METRICS_DB_DRIVER=com.mysql.jdbc.Driver

#### Set URL for registry DB

    CONFIG_PARAM_REGISTRY_DB_URL= jdbc:mysql://localhost:3306/registry_db

#### Set Username for registry DB

    CONFIG_PARAM_REGISTRY_DB_USER_NAME=root

#### Set Password for registry DB
```
    CONFIG_PARAM_REGISTRY_DB_PASSWORD=root
```
#### Set Driver class name for registry DB

    CONFIG_PARAM_REGISTRY_DB_DRIVER=com.mysql.jdbc.Driver

#### Set URL for user DB

    CONFIG_PARAM_USER_MGT_DB_URL= jdbc:mysql://localhost:3306/user_db

#### Set Username for user DB

    CONFIG_PARAM_USER_MGT_DB_USER_NAME=root

#### Set Password for user DB
```
    CONFIG_PARAM_USER_MGT_DB_PASSWORD=root
```
#### Set Driver class name for user DB

    CONFIG_PARAM_USER_MGT_DB_DRIVER=com.mysql.jdbc.Driver

##### Used in

* < MB_HOME >/repository/conf/user-mgt.xml
* < MB_HOME >/repository/conf/datasources/master-datasources.xml
* < MB_HOME >/repository/conf/datasources/metrics-datasources.xml
* < MB_HOME >/repository/conf/registry.xml


text:
#ifndef RUNTIME_INCLUDE_DART_API_DL_H_
#define RUNTIME_INCLUDE_DART_API_DL_H_

#include "dart_api.h"        /* NOLINT */
#include "dart_native_api.h" /* NOLINT */

/** \mainpage Dynamically Linked Dart API
 *
 * This exposes a subset of symbols from dart_api.h and dart_native_api.h
 * available in every Dart embedder through dynamic linking.
 *
 * All symbols are postfixed with _DL to indicate that they are dynamically
 * linked and to prevent conflicts with the original symbol.
 *
 * Link `dart_api_dl.c` file into your library and invoke
 * `Dart_InitializeApiDL` with `NativeApi.initializeApiDLData`.
 */

#ifdef __cplusplus
#define DART_EXTERN extern "C"
#else
#define DART_EXTERN extern
#endif

DART_EXTERN intptr_t Dart_InitializeApiDL(void* data);

// ============================================================================
// IMPORTANT! Never update these signatures without properly updating
// DART_API_DL_MAJOR_VERSION and DART_API_DL_MINOR_VERSION.
//
// Verbatim copy of `dart_native_api.h` and `dart_api.h` symbol names and types
// to trigger compile-time errors if the sybols in those files are updated
// without updating these.
//
// Function return and argument types, and typedefs are carbon copied. Structs
// are typechecked nominally in C/C++, so they are not copied, instead a
// comment is added to their definition.
typedef int64_t Dart_Port_DL;

typedef void (*Dart_NativeMessageHandler_DL)(Dart_Port_DL dest_port_id,
                                             Dart_CObject* message);

// dart_native_api.h symbols can be called on any thread.
#define DART_NATIVE_API_DL_SYMBOLS(F)                                          \
  /***** dart_native_api.h *****/                                              \
  /* Dart_Port */                                                              \
  F(Dart_PostCObject, bool, (Dart_Port_DL port_id, Dart_CObject * message))    \
  F(Dart_PostInteger, bool, (Dart_Port_DL port_id, int64_t message))           \
  F(Dart_NewNativePort, Dart_Port_DL,                                          \
    (const char* name, Dart_NativeMessageHandler_DL handler,                   \
     bool handle_concurrently))                                                \
  F(Dart_CloseNativePort, bool, (Dart_Port_DL native_port_id))

// dart_api.h symbols can only be called on Dart threads.
#define DART_API_DL_SYMBOLS(F)                                                 \
  /***** dart_api.h *****/                                                     \
  /* Errors */                                                                 \
  F(Dart_IsError, bool, (Dart_Handle handle))                                  \
  F(Dart_IsApiError, bool, (Dart_Handle handle))                               \
  F(Dart_IsUnhandledExceptionError, bool, (Dart_Handle handle))                \
  F(Dart_IsCompilationError, bool, (Dart_Handle handle))                       \
  F(Dart_IsFatalError, bool, (Dart_Handle handle))                             \
  F(Dart_GetError, const char*, (Dart_Handle handle))                          \
  F(Dart_ErrorHasException, bool, (Dart_Handle handle))                        \
  F(Dart_ErrorGetException, Dart_Handle, (Dart_Handle handle))                 \
  F(Dart_ErrorGetStackTrace, Dart_Handle, (Dart_Handle handle))                \
  F(Dart_NewApiError, Dart_Handle, (const char* error))                        \
  F(Dart_NewCompilationError, Dart_Handle, (const char* error))                \
  F(Dart_NewUnhandledExceptionError, Dart_Handle, (Dart_Handle exception))     \
  F(Dart_PropagateError, void, (Dart_Handle handle))                           \
  /* Dart_Handle, Dart_PersistentHandle, Dart_WeakPersistentHandle */          \
  F(Dart_HandleFromPersistent, Dart_Handle, (Dart_PersistentHandle object))    \
  F(Dart_HandleFromWeakPersistent, Dart_Handle,                                \
    (Dart_WeakPersistentHandle object))                                        \
  F(Dart_NewPersistentHandle, Dart_PersistentHandle, (Dart_Handle object))     \
  F(Dart_SetPersistentHandle, void,                                            \
    (Dart_PersistentHandle obj1, Dart_Handle obj2))                            \
  F(Dart_DeletePersistentHandle, void, (Dart_PersistentHandle object))         \
  F(Dart_NewWeakPersistentHandle, Dart_WeakPersistentHandle,                   \
    (Dart_Handle object, void* peer, intptr_t external_allocation_size,        \
     Dart_HandleFinalizer callback))                                           \
  F(Dart_DeleteWeakPersistentHandle, void, (Dart_WeakPersistentHandle object)) \
  F(Dart_UpdateExternalSize, void,                                             \
    (Dart_WeakPersistentHandle object, intptr_t external_allocation_size))     \
  F(Dart_NewFinalizableHandle, Dart_FinalizableHandle,                         \
    (Dart_Handle object, void* peer, intptr_t external_allocation_size,        \
     Dart_HandleFinalizer callback))                                           \
  F(Dart_DeleteFinalizableHandle, void,                                        \
    (Dart_FinalizableHandle object, Dart_Handle strong_ref_to_object))         \
  F(Dart_UpdateFinalizableExternalSize, void,                                  \
    (Dart_FinalizableHandle object, Dart_Handle strong_ref_to_object,          \
     intptr_t external_allocation_size))                                       \
  /* Dart_Port */                                                              \
  F(Dart_Post, bool, (Dart_Port_DL port_id, Dart_Handle object))               \
  F(Dart_NewSendPort, Dart_Handle, (Dart_Port_DL port_id))                     \
  F(Dart_SendPortGetId, Dart_Handle,                                           \
    (Dart_Handle port, Dart_Port_DL * port_id))                                \
  /* Scopes */                                                                 \
  F(Dart_EnterScope, void, ())                                                 \
  F(Dart_ExitScope, void, ())

#define DART_API_ALL_DL_SYMBOLS(F)                                             \
  DART_NATIVE_API_DL_SYMBOLS(F)                                                \
  DART_API_DL_SYMBOLS(F)
// IMPORTANT! Never update these signatures without properly updating
// DART_API_DL_MAJOR_VERSION and DART_API_DL_MINOR_VERSION.
//
// End of verbatim copy.
// ============================================================================

#define DART_API_DL_DECLARATIONS(name, R, A)                                   \
  typedef R(*name##_Type) A;                                                   \
  DART_EXTERN name##_Type name##_DL;

DART_API_ALL_DL_SYMBOLS(DART_API_DL_DECLARATIONS)

#undef DART_API_DL_DEFINITIONS

#undef DART_EXTERN

#endif /* RUNTIME_INCLUDE_DART_API_DL_H_ */ /* NOLINT */


text:
class Chromatch < Sinatra::Base
  get '/' do
    redirect '/home' if logged_in?
    erb :public, :layout => false
  end
end


text:
require 'spec_helper'
require 'capybara/webkit/driver'

describe Capybara::Webkit::Driver, "#resize_window(width, height)" do
  include AppRunner

  let(:driver) do
    driver_for_html(<<-HTML)

UNKNOWN

    HTML
  end

  DEFAULT_DIMENTIONS = "[1680x1050]"

  it "resizes the window to the specified size" do
    driver.visit("#{AppRunner.app_host}/")

    driver.resize_window(800, 600)
    driver.html.should include("[800x600]")

    driver.resize_window(300, 100)
    driver.html.should include("[300x100]")
  end

  it "resizes the window to the specified size even before the document has loaded" do
    driver.resize_window(800, 600)
    driver.visit("#{AppRunner.app_host}/")
    driver.html.should include("[800x600]")
  end

  it "resets the window to the default size when the driver is reset" do
    driver.resize_window(800, 600)
    driver.reset!
    driver.visit("#{AppRunner.app_host}/")
    driver.html.should include(DEFAULT_DIMENTIONS)
  end

  it "resizes windows by handle" do
    driver.visit("#{AppRunner.app_host}/")
    driver.open_new_window
    driver.visit("#{AppRunner.app_host}/")

    driver.resize_window_to(driver.window_handles.first, 800, 600)
    driver.resize_window_to(driver.window_handles.last, 400, 300)

    driver.window_size(driver.window_handles.first).should eq [800, 600]
    driver.window_size(driver.window_handles.last).should eq [400, 300]
  end

  it "maximizes a window" do
    driver.visit("#{AppRunner.app_host}/")
    driver.resize_window(400, 300)
    driver.maximize_window(driver.current_window_handle)
    width, height = *driver.window_size(driver.current_window_handle)

    width.should be > 400
    height.should be > 300
  end
end


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

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.SmallTests;
import org.apache.hadoop.hbase.io.hfile.Compression;
import org.apache.hadoop.io.DataOutputBuffer;
import org.apache.hadoop.io.compress.CompressionCodec;
import org.apache.hadoop.io.compress.CompressionOutputStream;
import org.apache.hadoop.util.NativeCodeLoader;
import org.apache.hadoop.util.ReflectionUtils;
import org.junit.Test;
import org.junit.experimental.categories.Category;

import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;

import static org.junit.Assert.*;

@Category(SmallTests.class)
public class TestCompressionTest {

  @Test
  public void testTestCompression() {

    // This test will fail if you run the tests with LZO compression available.
    try {
      CompressionTest.testCompression(Compression.Algorithm.LZO);
      fail(); // always throws
    } catch (IOException e) {
      // there should be a 'cause'.
      assertNotNull(e.getCause());
    }

    // this is testing the caching of the test results.
    try {
      CompressionTest.testCompression(Compression.Algorithm.LZO);
      fail(); // always throws
    } catch (IOException e) {
      // there should be NO cause because it's a direct exception not wrapped
      assertNull(e.getCause());
    }

    assertFalse(CompressionTest.testCompression("LZO"));
    assertTrue(CompressionTest.testCompression("NONE"));
    assertTrue(CompressionTest.testCompression("GZ"));

    if (isCompressionAvailable("org.apache.hadoop.io.compress.SnappyCodec")) {
      if (NativeCodeLoader.isNativeCodeLoaded()) {
        try {
          System.loadLibrary("snappy");

          try {
            Configuration conf = new Configuration();
            CompressionCodec codec = (CompressionCodec)
              ReflectionUtils.newInstance(
                conf.getClassByName("org.apache.hadoop.io.compress.SnappyCodec"), conf);

            DataOutputBuffer compressedDataBuffer = new DataOutputBuffer();
            CompressionOutputStream deflateFilter =
              codec.createOutputStream(compressedDataBuffer);

            byte[] data = new byte[1024];
            DataOutputStream deflateOut = new DataOutputStream(
              new BufferedOutputStream(deflateFilter));
            deflateOut.write(data, 0, data.length);
            deflateOut.flush();
            deflateFilter.finish();

            // Snappy Codec class, Snappy nativelib and Hadoop nativelib with
            // Snappy JNIs are present
            assertTrue(CompressionTest.testCompression("SNAPPY"));
          }
          catch (UnsatisfiedLinkError ex) {
            // Hadoop nativelib does not have Snappy JNIs

            // cannot assert the codec here because the current logic of
            // CompressionTest checks only classloading, not the codec
            // usage.
          }
          catch (Exception ex) {
          }
        }
        catch (UnsatisfiedLinkError ex) {
          // Snappy nativelib is not available
          assertFalse(CompressionTest.testCompression("SNAPPY"));
        }
      }
      else {
        // Hadoop nativelib is not available
        assertFalse(CompressionTest.testCompression("SNAPPY"));
      }
    }
    else {
      // Snappy Codec class is not available
      assertFalse(CompressionTest.testCompression("SNAPPY"));
    }
  }

  private boolean isCompressionAvailable(String codecClassName) {
    try {
      Thread.currentThread().getContextClassLoader().loadClass(codecClassName);
      return true;
    }
    catch (Exception ex) {
      return false;
    }
  }

}


text:
<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link href='//fonts.googleapis.com/css?family=Raleway:400,300,600' rel='stylesheet' type='text/css'>
  <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/normalize/3.0.2/normalize.min.css">
  <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/skeleton/2.0.1/skeleton.min.css">

  <title>snabbt.js</title>

snabbt.js is a perfect fit for text animations. Each letter is rotated around the x-axis with a really tight perspective.

  <button class="button button-primary" id="again-please" onclick="animate()">Again please!</button>

DOM elements animated with snabbt.js.


text:
using UnityEngine;
using System.Collections;

public class FaceUpdate : MonoBehaviour
{
	public AnimationClip[] animations;

	Animator anim;

    Transform player;
    PlayerEmotions playerEmotions;

	public float delayWeight;

    void Awake ()
    {
        player = GameObject.FindGameObjectWithTag ("Player").transform;
        playerEmotions = player.GetComponent<PlayerEmotions> ();
    }

	void Start ()
	{
		anim = GetComponent<Animator> ();
	}

	void OnGUI ()
	{
	}

	float current = 0;

	void Update ()
	{
		if (Input.GetMouseButton (0)) {
			current = 1;
		} else {
			current = Mathf.Lerp (current, 0, delayWeight);
		}

        anim.SetLayerWeight (1, 1);
        float dominantEmotion = Mathf.Max (playerEmotions.currentAnger, playerEmotions.currentSadness, playerEmotions.currentEyeClosure,
                                    playerEmotions.currentJoy, playerEmotions.currentSurprise);

        if (dominantEmotion <= 5) {
            anim.SetLayerWeight (1, current);
        } else if (playerEmotions.currentJoy == dominantEmotion) {
            if (playerEmotions.currentJoy > 60) {
                Debug.Log ("smile1@unitychan");
                anim.CrossFade ("smile1@unitychan", 0.1f);
            } else {
                Debug.Log ("smile2@unitychan");
                anim.CrossFade ("smile2@unitychan", 0.1f);
            }
        } else if (playerEmotions.currentAnger == dominantEmotion) {
            if (playerEmotions.currentAnger > 40) {
                Debug.Log ("angry2@unitychan");
                anim.CrossFade ("angry2@unitychan", 0.1f);
            } else {
                Debug.Log ("angry1@unitychan");
                anim.CrossFade ("angry1@unitychan", 0.1f);
            }
        } else if (playerEmotions.currentSurprise == dominantEmotion) {
            Debug.Log ("sap@unitychan");
            anim.CrossFade ("sap@unitychan", 0.1f);
        } else if (playerEmotions.currentSadness == dominantEmotion) {
            if (playerEmotions.currentSadness > 50) {
                Debug.Log ("disstract1@unitychan");
                anim.CrossFade ("disstract1@unitychan", 0.1f);
            } else {
                Debug.Log ("disstract2@unitychan");
                anim.CrossFade ("disstract2@unitychan", 0.1f);
            }
        } else {
            Debug.Log ("eye_close@unitychan");
            anim.CrossFade ("eye_close@unitychan", 0.1f);
        }
	}
}


text:
package br.com.digicard.store;

import java.util.Collection;

import com.cloudant.client.api.Database;

import br.com.digicard.vo.User;

/**
 * Defines the API for a User store.
 *
 */
public interface UserStore {

	/**
	 * Get the target db object.
	 *
	 * @return Database.
	 * @throws Exception
	 */
	public Database getDB();

	/**
	 * Gets all Users from the store.
	 *
	 * @return All Users.
	 * @throws Exception
	 */
	public Collection<User> getAll();

	/**
	 * Gets an individual User from the store.
	 *
	 * @param id
	 *            The ID of the ToDo to get.
	 * @return The ToDo.
	 */
	public User get(String id);

	/**
	 * Persists a User to the store.
	 *
	 * @param td
	 *            The ToDo to persist.
	 * @return The persisted ToDo. The ToDo will not have a unique ID..
	 */
	public String persist(User vi);

	/**
	 * Updates a User in the store.
	 *
	 * @param id
	 *            The ID of the User to update.
	 * @param td
	 *            The User with updated information.
	 * @return The updated User.
	 */
	public User update(String id, User vi);

	/**
	 * Deletes a ToDo from the store.
	 *
	 * @param id
	 *            The ID of the User to delete.
	 */
	public void delete(String id);

	/**
	 * Counts the number of Users
	 *
	 * @return The total number of Users.
	 * @throws Exception
	 */
	public int count() throws Exception;
}


text:
/* jshint -W079 */

import render from '../module/index';

const test = require('tape-catch');
const noop = require('1-liners/noop');
const always = require('1-liners/always');
const map = require('1-liners/map');
const curry = require('1-liners/curry');
const hasOwnProperty = curry(require('1-liners/hasOwnProperty'));
const property = curry(require('1-liners/property'));
const omit = require('101/omit');
const plus = curry(require('1-liners/plus'));
const dummy = require('doxie-dummy');

const title = plus('Programmatic API:  ');

test(title('Renders comments' output'), (is) => {
  const input = dummy([
    {data: {dummyProperty: false}},
    {data: {dummyProperty: false}, metadata: 'something'},
    {data: {dummyProperty: true}},
  ]);

  const check = (template) => render(template)(input);
  const checkOutputs = (template) => map(property('output'),
    check(template).docs
  );

  is.deepEqual(
    checkOutputs(always('result')),
    ['result', 'result', 'result'],
    'stuffing the returned string into the `.output` property'
  );

  is.deepEqual(
    map(omit('output'),
      check(always('anything')).docs
    ),
    input.docs,
    'leaving the rest of the comment intact'
  );

  is.deepEqual(
    check(noop),
    input,
    'ignoring comment output when the render function returns no value'
  );

  is.deepEqual(
    map(hasOwnProperty('output'),
      check(({data}) => (data.dummyProperty ? 'Yeeeah!' : undefined)).docs
    ),
    [false, false, true],
    'handling it well when only some comments produce output'
  );

  is.deepEqual(
    checkOutputs(({data}) => data.dummyProperty),
    ['false', 'false', 'true'],
    'casting non-string return values'
  );

  is.deepEqual(
    checkOutputs(({data}) => data.dummyProperty ? null : undefined),
    [undefined, undefined, null],
    'but not when they are `null` or `undefined`'
  );

  is.end();
});

test(title('Fails with informative messages'), (is) => {
  is.throws(
    () => render(/something wrong/),
    /expected a function/i,
    'when given a non-function'
  );

  is.end();
});


text:
package org.openehealth.ipf.commons.ihe.hpd.stub.dsmlv2;

import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for AttributeDescriptions complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="AttributeDescriptions">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence maxOccurs="unbounded" minOccurs="0">
 *         <element name="attribute" type="{urn:oasis:names:tc:DSML:2:0:core}AttributeDescription"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "AttributeDescriptions", propOrder = {
    "attribute"
})
public class AttributeDescriptions {

    protected List<AttributeDescription> attribute;

    /**
     * Gets the value of the attribute property.
     *
     *

     * This accessor method returns a reference to the live list,
     * not a snapshot. Therefore any modification you make to the
     * returned list will be present inside the JAXB object.
     * This is why there is not a set method for the attribute property.
     *
     *

     * For example, to add a new item, do as follows:
     *

     *    getAttribute().add(newItem);
     *

     *
     *
     *

     * Objects of the following type(s) are allowed in the list
     * {@link AttributeDescription }
     *
     *
     */
    public List<AttributeDescription> getAttribute() {
        if (attribute == null) {
            attribute = new ArrayList<>();
        }
        return this.attribute;
    }

}


text:
goog.require('com.onesoft.livetube.entity.CSListTypeCardMobile');
goog.require('com.onesoft.livetube.entity.SCListTypeCardMobile');
goog.require('com.onesoft.livetube.entity.CSInputCard');
goog.require('com.onesoft.livetube.entity.SCInputCard');
goog.require('com.onesoft.livetube.entity.CSListCardMobile');
goog.require('com.onesoft.livetube.entity.SCListCardMobile');
goog.require('com.onesoft.livetube.entity.TypeCardMobile');
goog.require('com.onesoft.livetube.entity.SCInputCard');
goog.require('com.onesoft.livetube.entity.SCInputCard.Codes');

angular.module('livetube.card', ['ngRoute'])
    .config(['$routeProvider', function ($routeProvider) {
        $routeProvider.when('/cards', {
            templateUrl: 'partials/cards.html',
            controller: 'CardCtrl'
        });
    }])
    .controller('CardCtrl', function ($rootScope, $scope, $location, $routeParams, $window, ltSession, authService, vcRecaptchaService) {

        $scope.providers = [];
        $scope.card = {};
        $scope.success = false;
        $scope.errors = [];

        $scope.init = function () {
            $scope.errors =[];

            //goog.events.unlisten(ltSession, com.onesoft.livetube.net.SessionHandler.EventTypes.MESSAGE, this.onMessage, false, this);
            goog.events.listen(ltSession, com.onesoft.livetube.net.SessionHandler.EventTypes.MESSAGE, $scope.onMessage, false, this);
            var req = new com.onesoft.livetube.entity.CSListTypeCardMobile();
            ltSession.getCurrentConnection().sendMessage(req);
            if (!authService.isLoggedIn()) {
                $rootScope.$emit(com.onesoft.livetube.events.EventTypes.REQUEST_LOGIN, {returnUrl: '/cards'});
                $location.path('/login');
            }
        };

        $scope.setResponse = function (response) {
            $scope.response = response;
        };
        $scope.setWidgetId = function (widgetId) {
            $scope.widgetId = widgetId;
        };
        $scope.cbExpiration = function() {
            $scope.response = null;
        };

        $scope.send = function () {
            $scope.errors =[];
            if($scope.$parent.captchaEnable && $scope.response == null){
                $scope.errors.push('Xin vui lòng nhập mã xác thực!');
                return;
            }
            var req = new com.onesoft.livetube.entity.CSInputCard();
            req.setCardNumber($scope.card.cardNumber);
            req.setSeri($scope.card.pinCode);
            req.setTypeCardMobileId($scope.card.providerId);
            ltSession.getCurrentConnection().sendMessage(req);
            $rootScope.spinnerActive = true;
            $scope.spinnerActive = true;

        }

        $scope.onMessage = function (e) {

            var msg = e.message;
            switch (parseInt(msg.tag)) {
                case com.onesoft.livetube.base.LiveTag.SC_LIST_TYPE_CARD_MOBILE:
                    $scope.providers = msg.getTypeCardMobiles();
                    $scope.$apply();
                    break;
                case com.onesoft.livetube.base.LiveTag.SC_INPUT_CARD:
                    switch (msg.getResponseCode()) {
                        case com.onesoft.livetube.entity.SCInputCard.Codes.INPUT_CARD_SUCCESS:
                            $scope.success = true;
                            $scope.$apply();
                            break;
                        case com.onesoft.livetube.entity.SCInputCard.Codes.INPUT_CARD_SERI_UNSUCCESS:
                            $scope.errors.push('Nạp thẻ không thành công! Lỗi serial');
                            vcRecaptchaService.reload($scope.widgetId);
                            $scope.$apply();
                            break;
                        case com.onesoft.livetube.entity.SCInputCard.Codes.INPUT_CARD_NUMBER_UNSUCCESS:
                            $scope.errors.push('Nạp thẻ không thành công! Lỗi số thẻ');
                            vcRecaptchaService.reload($scope.widgetId);
                            $scope.$apply();
                            break;
                        case com.onesoft.livetube.entity.SCInputCard.Codes.INPUT_CARD_SLOW_UNSUCCESS:
                            $scope.errors.push('Hệ thống đang xử lý');
                            vcRecaptchaService.reload($scope.widgetId);
                            $scope.$apply();
                            break;
                        case com.onesoft.livetube.entity.SCInputCard.Codes.INPUT_CARD_INPUTED_UNSUCCESS:
                            $scope.errors.push('Thẻ đã sử dụng hoặc không chính xác.');
                            vcRecaptchaService.reload($scope.widgetId);
                            $scope.$apply();
                            break;
                        case com.onesoft.livetube.entity.SCInputCard.Codes.INPUT_CARD_SERVER_FAIL_UNSUCCESS:
                            $scope.errors.push('Hệ thống viễn thông đang bảo trì');
                            vcRecaptchaService.reload($scope.widgetId);
                            $scope.$apply();
                            break;
                    }
                    $scope.card ={};
                    $scope.$apply();
                    break;
                case com.onesoft.livetube.base.LiveTag.SC_LIST_CARD_MOBILE:
                    break;
            }
        }
    }
)


text:
package com.hazelcast.client.cluster;

import com.hazelcast.client.config.ClientConfig;
import com.hazelcast.client.spi.properties.ClientProperty;
import com.hazelcast.client.test.TestHazelcastFactory;
import com.hazelcast.config.Config;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.IMap;
import com.hazelcast.core.OperationTimeoutException;
import com.hazelcast.instance.DefaultNodeExtension;
import com.hazelcast.instance.HazelcastInstanceFactory;
import com.hazelcast.instance.Node;
import com.hazelcast.instance.NodeExtension;
import com.hazelcast.nio.Address;
import com.hazelcast.test.HazelcastParallelClassRunner;
import com.hazelcast.test.HazelcastTestSupport;
import com.hazelcast.test.annotation.ParallelTest;
import com.hazelcast.test.annotation.QuickTest;
import com.hazelcast.test.mocknetwork.MockNodeContext;
import com.hazelcast.test.mocknetwork.TestNodeRegistry;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;

import java.io.IOException;
import java.net.UnknownHostException;
import java.util.concurrent.atomic.AtomicBoolean;

import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail;

@RunWith(HazelcastParallelClassRunner.class)
@Category({QuickTest.class, ParallelTest.class})
public class ClientNodeExtensionTest
        extends HazelcastTestSupport {
    private TestHazelcastFactory factory;

    @Before
    public void before()
            throws IOException {
        factory = new TestHazelcastFactory();
    }

    @After
    public void after() {
        factory.terminateAll();
    }

    private class ManagedExtensionNodeContext
            extends MockNodeContext {
        private AtomicBoolean startupDone;

        protected ManagedExtensionNodeContext(TestNodeRegistry registry, Address thisAddress, boolean isStarted) {
            super(registry, thisAddress);
            startupDone = new AtomicBoolean(isStarted);
        }

        @Override
        public NodeExtension createNodeExtension(Node node) {
            return new DefaultNodeExtension(node) {
                @Override
                public boolean isStartCompleted() {
                    return startupDone.get() && super.isStartCompleted();
                }
            };
        }

        public void setStartupDone(boolean started) {
            this.startupDone.set(started);
        }
    }

    @Test(expected = IllegalStateException.class)
    public void test_canNotConnect_whenNodeExtensionIsNotComplete()
            throws UnknownHostException {
        HazelcastInstanceFactory.newHazelcastInstance(new Config(), randomName(),
                new ManagedExtensionNodeContext(factory.getRegistry(), new Address("127.0.0.1", 5555), false));

        ClientConfig clientConfig = new ClientConfig();
        clientConfig.getNetworkConfig().addAddress("127.0.0.1:5555");
        factory.newHazelcastClient(clientConfig);
    }

    @Test(expected = OperationTimeoutException.class)
    public void test_canGetFromMap_whenNodeExtensionIsNotComplete() {
        IMap<Object, Object> map = null;
        ManagedExtensionNodeContext nodeContext = null;
        try {
            nodeContext = new ManagedExtensionNodeContext(factory.getRegistry(), new Address("127.0.0.1", 5555), true);

            HazelcastInstanceFactory.newHazelcastInstance(new Config(), randomName(), nodeContext);

            ClientConfig clientConfig = new ClientConfig();
            clientConfig.setProperty(ClientProperty.INVOCATION_TIMEOUT_SECONDS.getName(), "3");
            clientConfig.getNetworkConfig().addAddress("127.0.0.1:5555");

            HazelcastInstance hazelcastClient = factory.newHazelcastClient(clientConfig);

            map = hazelcastClient.getMap(randomMapName());

            assertNull(map.get("dummy"));
        } catch (Throwable t) {
            fail("Should not throw exception! Error:" + t);
        }

        nodeContext.setStartupDone(false);

        map.get("dummy");
    }
}


text:
/* eslint-disable */
var gulp = require('gulp');
var path = require('path');
var ngc = require('@angular/compiler-cli/src/main').main;
var rollup = require('gulp-rollup');
var rename = require('gulp-rename');
var del = require('del');
var runSequence = require('run-sequence');
var inlineResources = require('./tools/gulp/inline-resources');
var replace = require('gulp-replace');
var sass = require('gulp-sass');

const rootFolder = path.join(__dirname);
const srcFolder = path.join(rootFolder, 'src');
const tmpFolder = path.join(rootFolder, '.tmp');
const buildFolder = path.join(rootFolder, 'build');
const distFolder = path.join(rootFolder, 'dist');

/**
 * 1. Delete /dist folder
 */
gulp.task('clean:dist', function () {

  // Delete contents but not dist folder to avoid broken npm links
  // when dist directory is removed while npm link references it.
  return deleteFolders([distFolder + '/**', '!' + distFolder]);
});

/**
 * 2. Clone the /src folder into /.tmp. If an npm link inside /src has been made,
 *    then it's likely that a node_modules folder exists. Ignore this folder
 *    when copying to /.tmp.
 */
gulp.task('copy:source', function () {
  return gulp.src([`${srcFolder}/**/*`, `!${srcFolder}/node_modules`])
    .pipe(gulp.dest(tmpFolder));
});

/**
 * 3. Inline template (.html) and style (.css) files into the the component .ts files.
 *    We do this on the /.tmp folder to avoid editing the original /src files
 */
gulp.task('inline-resources', function () {
  return Promise.resolve()
    .then(() => inlineResources(tmpFolder));
});

/**
 * Generate the theme files
 */
gulp.task('build:themes', function () {
  return gulp.src(`${tmpFolder}/styles/themes/**/*.scss`)
    .pipe(sass().on('error', sass.logError))
    .pipe(gulp.dest(`${distFolder}/themes`));
});

/**
 * 4. Run the Angular compiler, ngc, on the /.tmp folder. This will output all
 *    compiled modules to the /build folder.
 */
gulp.task('ngc', function () {
  return ngc({
    project: `${tmpFolder}/tsconfig.es5.json`
  })
    .then((exitCode) => {
      if (exitCode === 1) {
        // This error is caught in the 'compile' task by the runSequence method callback
        // so that when ngc fails to compile, the whole compile process stops running
        throw new Error('ngc compilation failed');
      }
    });
});

/**
 * 5. Run rollup inside the /build folder to generate our Flat ES module and place the
 *    generated file into the /dist folder
 */
gulp.task('rollup:fesm', function () {
  return gulp.src(`${buildFolder}/**/*.js`)
  // transform the files here.
    .pipe(rollup({

      // Bundle's entry point
      // See "input" in https://rollupjs.org/#core-functionality
      input: `${buildFolder}/index.js`,

      // Allow mixing of hypothetical and actual files. "Actual" files can be files
      // accessed by Rollup or produced by plugins further down the chain.
      // This prevents errors like: 'path/file' does not exist in the hypothetical file system
      // when subdirectories are used in the `src` directory.
      allowRealFiles: true,

      // A list of IDs of modules that should remain external to the bundle
      // See "external" in https://rollupjs.org/#core-functionality
      external: [
        '@angular/core',
        '@angular/common'
      ],

      // Format of generated bundle
      // See "format" in https://rollupjs.org/#core-functionality
      format: 'es'
    }))
    .pipe(gulp.dest(distFolder));
});

/**
 * 6. Run rollup inside the /build folder to generate our UMD module and place the
 *    generated file into the /dist folder
 */
gulp.task('rollup:umd', function () {
  return gulp.src(`${buildFolder}/**/*.js`)
  // transform the files here.
    .pipe(rollup({

      // Bundle's entry point
      // See "input" in https://rollupjs.org/#core-functionality
      input: `${buildFolder}/index.js`,

      // Allow mixing of hypothetical and actual files. "Actual" files can be files
      // accessed by Rollup or produced by plugins further down the chain.
      // This prevents errors like: 'path/file' does not exist in the hypothetical file system
      // when subdirectories are used in the `src` directory.
      allowRealFiles: true,

      // A list of IDs of modules that should remain external to the bundle
      // See "external" in https://rollupjs.org/#core-functionality
      external: [
        '@angular/core',
        '@angular/common'
      ],

      // Format of generated bundle
      // See "format" in https://rollupjs.org/#core-functionality
      format: 'umd',

      // Export mode to use
      // See "exports" in https://rollupjs.org/#danger-zone
      exports: 'named',

      // The name to use for the module for UMD/IIFE bundles
      // (required for bundles with exports)
      // See "name" in https://rollupjs.org/#core-functionality
      name: 'ic-datepicker',

      // See "globals" in https://rollupjs.org/#core-functionality
      globals: {
        typescript: 'ts'
      }

    }))
    .pipe(rename('ic-datepicker.umd.js'))
    .pipe(gulp.dest(distFolder));
});

/**
 * 7. Copy all the files from /build to /dist, except .js files. We ignore all .js from /build
 *    because with don't need individual modules anymore, just the Flat ES module generated
 *    on step 5.
 */
gulp.task('copy:build', function () {
  return gulp.src([`${buildFolder}/**/*`, `!${buildFolder}/**/*.js`])
    .pipe(gulp.dest(distFolder));
});

/**
 *
 */
gulp.task('copy:scss', function () {
  return gulp.src([`${srcFolder}/styles/*.scss`])
      .pipe(gulp.dest(`${distFolder}/styles`));
});

/**
 * 8. Copy package.json from /src to /dist
 */
gulp.task('copy:manifest', function () {
  return gulp.src([`${srcFolder}/package.json`])
    .pipe(gulp.dest(distFolder));
});

/**
 * 9. Copy README.md from / to /dist
 */
gulp.task('copy:readme', function () {
  return gulp.src([path.join(rootFolder, 'README.MD')])
    .pipe(gulp.dest(distFolder));
});

/**
 * 10. Replace the moment import syntax. The former is required for the build, but the latter for use in the consuming
 *     application
 */
gulp.task('replace:momentImports', function(){
  gulp.src(`${distFolder}/**/*.d.ts`)
      .pipe(replace("import moment from 'moment'", "import * as moment from 'moment'"))
      .pipe(gulp.dest(distFolder));
});

/**
 * 11. Delete /.tmp folder
 */
gulp.task('clean:tmp', function () {
  return deleteFolders([tmpFolder]);
});

/**
 * 12. Delete /build folder
 */
gulp.task('clean:build', function () {
  return deleteFolders([buildFolder]);
});

gulp.task('compile', function () {
  runSequence(
    'clean:dist',
    'copy:source',
    'inline-resources',
    'build:themes',
    'ngc',
    'rollup:fesm',
    'rollup:umd',
    'copy:build',
    'copy:scss',
    'copy:manifest',
    'copy:readme',
    'replace:momentImports',
    'clean:build',
    'clean:tmp',
    function (err) {
      if (err) {
        console.log('ERROR:', err.message);
        deleteFolders([distFolder, tmpFolder, buildFolder]);
      } else {
        console.log('Compilation finished successfully');
      }
    });
});

/**
 * Watch for any change in the /src folder and compile files
 */
gulp.task('watch', function () {
  gulp.watch(`${srcFolder}/**/*`, ['compile']);
});

gulp.task('clean', ['clean:dist', 'clean:tmp', 'clean:build']);

gulp.task('build', ['clean', 'compile']);
gulp.task('build:watch', ['build', 'watch']);
gulp.task('default', ['build:watch']);

/**
 * Deletes the specified folder
 */
function deleteFolders(folders) {
  return del(folders);
}


text:
package im.actor.sdk.controllers.pickers.file;

import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.AlphaAnimation;
import android.view.animation.AnimationSet;
import android.view.animation.TranslateAnimation;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.ListView;
import android.support.v7.widget.SearchView;
import android.widget.TextView;

import im.actor.sdk.controllers.pickers.file.items.ExplorerItem;
import im.actor.sdk.controllers.pickers.file.search.IndexTask;
import im.actor.sdk.controllers.pickers.file.search.SearchTask;
import im.actor.sdk.controllers.pickers.file.view.MaterialInterpolator;
import im.actor.sdk.view.SearchViewHacker;

import java.io.File;
import java.util.ArrayList;

import im.actor.sdk.R;

public class SearchFileFragment extends Fragment implements AbsListView.OnScrollListener {
    private View rootView;
    private String lastTitle;
    private ArrayList<ExplorerItem> items = new ArrayList<ExplorerItem>();
    SearchTask searchingTask;
    private ListView listView;
    private ExplorerAdapter adapter;
    private String root;
    private TextView status;
    private BasePickerActivity pickerActivity;
    private SearchView searchView;
    private boolean animated = false;
    private IndexTask indexingTask;
    private ArrayList<File> index = new ArrayList<File>();
    private String query;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        rootView = inflater.inflate(R.layout.picker_fragment_file_search, container, false);
        root = getArguments().getString("root");

//        ViewGroup searchContainer = (ViewGroup) rootView.findViewById(R.id.search_container);
        View contentContainer = rootView.findViewById(R.id.content_container);

        status = (TextView) rootView.findViewById(R.id.status);
        // progress = new IndeterminateWrapper(pickerActivity);
        // progress.show();
        listView = (ListView) contentContainer.findViewById(R.id.list);
        listView.setOnScrollListener(this);

        adapter = new ExplorerAdapter(pickerActivity, items);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(pickerActivity);
        AlphaAnimation alphaAnimation = new AlphaAnimation(0, 1);
        alphaAnimation.setDuration(300);
        alphaAnimation.setInterpolator(new MaterialInterpolator());

        TranslateAnimation translateAnimation = new TranslateAnimation(0, 0, -150, 0);
        translateAnimation.setDuration(450);
        translateAnimation.setInterpolator(new MaterialInterpolator());

        //  searchContainer.startAnimation(translateAnimation);
        contentContainer.startAnimation(alphaAnimation);

        /**/

        pickerActivity.getSupportActionBar().setTitle(R.string.picker_file_search_activity_title);
        if (index.isEmpty()) {
            indexingTask = new IndexTask(new File(root)) {
                @Override
                public void onIndexingEnded(ArrayList<File> indexedItems) {
                    index.clear();
                    index.addAll(indexedItems);
                    indexingTask = null;
                    if (searchingTask != null) {
                        searchingTask.execute();
                    } else {
                        //  progress.hide();
                    }
                }
            };
            //searchingProgressBar.progressiveStart();
            indexingTask.execute();
        } else {
        }
        return rootView;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        if (item.getItemId() == R.id.menu_search) {
            searchView.setIconified(!searchView.isIconified());
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {

        inflater.inflate(R.menu.picker_search, menu);
        MenuItem searchMenuItem = menu.getItem(0);

        searchView = (SearchView) searchMenuItem.getActionView();

        searchView.setIconified(false);
        int searchPlateId = searchView.getContext().getResources().getIdentifier("android:id/search_plate", null, null);
        View searchPlate = searchView.findViewById(searchPlateId);
        if (searchPlate != null) {
            // searchPlate.setBackgroundColor(Color.DKGRAY);
            int searchTextId = searchPlate.getContext().getResources().getIdentifier("android:id/search_src_text", null, null);
            TextView searchText = (TextView) searchPlate.findViewById(searchTextId);
            if (searchText != null) {
                searchText.setTextColor(Color.WHITE);
                searchText.setHintTextColor(Color.WHITE);
            }
        }

        /*
        SearchViewHacker.setCloseIcon(searchView, R.drawable.bar_clear_search);
        SearchViewHacker.setIcon(searchView, R.drawable.picker_bar_search);
        SearchViewHacker.setText(searchView, getResources().getColor(R.color.picker_file_searchbox_focused_color));
        SearchViewHacker.setEditText(searchView, R.drawable.picker_search_text_box);
        SearchViewHacker.setHint(searchView, getString(R.string.picker_file_search_query_text), 0, getResources().getColor(R.color.picker_file_searchbox_hint_color), null);
        SearchViewHacker.disableMagIcon(searchView);
        */

        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String s) {

                hideKeyBoard();
                return true;
            }

            @Override
            public boolean onQueryTextChange(String query) {

                if (query.equals("")) {
                    SearchViewHacker.disableCloseButton(searchView);
                    return true;
                } else {
                    SearchViewHacker.setCloseIcon(searchView, R.drawable.bar_clear_search);

                }
                SearchFileFragment.this.query = query;

                if (searchingTask != null) {
                    searchingTask.cancel(true);
                    searchingTask = null;
                }
                File rootFile = new File(root);
                if (root == null || root.equals("")) {
                    rootFile = null;
                }
                // progress.show();
                searchingTask = new SearchTask(rootFile, query, index) {
                    @Override
                    public void onSearchEnded(final ArrayList<ExplorerItem> files) {
                        searchingTask = null;
                        // progress.hide();
                        if (files.isEmpty()) {
                            status.setVisibility(View.VISIBLE);
                            status.setText(R.string.picker_empty);
                            items.clear();
                            adapter.notifyDataSetChanged();
                            // listView.setVisibility(View.GONE);
                        } else {
                            showItems(files);
                            /*
                            AnimationSet outAnimation = new AnimationSet(true);
                            outAnimation.addAnimation(new TranslateAnimation(0, 0, 100, 0));
                            outAnimation.addAnimation(new AlphaAnimation(0,1));
                            outAnimation.setDuration(350);
                            outAnimation.setInterpolator(new MaterialInterpolator());
                            outAnimation.setAnimationListener(new Animation.AnimationListener() {
                                @Override
                                public void onAnimationStart(Animation animation) {
                                    animated = true;
                                }

                                @Override
                                public void onAnimationEnd(Animation animation) {
                                    animated = false;
                                }

                                @Override
                                public void onAnimationRepeat(Animation animation) {

                                }
                            });
                            listView.startAnimation(outAnimation);*/
                        }

                    }
                };
                if (indexingTask == null || !index.isEmpty()) {
                    searchingTask.execute();
                }
                return false;
            }
        });
        searchView.setOnCloseListener(new SearchView.OnCloseListener() {
            @Override
            public boolean onClose() {

                hideKeyBoard();
                getActivity().onBackPressed();
                return false;
            }
        });
        searchView.setOnQueryTextFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                if (searchView.getQuery().length() == 0) {
                    searchView.postDelayed(new Runnable() {
                        @Override
                        public void run() {

                            SearchViewHacker.disableCloseButton(searchView);
                        }
                    }, 0);
                    SearchViewHacker.disableCloseButton(searchView);
                } else
                    SearchViewHacker.setCloseIcon(searchView, R.drawable.bar_clear_search);
            }
        });
        searchView.requestFocusFromTouch();
        SearchViewHacker.disableCloseButton(searchView);
        InputMethodManager inputMethodManager = (InputMethodManager) pickerActivity.getSystemService(Context.INPUT_METHOD_SERVICE);
        inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
        if (query != null) {
            searchView.setQuery(query, false);
        }
    }

    private void showItems(ArrayList<ExplorerItem> found) {
        items.clear();
        items.addAll(found);
        status.setVisibility(View.GONE);
        adapter.notifyDataSetChanged();
        if (!animated) {
            listView.setAlpha(0);
            listView.post(new Runnable() {
                @Override
                public void run() {
                    listView.setAlpha(1);
                    for (int i = 0; i < listView.getChildCount(); i++) {
                        View searchItemView = listView.getChildAt(i);
                        AnimationSet slideInAnimation = new AnimationSet(true);
                        slideInAnimation.setInterpolator(new MaterialInterpolator());
                        slideInAnimation.setDuration(200);
                        if (i != 0) {
                            slideInAnimation.setStartOffset(i * 50 + 25);
                        } else {
                            slideInAnimation.setStartOffset(75);
                        }
                        AlphaAnimation alphaAnimation = new AlphaAnimation(0, 1);
                        slideInAnimation.addAnimation(alphaAnimation);
                        TranslateAnimation translateAnimation = new TranslateAnimation(0, 0, 150, 0);
                        slideInAnimation.addAnimation(translateAnimation);
                        searchItemView.startAnimation(slideInAnimation);
                    }
                }
            });

            animated = true;
        } else
            listView.setVisibility(View.VISIBLE);
    }

    @Override
    public void onPause() {
        super.onPause();

        hideKeyBoard();
        pickerActivity.getSupportActionBar().setIcon(R.drawable.picker_bar_filepicker_icon);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onResume() {
        super.onResume();
        // pickerActivity.searchDisable();
        pickerActivity.setFragment(this);
        pickerActivity.invalidateOptionsMenu();
        pickerActivity.getSupportActionBar().setIcon(R.drawable.picker_bar_search);
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        this.pickerActivity = (BasePickerActivity) activity;
    }

    void hideKeyBoard() {
        if (searchView != null)
            searchView.clearFocus();
        pickerActivity.getWindow().setSoftInputMode(
                WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);

        View focusedView = pickerActivity.getCurrentFocus();
        if (focusedView != null) {
            InputMethodManager inputMethodManager = (InputMethodManager) pickerActivity.getSystemService(Context.INPUT_METHOD_SERVICE);
            inputMethodManager.hideSoftInputFromWindow(focusedView.getWindowToken(), InputMethodManager.HIDE_IMPLICIT_ONLY);
        }
    }

    @Override
    public void onScrollStateChanged(AbsListView absListView, int i) {
        switch (i) {
            case SCROLL_STATE_FLING:
                break;
            case SCROLL_STATE_IDLE:
                break;
            case SCROLL_STATE_TOUCH_SCROLL:
                hideKeyBoard();
                break;
        }
    }

    @Override
    public void onScroll(AbsListView absListView, int i, int i2, int i3) {

    }
}


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

    <dimen name="small_text">24dp</dimen>
    <dimen name="normal_text">32dp</dimen>
    <dimen name="large_text">48dp</dimen>

</resources>