text:
package com.softwinner.explore;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Stack;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

import android.content.Context;
import android.os.StatFs;
import android.util.Log;

/**
 * This class is completely modular, which is to say that it has
 * no reference to the any GUI activity. This class could be taken
 * and placed into in other java (not just Android) project and work.
 *

 *

 * This class handles all file and folder operations on the system.
 * This class dictates how files and folders are copied/pasted, (un)zipped
 * renamed and searched. The EventHandler class will generally call these
 * methods and have them performed in a background thread. Threading is not
 * done in this class.
 *
 * @author Joe Berria
 *
 */
public class FileManager {
	private static final String TAG = FileManager.class.getSimpleName();
	public  static final int ROOT_FLASH = 0;
	public  static final int ROOT_SDCARD = 1;
	public  static final int ROOT_USBHOST = 2;
	public	static final int ROOT_UNKNOWN = 3;

	private static final int BUFFER = 		2048;
	private static final int SORT_NONE = 	0;
	private static final int SORT_ALPHA = 	1;
	private static final int SORT_TYPE = 	2;

	private ArrayList<String> flashPath;
	private ArrayList<String> sdcardPath;
	private ArrayList<String> usbPath;
	private DevicePath mDevices;

	private boolean mShowHiddenFiles = false;
	private int mSortType = SORT_ALPHA;
	private long mDirSize = 0;
	private Stack<String> mPathStack;
	private ArrayList<String> mDirContent;

	public String flashList = "Sdcard";
	public String sdcardList = "External Sdcard";
	public String usbhostList = "Usb";

	private Context mContext ;
	/**
	 * Constructs an object of the class
	 *

	 * this class uses a stack to handle the navigation of directories.
	 */
	public FileManager(Context context) {
		mDirContent = new ArrayList<String>();
		mPathStack = new Stack<String>();
		mContext = context;

		flashList = mContext.getResources().getString(R.string.flash);
		sdcardList = mContext.getResources().getString(R.string.extsd);
		usbhostList = mContext.getResources().getString(R.string.usbhost);

		mDevices = new DevicePath(context);
		flashPath = mDevices.getInterStoragePath();
		sdcardPath = mDevices.getSdStoragePath();
		usbPath = mDevices.getUsbStoragePath();
		mPathStack.push("/");
		mPathStack.push(flashList);
	}

	/**
	 * This will return a string of the current directory path
	 * @return the current directory
	 */
	public String getCurrentDir() {
		return mPathStack.peek();
	}

	/**
	 * This will return a string of the current home path.
	 * @return	the home directory
	 */
	public ArrayList<String> getHomeDir(int root_type) {
		//This will eventually be placed as a settings item
		mPathStack.clear();
		mPathStack.push("/");
		switch(root_type)
		{
			case ROOT_SDCARD:
				mPathStack.push(sdcardList);
				return mDevices.getMountedPath(sdcardPath);

			case ROOT_USBHOST:
				mPathStack.push(usbhostList);
				return mDevices.getMountedPath(usbPath);

			case ROOT_FLASH:
			default:
				mPathStack.push(flashList);
				return mDevices.getMountedPath(flashPath);

		}
	}

	/**
	 * This will tell if current path is root
	 * @return	is root?
	 */
	public boolean isRoot() {
		//This will eventually be placed as a settings item
		String tmp = mPathStack.peek();

		if(tmp.equals(sdcardList) ||
			tmp.equals(usbhostList) ||
			tmp.equals(flashList))
		{
			return true;
		}

		return false;
	}

	/**
	 * This will tell which root we are in;
	 * @return	which root?
	 */
	public int whichRoot() {
		//This will eventually be placed as a settings item
		String tmp = mPathStack.peek();
		if(tmp.equals(flashList)){
			return ROOT_FLASH;
		}else if(tmp.equals(sdcardList)){
			return ROOT_SDCARD;
		}else if(tmp.equals(usbhostList)){
			return ROOT_USBHOST;
		}else{
			for(String st:sdcardPath){
				if(tmp.startsWith(st)){
					return ROOT_SDCARD;
				}
			}
			for(String st:flashPath){
				if(tmp.startsWith(st)){
					return ROOT_FLASH;
				}
			}
			for(String st:usbPath){
				if(tmp.startsWith(st)){
					return ROOT_USBHOST;
				}
			}
		}
		return ROOT_UNKNOWN;
	}

	/**
	 * This will determine if hidden files and folders will be visible to the
	 * user.
	 * @param choice	true if user is veiwing hidden files, false otherwise
	 */
	public void setShowHiddenFiles(boolean choice) {
		mShowHiddenFiles = choice;
	}

	/**
	 *
	 * @param type
	 */
	public void setSortType(int type) {
		mSortType = type;
	}

	/**
	 * This will return a string that represents the path of the previous path
	 * @return	returns the previous path
	 */
	public ArrayList<String> getPreviousDir() {
		int size = mPathStack.size();

		if (size >= 2)
			mPathStack.pop();

		else if(size == 0)
			mPathStack.push(flashList);

		String st = mPathStack.peek();
		if(st.equals(flashList)){
			return mDevices.getMountedPath(flashPath);
		}else if(st.equals(sdcardList)){
			return mDevices.getMountedPath(sdcardPath);
		}else if(st.equals(usbhostList)){
			return mDevices.getMountedPath(usbPath);
		}else{
			return populate_list();
		}
	}

	/**
	 *
	 * @param path
	 * @param isFullPath
	 * @return
	 */
	public ArrayList<String> getNextDir(String path) {
		if(!path.equals(mPathStack.peek())) {
			mPathStack.push(path);
		}
		if(flashList.equals(path)){
			return mDevices.getMountedPath(flashPath);
		}else if(sdcardList.equals(path)){
			return mDevices.getMountedPath(sdcardPath);
		}else if(usbhostList.equals(path)){
			return mDevices.getMountedPath(usbPath);
		}else{
			return populate_list();
		}
	}

