text:
package com.googlecode.android_scripting.activity;

import static com.hipipal.texteditor.common.FileUtils.copyFile;
import static com.hipipal.texteditor.common.FileUtils.createFile;

import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map.Entry;

import net.londatiga.android.ActionItem;
import net.londatiga.android.QuickAction;
import python.listview.JazzyHelper;
import python.listview.JazzyListView;
import zce.app.crash.CrashEmail;
import zce.app.sdpath.GetPath;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.DataSetObserver;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.support.v4.view.ActionProvider;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.SearchView.OnQueryTextListener;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.SubMenu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.TextView;

import com.google.common.base.Predicate;
import com.google.common.collect.Collections2;
import com.google.common.collect.Lists;
import com.googlecode.android_scripting.ActivityFlinger;
import com.googlecode.android_scripting.Analytics;
import com.googlecode.android_scripting.BaseApplication;
import com.googlecode.android_scripting.Constants;
import com.googlecode.android_scripting.FileUtils;
import com.googlecode.android_scripting.IntentBuilders;
import com.googlecode.android_scripting.Log;
import com.googlecode.android_scripting.R;
import com.googlecode.android_scripting.ScriptListAdapter;
import com.googlecode.android_scripting.ScriptStorageAdapter;
import com.googlecode.android_scripting.dialog.Decompile;
import com.googlecode.android_scripting.dialog.Help;
import com.googlecode.android_scripting.dialog.UsageTrackingConfirmation;
import com.googlecode.android_scripting.facade.FacadeConfiguration;
import com.googlecode.android_scripting.interpreter.Interpreter;
import com.googlecode.android_scripting.interpreter.InterpreterConfiguration;
import com.googlecode.android_scripting.interpreter.InterpreterConfiguration.ConfigurationObserver;

import de.keyboardsurfer.mobile.app.android.widget.crouton.Crouton;
import de.keyboardsurfer.mobile.app.android.widget.crouton.Style;

/**
 * Manages creation, deletion, and execution of stored scripts.
 *
 * @author Damon Kohler (damonkohler@gmail.com) changed ざ凍結の→愛
 *         (892768447@qq.com)
 */

@SuppressLint("DefaultLocale")
public class ScriptManager extends ActionBarActivity {

	private final static String EMPTY = "";
	private List<File> mScripts;
	private JazzyListView mList;
	private ScriptManagerAdapter mAdapter;
	private SharedPreferences mPreferences;
	private HashMap<Integer, Interpreter> mAddMenuIds;
	private ScriptListObserver mObserver;
	private InterpreterConfiguration mConfiguration;
	// private SearchManager mManager;
	private boolean mInSearchResultMode = false;
	private String mQuery = EMPTY;
	private File mCurrentDir;
	private File mBaseDir;
	private final Handler mHandler = new Handler();
	private File mCurrent;
	private final int[] effects = { JazzyHelper.STANDARD, JazzyHelper.GROW,
			JazzyHelper.CARDS, JazzyHelper.CURL, JazzyHelper.WAVE,
			JazzyHelper.FLIP, JazzyHelper.FLY, JazzyHelper.REVERSE_FLY,
			JazzyHelper.HELIX, JazzyHelper.FAN, JazzyHelper.TILT,
			JazzyHelper.ZIPPER, JazzyHelper.FADE, JazzyHelper.TWIRL,
			JazzyHelper.SLIDE_IN };

	private static enum MenuId {
		BUILD, DECOMPILE, DELETE, HELP, FOLDER_ADD, QRCODE_ADD, INTERPRETER_MANAGER, PREFERENCES, LOGCAT_VIEWER, TRIGGER_MANAGER, REFRESH, SEARCH, RENAME, EXTERNAL;
		public int getId() {
			return ordinal() + Menu.FIRST;
		}
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.script_manager);
		setTitle("sl4a");
		File sl4a = null;
		mBaseDir = new File(new GetPath().path(this) + "/sl4a/scripts/");
		Log.i("mBaseDir: " + mBaseDir.getAbsolutePath());
		sl4a = mBaseDir.getParentFile();
		if (!sl4a.exists()) {
			sl4a.mkdirs();
			try {
				FileUtils.chmod(sl4a, 0755);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		File tfile = new File(mBaseDir.getAbsolutePath() + "/template/");
		if (!tfile.exists()) {
			tfile.mkdirs();// 创建模版路径
		}
		if (!FileUtils.makeDirectories(mBaseDir, 0755)) {
			new AlertDialog.Builder(this)
					.setTitle("Error")
					.setMessage(
							getString(R.string.s_Failedtocreate) + "\n"
									+ mBaseDir + "\n"
									+ getString(R.string.s_PleaseCheck))
					.setIcon(android.R.drawable.ic_dialog_alert)
					.setPositiveButton("Ok", null).show();
		}

		mCurrentDir = mBaseDir;
		mPreferences = PreferenceManager.getDefaultSharedPreferences(this);
		mAdapter = new ScriptManagerAdapter(this);
		mObserver = new ScriptListObserver();
		mAdapter.registerDataSetObserver(mObserver);
		mConfiguration = ((BaseApplication) getApplication())
				.getInterpreterConfiguration();
		// mManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
		mList = (JazzyListView) findViewById(android.R.id.list);
		registerForContextMenu(mList);
		updateAndFilterScriptList(mQuery);
		mList.setAdapter(mAdapter);
		ActivityFlinger.attachView(mList, this);
		ActivityFlinger.attachView(getWindow().getDecorView(), this);
		startService(IntentBuilders.buildTriggerServiceIntent());
		UsageTrackingConfirmation.show(this);
		Analytics.trackActivity(this);
		setupJazziness(JazzyHelper.HELIX);
		mList.setOnItemClickListener(listItemClick);
		mList.setOnScrollListener(scrollListener);
		new CrashEmail(this,"892768447@qq.com");
	}

	protected OnScrollListener scrollListener = new OnScrollListener() {
		@Override
		public void onScrollStateChanged(AbsListView view, int scrollState) {
			switch (scrollState) {
			case OnScrollListener.SCROLL_STATE_IDLE:
				// 当不滚动时
				// 判断是否滚动到底部
				if (mList.getLastVisiblePosition() == (mList.getCount() - 1)) {
					setupJazziness(getEffects());
				}
				// 判断是否滚动到顶部
				if (mList.getFirstVisiblePosition() == 1) {
					setupJazziness(getEffects());
				}
			}
		}

		@Override
		public void onScroll(AbsListView absListView, int firstVisibleItem,
				int visibleItemCount, int totalItemCount) {
		}
	};

	protected OnItemClickListener listItemClick = new OnItemClickListener() {
		@Override
		public void onItemClick(AdapterView<?> arg0, View view, int position,
				long id) {
			final File file = (File) mList.getItemAtPosition(position);
			mCurrent = file;
			if (file.isDirectory()) {
				mCurrentDir = file;
				mAdapter.notifyDataSetInvalidated();
				return;
			}
			if (FacadeConfiguration.getSdkLevel() <= 3
					|| !mPreferences.getBoolean("use_quick_menu", true)) {
				doDialogMenu();
				return;
			}

			final QuickAction actionMenu = new QuickAction(view);

			ActionItem terminal = new ActionItem();
			terminal.setIcon(getResources().getDrawable(R.drawable.terminal));
			terminal.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					Intent intent = new Intent(ScriptManager.this,
							ScriptingLayerService.class);
					intent.setAction(Constants.ACTION_LAUNCH_FOREGROUND_SCRIPT);
					intent.putExtra(Constants.EXTRA_SCRIPT_PATH, file.getPath());
					startService(intent);
					dismissQuickActions(actionMenu);
				}
			});