	/**
	 *
	 * @param old		the file to be copied
	 * @param newDir	the directory to move the file to
	 * @return
	 */
	public int copyToDirectory(String old, String newDir) {
		File old_file = new File(old);
		File temp_dir = new File(newDir);
		byte[] data = new byte[BUFFER];
		int read = 0;
		String copyName = mContext.getResources().getString(R.string.Copied);

		if(old_file.isFile() && temp_dir.isDirectory() && temp_dir.canWrite()){
			//如果复制到自己的父目录,则
			String new_name = "";
			if(old_file.getParent().equals(temp_dir.getAbsolutePath())){
				new_name = newDir + "/" + copyName + old.substring(old.lastIndexOf("/") + 1, old.length());
				int n = 2;
				while(new File(new_name).exists()){
					new_name = newDir + "/" + copyName + n + "_" + old.substring(old.lastIndexOf("/") + 1, old.length());
					n++;
				}
			}else{
				new_name = newDir + old.substring(old.lastIndexOf("/"), old.length());
			}

			File cp_file = new File(new_name);
			try {
				BufferedOutputStream o_stream = new BufferedOutputStream(
												new FileOutputStream(cp_file));
				BufferedInputStream i_stream = new BufferedInputStream(
											   new FileInputStream(old_file));

				while((read = i_stream.read(data, 0, BUFFER)) != -1)
					o_stream.write(data, 0, read);

				o_stream.flush();
				i_stream.close();
				o_stream.close();

				RefreshMedia mRefresh = new RefreshMedia(mContext);
				mRefresh.notifyMediaAdd(new_name);
			} catch (FileNotFoundException e) {
				Log.e("FileNotFoundException", e.getMessage());
				return -1;

			} catch (IOException e) {
				Log.e("IOException", e.getMessage());
				return -1;
			}

		}else if(old_file.isDirectory() && temp_dir.isDirectory() && temp_dir.canWrite()) {
			String files[] = old_file.list();
			String dir = "copyFile";
			//如果复制到自己的父目录,则
			if(old_file.getParent().equals(temp_dir.getAbsolutePath())){
				dir = newDir + "/" + copyName + old.substring(old.lastIndexOf("/") + 1, old.length());
				int n = 2;
				while(new File(dir).exists()){
					dir = newDir + "/" + copyName + n + "_" + old.substring(old.lastIndexOf("/") + 1, old.length());
					n++;
				}
			}else{
				dir = newDir + old.substring(old.lastIndexOf("/"), old.length());
			}
			int len = files.length;
			File file = new File(dir);
			if(!file.exists()){
				if(!file.mkdir()){
					return -1;
				}
			}
			for(int i = 0; i < len; i++)
				copyToDirectory(old + "/" + files[i], dir);

		} else if(!temp_dir.canWrite())
			return -1;

		return 0;
	}

	/**
	 *
	 * @param toDir
	 * @param fromDir
	 */
	public void extractZipFilesFromDir(String zipName, String toDir, String fromDir) {
		byte[] data = new byte[BUFFER];
		ZipEntry entry;
		ZipInputStream zipstream;

		/* create new directory for zip file */
		String org_path = fromDir + "/" + zipName;
		String dest_path = toDir + zipName.substring(0, zipName.length() - 4);
		String zipDir = dest_path + "/";

		new File(zipDir).mkdir();
		try {
			zipstream = new ZipInputStream(new FileInputStream(org_path));

			while((entry = zipstream.getNextEntry()) != null) {
				if(entry.isDirectory()) {
					String ndir = zipDir + entry.getName() + "/";

					new File(ndir).mkdir();

				} else {
					int read = 0;
					FileOutputStream out = new FileOutputStream(
												zipDir + entry.getName());
					while((read = zipstream.read(data, 0, BUFFER)) != -1)
						out.write(data, 0, read);

					zipstream.closeEntry();
					out.close();

					RefreshMedia mRefresh = new RefreshMedia(mContext);
					mRefresh.notifyMediaAdd(zipDir + entry.getName());
				}
			}

		} catch (FileNotFoundException e) {
			e.printStackTrace();

		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 *
	 * @param zip_file
	 * @param directory
	 */
	public void extractZipFiles(String zip_file, String directory) {
		byte[] data = new byte[BUFFER];
		ZipEntry entry;
		ZipInputStream zipstream;

		/* create new directory for zip file */
		String path = zip_file;
		String name = path.substring(path.lastIndexOf("/") + 1,
									 path.length() - 4);
		String zipDir = path.substring(0, path.lastIndexOf("/") +1) +
									   name + "/";
		new File(zipDir).mkdir();
		try {
			zipstream = new ZipInputStream(new FileInputStream(path));

			while((entry = zipstream.getNextEntry()) != null) {
				if(entry.isDirectory()) {
					String ndir = zipDir + entry.getName() + "/";

					new File(ndir).mkdir();

				} else {
					int read = 0;
					FileOutputStream out = new FileOutputStream(
											zipDir + entry.getName());
					while((read = zipstream.read(data, 0, BUFFER)) != -1)
						out.write(data, 0, read);

					zipstream.closeEntry();
					out.close();

					RefreshMedia mRefresh = new RefreshMedia(mContext);
					mRefresh.notifyMediaAdd(zipDir + entry.getName());
				}
			}

		} catch (FileNotFoundException e) {
			e.printStackTrace();

		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 *
	 * @param path
	 */
	public void createZipFile(String path) {
		File dir = new File(path);
		String[] list = dir.list();
		String name = path.substring(path.lastIndexOf("/"), path.length());
		String _path;

		if(!dir.canRead() || !dir.canWrite())
			return;

		int len = list.length;

		if(path.charAt(path.length() -1) != '/')
			_path = path + "/";
		else
			_path = path;

		try {
			ZipOutputStream zip_out = new ZipOutputStream(
									  new BufferedOutputStream(
									  new FileOutputStream(_path + name + ".zip"), BUFFER));

			for (int i = 0; i < len; i++)
				zip_folder(new File(_path + list[i]), zip_out);

			zip_out.close();

		} catch (FileNotFoundException e) {
			Log.e("File not found", e.getMessage());

		} catch (IOException e) {
			Log.e("IOException", e.getMessage());
		}
	}

	/**
	 *
	 * @param filePath
	 * @param newName
	 * @return -1:newName file is exist; -2:rename fail; 0:rename success;
	 */
	public int renameTarget(String filePath, String newName) {
		File src = new File(filePath);
		String ext = "";
		File dest;

		if(src.isFile())
			/*get file extension*/
			ext = filePath.substring(filePath.lastIndexOf("."), filePath.length());

		if(newName.length() < 1)
			return -2;

		String temp = filePath.substring(0, filePath.lastIndexOf("/"));

		String destPath = temp + "/" + newName + ext;
		dest = new File(destPath);

		//add to make sure destPath is not exists !
		//Beacuse FS can not exists the same file name in the same diretory !
		if(dest.exists()){
			return -1;
		}

		if(src.renameTo(dest))
		{
			RefreshMedia mRefresh = new RefreshMedia(mContext);
			mRefresh.notifyMediaAdd(destPath);
			mRefresh.notifyMediaDelete(filePath);
			return 0;
		}
		else
			return -2;
	}

	/**
	 *
	 * @param path
	 * @param name
	 * @return
	 */
	public int createDir(String path, String name) {
		int len = path.length();

		if(len < 1 || len < 1)
			return -1;

		if(path.charAt(len - 1) != '/')
			path += "/";

		if (new File(path+name).mkdir())
			return 0;

		return -1;
	}

	/**
	 * The full path name of the file to delete.
	 *
	 * @param path name
	 * @return
	 */
	public int deleteTarget(String path) {
		File target = new File(path);

		if(target.exists() && target.isFile() && target.canWrite()) {
			target.delete();

			RefreshMedia mRefresh = new RefreshMedia(mContext);
			mRefresh.notifyMediaDelete(path);
            try
            {
                Thread.currentThread().sleep(500);
            }
            catch(Exception e) {};

			return 0;
		}

		else if(target.exists() && target.isDirectory() && target.canRead()) {
			String[] file_list = target.list();

			if(file_list != null && file_list.length == 0) {
				target.delete();
				try
                {
                    Thread.currentThread().sleep(500);
                }
                catch(Exception e) {};

				return 0;

			} else if(file_list != null && file_list.length > 0) {

				for(int i = 0; i < file_list.length; i++) {
					String filePath = target.getAbsolutePath() + "/" + file_list[i];
					File temp_f = new File(filePath);

					if(temp_f.isDirectory())
						deleteTarget(temp_f.getAbsolutePath());
					else if(temp_f.isFile())
					{
						temp_f.delete();

						RefreshMedia mRefresh = new RefreshMedia(mContext);
						mRefresh.notifyMediaDelete(filePath);
					}
				}
			}
			if(target.exists())
				if(target.delete()){
				    try
                    {
                        Thread.currentThread().sleep(500);
                    }
                    catch(Exception e) {};

					return 0;
		        }
		}
		return -1;
	}

	/**
	 *
	 * @param name
	 * @return
	 */
	public boolean isDirectory(String name) {
		return new File(mPathStack.peek() + "/" + name).isDirectory();
	}

	/**
	 * converts integer from wifi manager to an IP address.
	 *
	 * @param des
	 * @return
	 */
	public static String integerToIPAddress(int ip) {
		String ascii_address = "";
		int[] num = new int[4];

		num[0] = (ip & 0xff000000) >> 24;
		num[1] = (ip & 0x00ff0000) >> 16;
		num[2] = (ip & 0x0000ff00) >> 8;
		num[3] = ip & 0x000000ff;

		ascii_address = num[0] + "." + num[1] + "." + num[2] + "." + num[3];

		return ascii_address;
	 }

	/**
	 *
	 * @param dir
	 * @param pathName
	 * @return
	 */
	public ArrayList<String> searchInDirectory(String dir, String pathName) {
		ArrayList<String> names = new ArrayList<String>();
		search_file(dir, pathName, names);

		return names;
	}

	/**
	 *
	 * @param path
	 * @return
	 */
	public long getDirSize(String path) {
		get_dir_size(new File(path));

		return mDirSize;
	}

	private static final Comparator alph = new Comparator<String>() {
		@Override
		public int compare(String arg0, String arg1) {
			return arg0.toLowerCase().compareTo(arg1.toLowerCase());
		}
	};

	private static final Comparator type = new Comparator<String>() {
		@Override
		public int compare(String arg0, String arg1) {
			String ext = null;
			String ext2 = null;

			try {
				ext = arg0.substring(arg0.lastIndexOf(".") + 1, arg0.length());
				ext2 = arg1.substring(arg1.lastIndexOf(".") + 1, arg1.length());

			} catch (IndexOutOfBoundsException e) {
				return 0;
			}

			return ext.compareTo(ext2);
		}
	};

	/* (non-Javadoc)
	 * this function will take the string from the top of the directory stack
	 * and list all files/folders that are in it and return that list so
	 * it can be displayed. Since this function is called every time we need
	 * to update the the list of files to be shown to the user, this is where
	 * we do our sorting (by type, alphabetical, etc).
	 *
	 * @return
	 */
	private ArrayList<String> populate_list() {

		if(!mDirContent.isEmpty())
			mDirContent.clear();
		try
		{
			String path = mPathStack.peek();
			File file = new File(path);

			if(file.exists() && file.canRead() && file.isDirectory()) {
//				String[] list = file.list();
				File[] fList = file.listFiles();
				boolean isPartition = false;
				if(mDevices.hasMultiplePartition(path)){
					Log.d("chen",path + " has multi partition");
					isPartition = true;
				}
				if(fList != null)
				{
					int len = fList.length;

					/* add files/folder to arraylist depending on hidden status */
					for (int i = 0; i < len; i++) {
						if(isPartition){
							try{
								StatFs statFs = new StatFs(fList[i].getAbsolutePath());
								int count = statFs.getBlockCount();
								Log.d("chen",fList[i].getName() + "  " + count);
								if(count == 0){
									continue;
								}
							}catch(Exception e){
								Log.d(TAG,fList[i].getName() + "  exception");
								continue;
							}
						}
						String name = fList[i].getName();
						if(!mShowHiddenFiles) {
							if(name.charAt(0) != '.')
								mDirContent.add(name);

						} else {
							mDirContent.add(name);
						}
					}

					/* sort the arraylist that was made from above for loop */
					switch(mSortType)
					{
						case SORT_NONE:
							//no sorting needed
							break;

						case SORT_ALPHA:
							Object[] tt = mDirContent.toArray();
							mDirContent.clear();

							Arrays.sort(tt, alph);

							for (Object a : tt){
								mDirContent.add((String)a);
							}
							break;

						case SORT_TYPE:
							Object[] t = mDirContent.toArray();
							String dir = mPathStack.peek();

							Arrays.sort(t, type);
							mDirContent.clear();

							for (Object a : t){
								if(new File(dir + "/" + (String)a).isDirectory())
									mDirContent.add(0, (String)a);
								else
									mDirContent.add((String)a);
							}
							break;
					}
				}
			}
		}catch(Exception e)
		{
			/* clear any operate made above */
			Log.e("FileManager", "unknow exception");
			mDirContent.clear();
		}
		return mDirContent;
	}

	/*
	 *
	 * @param file
	 * @param zout
	 * @throws IOException
	 */
	private void zip_folder(File file, ZipOutputStream zout) throws IOException {
		byte[] data = new byte[BUFFER];
		int read;

		if(file.isFile()){
			ZipEntry entry = new ZipEntry(file.getName());
			zout.putNextEntry(entry);
			BufferedInputStream instream = new BufferedInputStream(
										   new FileInputStream(file));

			while((read = instream.read(data, 0, BUFFER)) != -1)
				zout.write(data, 0, read);

			zout.closeEntry();
			instream.close();

		} else {
			String[] list = file.list();
			int len = list.length;

			for(int i = 0; i < len; i++)
				zip_folder(new File(file.getPath() +"/"+ list[i]), zout);
		}
	}

	/*
	 * This function will be rewritten as there is a problem getting
	 * the directory size in certain folders from root. ex /sys, /proc.
	 * The app will continue until a stack overflow. get size is fine uder the
	 * sdcard folder.
	 *
	 * @param path
	 */
	private void get_dir_size(File path) {
		File[] list = path.listFiles();
		int len;

		if(list != null) {
			len = list.length;

			for (int i = 0; i < len; i++) {
				if(list[i].isFile() && list[i].canRead()) {
					mDirSize += list[i].length();

				} else if(list[i].isDirectory() && list[i].canRead()) {
					get_dir_size(list[i]);
				}
			}
		}
	}

	/*
	 * (non-JavaDoc)
	 * I dont like this method, it needs to be rewritten. Its hacky in that
	 * if you are searching in the root dir (/) then it is not going to be treated
	 * as a recursive method so the user dosen't have to sit forever and wait.
	 *
	 * I will rewrite this ugly method.
	 *
	 * @param dir		directory to search in
	 * @param fileName	filename that is being searched for
	 * @param n			ArrayList to populate results
	 */
	private void search_file(String dir, String fileName, ArrayList<String> n) {
		File root_dir = new File(dir);
		String[] list = root_dir.list();

		if(list != null && root_dir.canRead()) {
			int len = list.length;

			for (int i = 0; i < len; i++) {
				File check = new File(dir + "/" + list[i]);
				String name = check.getName();

				if(check.isFile() && name.toLowerCase().
										contains(fileName.toLowerCase())) {
					n.add(check.getPath());
				}
				else if(check.isDirectory()) {
					if(name.toLowerCase().contains(fileName.toLowerCase()))
						n.add(check.getPath());

					else if(check.canRead() && !dir.equals("/"))
						search_file(check.getAbsolutePath(), fileName, n);
				}
			}
		}
	}
}


text:
package com.venky.swf.plugins.background.core;

import com.venky.core.util.MultiException;
import com.venky.swf.db.Database;
import com.venky.swf.db.Transaction;

import java.util.Iterator;
import java.util.LinkedList;

public class CompositeTask implements Task {
	private final LinkedList<Task> tasks ;
	private static final long serialVersionUID = -6287257141086371584L;
	private boolean splitTasksOnException = false;

	public CompositeTask(){
		this.tasks = new LinkedList<>();
	}
	private Priority priority = Priority.LOW;
	public CompositeTask(Task...tasks ) {
        this(false,tasks);
    }
	public CompositeTask(boolean splitTasksOnException , Task...tasks ) {
        this.splitTasksOnException = splitTasksOnException;
		this.tasks = new LinkedList<>();
		add(tasks);
	}
	public void add(Task... tasks){
        for (Task t : tasks){
            this.tasks.add(t);
            if (priority.getValue() > t.getTaskPriority().getValue()){ //Lower the value higher the priority.
                priority = t.getTaskPriority();
            }
            canExecuteRemotely = canExecuteRemotely && t.canExecuteRemotely();
        }
    }

    private boolean canExecuteRemotely = true;

	@Override
    public boolean canExecuteRemotely(){
        return canExecuteRemotely;
    }
	@Override
	public Priority getTaskPriority(){
		return priority;
	}

	@Override
	public void execute() {
        Transaction parentTxn = Database.getInstance().getTransactionManager().createTransaction();
        try {
            MultiException multiException = new MultiException();
            for (Iterator<Task> taskIterator = tasks.iterator(); taskIterator.hasNext() ; ) {
                Task task = taskIterator.next();
                Transaction txn = Database.getInstance().getTransactionManager().createTransaction();
                try {
                    task.execute();
                    txn.commit();
                    taskIterator.remove();
                }catch (Exception ex){
                    txn.rollback(ex);// Task not removed will be resubmitted if required.
                    multiException.add(ex);
                }
            }

            if (!tasks.isEmpty()) {
                if (splitTasksOnException){
                    TaskManager.instance().executeAsync(tasks,false); //Submit errored tasks for retry. // May throw serializable exception
                }else {
                    throw multiException;
                }
            }
            parentTxn.commit(); //Don't waste work done by successful tasks.
        }catch ( Exception ex ) {
            parentTxn.rollback(ex);
            throw ex;
        }
	}

}

redpajama_set_name: RedPajamaGithub


text:
import { IDisposable } from "../../Types/Contracts";
import { DocumentStoreBase } from "../DocumentStoreBase";
import { IServerOperation, AwaitableServerOperation, OperationIdResult } from "./OperationAbstractions";
import { ClusterRequestExecutor } from "../../Http/ClusterRequestExecutor";
import { RavenCommand } from "../../Http/RavenCommand";
import { ServerWideOperationCompletionAwaiter } from "../../ServerWide/Operations/ServerWideOperationCompletionAwaiter";
import { getLogger } from "../../Utility/LogUtil";
import { throwError } from "../../Exceptions/index";
import { StringUtil } from "../../Utility/StringUtil";
import { Topology } from "../../Http/Topology";
import { GetBuildNumberOperation } from "../../ServerWide/Operations/GetBuildNumberOperation";
import { IRequestExecutorOptions } from "../../Http/RequestExecutor";

const log = getLogger({ module: "ServerOperationExecutor" });

export class ServerOperationExecutor implements IDisposable {

    private readonly _cache: Map<string, ServerOperationExecutor>;
    private readonly _nodeTag: string;
    private readonly _store: DocumentStoreBase;
    private readonly _requestExecutor: ClusterRequestExecutor;
    private readonly _initialRequestExecutor: ClusterRequestExecutor;

    public constructor(store: DocumentStoreBase);
    public constructor(store: DocumentStoreBase,
                       requestExecutor: ClusterRequestExecutor,
                       initialRequestExecutor: ClusterRequestExecutor,
                       cache: Map<string, ServerOperationExecutor>,
                       nodeTag: string);
    public constructor(store: DocumentStoreBase,
                       requestExecutor?: ClusterRequestExecutor,
                       initialRequestExecutor?: ClusterRequestExecutor,
                       cache?: Map<string, ServerOperationExecutor>,
                       nodeTag?: string) {
        requestExecutor = requestExecutor || ServerOperationExecutor._createRequestExecutor(store);
        cache = cache || new Map<string, ServerOperationExecutor>();

        if (!store) {
            throwError("InvalidArgumentException", "Store cannot be null");
        }

        if (!requestExecutor) {
            throwError("InvalidArgumentException", "RequestExecutor cannot be null");
        }

        this._store = store;
        this._requestExecutor = requestExecutor;
        this._initialRequestExecutor = initialRequestExecutor;
        this._nodeTag = nodeTag;
        this._cache = cache;

        store.registerEvents(this._requestExecutor);

        if (!nodeTag) {
            store.once("afterDispose",
                (callback) => {
                    log.info("Dispose request executor.");
                    this._requestExecutor.dispose();
                    callback();
                });
        }
    }

    public async forNode(nodeTag: string): Promise<ServerOperationExecutor> {
        if (StringUtil.isNullOrWhitespace(nodeTag)) {
            throwError("InvalidArgumentException", "Value cannot be null or whitespace.");
        }

        if ((!nodeTag && !this._nodeTag) || StringUtil.equalsIgnoreCase(this._nodeTag, nodeTag)) {
            return this;
        }

        if (this._store.conventions.disableTopologyUpdates) {
            throwError("InvalidOperationException", "Cannot switch server operation executor, because conventions.disableTopologyUpdates is set to 'true'");
        }

        const existingValue = this._cache.get(nodeTag.toLowerCase());
        if (existingValue) {
            return existingValue;
        }

        const requestExecutor = this._initialRequestExecutor || this._requestExecutor;
        const topology: Topology = await this._getTopology(requestExecutor);

        const node = topology.nodes
            .find(x => StringUtil.equalsIgnoreCase(x.clusterTag, nodeTag));

        if (!node) {
            const availableNodes = topology
                .nodes
                .map(x => x.clusterTag)
                .join(", ");

            throwError("InvalidOperationException",
                "Could not find node '" + nodeTag + "' in the topology. Available nodes: " + availableNodes);
        }

        const clusterExecutor = ClusterRequestExecutor.createForSingleNode(node.url, {
            authOptions: this._store.authOptions
        });

        return new ServerOperationExecutor(this._store, clusterExecutor, requestExecutor, this._cache, node.clusterTag);
    }

    public async send(operation: AwaitableServerOperation): Promise<ServerWideOperationCompletionAwaiter>;
    public async send<TResult>(operation: IServerOperation<TResult>): Promise<TResult>;
    public async send<TResult>(operation: AwaitableServerOperation | IServerOperation<TResult>)
        : Promise<ServerWideOperationCompletionAwaiter | TResult> {

        const command = operation.getCommand(this._requestExecutor.conventions);

        await this._requestExecutor.execute(command as RavenCommand<TResult>);

        if (operation.resultType === "OperationId") {
            const idResult = command.result as OperationIdResult;
            return new ServerWideOperationCompletionAwaiter(
                this._requestExecutor, this._requestExecutor.conventions, idResult.operationId,
                command.selectedNodeTag || idResult.operationNodeTag
            );
        }

        return command.result as TResult;
    }

    public dispose(): void {
        if (this._nodeTag) {
            return;
        }

        if (this._requestExecutor) {
            this._requestExecutor.dispose();
        }

        if (this._cache) {
            for (const [key, value] of this._cache.entries()) {
                const requestExecutor = value._requestExecutor;
                if (requestExecutor) {
                    requestExecutor.dispose();
                }
            }

            this._cache.clear();
        }
    }

    private async _getTopology(requestExecutor: ClusterRequestExecutor): Promise<Topology> {
        let topology: Topology = null;
        try {
            topology = requestExecutor.getTopology();
            if (!topology) {
                // a bit rude way to make sure that topology has been refreshed
                // but it handles a case when first topology update failed

                const operation  = new GetBuildNumberOperation();
                const command = operation.getCommand(requestExecutor.conventions);
                await requestExecutor.execute(command);
                topology = requestExecutor.getTopology();
            }
        } catch {
            // ignored
        }

        if (!topology) {
            throwError("InvalidOperationException", "Could not fetch the topology");
        }

        return topology;
    }

    private static _createRequestExecutor(store: DocumentStoreBase): ClusterRequestExecutor {
        const args: IRequestExecutorOptions = {
            authOptions: store.authOptions,
            documentConventions: store.conventions
        };
        return store.conventions.disableTopologyUpdates
            ? ClusterRequestExecutor.createForSingleNode(store.urls[0], args)
            : ClusterRequestExecutor.create(store.urls, args);
    }
}


text:
package superheroes.entity;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

/**
 * Created by catop on 3/11/15.
 */
public class Url {

    private static final Logger LOGGER = LogManager.getLogger(Url.class.getName());

    private Integer id;
    private String type;
    private String url;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Url)) return false;

        Url url1 = (Url) o;

        if (type != null ? !type.equals(url1.type) : url1.type != null) return false;
        return !(url != null ? !url.equals(url1.url) : url1.url != null);

    }

    @Override
    public int hashCode() {
        int result = type != null ? type.hashCode() : 0;
        result = 31 * result + (url != null ? url.hashCode() : 0);
        return result;
    }

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder("Url{");
        sb.append("id=").append(id);
        sb.append(", type='").append(type).append('\'');
        sb.append(", url='").append(url).append('\'');
        sb.append('}');
        return sb.toString();
    }
}