			final ActionItem background = new ActionItem();
			background.setIcon(getResources()
					.getDrawable(R.drawable.background));
			background.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					Intent intent = new Intent(ScriptManager.this,
							ScriptingLayerService.class);
					intent.setAction(Constants.ACTION_LAUNCH_BACKGROUND_SCRIPT);
					intent.putExtra(Constants.EXTRA_SCRIPT_PATH, file.getPath());
					startService(intent);
					dismissQuickActions(actionMenu);
				}
			});

			final ActionItem edit = new ActionItem();
			edit.setIcon(getResources().getDrawable(
					android.R.drawable.ic_menu_edit));
			edit.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					editScript(file);
					dismissQuickActions(actionMenu);
				}
			});

			final ActionItem delete = new ActionItem();
			delete.setIcon(getResources().getDrawable(
					android.R.drawable.ic_menu_delete));
			delete.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					delete(file);
					dismissQuickActions(actionMenu);
				}
			});

			final ActionItem rename = new ActionItem();
			rename.setIcon(getResources().getDrawable(
					android.R.drawable.ic_menu_save));
			rename.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					rename(file);
					dismissQuickActions(actionMenu);
				}
			});

			final ActionItem external = new ActionItem();
			external.setIcon(getResources().getDrawable(
					android.R.drawable.ic_menu_directions));
			external.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					// externalEditor(file);
					dismissQuickActions(actionMenu);
					if (!file.getAbsolutePath().endsWith(".pyc")
							&& !file.isDirectory()) {
						// 非文件夹或者非pyc文件提示无法反编译
						Crouton.cancelAllCroutons();
						Crouton.showText(ScriptManager.this,
								getString(R.string.s_Cannotdecompile),
								Style.ALERT);
					} else {
						Decompile.show(ScriptManager.this,
								file.getAbsolutePath());
					}
				}
			});

			actionMenu.addActionItems(terminal, background, edit, rename,
					delete, external);
			actionMenu.setAnimStyle(QuickAction.ANIM_GROW_FROM_CENTER);
			actionMenu.show();
		}
	};

	private void setupJazziness(int effect) {
		mList.setTransitionEffect(effect);
	}

	@SuppressWarnings("serial")
	public void updateAndFilterScriptList(final String query) {
		List<File> scripts;
		if (mPreferences.getBoolean("show_all_files", false)) {
			scripts = ScriptStorageAdapter.listAllScripts(mCurrentDir);
		} else {
			scripts = ScriptStorageAdapter.listExecutableScripts(mCurrentDir,
					mConfiguration);
		}
		mScripts = Lists.newArrayList(Collections2.filter(scripts,
				new Predicate<File>() {
					@Override
					public boolean apply(File file) {
						return file.getName().toLowerCase()
								.contains(query.toLowerCase());
					}
				}));

		synchronized (mQuery) {
			if (!mQuery.equals(query)) {
				if (query == null || query.equals(EMPTY)) {
					// ((TextView) findViewById(R.id.left_text))
					// .setText("Scripts");
				} else {
					// ((TextView) findViewById(R.id.left_text)).setText(query);
				}
				mQuery = query;
			}
		}

		if (mScripts.size() == 0) {
			((TextView) findViewById(android.R.id.empty)).setText("");
		} else {
			((TextView) findViewById(android.R.id.empty)).setText("");
		}

		// TODO(damonkohler): Extending the File class here seems odd.
		if (!mCurrentDir.equals(mBaseDir)) {
			mScripts.add(0, new File(mCurrentDir.getParent()) {
				@Override
				public boolean isDirectory() {
					return true;
				}

				@Override
				public String getName() {
					return "..";
				}
			});
		}
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		menu.add(Menu.NONE, MenuId.RENAME.getId(), Menu.NONE,
				getString(R.string.s_Rename));
		menu.add(Menu.NONE, MenuId.DELETE.getId(), Menu.NONE,
				getString(R.string.s_Delete));
		menu.add(Menu.NONE, MenuId.DECOMPILE.getId(), Menu.NONE,
				getString(R.string.s_Decompile));
		menu.add(Menu.NONE, MenuId.BUILD.getId(), Menu.NONE,
				getString(R.string.s_Build));
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		AdapterView.AdapterContextMenuInfo info;
		try {
			info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
		} catch (ClassCastException e) {
			Log.e("Bad menuInfo", e);
			return false;
		}
		File file = (File) mAdapter.getItem(info.position);
		int itemId = item.getItemId();
		if (itemId == MenuId.DELETE.getId()) {
			delete(file);
			return true;
		} else if (itemId == MenuId.RENAME.getId()) {
			rename(file);
			return true;
		} else if (itemId == MenuId.DECOMPILE.getId()) {
			if (!file.getAbsolutePath().endsWith(".pyc") && !file.isDirectory()) {
				// 非文件夹或者非pyc文件提示无法反编译
				Crouton.cancelAllCroutons();
				Crouton.showText(this, getString(R.string.s_Cannotdecompile),
						Style.ALERT);
				return true;
			}
			Decompile.show(this, file.getAbsolutePath());
			return true;
		} else if (itemId == MenuId.BUILD.getId()) {
			// 打包项目
		}
		return false;
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (mInSearchResultMode) {
				mInSearchResultMode = false;
				mAdapter.notifyDataSetInvalidated();
				return true;
			}
			if (!mCurrentDir.equals(mBaseDir)) {// 返回键返回上级目录
				mCurrent = mCurrent.getParentFile();
				mCurrentDir = mCurrent;
				mAdapter.notifyDataSetInvalidated();
				return true;
			}
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public void onStop() {
		super.onStop();
		mConfiguration.unregisterObserver(mObserver);
	}

	@Override
	public void onStart() {
		super.onStart();
		mConfiguration.registerObserver(mObserver);
	}

	@Override
	protected void onResume() {
		super.onResume();
		if (!mInSearchResultMode || mScripts.isEmpty()) {
			((TextView) findViewById(android.R.id.empty))
					.setText(R.string.no_scripts_message);
		} else {
			((TextView) findViewById(android.R.id.empty)).setText("");
		}
		updateAndFilterScriptList(mQuery);
		mAdapter.notifyDataSetChanged();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.script_menu, menu);
		MenuItemCompat.setShowAsAction(menu.findItem(R.id.script_add),
				MenuItemCompat.SHOW_AS_ACTION_ALWAYS);
		MenuItemCompat.setActionProvider(menu.findItem(R.id.script_add),
				new AddActionProvider(this));// 自定义子菜单

		MenuItemCompat.setShowAsAction(menu.findItem(R.id.script_view),
				MenuItemCompat.SHOW_AS_ACTION_ALWAYS);
		MenuItemCompat.setShowAsAction(menu.findItem(R.id.script_setting),
				MenuItemCompat.SHOW_AS_ACTION_ALWAYS);
		MenuItem item = menu.findItem(R.id.script_search);
		SearchView searchView = new SearchView(this.getSupportActionBar()
				.getThemedContext());
		MenuItemCompat.setShowAsAction(item,
				MenuItemCompat.SHOW_AS_ACTION_ALWAYS);
		MenuItemCompat.setActionView(item, searchView);// 设置搜索窗口
		searchView.setOnQueryTextListener(new OnQueryTextListener() {
			@Override
			public boolean onQueryTextSubmit(String query) {
				mInSearchResultMode = true;
				updateAndFilterScriptList(query);
				mAdapter.notifyDataSetChanged();
				return false;
			}

			@Override
			public boolean onQueryTextChange(String query) {
				mInSearchResultMode = true;
				updateAndFilterScriptList(query);
				mAdapter.notifyDataSetChanged();
				return false;
			}
		});
		return true;
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		Log.e("onPrepareOptionsMenu");
		super.onPrepareOptionsMenu(menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		int id = item.getItemId();
		if (id == R.id.script_help) {
			Help.show(this);
		} else if (id == R.id.script_example) {
			InstallExampleDialog installExampleDialog = new InstallExampleDialog(
					this, this, new AlertDialog.Builder(this));
			installExampleDialog.setDestPath(mBaseDir.getAbsolutePath());
			installExampleDialog.start();// 解压例子
		} else if (id == R.id.script_about) {
			startActivity(new Intent(this, AboutActivity.class));
		} else if (id == R.id.script_interpreters) {
			// Show interpreter manger.
			startActivity(new Intent(this, InterpreterManager.class));
		} else if (id == R.id.script_preferences) {
			startActivity(new Intent(this, Preferences.class));
		} else if (id == R.id.script_triggers) {
			startActivity(new Intent(this, TriggerManager.class));
		} else if (id == R.id.script_logcat) {
			startActivity(new Intent(this, LogcatViewer.class));
		} else if (id == R.id.script_refresh) {
			updateAndFilterScriptList(mQuery);
			mAdapter.notifyDataSetChanged();
		}
		return true;
	}

	private void menuItemClick(int itemId) {
		if (itemId == MenuId.FOLDER_ADD.getId()) {
			addFolder();
			return;
		}
		if (mAddMenuIds.containsKey(itemId)) {
			// Add a new script.
			newfile(itemId);
			// Intent intent = new Intent(Constants.ACTION_EDIT_SCRIPT);
			// Interpreter interpreter = mAddMenuIds.get(itemId);
			// intent.putExtra(Constants.EXTRA_SCRIPT_PATH,
			// new File(mCurrentDir.getPath(), interpreter.getExtension())
			// .getPath());
			// intent.putExtra(Constants.EXTRA_SCRIPT_CONTENT,
			// interpreter.getContentTemplate());
			// intent.putExtra(Constants.EXTRA_IS_NEW_SCRIPT, true);
			// startActivity(intent);
			// synchronized (mQuery) {
			// mQuery = EMPTY;
			// }
		}
	}

	// Quickedit chokes on sdk 3 or below, and some Android builds. Provides
	// alternative menu.
	private void doDialogMenu() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		final CharSequence[] menuList = { getString(R.string.s_RunForeground),
				getString(R.string.s_RunBackground),
				getString(R.string.s_Edit), getString(R.string.s_Delete),
				getString(R.string.s_Rename),
				getString(R.string.s_ExternalEditor) };
		builder.setTitle(mCurrent.getName());
		builder.setItems(menuList, new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				Intent intent;
				switch (which) {
				case 0:
					intent = new Intent(ScriptManager.this,
							ScriptingLayerService.class);
					intent.setAction(Constants.ACTION_LAUNCH_FOREGROUND_SCRIPT);
					intent.putExtra(Constants.EXTRA_SCRIPT_PATH,
							mCurrent.getPath());
					startService(intent);
					break;
				case 1:
					intent = new Intent(ScriptManager.this,
							ScriptingLayerService.class);
					intent.setAction(Constants.ACTION_LAUNCH_BACKGROUND_SCRIPT);
					intent.putExtra(Constants.EXTRA_SCRIPT_PATH,
							mCurrent.getPath());
					startService(intent);
					break;
				case 2:
					editScript(mCurrent);
					break;
				case 3:
					delete(mCurrent);
					break;
				case 4:
					rename(mCurrent);
					break;
				case 5:
					// if (!mCurrent.getAbsolutePath().endsWith(".pyc")
					// && !mCurrent.isDirectory()) {
					// // 非文件夹或者非pyc文件提示无法反编译
					// Crouton.cancelAllCroutons();
					// Crouton.showText(ScriptManager.this,
					// getString(R.string.s_Cannotdecompile),
					// Style.ALERT);
					// } else {
					// Decompile.show(ScriptManager.this,
					// mCurrent.getAbsolutePath());
					// }
					externalEditor(mCurrent);
					break;
				}
			}
		});
		builder.show();
	}

	protected void externalEditor(File file) {
		Intent intent = new Intent(Intent.ACTION_EDIT);
		intent.setDataAndType(Uri.fromFile(file), "text/plain");
		try {
			startActivity(intent);
		} catch (Exception e) {
			Crouton.showText(this,
					getString(R.string.s_UnableOpeneditor) + e.toString(),
					Style.ALERT);
		}
	}

	private void dismissQuickActions(final QuickAction action) {
		// HACK(damonkohler): Delay the dismissal to avoid an otherwise
		// noticeable flicker.
		mHandler.postDelayed(new Runnable() {
			@Override
			public void run() {
				action.dismiss();
			}
		}, 1);
	}

	/**
	 * Opens the script for editing.
	 *
	 * @param script
	 *            the name of the script to edit
	 */
	private void editScript(File script) {
		Intent i = new Intent(Constants.ACTION_EDIT_SCRIPT);
		i.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
		i.putExtra(Constants.EXTRA_SCRIPT_PATH, script.getAbsolutePath());
		startActivity(i);
	}

	private void delete(final File file) {
		AlertDialog.Builder alert = new AlertDialog.Builder(this);
		alert.setTitle("Delete");
		alert.setMessage(getString(R.string.s_Woulddelete) + file.getName()
				+ "?");
		alert.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				FileUtils.delete(file);
				mScripts.remove(file);
				mAdapter.notifyDataSetChanged();
			}
		});
		alert.setNegativeButton("No", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				// Ignore.
			}
		});
		alert.show();
	}

	private void addFolder() {
		final EditText folderName = new EditText(this);
		folderName.setHint(getString(R.string.s_FolderName));
		AlertDialog.Builder alert = new AlertDialog.Builder(this);
		alert.setTitle(getString(R.string.s_AddFolder));
		alert.setView(folderName);
		alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				String name = folderName.getText().toString();
				if (name.length() == 0) {
					Log.e(ScriptManager.this, getString(R.string.s_Nameempty));
					return;
				} else {
					for (File f : mScripts) {
						if (f.getName().equals(name)) {
							Log.e(ScriptManager.this, String.format(
									getString(R.string.s_Exists), name));
							return;
						}
					}
				}
				File dir = new File(mCurrentDir, name);
				if (!FileUtils.makeDirectories(dir, 0755)) {
					Log.e(ScriptManager.this, String.format(
							getString(R.string.s_Cannot_create), name));
				}
				mAdapter.notifyDataSetInvalidated();
			}
		});
		alert.show();
	}

	private void newfile(final int itemId) {
		final EditText newName = new EditText(this);
		AlertDialog.Builder alert = new AlertDialog.Builder(this);
		alert.setTitle(getString(R.string.s_New_File));
		alert.setView(newName);
		alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				Interpreter interpreter = mAddMenuIds.get(itemId);
				String ext = interpreter.getExtension();
				String name = newName.getText().toString();
				if (name.length() == 0) {
					Log.e(ScriptManager.this, getString(R.string.s_Nameempty));
					return;
				} else {
					for (File f : mScripts) {
						if (f.getName().equals(name)) {
							Crouton.showText(ScriptManager.this, String.format(
									getString(R.string.s_Exists), name),
									Style.ALERT);
							return;
						}
					}
				}
				if (name.endsWith(ext)) {
					// name = name.replace(ext, "");//去掉后缀
				} else {
					name = name + ext;
				}
				// 检测pyevet是否存在,不存在则复制
				File pyevent = new File(mCurrentDir, "pyevent.pyc");
				if (!pyevent.exists()) {
					try {
						copyFile(getAssets().open("pyevent.pyc"), pyevent);
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				pyevent = null;
				if (!createFile(mCurrentDir, name)) {
					// 创建文件
					Crouton.showText(ScriptManager.this,
							getString(R.string.s_Cannot_create) + name,
							Style.ALERT);
					return;
				}
				mAdapter.notifyDataSetInvalidated();
				Intent intent = new Intent(Constants.ACTION_EDIT_SCRIPT);
				intent.putExtra(Constants.EXTRA_SCRIPT_PATH, new File(
						mCurrentDir.getPath(), name).getPath());
				intent.putExtra(Constants.EXTRA_SCRIPT_CONTENT,
						interpreter.getContentTemplate());
				intent.putExtra(Constants.EXTRA_IS_NEW_SCRIPT, true);
				startActivity(intent);
				synchronized (mQuery) {
					mQuery = EMPTY;
				}
			}
		});
		alert.show();
	}

	private void rename(final File file) {
		final EditText newName = new EditText(this);
		newName.setText(file.getName());
		AlertDialog.Builder alert = new AlertDialog.Builder(this);
		alert.setTitle(getString(R.string.s_Rename));
		alert.setView(newName);
		alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				String name = newName.getText().toString();
				if (name.length() == 0) {
					Log.e(ScriptManager.this, getString(R.string.s_Nameempty));
					return;
				} else {
					for (File f : mScripts) {
						if (f.getName().equals(name)) {
							Log.e(ScriptManager.this, String.format(
									getString(R.string.s_Exists), name));
							return;
						}
					}
				}
				if (!FileUtils.rename(file, name)) {
					throw new RuntimeException(String.format(
							getString(R.string.s_Cannotrename), file.getPath()));
				}
				mAdapter.notifyDataSetInvalidated();
			}
		});
		alert.show();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		mConfiguration.unregisterObserver(mObserver);
		// mManager.setOnCancelListener(null);
		android.os.Process.killProcess(android.os.Process.myPid());
		System.exit(1);
	}

	public int getEffects() {
		return effects[(int) (Math.random() * effects.length)];
	}

	public void updatemAdapter() {
		mAdapter.notifyDataSetChanged();
	}

	private void buildMenuIdMaps() {
		mAddMenuIds = new LinkedHashMap<Integer, Interpreter>();
		int i = MenuId.values().length + Menu.FIRST;
		List<Interpreter> installed = mConfiguration.getInstalledInterpreters();
		Collections.sort(installed, new Comparator<Interpreter>() {
			@Override
			public int compare(Interpreter interpreterA,
					Interpreter interpreterB) {
				return interpreterA.getNiceName().compareTo(
						interpreterB.getNiceName());
			}
		});
		for (Interpreter interpreter : installed) {
			mAddMenuIds.put(i, interpreter);
			++i;
		}
	}

	private void buildAddMenu(SubMenu subMenu) {
		subMenu.add(getString(R.string.s_Folder)).setOnMenuItemClickListener(
				new OnMenuItemClickListener() {
					@Override
					public boolean onMenuItemClick(MenuItem item) {
						menuItemClick(MenuId.FOLDER_ADD.getId());
						return false;
					}
				});
		for (final Entry<Integer, Interpreter> entry : mAddMenuIds.entrySet()) {
			subMenu.add(entry.getValue().getNiceName())
					.setOnMenuItemClickListener(new OnMenuItemClickListener() {
						@Override
						public boolean onMenuItemClick(MenuItem item) {
							menuItemClick(entry.getKey());
							return false;
						}
					});

		}
	}

	private class AddActionProvider extends ActionProvider {

		public AddActionProvider(Context context) {
			super(context);
		}

		@Override
		public View onCreateActionView() {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public void onPrepareSubMenu(SubMenu subMenu) {
			// TODO Auto-generated method stub
			subMenu.clear();
			buildMenuIdMaps();
			buildAddMenu(subMenu);
			super.onPrepareSubMenu(subMenu);
		}

		@Override
		public boolean hasSubMenu() {
			// TODO Auto-generated method stub
			return true;
		}
	}

	private class ScriptListObserver extends DataSetObserver implements
			ConfigurationObserver {
		@Override
		public void onInvalidated() {
			updateAndFilterScriptList(EMPTY);
		}

		@Override
		public void onConfigurationChanged() {
			runOnUiThread(new Runnable() {
				@Override
				public void run() {
					updateAndFilterScriptList(mQuery);
					mAdapter.notifyDataSetChanged();
				}
			});
		}
	}

	private class ScriptManagerAdapter extends ScriptListAdapter {
		public ScriptManagerAdapter(Context context) {
			super(context);
		}

		@Override
		protected List<File> getScriptList() {
			return mScripts;
		}
	}
}