text:
import { createDecorator } from '../../../platform/instantiation/common/instantiation.js';
export var IBulkEditService = createDecorator('IWorkspaceEditService');


text:
package net.karlmartens.platform.function;

import java.util.Comparator;

/**
 * @author kmartens
 *
 */
class MaxFunction<T> implements Function<Pair<T, T>, T> {

  private final Comparator<T> _comparator;

  MaxFunction(Comparator<T> comparator) {
    _comparator = comparator;
  }

  @Override
  public T apply(Pair<T, T> arg) {
    final T a = arg.a();
    final T b = arg.b();
    if (_comparator.compare(a, b) >= 0)
      return a;

    return b;
  }

}


text:
#include "led.h"
#include "upm_types.h"

led_context led_init(uint8_t pin){
    // make sure MRAA is initialized
    int mraa_rv;
    if ((mraa_rv = mraa_init()) != MRAA_SUCCESS)
    {
        printf("%s: mraa_init() failed (%d).\n", __FUNCTION__, mraa_rv);
        return NULL;
    }

    led_context dev =
      (led_context)malloc(sizeof(struct _led_context));

    if (!dev)
      return NULL;

    dev->led_pin = pin;
    dev->gpio = mraa_gpio_init(dev->led_pin);

    if (mraa_gpio_dir(dev->gpio, MRAA_GPIO_OUT) != MRAA_SUCCESS)
      return NULL;

    return dev;
}

void led_close(led_context dev){
    free(dev);
}

upm_result_t led_on(led_context dev){
    if (mraa_gpio_write(dev->gpio, 1) != MRAA_SUCCESS)
        return UPM_ERROR_OPERATION_FAILED;

    return UPM_SUCCESS;
}

upm_result_t led_off(led_context dev){
    if (mraa_gpio_write(dev->gpio, 0) != MRAA_SUCCESS)
        return UPM_ERROR_OPERATION_FAILED;

    return UPM_SUCCESS;
}


text:
import addDigits from './addDigits';
import getDigits from './getDigits';
import joinDigits from './joinDigits';
import multiplyDigits from './multiplyDigits';

/**
 * Memoization for reusable part of computation. The `power` value in
 * the core loop of `convert()` varies only by `inBase`/`outBase`,
 * independently of the `number` to be converted, so we keep it around
 * and re-use it to avoid repeated calls to `multiplyDigits()`.
 */
const memo = [];

function getPowers(inBase: number, outBase: number): Array<Array<number>> {
  let outer = memo[inBase];
  if (!outer) {
    outer = memo[inBase] = [];
  }
  let nested = outer[outBase];
  if (!nested) {
    nested = outer[outBase] = [[1]];
  }
  return nested;
}

/**
 * Convert `number` in base `inBase`, to base `outBase`. Both the input `number`
 * and return value are string representations.
 */