text:
package drouter

import (
	"net"
	"strings"
	"sync"

	log "github.com/Sirupsen/logrus"
	"github.com/TrilliumIT/iputil"
	dockertypes "github.com/docker/engine-api/types"
	dockernetworks "github.com/docker/engine-api/types/network"
	"github.com/llimllib/ipaddress"
	"github.com/vishvananda/netlink"
	"golang.org/x/net/context"
)

type network struct {
	Name        string
	ID          string
	Subnets     []*net.IPNet
	Options     map[string]string
	log         *log.Entry
	connectLock sync.RWMutex
	adminDown   bool
}

func newNetwork(n *dockertypes.NetworkResource) *network {
	//create the network
	drn := &network{
		Name:      n.Name,
		ID:        n.ID,
		Options:   n.Options,
		adminDown: false,
		log: log.WithFields(log.Fields{
			"network": map[string]string{
				"Name": n.Name,
				"ID":   n.ID,
			}}),
	}
	for _, ic := range n.IPAM.Config {
		_, subnet, err := net.ParseCIDR(ic.Subnet)
		if err != nil {
			log.WithFields(log.Fields{
				"Subnet": ic.Subnet,
				"Error":  err,
			}).Error("Failed to parse IPAM Subnet.")
			continue
		}
		drn.Subnets = append(drn.Subnets, subnet)
	}

	return drn
}

func (n *network) logError(msg string, err error) {
	n.log.WithFields(log.Fields{"Error": err}).Error(msg)
}

//connects to a drNetwork
func (n *network) connect() {
	n.log.Debug("Connecting to network")
	n.connectLock.Lock()
	defer n.connectLock.Unlock()
	if isConnected(n) {
		n.log.Debug("Already connected.")
		return
	}

	endpointSettings := &dockernetworks.EndpointSettings{}
	//select drouter IP for network
	if ipOffset != 0 {
		var ip net.IP
		n.log.WithFields(log.Fields{
			"ip-offset": ipOffset,
		}).Debug("IP-Offset configured")
		for _, subnet := range n.Subnets {
			if ipOffset > 0 {
				ip = iputil.IPAdd(subnet.IP, ipOffset)
			} else {
				last := ipaddress.LastAddress(subnet)
				ip = iputil.IPAdd(last, ipOffset)
			}
			n.log.WithFields(log.Fields{
				"IP":     ip,
				"Subnet": subnet,
			}).Debug("Requesting IP on Subnet.")
			if endpointSettings.IPAddress == "" {
				endpointSettings.IPAddress = ip.String()
				endpointSettings.IPAMConfig = &dockernetworks.EndpointIPAMConfig{
					IPv4Address: ip.String(),
				}
			} else {
				endpointSettings.Aliases = append(endpointSettings.Aliases, ip.String())
			}
		}
	}
	//connect to network
	err := dockerClient.NetworkConnect(context.Background(), n.ID, selfContainerID, endpointSettings)
	if err != nil {
		// this should never happen, we already checked for it.
		if strings.Contains(err.Error(), "already exists") {
			n.log.WithFields(log.Fields{
				"Error": err,
			}).Warning("Attempted to connect to a network that drouter is already connected to")
			return
		}

		n.logError("Failed to connect to network.", err)
		return
	}
	n.log.Debug("Connected to network")
}

//disconnects from this drNetwork
func (n *network) disconnect() {
	n.connectLock.Lock()
	defer n.connectLock.Unlock()
	if !isConnected(n) {
		return
	}

	n.log.Debug("Disconnecting from network")
	n.removeRoutes()

	//finished route removal, disconnect
	err := dockerClient.NetworkDisconnect(context.Background(), n.ID, selfContainerID, true)
	if err != nil {
		n.logError("Failed to disconnect from network", err)
		return
	}
	n.log.Debug("Disconnected from network")
}

func (n *network) isConnected() bool {
	n.connectLock.RLock()
	defer n.connectLock.RUnlock()
	return isConnected(n)
}

func isConnected(n *network) bool {
	routes, err := netlink.RouteList(nil, netlink.FAMILY_ALL)
	if err != nil {
		n.logError("Failed to get routes.", err)
		return false
	}

	for _, subnet := range n.Subnets {
		for _, r := range routes {
			if r.Gw != nil {
				continue
			}
			if iputil.SubnetEqualSubnet(r.Dst, subnet) {
				//if we are connected to /any/ subnet, then we must be connected to the vxlan already
				//if we are missing only one subnet, we can't re-connect anyway
				//so don't continue here
				return true
			}
		}
	}
	return false
}

func (n *network) isDRouter() bool {
	return n.Options["drouter"] == instanceName || n.ID == transitNetID
}

func (n *network) connectEvent() error {
	n.adminDown = false
	return nil
}

func (n *network) disconnectEvent() error {
	n.log.Debug("Network disconnect detected")
	if !aggressive {
		//do nothing on disconnect event if not aggressive mode
		return nil
	}

	n.adminDown = true
	n.removeRoutes()

	return nil
}

func (n *network) removeRoutes() {
	var routeDelWG sync.WaitGroup
	for _, subnet := range n.Subnets {
		routeDelWG.Add(1)
		sn := subnet
		go func() {
			defer routeDelWG.Done()
			coveredByStatic := subnetCoveredByStatic(sn)

			//remove host shortcut routes
			if hostShortcut && !coveredByStatic {
				routeDelWG.Add(1)
				go func() {
					defer routeDelWG.Done()
					n.log.WithFields(log.Fields{
						"Subnet": sn,
					}).Debug("Deleting host routes to subnet.")
					p2p.delHostRoute(sn)
				}()
			}

			n.log.WithFields(log.Fields{
				"Subnet": sn,
			}).Debug("Deleting routes to subnet from all containers.")
			err := modifyRoute(sn, delRoute)
			if err != nil {
				n.logError("Failed to delete routes", err)
			}
		}()
	}

	n.log.Debug("Waiting for route removals to complete")
	routeDelWG.Wait()
}

redpajama_set_name: RedPajamaGithub


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

    const Interval1d = require('oroworkflow/js/tools/path-finder/interval1d');

    describe('oroworkflow/js/tools/path-finder/interval1d', function() {
        it('interval initialization', function() {
            const a = new Interval1d(5, 7);
            expect(a.min).toBe(5);
            expect(a.max).toBe(7);
            expect(function() {
                return new Interval1d(10, 7);
            }).toThrow(jasmine.any(RangeError));
        });

        it('check width calculation', function() {
            const a = new Interval1d(5, 7);
            expect(a.width).toBe(2);
            a.width = 10;
            expect(a.max).toBe(15);
        });

        it('check intersections', function() {
            const a = new Interval1d(5, 15);
            const b = new Interval1d(2, 8);
            const c = new Interval1d(30, 40);
            const intersection = a.intersection(b);
            expect(intersection instanceof Interval1d).toBe(true);
            expect(intersection.min).toBe(5);
            expect(intersection.max).toBe(8);
            expect(a.intersection(c)).toBe(null);
        });

        it('check union', function() {
            const a = new Interval1d(5, 15);
            const b = new Interval1d(2, 8);
            const union = a.union(b);
            expect(union instanceof Interval1d).toBe(true);
            expect(union.min).toBe(2);
            expect(union.max).toBe(15);
        });

        it('check contains', function() {
            const a = new Interval1d(2, 12);
            expect(a.contains(1)).toBe(false);
            expect(a.contains(2)).toBe(true);
            expect(a.contains(6)).toBe(true);
            expect(a.contains(12)).toBe(true);
            expect(a.contains(17)).toBe(false);
        });

        it('check containsNonInclusive', function() {
            const a = new Interval1d(2, 12);
            expect(a.containsNonInclusive(1)).toBe(false);
            expect(a.containsNonInclusive(2)).toBe(false);
            expect(a.containsNonInclusive(6)).toBe(true);
            expect(a.containsNonInclusive(12)).toBe(false);
            expect(a.containsNonInclusive(17)).toBe(false);
        });

        it('check calculate distance', function() {
            const a = new Interval1d(9, 12);
            expect(a.distanceTo(3)).toBe(6);
            expect(a.distanceTo(10)).toBe(0);
            expect(a.distanceTo(23)).toBe(11);
        });
    });
});