export default function convert(
  number: string,
  inBase: number,
  outBase: number
): string {
  if (inBase === outBase) {
    return number;
  }
  const digits = getDigits(number, inBase);
  const powers = getPowers(inBase, outBase);
  let result = [0];
  for (let i = 0; i < digits.length; i++) {
    const power = powers[i];
    if (digits[i]) {
      result = addDigits(
        result,
        multiplyDigits(power, digits[i], outBase),
        outBase
      );
    }

    if (powers.length < i + 2) {
      powers[i + 1] = multiplyDigits(power, inBase, outBase);
    }
  }
  return joinDigits(result, outBase);
}


text:
<link href="assets/css/bootstrap.min.css" rel="stylesheet" />

empty slide (for example)


text:
<?php

namespace Cinetic\DashboardBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;

class DashboardController extends Controller
{
    /**
     * @Route("/dashboard", name="dashboard")
     *
     */
    public function indexAction()
    {
        return $this->render('dashboard/dashboard.html.twig');
    }
}


text:
#ifndef skgpu_tessellate_WangsFormula_DEFINED
#define skgpu_tessellate_WangsFormula_DEFINED

#include "include/core/SkM44.h"
#include "include/core/SkMatrix.h"
#include "include/core/SkPoint.h"
#include "include/core/SkString.h"
#include "include/private/SkFloatingPoint.h"
#include "include/private/SkVx.h"
#include "src/gpu/tessellate/Tessellation.h"