text:
<!DOCTYPE html>

		<title>My website</title>
		<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">

					bella

					This is a beautiful paragraph about my game.  My game features an alien space man character, a fence, and some coins.  When you get three coins, you win!  Then the game will restart.  It is very exciting.  There is a wall of grass/dirt blocks at the edge so the alien space man character does not go off the edge into the abyss.  At some point, I will likely add more features to this exciting game!


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

    /* istanbul ignore next */
    if (typeof define === 'function' && define.amd) {
        define(['./sorter'], uniqueFactory);
    } else if (typeof exports === 'object') {
        module.exports = uniqueFactory(
            require('./sorter')
        );
    } else {
        throw Error("no module loader found");
    }

    function uniqueFactory(sorter) {

        var undefined,
            DEFAULT_SORTABLE = false;

        function trivialOrder(a, b) {
            return a > b ? 1 : a < b ? -1 : 0;
        }

        function trivialCompare(a, b) {
            return a === b;
        }

        /**
         * Assume a sorted array. Remove duplicate elements with one pass.
         * @param arr A sorted array
         * @param order
         * @private
         */
        function _uniqueifySorted(arr, order) {
            var i = 0, n = 1, len = arr.length;
            if (len < 2) return;
            while (i < len) {
                if (order(arr[i], arr[n - 1]) !== 0) {
                    arr[n] = arr[i];
                    n++;
                }
                i++;
            }
            arr.length = n;
        }

        /**
         * Assume an unsorted array. Removes duplicates with two nested loops.
         * @param arr
         * @param compare
         * @private
         */
        function _uniqueifyNotSorted(arr, compare) {
            var i = 0, j, len = arr.length;
            while (i < len) {
                j = i + 1;
                while (j < len) {
                    if (compare(arr[i], arr[j])) {
                        arr[j--] = arr[--len];
                    }
                    j++;
                }
                i++;
            }
            arr.length = len;
        }

        /**
         * Uniqueify an array.
         * @param arr the array to uniqueify
         * @param sortable is this array sortable?
         * @param comparator a function which defines an order for the elements in
         * the array (if the array is sortabel), or elements equality if it is not.
         */
        return function () {

            var arr,
                sortable,
                comparator,
                args = Array.prototype.slice.call(arguments, 0);

            if (args.length === 0) args.push(this);

            if (args.length === 1) {
                if (Object.prototype.toString.call(args[0]) !== '[object Array]')
                    args.unshift(this);
                else
                    args.push(DEFAULT_SORTABLE);
            }

            if (args.length === 2) {
                if (Object.prototype.toString.call(args[0]) !== '[object Array]') {
                    args.unshift(this);
                } else if (args[1] === true) {
                    args.push(trivialOrder);
                } else if (args[1] === false) {
                    args.push(trivialCompare);
                } else {
                    args[2] = args[1];
                    args[1] = DEFAULT_SORTABLE;
                }
            }

            arr = args[0];
            sortable = args[1];
            comparator = args[2];

            if (Object.prototype.toString.call(arr) !== '[object Array]')
                throw Error("'arr' must be an array");
            if (!(sortable === true || sortable === false))
                throw Error("'sortable' must be a boolean");
            if (typeof comparator !== 'function')
                throw Error("'comparator' must be a function");

            if (sortable) {
                sorter(arr, comparator);
                _uniqueifySorted(arr, comparator);
            } else {
                _uniqueifyNotSorted(arr, comparator);
            }

            return arr.length;
        };
    }

}());


text:
import { Store, select } from '@ngrx/store';
import { Component, OnInit, ChangeDetectionStrategy } from '@angular/core';
import { Observable } from 'rxjs';

import {
  routeAnimations,
  selectIsAuthenticated
} from '../../../core/core.module';

import { State } from '../examples.state';