#define AI [[maybe_unused]] SK_ALWAYS_INLINE

// Wang's formula gives the minimum number of evenly spaced (in the parametric sense) line segments
// that a bezier curve must be chopped into in order to guarantee all lines stay within a distance
// of "1/precision" pixels from the true curve. Its definition for a bezier curve of degree "n" is
// as follows:
//
//     maxLength = max([length(p[i+2] - 2p[i+1] + p[i]) for (0 <= i <= n-2)])
//     numParametricSegments = sqrt(maxLength * precision * n*(n - 1)/8)
//
// (Goldman, Ron. (2003). 5.6.3 Wang's Formula. "Pyramid Algorithms: A Dynamic Programming Approach
// to Curves and Surfaces for Geometric Modeling". Morgan Kaufmann Publishers.)
namespace skgpu::wangs_formula {

// Returns the value by which to multiply length in Wang's formula. (See above.)
template<int Degree> constexpr float length_term(float precision) {
    return (Degree * (Degree - 1) / 8.f) * precision;
}
template<int Degree> constexpr float length_term_p2(float precision) {
    return ((Degree * Degree) * ((Degree - 1) * (Degree - 1)) / 64.f) * (precision * precision);
}

AI float root4(float x) {
    return sqrtf(sqrtf(x));
}

// Returns nextlog2(sqrt(x)):
//
//   log2(sqrt(x)) == log2(x^(1/2)) == log2(x)/2 == log2(x)/log2(4) == log4(x)
//
AI int nextlog4(float x) {
    return (sk_float_nextlog2(x) + 1) >> 1;
}

// Returns nextlog2(sqrt(sqrt(x))):
//
//   log2(sqrt(sqrt(x))) == log2(x^(1/4)) == log2(x)/4 == log2(x)/log2(16) == log16(x)
//
AI int nextlog16(float x) {
    return (sk_float_nextlog2(x) + 3) >> 2;
}

// Represents the upper-left 2x2 matrix of an affine transform for applying to vectors:
//
//     VectorXform(p1 - p0) == M * float3(p1, 1) - M * float3(p0, 1)
//
class VectorXform {
public:
    AI VectorXform() : fC0{1.0f, 0.f}, fC1{0.f, 1.f} {}
    AI explicit VectorXform(const SkMatrix& m) { *this = m; }
    AI explicit VectorXform(const SkM44& m) { *this = m; }

    AI VectorXform& operator=(const SkMatrix& m) {
        SkASSERT(!m.hasPerspective());
        fC0 = {m.rc(0,0), m.rc(1,0)};
        fC1 = {m.rc(0,1), m.rc(1,1)};
        return *this;
    }
    AI VectorXform& operator=(const SkM44& m) {
        SkASSERT(m.rc(3,0) == 0.f && m.rc(3,1) == 0.f && m.rc(3,2) == 0.f && m.rc(3,3) == 1.f);
        fC0 = {m.rc(0,0), m.rc(1,0)};
        fC1 = {m.rc(0,1), m.rc(1,1)};
        return *this;
    }
    AI skvx::float2 operator()(skvx::float2 vector) const {
        return fC0 * vector.x() + fC1 * vector.y();
    }
    AI skvx::float4 operator()(skvx::float4 vectors) const {
        return join(fC0 * vectors.x() + fC1 * vectors.y(),
                    fC0 * vectors.z() + fC1 * vectors.w());
    }
private:
    // First and second columns of 2x2 matrix
    skvx::float2 fC0;
    skvx::float2 fC1;
};

// Returns Wang's formula, raised to the 4th power, specialized for a quadratic curve.
AI float quadratic_p4(float precision,
                      skvx::float2 p0, skvx::float2 p1, skvx::float2 p2,
                      const VectorXform& vectorXform = VectorXform()) {
    skvx::float2 v = -2*p1 + p0 + p2;
    v = vectorXform(v);
    skvx::float2 vv = v*v;
    return (vv[0] + vv[1]) * length_term_p2<2>(precision);
}
AI float quadratic_p4(float precision,
                      const SkPoint pts[],
                      const VectorXform& vectorXform = VectorXform()) {
    return quadratic_p4(precision,
                        skvx::bit_pun<skvx::float2>(pts[0]),
                        skvx::bit_pun<skvx::float2>(pts[1]),
                        skvx::bit_pun<skvx::float2>(pts[2]),
                        vectorXform);
}

// Returns Wang's formula specialized for a quadratic curve.
AI float quadratic(float precision,
                   const SkPoint pts[],
                   const VectorXform& vectorXform = VectorXform()) {
    return root4(quadratic_p4(precision, pts, vectorXform));
}

// Returns the log2 value of Wang's formula specialized for a quadratic curve, rounded up to the
// next int.
AI int quadratic_log2(float precision,
                      const SkPoint pts[],
                      const VectorXform& vectorXform = VectorXform()) {
    // nextlog16(x) == ceil(log2(sqrt(sqrt(x))))
    return nextlog16(quadratic_p4(precision, pts, vectorXform));
}

// Returns Wang's formula, raised to the 4th power, specialized for a cubic curve.
AI float cubic_p4(float precision,
                  skvx::float2 p0, skvx::float2 p1, skvx::float2 p2, skvx::float2 p3,
                  const VectorXform& vectorXform = VectorXform()) {
    skvx::float4 p01{p0, p1};
    skvx::float4 p12{p1, p2};
    skvx::float4 p23{p2, p3};
    skvx::float4 v = -2*p12 + p01 + p23;
    v = vectorXform(v);
    skvx::float4 vv = v*v;
    return std::max(vv[0] + vv[1], vv[2] + vv[3]) * length_term_p2<3>(precision);
}
AI float cubic_p4(float precision,
                  const SkPoint pts[],
                  const VectorXform& vectorXform = VectorXform()) {
    return cubic_p4(precision,
                    skvx::bit_pun<skvx::float2>(pts[0]),
                    skvx::bit_pun<skvx::float2>(pts[1]),
                    skvx::bit_pun<skvx::float2>(pts[2]),
                    skvx::bit_pun<skvx::float2>(pts[3]),
                    vectorXform);
}

// Returns Wang's formula specialized for a cubic curve.
AI float cubic(float precision,
               const SkPoint pts[],
               const VectorXform& vectorXform = VectorXform()) {
    return root4(cubic_p4(precision, pts, vectorXform));
}

// Returns the log2 value of Wang's formula specialized for a cubic curve, rounded up to the next
// int.
AI int cubic_log2(float precision,
                  const SkPoint pts[],
                  const VectorXform& vectorXform = VectorXform()) {
    // nextlog16(x) == ceil(log2(sqrt(sqrt(x))))
    return nextlog16(cubic_p4(precision, pts, vectorXform));
}

// Returns the maximum number of line segments a cubic with the given device-space bounding box size
// would ever need to be divided into, raised to the 4th power. This is simply a special case of the
// cubic formula where we maximize its value by placing control points on specific corners of the
// bounding box.
AI float worst_case_cubic_p4(float precision, float devWidth, float devHeight) {
    float kk = length_term_p2<3>(precision);
    return 4*kk * (devWidth * devWidth + devHeight * devHeight);
}

// Returns the maximum number of line segments a cubic with the given device-space bounding box size
// would ever need to be divided into.
AI float worst_case_cubic(float precision, float devWidth, float devHeight) {
    return root4(worst_case_cubic_p4(precision, devWidth, devHeight));
}

// Returns the maximum log2 number of line segments a cubic with the given device-space bounding box
// size would ever need to be divided into.
AI int worst_case_cubic_log2(float precision, float devWidth, float devHeight) {
    // nextlog16(x) == ceil(log2(sqrt(sqrt(x))))
    return nextlog16(worst_case_cubic_p4(precision, devWidth, devHeight));
}

// Returns Wang's formula specialized for a conic curve, raised to the second power.
// Input points should be in projected space.
//
// This is not actually due to Wang, but is an analogue from (Theorem 3, corollary 1):
//   J. Zheng, T. Sederberg. "Estimating Tessellation Parameter Intervals for
//   Rational Curves and Surfaces." ACM Transactions on Graphics 19(1). 2000.
AI float conic_p2(float precision,
                  skvx::float2 p0, skvx::float2 p1, skvx::float2 p2,
                  float w,
                  const VectorXform& vectorXform = VectorXform()) {
    p0 = vectorXform(p0);
    p1 = vectorXform(p1);
    p2 = vectorXform(p2);

    // Compute center of bounding box in projected space
    const skvx::float2 C = 0.5f * (min(min(p0, p1), p2) + max(max(p0, p1), p2));

    // Translate by -C. This improves translation-invariance of the formula,
    // see Sec. 3.3 of cited paper
    p0 -= C;
    p1 -= C;
    p2 -= C;

    // Compute max length
    const float max_len = sqrtf(std::max(dot(p0, p0), std::max(dot(p1, p1), dot(p2, p2))));

    // Compute forward differences
    const skvx::float2 dp = -2*w*p1 + p0 + p2;
    const float dw = fabsf(-2 * w + 2);

    // Compute numerator and denominator for parametric step size of linearization. Here, the
    // epsilon referenced from the cited paper is 1/precision.
    const float rp_minus_1 = std::max(0.f, max_len * precision - 1);
    const float numer = sqrtf(dot(dp, dp)) * precision + rp_minus_1 * dw;
    const float denom = 4 * std::min(w, 1.f);

    // Number of segments = sqrt(numer / denom).
    // This assumes parametric interval of curve being linearized is [t0,t1] = [0, 1].
    // If not, the number of segments is (tmax - tmin) / sqrt(denom / numer).
    return numer / denom;
}
AI float conic_p2(float precision,
                  const SkPoint pts[],
                  float w,
                  const VectorXform& vectorXform = VectorXform()) {
    return conic_p2(precision,
                    skvx::bit_pun<skvx::float2>(pts[0]),
                    skvx::bit_pun<skvx::float2>(pts[1]),
                    skvx::bit_pun<skvx::float2>(pts[2]),
                    w,
                    vectorXform);
}

// Returns the value of Wang's formula specialized for a conic curve.
AI float conic(float tolerance,
               const SkPoint pts[],
               float w,
               const VectorXform& vectorXform = VectorXform()) {
    return sqrtf(conic_p2(tolerance, pts, w, vectorXform));
}

// Returns the log2 value of Wang's formula specialized for a conic curve, rounded up to the next
// int.
AI int conic_log2(float tolerance,
                  const SkPoint pts[],
                  float w,
                  const VectorXform& vectorXform = VectorXform()) {
    // nextlog4(x) == ceil(log2(sqrt(x)))
    return nextlog4(conic_p2(tolerance, pts, w, vectorXform));
}

}  // namespace skgpu::wangs_formula

#undef AI

#endif  // skgpu_tessellate_WangsFormula_DEFINED