@Component({
  selector: 'anms-examples',
  templateUrl: './examples.component.html',
  styleUrls: ['./examples.component.scss'],
  animations: [routeAnimations],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class ExamplesComponent implements OnInit {
  isAuthenticated$: Observable<boolean> | undefined;

  examples = [
    { link: 'todos', label: 'anms.examples.menu.todos' },
    { link: 'stock-market', label: 'anms.examples.menu.stocks' },
    { link: 'theming', label: 'anms.examples.menu.theming' },
    { link: 'crud', label: 'anms.examples.menu.crud' },
    {
      link: 'simple-state-management',
      label: 'anms.examples.menu.simple-state-management'
    },
    { link: 'form', label: 'anms.examples.menu.form' },
    { link: 'notifications', label: 'anms.examples.menu.notifications' },
    { link: 'elements', label: 'anms.examples.menu.elements' },
    { link: 'authenticated', label: 'anms.examples.menu.auth', auth: true }
  ];

  constructor(private store: Store<State>) {}

  ngOnInit(): void {
    this.isAuthenticated$ = this.store.pipe(select(selectIsAuthenticated));
  }
}


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

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.Matchers.anyLong;
import static org.mockito.Matchers.eq;
import static org.mockito.Matchers.isA;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import org.apache.hadoop.hbase.HBaseClassTestRule;
import org.apache.hadoop.hbase.HBaseTestingUtility;
import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.ServerName;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.ColumnFamilyDescriptor;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.RegionInfo;
import org.apache.hadoop.hbase.client.Table;
import org.apache.hadoop.hbase.testclassification.MediumTests;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.util.ToolRunner;
import org.apache.log4j.Appender;
import org.apache.log4j.LogManager;
import org.apache.log4j.spi.LoggingEvent;
import org.junit.After;
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.rules.TestName;
import org.junit.runner.RunWith;
import org.mockito.ArgumentMatcher;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

import org.apache.hbase.thirdparty.com.google.common.collect.Iterables;

@RunWith(MockitoJUnitRunner.class)
@Category({MediumTests.class})
public class TestCanaryTool {

  @ClassRule
  public static final HBaseClassTestRule CLASS_RULE =
      HBaseClassTestRule.forClass(TestCanaryTool.class);

  private HBaseTestingUtility testingUtility;
  private static final byte[] FAMILY = Bytes.toBytes("f");
  private static final byte[] COLUMN = Bytes.toBytes("col");

  @Rule
  public TestName name = new TestName();

  @Before
  public void setUp() throws Exception {
    testingUtility = new HBaseTestingUtility();
    testingUtility.startMiniCluster();
    LogManager.getRootLogger().addAppender(mockAppender);
  }

  @After
  public void tearDown() throws Exception {
    testingUtility.shutdownMiniCluster();
    LogManager.getRootLogger().removeAppender(mockAppender);
  }

  @Mock
  Appender mockAppender;

  @Test
  public void testBasicZookeeperCanaryWorks() throws Exception {
    final String[] args = { "-t", "10000", "-zookeeper" };
    testZookeeperCanaryWithArgs(args);
  }

  @Test
  public void testZookeeperCanaryPermittedFailuresArgumentWorks() throws Exception {
    final String[] args = { "-t", "10000", "-zookeeper", "-treatFailureAsError", "-permittedZookeeperFailures", "1" };
    testZookeeperCanaryWithArgs(args);
  }

  @Test
  public void testBasicCanaryWorks() throws Exception {
    final TableName tableName = TableName.valueOf(name.getMethodName());
    Table table = testingUtility.createTable(tableName, new byte[][] { FAMILY });
    // insert some test rows
    for (int i=0; i<1000; i++) {
      byte[] iBytes = Bytes.toBytes(i);
      Put p = new Put(iBytes);
      p.addColumn(FAMILY, COLUMN, iBytes);
      table.put(p);
    }
    ExecutorService executor = new ScheduledThreadPoolExecutor(1);
    CanaryTool.RegionStdOutSink sink = spy(new CanaryTool.RegionStdOutSink());
    CanaryTool canary = new CanaryTool(executor, sink);
    String[] args = { "-writeSniffing", "-t", "10000", tableName.getNameAsString() };
    assertEquals(0, ToolRunner.run(testingUtility.getConfiguration(), canary, args));
    assertEquals("verify no read error count", 0, canary.getReadFailures().size());
    assertEquals("verify no write error count", 0, canary.getWriteFailures().size());
    verify(sink, atLeastOnce()).publishReadTiming(isA(ServerName.class), isA(RegionInfo.class),
      isA(ColumnFamilyDescriptor.class), anyLong());
  }

  @Test
  public void testCanaryRegionTaskResult() throws Exception {
    TableName tableName = TableName.valueOf("testCanaryRegionTaskResult");
    Table table = testingUtility.createTable(tableName, new byte[][] { FAMILY });
    // insert some test rows
    for (int i=0; i<1000; i++) {
      byte[] iBytes = Bytes.toBytes(i);
      Put p = new Put(iBytes);
      p.addColumn(FAMILY, COLUMN, iBytes);
      table.put(p);
    }
    ExecutorService executor = new ScheduledThreadPoolExecutor(1);
    CanaryTool.RegionStdOutSink sink = spy(new CanaryTool.RegionStdOutSink());
    CanaryTool canary = new CanaryTool(executor, sink);
    String[] args = { "-writeSniffing", "-t", "10000", "testCanaryRegionTaskResult" };
    assertEquals(0, ToolRunner.run(testingUtility.getConfiguration(), canary, args));

    assertTrue("canary should expect to scan at least 1 region",
        sink.getTotalExpectedRegions() > 0);
    assertTrue("there should be no read failures", sink.getReadFailureCount() == 0);
    assertTrue("there should be no write failures", sink.getWriteFailureCount() == 0);
    assertTrue("verify read success count > 0", sink.getReadSuccessCount() > 0);
    assertTrue("verify write success count > 0", sink.getWriteSuccessCount() > 0);
    verify(sink, atLeastOnce()).publishReadTiming(isA(ServerName.class), isA(RegionInfo.class),
        isA(ColumnFamilyDescriptor.class), anyLong());
    verify(sink, atLeastOnce()).publishWriteTiming(isA(ServerName.class), isA(RegionInfo.class),
        isA(ColumnFamilyDescriptor.class), anyLong());

    assertEquals("canary region success count should equal total expected regions",
        sink.getReadSuccessCount() + sink.getWriteSuccessCount(), sink.getTotalExpectedRegions());
    Map<String, List<CanaryTool.RegionTaskResult>> regionMap = sink.getRegionMap();
    assertFalse("verify region map has size > 0", regionMap.isEmpty());

    for (String regionName : regionMap.keySet()) {
      for (CanaryTool.RegionTaskResult res: regionMap.get(regionName)) {
        assertNotNull("verify getRegionNameAsString()", regionName);
        assertNotNull("verify getRegionInfo()", res.getRegionInfo());
        assertNotNull("verify getTableName()", res.getTableName());
        assertNotNull("verify getTableNameAsString()", res.getTableNameAsString());
        assertNotNull("verify getServerName()", res.getServerName());
        assertNotNull("verify getServerNameAsString()", res.getServerNameAsString());
        assertNotNull("verify getColumnFamily()", res.getColumnFamily());
        assertNotNull("verify getColumnFamilyNameAsString()", res.getColumnFamilyNameAsString());

        if (regionName.contains(CanaryTool.DEFAULT_WRITE_TABLE_NAME.getNameAsString())) {
          assertTrue("write to region " + regionName + " succeeded", res.isWriteSuccess());
          assertTrue("write took some time", res.getWriteLatency() > -1);
        } else {
          assertTrue("read from region " + regionName + " succeeded", res.isReadSuccess());
          assertTrue("read took some time", res.getReadLatency() > -1);
        }
      }
    }
  }

  @Test
  public void testReadTableTimeouts() throws Exception {
    final TableName [] tableNames = new TableName[2];
    tableNames[0] = TableName.valueOf(name.getMethodName() + "1");
    tableNames[1] = TableName.valueOf(name.getMethodName() + "2");
    // Create 2 test tables.
    for (int j = 0; j<2; j++) {
      Table table = testingUtility.createTable(tableNames[j], new byte[][] { FAMILY });
      // insert some test rows
      for (int i=0; i<1000; i++) {
        byte[] iBytes = Bytes.toBytes(i + j);
        Put p = new Put(iBytes);
        p.addColumn(FAMILY, COLUMN, iBytes);
        table.put(p);
      }
    }
    ExecutorService executor = new ScheduledThreadPoolExecutor(1);
    CanaryTool.RegionStdOutSink sink = spy(new CanaryTool.RegionStdOutSink());
    CanaryTool canary = new CanaryTool(executor, sink);
    String configuredTimeoutStr = tableNames[0].getNameAsString() + "=" + Long.MAX_VALUE + "," +
      tableNames[1].getNameAsString() + "=0";
    String[] args = {"-readTableTimeouts", configuredTimeoutStr, name.getMethodName() + "1",
      name.getMethodName() + "2"};
    assertEquals(0, ToolRunner.run(testingUtility.getConfiguration(), canary, args));
    verify(sink, times(tableNames.length)).initializeAndGetReadLatencyForTable(isA(String.class));
    for (int i=0; i<2; i++) {
      assertNotEquals("verify non-null read latency", null, sink.getReadLatencyMap().get(tableNames[i].getNameAsString()));
      assertNotEquals("verify non-zero read latency", 0L, sink.getReadLatencyMap().get(tableNames[i].getNameAsString()));
    }
    // One table's timeout is set for 0 ms and thus, should lead to an error.
    verify(mockAppender, times(1)).doAppend(argThat(new ArgumentMatcher<LoggingEvent>() {
      @Override
      public boolean matches(LoggingEvent argument) {
        return ((LoggingEvent) argument).getRenderedMessage().contains("exceeded the configured read timeout.");
      }
    }));
    verify(mockAppender, times(2)).doAppend(argThat(new ArgumentMatcher<LoggingEvent>() {
      @Override
      public boolean matches(LoggingEvent argument) {
        return argument.getRenderedMessage().contains("Configured read timeout");
      }
    }));
  }

  @Test
  public void testWriteTableTimeout() throws Exception {
    ExecutorService executor = new ScheduledThreadPoolExecutor(1);
    CanaryTool.RegionStdOutSink sink = spy(new CanaryTool.RegionStdOutSink());
    CanaryTool canary = new CanaryTool(executor, sink);
    String[] args = { "-writeSniffing", "-writeTableTimeout", String.valueOf(Long.MAX_VALUE)};
    assertEquals(0, ToolRunner.run(testingUtility.getConfiguration(), canary, args));
    assertNotEquals("verify non-null write latency", null, sink.getWriteLatency());
    assertNotEquals("verify non-zero write latency", 0L, sink.getWriteLatency());
    verify(mockAppender, times(1)).doAppend(argThat(
        new ArgumentMatcher<LoggingEvent>() {
          @Override
          public boolean matches(LoggingEvent argument) {
            return argument.getRenderedMessage().contains("Configured write timeout");
          }
        }));
  }

  //no table created, so there should be no regions
  @Test
  public void testRegionserverNoRegions() throws Exception {
    runRegionserverCanary();
    verify(mockAppender).doAppend(argThat(new ArgumentMatcher<LoggingEvent>() {
      @Override
      public boolean matches(LoggingEvent argument) {
        return argument.getRenderedMessage().contains("Regionserver not serving any regions");
      }
    }));
  }

  //by creating a table, there shouldn't be any region servers not serving any regions
  @Test
  public void testRegionserverWithRegions() throws Exception {
    final TableName tableName = TableName.valueOf(name.getMethodName());
    testingUtility.createTable(tableName, new byte[][] { FAMILY });
    runRegionserverCanary();
    verify(mockAppender, never()).doAppend(argThat(new ArgumentMatcher<LoggingEvent>() {
      @Override
      public boolean matches(LoggingEvent argument) {
        return argument.getRenderedMessage().contains("Regionserver not serving any regions");
      }
    }));
  }

  @Test
  public void testRawScanConfig() throws Exception {
    final TableName tableName = TableName.valueOf(name.getMethodName());
    Table table = testingUtility.createTable(tableName, new byte[][] { FAMILY });
    // insert some test rows
    for (int i=0; i<1000; i++) {
      byte[] iBytes = Bytes.toBytes(i);
      Put p = new Put(iBytes);
      p.addColumn(FAMILY, COLUMN, iBytes);
      table.put(p);
    }
    ExecutorService executor = new ScheduledThreadPoolExecutor(1);
    CanaryTool.RegionStdOutSink sink = spy(new CanaryTool.RegionStdOutSink());
    CanaryTool canary = new CanaryTool(executor, sink);
    String[] args = { "-t", "10000", name.getMethodName() };
    org.apache.hadoop.conf.Configuration conf =
      new org.apache.hadoop.conf.Configuration(testingUtility.getConfiguration());
    conf.setBoolean(HConstants.HBASE_CANARY_READ_RAW_SCAN_KEY, true);
    assertEquals(0, ToolRunner.run(conf, canary, args));
    verify(sink, atLeastOnce())
        .publishReadTiming(isA(ServerName.class), isA(RegionInfo.class),
        isA(ColumnFamilyDescriptor.class), anyLong());
    assertEquals("verify no read error count", 0, canary.getReadFailures().size());
  }

  private void runRegionserverCanary() throws Exception {
    ExecutorService executor = new ScheduledThreadPoolExecutor(1);
    CanaryTool canary = new CanaryTool(executor, new CanaryTool.RegionServerStdOutSink());
    String[] args = { "-t", "10000", "-regionserver"};
    assertEquals(0, ToolRunner.run(testingUtility.getConfiguration(), canary, args));
    assertEquals("verify no read error count", 0, canary.getReadFailures().size());
  }

  private void testZookeeperCanaryWithArgs(String[] args) throws Exception {
    Integer port =
      Iterables.getOnlyElement(testingUtility.getZkCluster().getClientPortList(), null);
    testingUtility.getConfiguration().set(HConstants.ZOOKEEPER_QUORUM, "localhost:" + port);
    ExecutorService executor = new ScheduledThreadPoolExecutor(2);
    CanaryTool.ZookeeperStdOutSink sink = spy(new CanaryTool.ZookeeperStdOutSink());
    CanaryTool canary = new CanaryTool(executor, sink);
    assertEquals(0, ToolRunner.run(testingUtility.getConfiguration(), canary, args));

    String baseZnode = testingUtility.getConfiguration()
      .get(HConstants.ZOOKEEPER_ZNODE_PARENT, HConstants.DEFAULT_ZOOKEEPER_ZNODE_PARENT);
    verify(sink, atLeastOnce())
      .publishReadTiming(eq(baseZnode), eq("localhost:" + port), anyLong());
  }
}


text:
<?php

namespace ActiveResource;

class ConnectionManager
{
	/**
	 * @var array<Connection>
	 */
	protected static $connections = [];

	/**
	 * Add an API connection
	 *
	 * @param string $name
	 * @param Connection $connection
	 * @return void
	 */
	public static function add($name, Connection $connection): void
	{
		self::$connections[$name] = $connection;
	}

	/**
	 * Get an API connection by its name
	 *
	 * @param string $name
	 * @throws ActiveResourceException
	 * @return Connection
	 */
	public static function get($name): Connection
	{
		if( isset(self::$connections[$name]) ){
			return self::$connections[$name];
		}

		throw new ActiveResourceException("Connection \"{$name}\" not found");
	}
}


text:
Image helper utilities.

## Installation

```bash
bower install koco-image-utilities
```

## Usage with KOCO

This is a shared module that is used in many other module. The convention is to configure an alias in the `require.configs.js` with the name `string-utilties` like so:

```javascript
paths: {
  ...
  'image-utilities': 'bower_components/koco-image-utilities/src/image-utilities'
  ...
}
```


text:
package org.apache.mahout.classifier.sequencelearning.hmm;

import org.apache.mahout.math.DenseMatrix;
import org.apache.mahout.math.Matrix;
import org.apache.mahout.math.Vector;

/**
 * Class containing implementations of the three major HMM algorithms: forward,
 * backward and Viterbi
 */
public final class HmmAlgorithms {

  /**
   * No public constructors for utility classes.
   */
  private HmmAlgorithms() {
    // nothing to do here really
  }

  /**
   * External function to compute a matrix of alpha factors
   *
   * @param model        model to run forward algorithm for.
   * @param observations observation sequence to train on.
   * @param scaled       Should log-scaled beta factors be computed?
   * @return matrix of alpha factors.
   */
  public static Matrix forwardAlgorithm(HmmModel model, int[] observations, boolean scaled) {
    Matrix alpha = new DenseMatrix(observations.length, model.getNrOfHiddenStates());
    forwardAlgorithm(alpha, model, observations, scaled);

    return alpha;
  }

  /**
   * Internal function to compute the alpha factors
   *
   * @param alpha        matrix to store alpha factors in.
   * @param model        model to use for alpha factor computation.
   * @param observations observation sequence seen.
   * @param scaled       set to true if log-scaled beta factors should be computed.
   */
  static void forwardAlgorithm(Matrix alpha, HmmModel model, int[] observations, boolean scaled) {

    // fetch references to the model parameters
    Vector ip = model.getInitialProbabilities();
    Matrix b = model.getEmissionMatrix();
    Matrix a = model.getTransitionMatrix();

    if (scaled) { // compute log scaled alpha values
      // Initialization
      for (int i = 0; i < model.getNrOfHiddenStates(); i++) {
        alpha.setQuick(0, i, Math.log(ip.getQuick(i) * b.getQuick(i, observations[0])));
      }

      // Induction
      for (int t = 1; t < observations.length; t++) {
        for (int i = 0; i < model.getNrOfHiddenStates(); i++) {
          double sum = Double.NEGATIVE_INFINITY; // log(0)
          for (int j = 0; j < model.getNrOfHiddenStates(); j++) {
            double tmp = alpha.getQuick(t - 1, j) + Math.log(a.getQuick(j, i));
            if (tmp > Double.NEGATIVE_INFINITY) {
              // make sure we handle log(0) correctly
              sum = tmp + Math.log1p(Math.exp(sum - tmp));
            }
          }
          alpha.setQuick(t, i, sum + Math.log(b.getQuick(i, observations[t])));
        }
      }
    } else {

      // Initialization
      for (int i = 0; i < model.getNrOfHiddenStates(); i++) {
        alpha.setQuick(0, i, ip.getQuick(i) * b.getQuick(i, observations[0]));
      }

      // Induction
      for (int t = 1; t < observations.length; t++) {
        for (int i = 0; i < model.getNrOfHiddenStates(); i++) {
          double sum = 0.0;
          for (int j = 0; j < model.getNrOfHiddenStates(); j++) {
            sum += alpha.getQuick(t - 1, j) * a.getQuick(j, i);
          }
          alpha.setQuick(t, i, sum * b.getQuick(i, observations[t]));
        }
      }
    }
  }

  /**
   * External function to compute a matrix of beta factors
   *
   * @param model        model to use for estimation.
   * @param observations observation sequence seen.
   * @param scaled       Set to true if log-scaled beta factors should be computed.
   * @return beta factors based on the model and observation sequence.
   */
  public static Matrix backwardAlgorithm(HmmModel model, int[] observations, boolean scaled) {
    // initialize the matrix
    Matrix beta = new DenseMatrix(observations.length, model.getNrOfHiddenStates());
    // compute the beta factors
    backwardAlgorithm(beta, model, observations, scaled);

    return beta;
  }

  /**
   * Internal function to compute the beta factors
   *
   * @param beta         Matrix to store resulting factors in.
   * @param model        model to use for factor estimation.
   * @param observations sequence of observations to estimate.
   * @param scaled       set to true to compute log-scaled parameters.
   */
  static void backwardAlgorithm(Matrix beta, HmmModel model, int[] observations, boolean scaled) {
    // fetch references to the model parameters
    Matrix b = model.getEmissionMatrix();
    Matrix a = model.getTransitionMatrix();

    if (scaled) { // compute log-scaled factors
      // initialization
      for (int i = 0; i < model.getNrOfHiddenStates(); i++) {
        beta.setQuick(observations.length - 1, i, 0);
      }

      // induction
      for (int t = observations.length - 2; t >= 0; t--) {
        for (int i = 0; i < model.getNrOfHiddenStates(); i++) {
          double sum = Double.NEGATIVE_INFINITY; // log(0)
          for (int j = 0; j < model.getNrOfHiddenStates(); j++) {
            double tmp = beta.getQuick(t + 1, j) + Math.log(a.getQuick(i, j))
                + Math.log(b.getQuick(j, observations[t + 1]));
            if (tmp > Double.NEGATIVE_INFINITY) {
              // handle log(0)
              sum = tmp + Math.log1p(Math.exp(sum - tmp));
            }
          }
          beta.setQuick(t, i, sum);
        }
      }
    } else {
      // initialization
      for (int i = 0; i < model.getNrOfHiddenStates(); i++) {
        beta.setQuick(observations.length - 1, i, 1);
      }
      // induction
      for (int t = observations.length - 2; t >= 0; t--) {
        for (int i = 0; i < model.getNrOfHiddenStates(); i++) {
          double sum = 0;
          for (int j = 0; j < model.getNrOfHiddenStates(); j++) {
            sum += beta.getQuick(t + 1, j) * a.getQuick(i, j) * b.getQuick(j, observations[t + 1]);
          }
          beta.setQuick(t, i, sum);
        }
      }
    }
  }

  /**
   * Viterbi algorithm to compute the most likely hidden sequence for a given
   * model and observed sequence
   *
   * @param model        HmmModel for which the Viterbi path should be computed
   * @param observations Sequence of observations
   * @param scaled       Use log-scaled computations, this requires higher computational
   *                     effort but is numerically more stable for large observation
   *                     sequences
   * @return nrOfObservations 1D int array containing the most likely hidden
   *         sequence
   */
  public static int[] viterbiAlgorithm(HmmModel model, int[] observations, boolean scaled) {

    // probability that the most probable hidden states ends at state i at
    // time t
    double[][] delta = new double[observations.length][model
        .getNrOfHiddenStates()];

    // previous hidden state in the most probable state leading up to state
    // i at time t
    int[][] phi = new int[observations.length - 1][model.getNrOfHiddenStates()];

    // initialize the return array
    int[] sequence = new int[observations.length];

    viterbiAlgorithm(sequence, delta, phi, model, observations, scaled);

    return sequence;
  }

  /**
   * Internal version of the viterbi algorithm, allowing to reuse existing
   * arrays instead of allocating new ones
   *
   * @param sequence     NrOfObservations 1D int array for storing the viterbi sequence
   * @param delta        NrOfObservations x NrHiddenStates 2D double array for storing the
   *                     delta factors
   * @param phi          NrOfObservations-1 x NrHiddenStates 2D int array for storing the
   *                     phi values
   * @param model        HmmModel for which the viterbi path should be computed
   * @param observations Sequence of observations
   * @param scaled       Use log-scaled computations, this requires higher computational
   *                     effort but is numerically more stable for large observation
   *                     sequences
   */
  static void viterbiAlgorithm(int[] sequence, double[][] delta, int[][] phi, HmmModel model, int[] observations,
      boolean scaled) {
    // fetch references to the model parameters
    Vector ip = model.getInitialProbabilities();
    Matrix b = model.getEmissionMatrix();
    Matrix a = model.getTransitionMatrix();

    // Initialization
    if (scaled) {
      for (int i = 0; i < model.getNrOfHiddenStates(); i++) {
        delta[0][i] = Math.log(ip.getQuick(i) * b.getQuick(i, observations[0]));
      }
    } else {

      for (int i = 0; i < model.getNrOfHiddenStates(); i++) {
        delta[0][i] = ip.getQuick(i) * b.getQuick(i, observations[0]);
      }
    }

    // Induction
    // iterate over the time
    if (scaled) {
      for (int t = 1; t < observations.length; t++) {
        // iterate over the hidden states
        for (int i = 0; i < model.getNrOfHiddenStates(); i++) {
          // find the maximum probability and most likely state
          // leading up
          // to this
          int maxState = 0;
          double maxProb = delta[t - 1][0] + Math.log(a.getQuick(0, i));
          for (int j = 1; j < model.getNrOfHiddenStates(); j++) {
            double prob = delta[t - 1][j] + Math.log(a.getQuick(j, i));
            if (prob > maxProb) {
              maxProb = prob;
              maxState = j;
            }
          }
          delta[t][i] = maxProb + Math.log(b.getQuick(i, observations[t]));
          phi[t - 1][i] = maxState;
        }
      }
    } else {
      for (int t = 1; t < observations.length; t++) {
        // iterate over the hidden states
        for (int i = 0; i < model.getNrOfHiddenStates(); i++) {
          // find the maximum probability and most likely state
          // leading up
          // to this
          int maxState = 0;
          double maxProb = delta[t - 1][0] * a.getQuick(0, i);
          for (int j = 1; j < model.getNrOfHiddenStates(); j++) {
            double prob = delta[t - 1][j] * a.getQuick(j, i);
            if (prob > maxProb) {
              maxProb = prob;
              maxState = j;
            }
          }
          delta[t][i] = maxProb * b.getQuick(i, observations[t]);
          phi[t - 1][i] = maxState;
        }
      }
    }

    // find the most likely end state for initialization
    double maxProb;
    if (scaled) {
      maxProb = Double.NEGATIVE_INFINITY;
    } else {
      maxProb = 0.0;
    }
    for (int i = 0; i < model.getNrOfHiddenStates(); i++) {
      if (delta[observations.length - 1][i] > maxProb) {
        maxProb = delta[observations.length - 1][i];
        sequence[observations.length - 1] = i;
      }
    }

    // now backtrack to find the most likely hidden sequence
    for (int t = observations.length - 2; t >= 0; t--) {
      sequence[t] = phi[t][sequence[t + 1]];
    }
  }

}


text:
using namespace vnotex;

LocalNotebookBackendFactory::LocalNotebookBackendFactory()
{
}

QString LocalNotebookBackendFactory::getName() const
{
    return QStringLiteral("local.vnotex");
}

QString LocalNotebookBackendFactory::getDisplayName() const
{
    return QObject::tr("Local Notebook Backend");
}

QString LocalNotebookBackendFactory::getDescription() const
{
    return QObject::tr("Local file system");
}

QSharedPointer<INotebookBackend> LocalNotebookBackendFactory::createNotebookBackend(const QString &p_rootPath)
{
    return QSharedPointer<LocalNotebookBackend>::create(getName(),
                                                        getDisplayName(),
                                                        getDescription(),
                                                        p_rootPath);
}


text:
rpm -Uvh http://mirrors.sohu.com/fedora-epel/epel-release-latest-6.noarch.rpm
rpm --import /etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-6

rpm -Uvh http://mirrors.sohu.com/fedora-epel/epel-release-latest-7.noarch.rpm
rpm --import /etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-7

#http://download.fedoraproject.org/pub/epel/
rpm -Uvh http://ftp.riken.jp/Linux/fedora/epel//epel-release-latest-6.noarch.rpm
rpm --import /etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-6

rpm -Uvh http://ftp.riken.jp/Linux/fedora/epel//epel-release-latest-7.noarch.rpm
rpm --import /etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-7

#http://mirrors.aliyun.com/epel/
rpm -Uvh http://mirrors.aliyun.com/epel/epel-release-latest-6.noarch.rpm
rpm --import /etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-6

rpm -Uvh http://mirrors.aliyun.com/epel/epel-release-latest-7.noarch.rpm
rpm --import /etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-7


text:
using System;

namespace Corelicious.Lucene {
    public class MultiStringFieldCache : MultiFieldCache<String> {
        protected override Boolean TryParse(String value, out String result) {
            result = value;
            return true;
        }
    }

    public class MultiGuidFieldCache : MultiFieldCache<Guid> {
        protected override Boolean TryParse(String value, out Guid result) {
            return Guid.TryParse(value, out result);
        }
    }

    public class MultiInt32FieldCache : MultiFieldCache<Int32> {
        protected override Boolean TryParse(String value, out Int32 result) {
            return Int32.TryParse(value, out result);
        }
    }
}


text:
using namespace ci;
using namespace ci::app;
using namespace std;

class SmartPointersApp : public App {
  public:
	void setup() override;
	void mouseDown( MouseEvent event ) override;
	void update() override;
	void draw() override;
};

void SmartPointersApp::setup()
{
}

void SmartPointersApp::mouseDown( MouseEvent event )
{
}

void SmartPointersApp::update()
{
}

void SmartPointersApp::draw()
{
	gl::clear( Color( 0, 0, 0 ) );
}

CINDER_APP( SmartPointersApp, RendererGl )


text:
object Macros {
  object Shmacros {
    def foo(x: Int): Int = macro Impls.foo
  }
  def bar(x: Int): Int = macro Impls.bar
}

class Macros {
  def quux(x: Int): Int = macro Impls.quux
}

object Test extends dotty.runtime.LegacyApp {
  import Macros.Shmacros._
  println(foo(2) + Macros.bar(2) * new Macros().quux(4))
}


text:
layout: page
title: Jean Mccoy's 104th Birthday
date: 2016-05-24
author: Andrea Stafford
tags: weekly links, java
status: published
summary: Cras condimentum laoreet leo quis vulputate. Donec at viverra dui.
banner: images/banner/leisure-01.jpg
booking:
  startDate: 03/22/2017
  endDate: 03/23/2017
  ctyhocn: GSPHSHX
  groupCode: JM1B
published: true
---
Praesent rhoncus risus et aliquet feugiat. In turpis quam, laoreet at nulla et, pharetra eleifend turpis. Curabitur eu elit mauris. Nunc commodo lorem et scelerisque accumsan. Ut vulputate placerat sem nec efficitur. Praesent urna diam, vulputate sit amet pretium eu, elementum et augue. Pellentesque lectus tortor, fringilla at rutrum a, porttitor sit amet tellus. Integer at pretium augue. Vestibulum nec ligula consectetur, aliquet dui non, efficitur mi. Nullam varius sodales varius.
Vestibulum vel mi justo. Nunc non sodales diam, in pulvinar libero. Suspendisse feugiat nisi in eros consectetur egestas. Maecenas orci augue, pulvinar fringilla ipsum et, viverra convallis nulla. Phasellus vestibulum, diam vitae gravida placerat, ipsum arcu volutpat est, in iaculis sapien nisl non risus. Quisque ipsum nibh, finibus vitae interdum ac, eleifend luctus tortor. Nullam aliquet, nunc nec vulputate pretium, ante ante mattis sem, et accumsan lectus nibh cursus dolor.

* Sed eget arcu pellentesque, congue turpis in, laoreet odio
* Proin condimentum nunc quis augue scelerisque semper eu quis erat
* Phasellus tristique ante in est sollicitudin, id tempus nisi accumsan
* Praesent dignissim dui vel pulvinar rutrum
* Vestibulum bibendum nulla vel finibus ullamcorper.

Vestibulum sit amet pulvinar tellus. Duis ornare accumsan feugiat. Nam ut pharetra ex. Morbi at fringilla odio, vel hendrerit quam. Nam in leo in nibh viverra faucibus et eu risus. Cras tristique maximus ligula, nec laoreet nunc porta eu. Cras blandit ante at ligula fringilla, quis pharetra justo posuere. Donec a maximus elit. Mauris ut purus sit amet justo tristique faucibus.


text:
require "rails_helper"

feature "Repositories support" do
  let!(:registry) { create(:registry) }
  let!(:user) { create(:admin) }
  let!(:user2) { create(:user) }
  let!(:user3) { create(:user) }
  let!(:team) { create(:team, owners: [user], contributors: [user2], viewers: [user3]) }
  let!(:namespace) { create(:namespace, team: team) }
  let!(:repository) { create(:repository, namespace: namespace) }
  let!(:starred_repo) { create(:repository, namespace: namespace) }
  let!(:star) { create(:star, user: user, repository: starred_repo) }

  before do
    login_as user, scope: :user
  end

  describe "repository#show" do
    scenario "Visual aid for each role is shown properly", js: true do
      visit repository_path(repository)
      expect(page).to have_content("Push Pull Owner")

      login_as user2, scope: :user
      visit repository_path(repository)
      expect(page).to have_content("Push Pull Contr.")

      login_as user3, scope: :user
      visit repository_path(repository)
      expect(page).to have_content("Pull Viewer")
    end

    scenario "A user can star a repository", js: true do
      visit repository_path(repository)
      expect(find("#toggle_star")).to be_visible
      find("#toggle_star").click
      wait_for_ajax
      expect(current_path).to eq repository_path(repository)

      # See the response.
      repo = Repository.find(repository.id)
      expect(find("#star-counter")).to have_content("1")
      expect(repo.stars.count).to be 1
    end

    scenario "A user can unstar a repository", js: true do
      visit repository_path(starred_repo)
      expect(find("#toggle_star")).to be_visible
      find("#toggle_star").click
      wait_for_ajax
      expect(current_path).to eq repository_path(starred_repo)

      # See the response.
      repo = Repository.find(repository.id)
      expect(find("#star-counter")).to have_content("0")
      expect(repo.stars.count).to be 0
    end

    scenario "Groupped tags are handled properly", js: true do
      ["", "", "same", "same", "another", "yet-another"].each_with_index do |digest, idx|
        create(:tag, name: "tag#{idx}", author: user, repository: repository, digest: digest,
               image_id: "Image")
      end

      expectations = [["tag0"], ["tag1"], ["tag2", "tag3"], ["tag4"], ["tag5"]]

      visit repository_path(repository)

      page.all(".tags tr").each_with_index do |row, idx|
        expect(row.text.include?("Image")).to be_truthy

        # Skip the header.
        next if idx == 0

        expectations[idx - 1].each { |tag| expect(row.text.include?(tag)).to be_truthy }
      end
    end

    scenario "it works if both the digest and the image_id are blank", js: true do
      create(:tag, author: user, repository: repository, digest: nil, image_id: nil)
      create(:tag, author: user, repository: repository, digest: "nonblank", image_id: nil)

      visit repository_path(repository)
    end
  end
end


text:
"""
Functions for dealing with markup text
"""

import warnings
import re
import six
from six import moves

from w3lib.util import to_bytes, to_unicode
from w3lib.url import safe_url_string

_ent_re = re.compile(r'&((?P<named>[a-z\d]+)|#(?P<dec>\d+)|#x(?P<hex>[a-f\d]+))(?P<semicolon>;?)', re.IGNORECASE)
_tag_re = re.compile(r'<[a-zA-Z\/!].*?>', re.DOTALL)
_baseurl_re = re.compile(six.u(r'<base\s[^>]*href\s*=\s*[\"\']\s*([^\"\'\s]+)\s*[\"\']'), re.I)
_meta_refresh_re = re.compile(six.u(r'<meta\s[^>]*http-equiv[^>]*refresh[^>]*content\s*=\s*(?P<quote>["\'])(?P<int>(\d*\.)?\d+)\s*;\s*url=\s*(?P<url>.*?)(?P=quote)'), re.DOTALL | re.IGNORECASE)
_cdata_re = re.compile(r'((?P<cdata_s><!\[CDATA\[)(?P<cdata_d>.*?)(?P<cdata_e>\]\]>))', re.DOTALL)

def remove_entities(text, keep=(), remove_illegal=True, encoding='utf-8'):
    r"""

    .. warning::

        This function is deprecated and will be removed in future.
        Please use :func:`replace_entities` instead.
    """

    warnings.warn(
        "`w3lib.html.remove_entities` function is deprecated and "
        "will be removed in future releases. Please use "
        "`w3lib.html.replace_entities` instead.",
        DeprecationWarning
    )

    return replace_entities(text, keep, remove_illegal, encoding)

def replace_entities(text, keep=(), remove_illegal=True, encoding='utf-8'):
    u"""Remove entities from the given `text` by converting them to their
    corresponding unicode character.

    `text` can be a unicode string or a byte string encoded in the given
    `encoding` (which defaults to 'utf-8').

    If `keep` is passed (with a list of entity names) those entities will
    be kept (they won't be removed).

    It supports both numeric entities (``&#nnnn;`` and ``&#hhhh;``)
    and named entities (such as `` `` or ``>``).

    If `remove_illegal` is ``True``, entities that can't be converted are removed.
    If `remove_illegal` is ``False``, entities that can't be converted are kept "as
    is". For more information see the tests.

    Always returns a unicode string (with the entities removed).

    >>> import w3lib.html
    >>> w3lib.html.replace_entities(b'Price: £100')
    u'Price: \\xa3100'
    >>> print(w3lib.html.replace_entities(b'Price: £100'))
    Price: £100
    >>>

    """

    def convert_entity(m):
        groups = m.groupdict()
        if groups.get('dec'):
            number = int(groups['dec'], 10)
        elif groups.get('hex'):
            number = int(groups['hex'], 16)
        elif groups.get('named'):
            entity_name = groups['named']
            if entity_name.lower() in keep:
                return m.group(0)
            else:
                number = (moves.html_entities.name2codepoint.get(entity_name) or
                    moves.html_entities.name2codepoint.get(entity_name.lower()))
        if number is not None:
            # Numeric character references in the 80-9F range are typically
            # interpreted by browsers as representing the characters mapped
            # to bytes 80-9F in the Windows-1252 encoding. For more info
            # see: http://en.wikipedia.org/wiki/Character_encodings_in_HTML
            try:
                if 0x80 <= number <= 0x9f:
                    return six.int2byte(number).decode('cp1252')
                else:
                    return six.unichr(number)
            except ValueError:
                pass

        return u'' if remove_illegal and groups.get('semicolon') else m.group(0)

    return _ent_re.sub(convert_entity, to_unicode(text, encoding))

def has_entities(text, encoding=None):
    return bool(_ent_re.search(to_unicode(text, encoding)))

def replace_tags(text, token='', encoding=None):
    """Replace all markup tags found in the given `text` by the given token.
    By default `token` is an empty string so it just removes all tags.

    `text` can be a unicode string or a regular string encoded as `encoding`
    (or ``'utf-8'`` if `encoding` is not given.)

    Always returns a unicode string.

    Examples:

    >>> import w3lib.html
    >>> w3lib.html.replace_tags(u'This text contains some tag')
    u'This text contains some tag'
    >>> w3lib.html.replace_tags('
Je ne parle pas fran\\xe7ais
', ' -- ', 'latin-1')
    u' -- Je ne parle pas  -- fran\\xe7ais --  -- '
    >>>

    """

    return _tag_re.sub(token, to_unicode(text, encoding))

_REMOVECOMMENTS_RE = re.compile(u'', re.DOTALL)
def remove_comments(text, encoding=None):
    """ Remove HTML Comments.

    >>> import w3lib.html
    >>> w3lib.html.remove_comments(b"test  whatever")
    u'test  whatever'
    >>>

    """

    text = to_unicode(text, encoding)
    return _REMOVECOMMENTS_RE.sub(u'', text)

def remove_tags(text, which_ones=(), keep=(), encoding=None):
    """ Remove HTML Tags only.

    `which_ones` and `keep` are both tuples, there are four cases:

    ==============  ============= ==========================================
    ``which_ones``  ``keep``      what it does
    ==============  ============= ==========================================
    **not empty**   empty         remove all tags in ``which_ones``
    empty           **not empty** remove all tags except the ones in ``keep``
    empty           empty         remove all tags
    **not empty**   **not empty** not allowed
    ==============  ============= ==========================================

    Remove all tags:

    >>> import w3lib.html
    >>> doc = '

This is a link: example

'
    >>> w3lib.html.remove_tags(doc)
    u'This is a link: example'
    >>>

    Keep only some tags:

    >>> w3lib.html.remove_tags(doc, keep=('div',))
    u'
This is a link: example
'
    >>>

    Remove only specific tags:

    >>> w3lib.html.remove_tags(doc, which_ones=('a','b'))
    u'

This is a link: example

'
    >>>

    You can't remove some and keep some:

    >>> w3lib.html.remove_tags(doc, which_ones=('a',), keep=('p',))
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "/usr/local/lib/python2.7/dist-packages/w3lib/html.py", line 101, in remove_tags
        assert not (which_ones and keep), 'which_ones and keep can not be given at the same time'
    AssertionError: which_ones and keep can not be given at the same time
    >>>

    """

    assert not (which_ones and keep), 'which_ones and keep can not be given at the same time'

    which_ones = {tag.lower() for tag in which_ones}
    keep = {tag.lower() for tag in keep}

    def will_remove(tag):
        tag = tag.lower()
        if which_ones:
            return tag in which_ones
        else:
            return tag not in keep

    def remove_tag(m):
        tag = m.group(1)
        return u'' if will_remove(tag) else m.group(0)

    regex = '</?([^ >/]+).*?>'
    retags = re.compile(regex, re.DOTALL | re.IGNORECASE)

    return retags.sub(remove_tag, to_unicode(text, encoding))

def remove_tags_with_content(text, which_ones=(), encoding=None):
    """Remove tags and their content.

    `which_ones` is a tuple of which tags to remove including their content.
    If is empty, returns the string unmodified.

    >>> import w3lib.html
    >>> doc = '

This is a link: example

'
    >>> w3lib.html.remove_tags_with_content(doc, which_ones=('b',))
    u'

 example

'
    >>>

    """

    text = to_unicode(text, encoding)
    if which_ones:
        tags = '|'.join([r'<%s.*?</%s>|<%s\s*/>' % (tag, tag, tag) for tag in which_ones])
        retags = re.compile(tags, re.DOTALL | re.IGNORECASE)
        text = retags.sub(u'', text)
    return text

def replace_escape_chars(text, which_ones=('\n', '\t', '\r'), replace_by=u'', \
        encoding=None):
    """Remove escape characters.

    `which_ones` is a tuple of which escape characters we want to remove.
    By default removes ``\\n``, ``\\t``, ``\\r``.

    `replace_by` is the string to replace the escape characters by.
    It defaults to ``''``, meaning the escape characters are removed.

    """

    text = to_unicode(text, encoding)
    for ec in which_ones:
        text = text.replace(ec, to_unicode(replace_by, encoding))
    return text

def unquote_markup(text, keep=(), remove_illegal=True, encoding=None):
    """
    This function receives markup as a text (always a unicode string or
    a UTF-8 encoded string) and does the following:

    1. removes entities (except the ones in `keep`) from any part of it
        that is not inside a CDATA
    2. searches for CDATAs and extracts their text (if any) without modifying it.
    3. removes the found CDATAs

    """

    def _get_fragments(txt, pattern):
        offset = 0
        for match in pattern.finditer(txt):
            match_s, match_e = match.span(1)
            yield txt[offset:match_s]
            yield match
            offset = match_e
        yield txt[offset:]

    text = to_unicode(text, encoding)
    ret_text = u''
    for fragment in _get_fragments(text, _cdata_re):
        if isinstance(fragment, six.string_types):
            # it's not a CDATA (so we try to remove its entities)
            ret_text += replace_entities(fragment, keep=keep, remove_illegal=remove_illegal)
        else:
            # it's a CDATA (so we just extract its content)
            ret_text += fragment.group('cdata_d')
    return ret_text

def get_base_url(text, baseurl='', encoding='utf-8'):
    """Return the base url if declared in the given HTML `text`,
    relative to the given base url.

    If no base url is found, the given `baseurl` is returned.

    """

    text = to_unicode(text, encoding)
    m = _baseurl_re.search(text)
    if m:
        return moves.urllib.parse.urljoin(
            safe_url_string(baseurl),
            safe_url_string(m.group(1), encoding=encoding)
        )
    else:
        return safe_url_string(baseurl)

def get_meta_refresh(text, baseurl='', encoding='utf-8', ignore_tags=('script', 'noscript')):
    """Return  the http-equiv parameter of the HTML meta element from the given
    HTML text and return a tuple ``(interval, url)`` where interval is an integer
    containing the delay in seconds (or zero if not present) and url is a
    string with the absolute url to redirect.

    If no meta redirect is found, ``(None, None)`` is returned.

    """

    if six.PY2:
        baseurl = to_bytes(baseurl, encoding)
    try:
        text = to_unicode(text, encoding)
    except UnicodeDecodeError:
        print(text)
        raise
    text = remove_tags_with_content(text, ignore_tags)
    text = remove_comments(replace_entities(text))
    m = _meta_refresh_re.search(text)
    if m:
        interval = float(m.group('int'))
        url = safe_url_string(m.group('url').strip(' "\''), encoding)
        url = moves.urllib.parse.urljoin(baseurl, url)
        return interval, url
    else:
        return None, None


text:
@interface Fraction : NSObject

@property int numerator,denominator;

-(void) print;                        //instance method
-(double) convertToNum;
-(void) setTo:(int) n over:(int) d;
-(void) add: (Fraction *) bFraction;
-(void) reduce;
-(Fraction *) initWith:(int) n over: (int) d;

@end


text:
#ifndef HEADER_CURL_PRINTF_H
#define HEADER_CURL_PRINTF_H

/*
 * This header should be included by ALL code in libcurl that uses any
 * *rintf() functions.
 */

#include <curl/mprintf.h>

# undef printf
# undef fprintf
# undef msnprintf
# undef vprintf
# undef vfprintf
# undef vsnprintf
# undef aprintf
# undef vaprintf
# define printf curl_mprintf
# define fprintf curl_mfprintf
# define msnprintf curl_msnprintf
# define vprintf curl_mvprintf
# define vfprintf curl_mvfprintf
# define mvsnprintf curl_mvsnprintf
# define aprintf curl_maprintf
# define vaprintf curl_mvaprintf
#endif /* HEADER_CURL_PRINTF_H */


text:
<?php

global $smarty;
global $plantilla;
global $usuario;

if (filter_has_var(INPUT_GET, 'id_entidad')) {
    $id_entidad = filter_input(INPUT_GET, 'id_entidad', FILTER_SANITIZE_NUMBER_INT);
    $entidad = new Entidad();
    $entidad->load("id = $id_entidad");
    $smarty->assign('entidad', $entidad);

    $carta = new Carta();
    $cartas = $carta->Find("id_entidad=$id_entidad ORDER BY fecha DESC");
    $smarty->assign('cartas', $cartas);

    $smarty->assign('_javascript', array('carta_listar'));
    $smarty->assign('_nombre_pagina', TXT_CARTAS_TITULO . ": " . $entidad->nombre);
    $plantilla = 'cartas/carta_listar.tpl';
} else {
    $error = ERR_PARAM;
    header("location:index.php?page=error&error=$error");
}


text:
package org.arquillian.smart.testing.surefire.provider;

import org.junit.Test;

import static org.assertj.core.api.Assertions.assertThat;

public class StringUtilsTest {

    @Test
    public void should_be_false_for_null() {
        // when
        final boolean isNumeric = StringUtils.isNumeric(null);

        // then
        assertThat(isNumeric).isFalse();
    }

    @Test
    public void should_be_false_for_float_string() {
        // when
        final boolean isNumeric = StringUtils.isNumeric("1.23");

        // then
        assertThat(isNumeric).isFalse();
    }

    @Test
    public void should_be_true_for_integer_string() {
        // when
        final boolean isNumeric = StringUtils.isNumeric("10");

        // then
        assertThat(isNumeric).isTrue();
    }

    @Test
    public void should_be_false_for_invalid_string() {
        // when
        final boolean isNumeric = StringUtils.isNumeric("a123");

        // then
        assertThat(isNumeric).isFalse();
    }
}


text:
module Exercises95 where

myEnumFromTo :: (Enum a) => a -> a -> [a]
myEnumFromTo x y
    | xz > yz = []
    | xz == yz = x:[]
    | otherwise = x : myEnumFromTo (succ x) y
            where xz = fromEnum x
                  yz = fromEnum y

eftBool :: Bool -> Bool -> [Bool]
eftBool = myEnumFromTo

eftOrd :: Ordering -> Ordering -> [Ordering]
eftOrd = myEnumFromTo

eftInt :: Int -> Int -> [Int]
eftInt = myEnumFromTo

eftChar :: Char -> Char -> [Char]
eftChar = myEnumFromTo


text:
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.

using IdentityModel;
using IdentityServer4.Extensions;
using IdentityServer4.Models;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Specialized;
using System.Threading.Tasks;

namespace IdentityServer4.Validation
{
    /// <summary>
    /// The token revocation request validator
    /// </summary>
    /// <seealso cref="IdentityServer4.Validation.ITokenRevocationRequestValidator" />
    public class TokenRevocationRequestValidator : ITokenRevocationRequestValidator
    {
        private readonly ILogger _logger;

        /// <summary>
        /// Initializes a new instance of the <see cref="TokenRevocationRequestValidator"/> class.
        /// </summary>
        /// <param name="logger">The logger.</param>
        public TokenRevocationRequestValidator(ILogger<TokenRevocationRequestValidator> logger)
        {
            _logger = logger;
        }

        /// <summary>
        /// Validates the request.
        /// </summary>
        /// <param name="parameters">The parameters.</param>
        /// <param name="client">The client.</param>
        /// <returns></returns>
        /// <exception cref="System.ArgumentNullException">
        /// parameters
        /// or
        /// client
        /// </exception>
        public Task<TokenRevocationRequestValidationResult> ValidateRequestAsync(NameValueCollection parameters, Client client)
        {
            _logger.LogTrace("ValidateRequestAsync called");

            if (parameters == null)
            {
                _logger.LogError("no parameters passed");
                throw new ArgumentNullException(nameof(parameters));
            }

            if (client == null)
            {
                _logger.LogError("no client passed");
                throw new ArgumentNullException(nameof(client));
            }

            ////////////////////////////
            // make sure token is present
            ///////////////////////////
            var token = parameters.Get("token");
            if (token.IsMissing())
            {
                _logger.LogError("No token found in request");
                return Task.FromResult(new TokenRevocationRequestValidationResult
                {
                    IsError = true,
                    Error = OidcConstants.TokenErrors.InvalidRequest
                });
            }

            var result = new TokenRevocationRequestValidationResult
            {
                IsError = false,
                Token = token,
                Client = client
            };

            ////////////////////////////
            // check token type hint
            ///////////////////////////
            var hint = parameters.Get("token_type_hint");
            if (hint.IsPresent())
            {
                if (Constants.SupportedTokenTypeHints.Contains(hint))
                {
                    _logger.LogDebug("Token type hint found in request: {tokenTypeHint}", hint);
                    result.TokenTypeHint = hint;
                }
                else
                {
                    _logger.LogError("Invalid token type hint: {tokenTypeHint}", hint);
                    result.IsError = true;
                    result.Error = Constants.RevocationErrors.UnsupportedTokenType;
                }
            }

            _logger.LogDebug("ValidateRequestAsync result: {validateRequestResult}", result);

            return Task.FromResult(result);
        }
    }
}


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

import static org.junit.Assert.*;

import java.util.Set;

import org.apache.taverna.scufl2.api.core.BlockingControlLink;
import org.apache.taverna.scufl2.api.core.Processor;
import org.apache.taverna.scufl2.api.core.Workflow;
import org.apache.taverna.scufl2.validation.correctness.CorrectnessValidator;
import org.apache.taverna.scufl2.validation.correctness.ReportCorrectnessValidationListener;
import org.apache.taverna.scufl2.validation.correctness.report.NullFieldProblem;
import org.apache.taverna.scufl2.validation.correctness.report.OutOfScopeValueProblem;
import org.junit.Test;

/**
 * @author alanrw
 *
 */
public class TestBlockingControlLink {

	@Test
	public void testCorrectnessOfMissingBlock() {
		BlockingControlLink bcl = new BlockingControlLink();
		Processor untilFinished = new Processor();
		bcl.setUntilFinished(untilFinished);

		CorrectnessValidator cv = new CorrectnessValidator();
		ReportCorrectnessValidationListener rcvl = new ReportCorrectnessValidationListener();

		cv.checkCorrectness(bcl, false, rcvl);
		assertEquals(0, rcvl.getNullFieldProblems().size());

	}

	@Test
	public void testCompletenessOfMissingBlock() {
		BlockingControlLink bcl = new BlockingControlLink();
		Processor untilFinished = new Processor();
		bcl.setUntilFinished(untilFinished);

		CorrectnessValidator cv = new CorrectnessValidator();
		ReportCorrectnessValidationListener rcvl = new ReportCorrectnessValidationListener();

		cv.checkCorrectness(bcl, true, rcvl);
		Set<NullFieldProblem> nullFieldProblems = rcvl.getNullFieldProblems();
		assertEquals(2, rcvl.getNullFieldProblems().size()); // parent and block
		boolean nullFieldProblem = false;
		for (NullFieldProblem nfp : nullFieldProblems) {
			if (nfp.getBean().equals(bcl) && nfp.getFieldName().equals("block")) {
				nullFieldProblem = true;
			}
		}
		assertTrue(nullFieldProblem);
	}

	@Test
	public void testCorrectnessOfMissingUntilFinished() {
		BlockingControlLink bcl = new BlockingControlLink();
		Processor block = new Processor();
		bcl.setBlock(block);

		CorrectnessValidator cv = new CorrectnessValidator();
		ReportCorrectnessValidationListener rcvl = new ReportCorrectnessValidationListener();

		cv.checkCorrectness(bcl, false, rcvl);
		assertEquals(0, rcvl.getNullFieldProblems().size());

	}

	@Test
	public void testCompletenessOfMissingUntilFinished() {
		BlockingControlLink bcl = new BlockingControlLink();
		Processor block = new Processor();
		bcl.setBlock(block);

		CorrectnessValidator cv = new CorrectnessValidator();
		ReportCorrectnessValidationListener rcvl = new ReportCorrectnessValidationListener();

		cv.checkCorrectness(bcl, true, rcvl);
		Set<NullFieldProblem> nullFieldProblems = rcvl.getNullFieldProblems();
		assertEquals(2, rcvl.getNullFieldProblems().size()); // parent and untilFinished
		boolean nullFieldProblem = false;
		for (NullFieldProblem nfp : nullFieldProblems) {
			if (nfp.getBean().equals(bcl) && nfp.getFieldName().equals("untilFinished")) {
				nullFieldProblem = true;
			}
		}
		assertTrue(nullFieldProblem);
	}

	@Test
	public void testWronglyScopedBlock() {
		Workflow wf = new Workflow();
		BlockingControlLink bcl = new BlockingControlLink();
		bcl.setParent(wf);
		Processor block = new Processor();
		Workflow otherWorkflow = new Workflow();
		block.setParent(otherWorkflow);
		bcl.setBlock(block);

		CorrectnessValidator cv = new CorrectnessValidator();
		ReportCorrectnessValidationListener rcvl = new ReportCorrectnessValidationListener();

		cv.checkCorrectness(bcl, false, rcvl);
		Set<OutOfScopeValueProblem> outOfScopeValueProblems = rcvl.getOutOfScopeValueProblems();
		assertEquals(1, outOfScopeValueProblems.size());
		boolean outOfScopeValueProblem = false;
		for (OutOfScopeValueProblem oosvp : outOfScopeValueProblems) {
			if (oosvp.getBean().equals(bcl) && oosvp.getFieldName().equals("block") && oosvp.getValue().equals(block)) {
				outOfScopeValueProblem = true;
			}
		}
		assertTrue(outOfScopeValueProblem);
	}

	@Test
	public void testValidlyScopedBlock() {
		Workflow wf = new Workflow();
		BlockingControlLink bcl = new BlockingControlLink();
		bcl.setParent(wf);
		Processor block = new Processor();
		block.setParent(wf);
		bcl.setBlock(block);

		CorrectnessValidator cv = new CorrectnessValidator();
		ReportCorrectnessValidationListener rcvl = new ReportCorrectnessValidationListener();

		cv.checkCorrectness(bcl, false, rcvl);
		Set<OutOfScopeValueProblem> outOfScopeValueProblems = rcvl.getOutOfScopeValueProblems();
		assertEquals(0, outOfScopeValueProblems.size());
	}
}


text:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <item
        android:title="Shuffle"
        android:id="@+id/action_shuffle"
        android:icon="@drawable/rand"
        android:orderInCategory="1"
        app:showAsAction="ifRoom|always"/>

    <item
        android:id="@+id/action_end"
        android:icon="@drawable/end"
        android:orderInCategory="2"
        app:showAsAction="ifRoom|always"
        android:title="End"/>

</menu>