text:
package com.oregonscientific.meep.store2;

import java.util.ArrayList;

import android.app.DialogFragment;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.oregonscientific.meep.store2.PaymentFragment.UpdateStatusListener;
import com.oregonscientific.meep.store2.adapter.ListAdapterShelf;
import com.oregonscientific.meep.store2.ctrl.AppInstallationCtrl;
import com.oregonscientific.meep.store2.ctrl.EbookCtrl;
import com.oregonscientific.meep.store2.ctrl.RestRequest.PurchaseItemListener;
import com.oregonscientific.meep.store2.ctrl.StoreItemDownloadCtrl;
import com.oregonscientific.meep.store2.global.MeepStoreApplication;
import com.oregonscientific.meep.store2.global.MeepStoreLog;
import com.oregonscientific.meep.store2.object.DownloadStoreItem;
import com.oregonscientific.meep.store2.object.MeepStoreItem;
import com.oregonscientific.meep.store2.object.PurchaseFeedback;

public class DetailFragment extends DialogFragment {

	public static MeepStoreItem getStoreItem() {
		return storeItem;
	}

	public static void setStoreItem(MeepStoreItem item) {
		storeItem = item;
	}

	public static String getPackageNameOfItem()
	{
		String pkgName = null;
		if(storeItem!=null)
		{
			pkgName = storeItem.getPackageName();
		}
		return pkgName;
	}

	private static MeepStoreItem storeItem;
	private String prefix;
	// ListAdapterScreenshot adapter;
	// HorizontalListView listview;
	HorizontalScrollView hs;
	LinearLayout imageList;
	Drawable drawable;
	PaymentFragment paymentFragment;
	PopUpDialogFragment popupFragment;
	ScreenShotFragment shotFragment;
	// ImageThreadLoader imageLoader;
	// ImageThreadLoader imageShotLoader;
	MeepStoreApplication mApp;
	ProgressBar progressBar;
	Button button;
	ArrayList<String> screenShots = new ArrayList<String>();
	AppInstallationCtrl.PakageListener mPackageListener = null;

	private final int NO_NETWORK = 3;
	private final int LOADING = 4;
	private final int TIMEOUT = 5;
	private final int SUCCESS_MESSAGE = 6;
	private final int INSTALLING = 7;
	private final int WAITING = 8;
	private final int DOWNLOADING = 9;
	private final int NOT_ENOUGH_SPACE = 10;
	private final int EBOOK_DOWNLOAD_SUCCESS = 11;
	private final int AWAITING_APPROVAL = 12;
	private final int INSTALL = 14;

	public interface ReloadItem {
		public void reloadAllItems();

		public void updateItemStatus(String action, String packetname, String id);
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setStyle(STYLE_NO_FRAME, android.R.style.Theme_Translucent_NoTitleBar_Fullscreen);
		// prefix = this.getResources().getString(R.string.prefix);
		mApp = (MeepStoreApplication) this.getActivity().getApplicationContext();
		// imageLoader = mApp.getImageLoader();
		// imageShotLoader = mApp.getImageShotLoader();

	}

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

		initStoreItemDownloadListener();
		initPackageListener();
	}

	// @Override
	// public void onStop() {
	// super.onStop();
	//
	// if (mApp.getAppCtrl() != null) {
	// mApp.getAppCtrl().removePackageListener(mPackageListener);
	// }
	// if (mApp.getStoreDownloadCtrl() != null) {
	// mApp.getStoreDownloadCtrl().removeDownloadListeners(mDownloadListener);
	// }
	// }

	public static DetailFragment newInstance(MeepStoreItem storeItem) {
		DetailFragment.storeItem = storeItem;
		DetailFragment myDialogFragment = new DetailFragment();
		return myDialogFragment;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View v = inflater.inflate(R.layout.layout_details, container, false);
		hs = (HorizontalScrollView) v.findViewById(R.id.horizontalScrollView);
		imageList = (LinearLayout) v.findViewById(R.id.imagesLinear);

		TextView name = (TextView) v.findViewById(R.id.textName);
		TextView info = (TextView) v.findViewById(R.id.textInfo);
		TextView size = (TextView) v.findViewById(R.id.textSize);
		TextView description = (TextView) v.findViewById(R.id.description);
		button = (Button) v.findViewById(R.id.button);
		progressBar = (ProgressBar) v.findViewById(R.id.progressBarDownload);
		ImageView recommend = (ImageView) v.findViewById(R.id.recommend);
		final ImageView image;
		final ImageView imageblock;
		View icon;
		boolean isEbook = false;
		if (storeItem.getItemType().equals(MeepStoreItem.TYPE_EBOOK)) {
			isEbook = true;
		}
		// content isnot ebook
		if (!isEbook) {
			icon = v.findViewById(R.id.icon);
			image = (ImageView) v.findViewById(R.id.image);
			imageblock = (ImageView) v.findViewById(R.id.imageblock);

			imageblock.setBackgroundResource(R.drawable.meep_market_description_block);
			mApp.getImageDownloader().download(mApp.getLoginInfo().url_prefix
					+ storeItem.getIconUrl(), 75, 75, image);
			// Bitmap cachedImage = null;
			// try {
			// prefix = mApp.getLoginInfo().url_prefix;
			// cachedImage =
			// imageLoader.loadImage(prefix+storeItem.getIconUrl(), new
			// ImageLoadedListener() {
			// public void imageLoaded(Bitmap imageBitmap) {
			// imageblock.setBackgroundResource(R.drawable.meep_market_description_block);
			// image.setImageBitmap(imageBitmap);
			// //notifyDataSetChanged();
			// }
			// });
			// } catch (MalformedURLException e) {
			// Log.e("APPSTATUS", "Bad remote image URL: " + e.toString());
			// }
			//
			// if( cachedImage != null ) {
			// imageblock.setBackgroundResource(R.drawable.meep_market_description_block);
			// image.setImageBitmap(cachedImage);
			// }else{
			// imageblock.setBackgroundResource(R.drawable.meep_market_description_block_dummy);
			// }
		} else {
			// content is ebook
			icon = v.findViewById(R.id.icon2);
			image = (ImageView) v.findViewById(R.id.imagebook);
			imageblock = (ImageView) v.findViewById(R.id.imageblockbook);

			imageblock.setBackgroundResource(R.drawable.meep_market_book_block);
			mApp.getImageDownloader().download(mApp.getLoginInfo().url_prefix
					+ storeItem.getIconUrl(), 75, 75, image);
			// Bitmap cachedImage = null;
			// try {
			// prefix = mApp.getLoginInfo().url_prefix;
			// cachedImage = imageLoader.loadImage(prefix +
			// storeItem.getIconUrl(),
			// new ImageLoadedListener() {
			// public void imageLoaded(Bitmap imageBitmap) {
			// imageblock.setBackgroundResource(R.drawable.meep_market_book_block);
			// image.setImageBitmap(imageBitmap);
			// // notifyDataSetChanged();
			// }
			// });
			// } catch (MalformedURLException e) {
			// Log.e("APPSTATUS", "Bad remote image URL: " + e.toString());
			// }
			//
			// if (cachedImage != null) {
			// imageblock.setBackgroundResource(R.drawable.meep_market_book_block);
			// image.setImageBitmap(cachedImage);
			// } else {
			// imageblock.setBackgroundResource(R.drawable.meep_market_book_block_dummy);
			// }
		}
		icon.setVisibility(View.VISIBLE);

		// BADGE
		setBadge(storeItem, v, isEbook);
		// common
		name.setText(storeItem.getName());
		info.setText(storeItem.getDeveloper());
		size.setText(storeItem.getSize() + "MB");
		description.setText(storeItem.getDescription());

		// Action
		button.setOnClickListener((new View.OnClickListener() {

			@Override
			public void onClick(View pV) {
				// show detail
				paymentFragment = PaymentFragment.newInstance(storeItem);
				paymentFragment.show(getFragmentManager(), "dialog");
				paymentFragment.setUpdateStatusListener(new UpdateStatusListener() {

					@Override
					public void awaiting() {
						handler.sendEmptyMessage(AWAITING_APPROVAL);
					}

					@Override
					public void waiting() {
						handler.sendEmptyMessage(WAITING);
					}
				});
			}
		}));

		if (storeItem.getItemAction().equals(MeepStoreItem.ACTION_NORMAL)) {
			button.setBackgroundResource(R.drawable.btn_item_description_coins);
			button.setText(Integer.toString(storeItem.getPrice()));
			button.setPadding(100, 0, 0, 0);

		} else if (storeItem.getItemAction().equals(MeepStoreItem.ACTION_FREE)) {
			button.setBackgroundResource(R.drawable.btn_item_description_free);
			button.setText(R.string.free);
			button.setPadding(30, 0, 0, 0);
		} else if (storeItem.getItemAction().equals(MeepStoreItem.ACTION_GET_IT)) {
			button.setBackgroundResource(R.drawable.btn_item_description_get);
			button.setText(R.string.getit);
			button.setPadding(30, 0, 0, 0);

		} else if (storeItem.getItemAction().equals(MeepStoreItem.ACTION_INSTALLED)) {
			showButtonUninstall();
		} else if (storeItem.getItemAction().equals(MeepStoreItem.ACTION_PURCHASED)) {
			if (storeItem.isRecovery()) {
				button.setText(R.string.recover);
			}
			showButtonInstall();

		} else if (storeItem.getItemAction().equals(MeepStoreItem.ACTION_DOWNLOADING)) {
			showProgressBar();
		} else if (storeItem.getItemAction().equals(MeepStoreItem.ACTION_PENDING_TO_DOWNLOAD)) {
			showButtonQueuing();
		} else if (storeItem.getItemAction().equals(MeepStoreItem.ACTION_PENDING)) {
			showButtonAwaitingApproval();
		} else if (storeItem.getItemAction().equals(MeepStoreItem.ACTION_INSTALLING)) {
			showButtonInstalling();
		} else if (storeItem.getItemAction().equals(MeepStoreItem.ACTION_EBOOK_DOWNLOADED)) {
			showButtonSuccess();
		} else if (storeItem.getItemAction().equals(MeepStoreItem.ACTION_BLOCKED)) {
			showTextBlocked();
		} else {
			button.setVisibility(View.GONE);
		}

		// Recommend
		if (storeItem.getRecommends() != null) {
			if (storeItem.getRecommends().equals(MeepStoreItem.RECOMMEND_RECOMMENDS)) {
				recommend.setImageResource(R.drawable.meep_store_gold);
			} else if (storeItem.getRecommends().equals(MeepStoreItem.RECOMMEND_FRIENDLY)) {
				recommend.setImageResource(R.drawable.meep_store_silver);
			} else if (storeItem.getRecommends().equals(MeepStoreItem.RECOMMEND_LIKES)) {
				recommend.setImageResource(R.drawable.meep_store_broze);
			} else {
				recommend.setVisibility(View.INVISIBLE);
			}
		} else {
			recommend.setVisibility(View.INVISIBLE);
		}

		// screenshot
		if (storeItem.getScreenShotUrls() == null
				&& storeItem.getScreenShotUrls().length == 0) {

		} else {
			screenShots.clear();
			for (String url : storeItem.getScreenShotUrls()) {
				screenShots.add(url);
				addFlowChildren(url);
			}
		}

		return v;
	}

	public void popupScreenshot(int index) {
		try {
			if (shotFragment == null) {
				shotFragment = ScreenShotFragment.newInstance(ScreenShotFragment.SCREENSHOT, index, screenShots);
				shotFragment.show(getFragmentManager(), "dialog");
			} else {
				ScreenShotFragment.setPictureIndex(index);
				shotFragment.loadImage();
				shotFragment.show(getFragmentManager(), "dialog");
			}
		} catch (IllegalStateException e) {
			e.printStackTrace();
		}
	}

	public void addFlowChildren(final String url) {

		View view = ((LayoutInflater) this.getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.item_screenshot, null);
		final ImageView image;
		image = (ImageView) view.findViewById(R.id.image);
		mApp.getImageDownloader().download(mApp.getLoginInfo().url_prefix + url, 200, 200, image);
		// mApp.getImageDownloader().download(mApp.getLoginInfo().url_prefix +
		// url, image);

		// Bitmap cachedImage = null;
		// try {
		// prefix = mApp.getLoginInfo().url_prefix;
		// cachedImage = imageShotLoader.loadImage(prefix + url, new
		// ImageLoadedListener() {
		// public void imageLoaded(final Bitmap imageBitmap) {
		// image.setImageBitmap(imageBitmap);
		// MeepStoreLog.logcatMessage("APPSTATUS", "screenshot loaded" + url);
		// notifyDataSetChanged();
		// }
		// });
		// } catch (MalformedURLException e) {
		// Log.e("APPSTATUS", "Bad remote image URL: " + e.toString());
		// }
		// if (cachedImage != null) {
		// image.setImageBitmap(cachedImage);
		// } else {
		// }

		image.setOnClickListener((new View.OnClickListener() {

			@Override
			public void onClick(View pV) {
				popupScreenshot(screenShots.lastIndexOf(url));
			}

		}));

		int w = 196;
		int h = 110;
		// add view and set padding
		LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(w, h);
		lp.setMargins(0, 0, 20, 0);
		imageList.addView(view, lp);

	}

	public void setBadge(MeepStoreItem item, View view, boolean isEbook) {
		ImageView badge;
		// BADGE
		if (!isEbook) {
			badge = (ImageView) view.findViewById(R.id.badge);
		} else {
			badge = (ImageView) view.findViewById(R.id.badgebook);
		}
		if (item.getBadge().equals(MeepStoreItem.BADGE_ACCESSORY)) {
			badge.setImageResource(R.drawable.meep_accessary);
		} else if (item.getBadge().equals(MeepStoreItem.BADGE_BESTSELLER)) {
			badge.setImageResource(R.drawable.meep_bestseller);

		} else if (item.getBadge().equals(MeepStoreItem.BADGE_HOTITEM)) {
			badge.setImageResource(R.drawable.meep_hotitem);

		} else if (item.getBadge().equals(MeepStoreItem.BADGE_SALE)) {
			badge.setImageResource(R.drawable.meep_sale);

		} else if (item.getBadge().equals(MeepStoreItem.BADGE_SDCARD)) {
			badge.setImageResource(R.drawable.meep_sdcard);

		} else {
			badge.setVisibility(View.GONE);
		}
	}

	public Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			try {
				switch (msg.what) {
				case EBOOK_DOWNLOAD_SUCCESS:
					showButtonSuccess();
					break;
				case NO_NETWORK:
					popupFragment = PopUpDialogFragment.newInstance(PopUpDialogFragment.NO_NETWORK);
					if (getFragmentManager() != null)
						popupFragment.show(getFragmentManager(), "dialog");
					break;
				case LOADING:
					popupFragment = PopUpDialogFragment.newInstance(PopUpDialogFragment.LOADING);
					if (getFragmentManager() != null)
						popupFragment.show(getFragmentManager(), "dialog");
					break;
				case TIMEOUT:
					popupFragment = PopUpDialogFragment.newInstance(PopUpDialogFragment.TIMEOUT);
					if (getFragmentManager() != null)
						popupFragment.show(getFragmentManager(), "dialog");
					break;
				case SUCCESS_MESSAGE:
					popupFragment = PopUpDialogFragment.newInstance(PopUpDialogFragment.COMMON_MESSAGE);
					if (getFragmentManager() != null)
						popupFragment.show(getFragmentManager(), "dialog");
					break;
				case INSTALLING:
					showButtonInstalling();
					break;
				case WAITING:
					showButtonQueuing();
					break;
				case DOWNLOADING:
					showProgressBar();
					break;
				case AWAITING_APPROVAL:
					showButtonAwaitingApproval();
					break;
				case NOT_ENOUGH_SPACE:
					popupFragment = PopUpDialogFragment.newInstance(PopUpDialogFragment.NOT_ENOUGH_SPACE);
					if (getFragmentManager() != null)
						popupFragment.show(getFragmentManager(), "dialog");
					break;
				case INSTALL:
					showButtonInstall();
					break;
				default:
					break;
				}
			} catch (Exception e) {
				MeepStoreLog.logcatMessage("test", "parent/current fragment has been closed");
			}
		}

	};

	public Handler getHandler() {
		return handler;
	}

	public void showProgressBar() {
		progressBar.setVisibility(View.VISIBLE);
		button.setVisibility(View.GONE);
		updateShelf(MeepStoreItem.ACTION_DOWNLOADING, storeItem.getPackageName(), storeItem.getItemId());
	}

	public void showUnclickableButton() {
		progressBar.setVisibility(View.GONE);
		button.setVisibility(View.VISIBLE);
		button.setPadding(0, 0, 0, 0);
		button.setClickable(false);
		button.setBackgroundColor(Color.TRANSPARENT);
	}

	public void showCommonButton() {
		progressBar.setVisibility(View.GONE);
		button.setVisibility(View.VISIBLE);
		button.setPadding(0, 0, 0, 0);
		button.setBackgroundResource(R.drawable.btn_item_description_blank);
	}

	public void showButtonInstalling() {
		showUnclickableButton();
		button.setText(R.string.installing);
		updateShelf(MeepStoreItem.ACTION_INSTALLING, storeItem.getPackageName(), storeItem.getItemId());
	}

	public void showButtonQueuing() {
		showUnclickableButton();
		button.setText(R.string.queuing_for_downloading);
		updateShelf(MeepStoreItem.ACTION_PENDING_TO_DOWNLOAD, storeItem.getPackageName(), storeItem.getItemId());
	}

	public void showButtonAwaitingApproval() {
		showUnclickableButton();
		button.setText(R.string.awaiting);
		updateShelf(MeepStoreItem.ACTION_PENDING, storeItem.getPackageName(), storeItem.getItemId());
	}

	public void showButtonSuccess() {
		// showUnclickableButton();
		// button.setText(R.string.ebook_success);
		showCommonButton();
		button.setText(R.string.uninstall2);
		button.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				EbookCtrl.removeEbook(storeItem);
				storeItem.setItemAction(MeepStoreItem.ACTION_PURCHASED);
				showButtonInstall();
				updateShelf(MeepStoreItem.ACTION_PURCHASED, storeItem.getPackageName(), storeItem.getItemId());
			}
		});
		updateShelf(MeepStoreItem.ACTION_EBOOK_DOWNLOADED, storeItem.getPackageName(), storeItem.getItemId());
	}

	public void updateShelf(String action, String packageName, String id) {
		if (getActivity() instanceof GenericStoreActivity) {
			try {
				((GenericStoreActivity) getActivity()).updateItemStatus(action, packageName, id);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	public void showButtonInstall() {
		if (button != null) {
			showCommonButton();
			button.setText(R.string.install);
			button.setOnClickListener((new View.OnClickListener() {

				@Override
				public void onClick(View pV) {
					if (mApp.isNetworkAvailable(getActivity())) {
						// loading
						handler.sendEmptyMessage(LOADING);
						pV.setEnabled(false);
						mApp.getRestRequest().purchaseStoreItem(storeItem.getItemId(), mApp.getUserToken());
						mApp.getRestRequest().setPurchaseItemListener(new PurchaseItemListener() {

							@Override
							public void onPurchaseReceived(
									PurchaseFeedback feedback) {
								if (popupFragment != null) {
									popupFragment.dismiss();
								}
								if (feedback != null) {
									switch (feedback.getCode()) {
									case 200:
										if (feedback.getUrl() != null) {
											DownloadStoreItem downloadItem = new DownloadStoreItem(feedback.getItem_id(), feedback.getName(), feedback.getType(), feedback.getImage(), feedback.getUrl(), "", feedback.getPackage_name());
											mApp.getStoreDownloadCtrl().addStoreDownloadItem(downloadItem);
										}
										if (mApp.isItemDownloading(storeItem.getItemId())) {
											storeItem.setItemAction(MeepStoreItem.ACTION_DOWNLOADING);
											showProgressBar();
										} else {
											storeItem.setItemAction(MeepStoreItem.ACTION_PENDING_TO_DOWNLOAD);
											showButtonQueuing();
										}
										break;
									case 999:
										handler.sendEmptyMessage(TIMEOUT);
										break;
									default:
										break;
									}
									button.setEnabled(true);
								} else {
									handler.sendEmptyMessage(TIMEOUT);
								}
								button.setEnabled(true);
							}
						});
					} else {
						// no network
						handler.sendEmptyMessage(NO_NETWORK);
					}
				}
			}));
		}

	}

	public void showButtonUninstall() {
		showCommonButton();
		button.setText(R.string.uninstall);
		button.setOnClickListener((new View.OnClickListener() {

			@Override
			public void onClick(View pV) {
				AppInstallationCtrl.uninstallApp(getActivity(), storeItem.getPackageName());
			}
		}));
	}
	public void showTextBlocked() {
		showUnclickableButton();
		button.setTextSize(20);
		button.setGravity(Gravity.LEFT);
		button.setText(R.string.not_allow_to_downlaod);
	}

	StoreItemDownloadCtrl.DownloadListener mDownloadListener = null;

	private void initStoreItemDownloadListener() {
		mDownloadListener = new StoreItemDownloadCtrl.DownloadListener() {

			@Override
			public void onDownloadProgress(String id, int percentage) {
				updateDownloadStatus(id, percentage);
			}

			@Override
			public void onDownloadCompleted(boolean downloadAborted,
					DownloadStoreItem item) {
				if (!downloadAborted)
					updateDownloadCompleted(item);
				else {
					handler.sendEmptyMessage(INSTALL);
				}
			}

			@Override
			public void onNoSpace() {
				handler.sendEmptyMessage(NOT_ENOUGH_SPACE);

			}
		};
		mApp.getStoreDownloadCtrl().addDownloadListeners(mDownloadListener);
	}

	private void updateDownloadStatus(String id, int progress) {
		MeepStoreLog.logcatMessage("APPSTATUS", "id:" + id + ",progress:" + progress);
		if (storeItem.getItemId().equals(id)) {
			// show progressbar
			handler.sendEmptyMessage(DOWNLOADING);
			if (!storeItem.getItemAction().equals(MeepStoreItem.ACTION_DOWNLOADING)) {
				storeItem.setItemAction(MeepStoreItem.ACTION_DOWNLOADING);
				// updateShelf(MeepStoreItem.ACTION_DOWNLOADING, null, id
				// ,progress);
			}
			storeItem.setProgress(progress);
			if (progressBar != null) {
				progressBar.setProgress(progress);
			}
		}
		// else
		// {
		//
		// if(progress ==1)
		// {
		// updateShelf(MeepStoreItem.ACTION_DOWNLOADING, null, id,progress);
		// }
		// }
	}

	private void updateDownloadCompleted(DownloadStoreItem item) {
		String id = item.getId();
		String type = item.getType();
		MeepStoreLog.logcatMessage("APPSTATUS", "complete id:" + id);
		if (storeItem.getItemId().equals(id)) {
			if (progressBar != null) {
				progressBar.setProgress(100);
			}
			handler.sendEmptyMessage(INSTALLING);
			if (type != null) {
				if (type.equals(MeepStoreItem.TYPE_EBOOK)) {
					storeItem.setItemAction(MeepStoreItem.ACTION_EBOOK_DOWNLOADED);
					handler.sendEmptyMessage(EBOOK_DOWNLOAD_SUCCESS);
					// updateShelf(MeepStoreItem.ACTION_EBOOK_DOWNLOADED, null,
					// id,-1);
				} else {
					storeItem.setItemAction(MeepStoreItem.ACTION_INSTALLING);
					// updateShelf(MeepStoreItem.ACTION_INSTALLING, null,
					// id,100);
				}
			}
		}
	}

	public void initPackageListener() {
		mPackageListener = new AppInstallationCtrl.PakageListener() {

			@Override
			public void onpackageReplaced(String packageName) {
				// AppInstallationCtrl.removeApk(packageName);
				// TODO Auto-generated method stub
				MeepStoreLog.logcatMessage("storedownload", "package replace 2");
				MeepStoreLog.logcatMessage("APPSTATUS", "replace app " + packageName);
			}

			@Override
			public void onpackageRemoved(String packageName) {
				// TODO Auto-generated method stub
				MeepStoreLog.logcatMessage("storedownload", "package remove 2");
				MeepStoreLog.logcatMessage("APPSTATUS", "remove app " + packageName);
				if (storeItem != null && packageName != null) {
					if (packageName.equals(storeItem.getPackageName())) {
						storeItem.setItemAction(MeepStoreItem.ACTION_PURCHASED);
						if (storeItem.isRecovery() && button != null) {
							button.setText(R.string.recover);
						}
						showButtonInstall();
					}
				}
				// updateShelf(MeepStoreItem.ACTION_PURCHASED,packageName,null,-1);
			}

			@Override
			public void onpackageAdded(String packageName) {
				// AppInstallationCtrl.removeApk(packageName);
				MeepStoreLog.logcatMessage("storedownload", "package add 2");
				// TODO Auto-generated method stub
				MeepStoreLog.logcatMessage("APPSTATUS", "add app " + packageName);
				if (storeItem != null && packageName != null) {
					if (packageName.equals(storeItem.getPackageName())) {
						storeItem.setItemAction(MeepStoreItem.ACTION_INSTALLED);
						showButtonUninstall();
					}
				}
				// updateShelf(MeepStoreItem.ACTION_INSTALLED,packageName,null,-1);
			}
		};
		MeepStoreLog.logcatMessage("AppCtrl", "detail");
		mApp.getAppCtrl().addPackageListener(mPackageListener);
	}

	@Override
	public void onDismiss(DialogInterface dialog) {
		// TODO Auto-generated method stub
		try {
			if (getActivity() instanceof GenericStoreActivity) {
				ListAdapterShelf listAdapterShelf = ((GenericStoreActivity) getActivity()).getShelfListAdapter();
				listAdapterShelf.enableItemButton();
			}
			super.onDismiss(dialog);
		} catch (Exception e) {
			MeepStoreLog.LogMsg("current activity has been closed");
		}
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		MeepStoreLog.logcatMessage("AppCtrl", "remove detail");
		if (mApp.getAppCtrl() != null) {
			mApp.getAppCtrl().removePackageListener(mPackageListener);
		}
		if (mApp.getStoreDownloadCtrl() != null) {
			mApp.getStoreDownloadCtrl().removeDownloadListeners(mDownloadListener);
		}
	}

}


text:
/* *
 *
 *  !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
 *
 * */
'use strict';
import Point from '../Core/Series/Point.js';
import Series from '../Core/Series/Series.js';
import U from '../Core/Utilities.js';
var defined = U.defined, extend = U.extend, find = U.find, pick = U.pick;
/* *
 *
 *  Composition
 *
 * */
var NodesComposition;
(function (NodesComposition) {
    /* *
     *
     *  Declarations
     *
     * */
    /* *
     *
     *  Constants
     *
     * */
    var composedClasses = [];
    /* *
     *
     *  Functions
     *
     * */
    /* eslint-disable valid-jsdoc */
    /**
     * @private
     */
    function compose(PointClass, SeriesClass) {
        if (composedClasses.indexOf(PointClass) === -1) {
            composedClasses.push(PointClass);
            var pointProto = PointClass.prototype;
            pointProto.setNodeState = setNodeState;
            pointProto.setState = setNodeState;
        }
        if (composedClasses.indexOf(SeriesClass) === -1) {
            composedClasses.push(SeriesClass);
            var seriesProto = SeriesClass.prototype;
            seriesProto.destroy = destroy;
            seriesProto.setData = setData;
        }
        return SeriesClass;
    }
    NodesComposition.compose = compose;
    /**
     * Create a single node that holds information on incoming and outgoing
     * links.
     * @private
     */
    function createNode(id) {
        var PointClass = this.pointClass, findById = function (nodes, id) { return find(nodes, function (node) { return node.id === id; }); };
        var node = findById(this.nodes, id), options;
        if (!node) {
            options = this.options.nodes && findById(this.options.nodes, id);
            node = (new PointClass()).init(this, extend({
                className: 'highcharts-node',
                isNode: true,
                id: id,
                y: 1 // Pass isNull test
            }, options));
            node.linksTo = [];
            node.linksFrom = [];
            node.formatPrefix = 'node';
            // for use in formats
            node.name = node.name || node.options.id || '';
            // Mass is used in networkgraph:
            node.mass = pick(
            // Node:
            node.options.mass, node.options.marker && node.options.marker.radius,
            // Series:
            this.options.marker && this.options.marker.radius,
            // Default:
            4);
            /**
             * Return the largest sum of either the incoming or outgoing links.
             * @private
             */
            node.getSum = function () {
                var sumTo = 0, sumFrom = 0;
                node.linksTo.forEach(function (link) {
                    sumTo += link.weight;
                });
                node.linksFrom.forEach(function (link) {
                    sumFrom += link.weight;
                });
                return Math.max(sumTo, sumFrom);
            };
            /**
             * Get the offset in weight values of a point/link.
             * @private
             */
            node.offset = function (point, coll) {
                var offset = 0;
                for (var i = 0; i < node[coll].length; i++) {
                    if (node[coll][i] === point) {
                        return offset;
                    }
                    offset += node[coll][i].weight;
                }
            };
            // Return true if the node has a shape, otherwise all links are
            // outgoing.
            node.hasShape = function () {
                var outgoing = 0;
                node.linksTo.forEach(function (link) {
                    if (link.outgoing) {
                        outgoing++;
                    }
                });
                return (!node.linksTo.length ||
                    outgoing !== node.linksTo.length);
            };
            this.nodes.push(node);
        }
        return node;
    }
    NodesComposition.createNode = createNode;
    /**
     * Destroy alll nodes and links.
     * @private
     */
    function destroy() {
        // Nodes must also be destroyed (#8682, #9300)
        this.data = []
            .concat(this.points || [], this.nodes);
        return Series.prototype.destroy.apply(this, arguments);
    }
    NodesComposition.destroy = destroy;
    /**
     * Extend generatePoints by adding the nodes, which are Point objects
     * but pushed to the this.nodes array.
     */
    function generatePoints() {
        var chart = this.chart, nodeLookup = {};
        Series.prototype.generatePoints.call(this);
        if (!this.nodes) {
            this.nodes = []; // List of Point-like node items
        }
        this.colorCounter = 0;
        // Reset links from previous run
        this.nodes.forEach(function (node) {
            node.linksFrom.length = 0;
            node.linksTo.length = 0;
            node.level = node.options.level;
        });
        // Create the node list and set up links
        this.points.forEach(function (point) {
            if (defined(point.from)) {
                if (!nodeLookup[point.from]) {
                    nodeLookup[point.from] = this.createNode(point.from);
                }
                nodeLookup[point.from].linksFrom.push(point);
                point.fromNode = nodeLookup[point.from];
                // Point color defaults to the fromNode's color
                if (chart.styledMode) {
                    point.colorIndex = pick(point.options.colorIndex, nodeLookup[point.from].colorIndex);
                }
                else {
                    point.color =
                        point.options.color || nodeLookup[point.from].color;
                }
            }
            if (defined(point.to)) {
                if (!nodeLookup[point.to]) {
                    nodeLookup[point.to] = this.createNode(point.to);
                }
                nodeLookup[point.to].linksTo.push(point);
                point.toNode = nodeLookup[point.to];
            }
            point.name = point.name || point.id; // for use in formats
        }, this);
        // Store lookup table for later use
        this.nodeLookup = nodeLookup;
    }
    NodesComposition.generatePoints = generatePoints;
    /**
     * Destroy all nodes on setting new data
     * @private
     */
    function setData() {
        if (this.nodes) {
            this.nodes.forEach(function (node) {
                node.destroy();
            });
            this.nodes.length = 0;
        }
        Series.prototype.setData.apply(this, arguments);
    }
    /**
     * When hovering node, highlight all connected links. When hovering a link,
     * highlight all connected nodes.
     */
    function setNodeState(state) {
        var args = arguments, others = this.isNode ? this.linksTo.concat(this.linksFrom) :
            [this.fromNode, this.toNode];
        if (state !== 'select') {
            others.forEach(function (linkOrNode) {
                if (linkOrNode && linkOrNode.series) {
                    Point.prototype.setState.apply(linkOrNode, args);
                    if (!linkOrNode.isNode) {
                        if (linkOrNode.fromNode.graphic) {
                            Point.prototype.setState.apply(linkOrNode.fromNode, args);
                        }
                        if (linkOrNode.toNode && linkOrNode.toNode.graphic) {
                            Point.prototype.setState.apply(linkOrNode.toNode, args);
                        }
                    }
                }
            });
        }
        Point.prototype.setState.apply(this, args);
    }
    NodesComposition.setNodeState = setNodeState;
})(NodesComposition || (NodesComposition = {}));
/* *
 *
 *  Default Export
 *
 * */
export default NodesComposition;

redpajama_set_name: RedPajamaGithub


text:
<?php
/**
 * Piwik - free/libre analytics platform
 *
 * @link http://piwik.org
 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
 */

namespace Piwik;

/**
 * Exception thrown when the requested plugin is not activated in the config file
 */
class PluginDeactivatedException extends \Exception
{
    public function __construct($module)
    {
        parent::__construct("The plugin $module is not enabled. You can activate the plugin on Settings > Plugins page in Piwik.");
    }
}


text:
<?php

namespace Oro\Bundle\SearchBundle\Engine;

use Oro\Bundle\SearchBundle\Provider\SearchMappingProvider;
use Oro\Bundle\SearchBundle\Query\Mode;
use Oro\Bundle\SearchBundle\Query\Query;
use Symfony\Component\PropertyAccess\PropertyAccessorInterface;

/**
 * Mapping index data from entities' data - common code.
 */
abstract class AbstractMapper
{
    /** @var SearchMappingProvider */
    protected $mappingProvider;

    /** @var PropertyAccessorInterface */
    protected $propertyAccessor;

    /**
     * @param SearchMappingProvider $mappingProvider
     * @param PropertyAccessorInterface $propertyAccessor
     */
    public function __construct(
        SearchMappingProvider $mappingProvider,
        PropertyAccessorInterface $propertyAccessor
    ) {
        $this->mappingProvider = $mappingProvider;
        $this->propertyAccessor = $propertyAccessor;
    }

    /**
     * Get object field value
     *
     * @param object|array $objectOrArray
     * @param string       $fieldName
     *
     * @return mixed
     */
    public function getFieldValue($objectOrArray, $fieldName)
    {
        if (is_object($objectOrArray)) {
            $getter = sprintf('get%s', $fieldName);
            if (method_exists($objectOrArray, $getter)) {
                return $objectOrArray->$getter();
            }
        }

        try {
            return $this->propertyAccessor->getValue($objectOrArray, $fieldName);
        } catch (\Exception $e) {
            return null;
        }
    }

    /**
     * Get mapping parameter for entity
     *
     * @param string $entity
     * @param string $parameter
     * @param mixed  $defaultValue
     *
     * @return mixed
     */
    public function getEntityMapParameter($entity, $parameter, $defaultValue = false)
    {
        return $this->mappingProvider->getEntityMapParameter($entity, $parameter, $defaultValue);
    }

    /**
     * Get mapping config for entity
     *
     * @param string $entity
     *
     * @return array
     */
    public function getEntityConfig($entity)
    {
        return $this->mappingProvider->getEntityConfig($entity);
    }

    /**
     * Returns mode attribute from entity mapping config
     *
     * @param string $entity
     *
     * @return bool|string
     */
    public function getEntityModeConfig($entity)
    {
        $config = $this->getEntityConfig($entity);
        $value  = Mode::NORMAL;

        if ($config) {
            $value = $config['mode'];
        }

        return $value;
    }

    /**
     * Set value for meta fields by type
     *
     * @param string $alias
     * @param array  $objectData
     * @param array  $fieldConfig
     * @param mixed  $value
     * @param bool   $isArray
     *
     * @return array
     */
    protected function setDataValue($alias, $objectData, $fieldConfig, $value, $isArray = false)
    {
        if ($value) {
            //check if field have target_fields parameter
            $targetFields = isset($fieldConfig['target_fields'])
                ? $fieldConfig['target_fields']
                : [$fieldConfig['name']];

            if ($fieldConfig['target_type'] != Query::TYPE_TEXT) {
                foreach ($targetFields as $targetField) {
                    if ($isArray) {
                        $objectData[$fieldConfig['target_type']][$targetField][] = $value;
                    } else {
                        $objectData[$fieldConfig['target_type']][$targetField] = $value;
                    }
                }
            } else {
                foreach ($targetFields as $targetField) {
                    if (!isset($objectData[$fieldConfig['target_type']][$targetField])) {
                        $objectData[$fieldConfig['target_type']][$targetField] = '';
                    }

                    $objectData[$fieldConfig['target_type']][$targetField] .= sprintf(' %s ', $value);
                }

                $objectData[$fieldConfig['target_type']] = array_map('trim', $objectData[$fieldConfig['target_type']]);
            }
        }

        return $objectData;
    }

    /**
     * @param string $fieldName
     * @param mixed $value
     * @return string
     */
    abstract protected function clearTextValue($fieldName, $value);

    /**
     * @param string $original
     * @param string $addition
     * @return string
     */
    public function buildAllDataField($original, $addition)
    {
        $addition = $this->clearTextValue(Indexer::TEXT_ALL_DATA_FIELD, $addition);
        $clearedAddition = Query::clearString($addition);

        $original .= sprintf(' %s %s ', $addition, $clearedAddition);
        $original = implode(
            Query::DELIMITER,
            array_unique(
                explode(
                    Query::DELIMITER,
                    $original
                )
            )
        );

        return trim($original);
    }

    /**
     * Fills "all_text" virtual field with data.
     *
     * @param array $objectData
     *
     * @return array
     */
    protected function generateAllTextField(array $objectData): array
    {
        if (empty($objectData[Query::TYPE_TEXT])) {
            return $objectData;
        }

        // "all_text" field might already exist if added by 'oro_search.prepare_entity_map' listeners.
        $textAllDataField = $objectData[Query::TYPE_TEXT][Indexer::TEXT_ALL_DATA_FIELD] ?? '';

        foreach ($objectData[Query::TYPE_TEXT] as $fieldName => $value) {
            if ($fieldName === Indexer::TEXT_ALL_DATA_FIELD) {
                continue;
            }

            $textAllDataField = $this->buildAllDataField($textAllDataField, $value);
        }

        $objectData[Query::TYPE_TEXT][Indexer::TEXT_ALL_DATA_FIELD] = $textAllDataField;

        return $objectData;
    }
}


text:
<?php

namespace Oro\Bundle\EmailBundle\Tests\Unit\Validator;

use Oro\Bundle\EmailBundle\Form\Model\Email;
use Oro\Bundle\EmailBundle\Validator\Constraints\EmailRecipients;
use Oro\Bundle\EmailBundle\Validator\EmailRecipientsValidator;

class EmailRecipientsValidatorTest extends \PHPUnit_Framework_TestCase
{
    /** @var EmailRecipients */
    protected $constraint;

    /** @var \PHPUnit_Framework_MockObject_MockObject */
    protected $context;

    protected function setUp()
    {
        $this->constraint = new EmailRecipients();
        $this->context = $this->getMock('Symfony\Component\Validator\ExecutionContextInterface');
    }

    public function testValidateNoErrors()
    {
        $this->context->expects($this->never())
            ->method('addViolation');
        $email = new Email();
        $email->setTo(['test1@mail.com'])
            ->setCc(['test2@mail.com'])
            ->setBcc(['test3@mail.com']);
        $this->getValidator()->validate($email, $this->constraint);
    }

    public function testValidateWithErrors()
    {
        $this->context->expects($this->once())
            ->method('addViolation')
            ->with($this->constraint->message);
        $email = new Email();
        $this->getValidator()->validate($email, $this->constraint);
    }

    /**
     * @return EmailRecipientsValidator
     */
    protected function getValidator()
    {
        $validator = new EmailRecipientsValidator();
        $validator->initialize($this->context);
        return $validator;
    }
}


text:
virtualenv venv
source venv/bin/activate
pip install mezzanine
mezzanine-project myproject
cd myproject
python manage.py createdb
python manage.py runserver


text:
package com.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Encrypt {

    public static String MD5 = "MD5";

    private static String toHexadecimal(byte[] digest){
        String hash = "";
        for(int i=0; i<digest.length; i++) {
            byte aux = digest[i];
            int b = aux & 0xff;
            if (Integer.toHexString(b).length() == 1) hash += "0";
            hash += Integer.toHexString(b);
        }
        return hash;
    }
    public static String getStringMessageDigest(String message, String algorithm){
        byte[] digest = null;
        byte[] buffer = message.getBytes();
        try {
            MessageDigest messageDigest = MessageDigest.getInstance(algorithm);
            messageDigest.reset();
            messageDigest.update(buffer);
            digest = messageDigest.digest();
        } catch (NoSuchAlgorithmException ex) {
            System.out.println("Error creando Digest");
        }
        return toHexadecimal(digest);
    }

    public static void main(String[] args) {
        Encrypt StringMD=new Encrypt();
        String mensaje = "1234";
        System.out.println("Mensaje = " + mensaje);
        System.out.println("MD5 = " + StringMD.getStringMessageDigest(mensaje, StringMD.MD5));

    }

}


text:
namespace Imgur.API.Enums
{
    /// <summary>
    ///     The order that the gallery should be sorted by.
    /// </summary>
    public enum CustomGallerySortOrder
    {
        /// <summary>
        ///     Sort the gallery by the most viral item first.
        /// </summary>
        Viral,

        /// <summary>
        ///     Sort the gallery by the most recent item first.
        /// </summary>
        Time,

        /// <summary>
        ///     Sort the gallery by the most top rated item in a period first.
        /// </summary>
        Top
    }
}


text:
package com.justplay1.shoppist.entity.mappers;

import com.justplay1.shoppist.entity.CategoryDAO;
import com.justplay1.shoppist.entity.CurrencyDAO;
import com.justplay1.shoppist.entity.ListItemDAO;
import com.justplay1.shoppist.entity.UnitDAO;
import com.justplay1.shoppist.models.CategoryModel;
import com.justplay1.shoppist.models.CurrencyModel;
import com.justplay1.shoppist.models.ListItemModel;
import com.justplay1.shoppist.models.UnitModel;

import org.junit.Before;
import org.junit.Test;

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

import static com.justplay1.shoppist.entity.DAOUtil.FAKE_ID;
import static com.justplay1.shoppist.entity.DAOUtil.FAKE_NAME;
import static com.justplay1.shoppist.entity.DAOUtil.FAKE_NOTE;
import static com.justplay1.shoppist.entity.DAOUtil.FAKE_PARENT_LIST_ID;
import static com.justplay1.shoppist.entity.DAOUtil.FAKE_PRICE;
import static com.justplay1.shoppist.entity.DAOUtil.FAKE_PRIORITY;
import static com.justplay1.shoppist.entity.DAOUtil.FAKE_QUANTITY;
import static com.justplay1.shoppist.entity.DAOUtil.FAKE_STATUS;
import static com.justplay1.shoppist.entity.DAOUtil.FAKE_TIME_CREATED;
import static com.justplay1.shoppist.entity.DAOUtil.createFakeCategoryDAO;
import static com.justplay1.shoppist.entity.DAOUtil.createFakeCategoryModel;
import static com.justplay1.shoppist.entity.DAOUtil.createFakeCurrencyDAO;
import static com.justplay1.shoppist.entity.DAOUtil.createFakeCurrencyModel;
import static com.justplay1.shoppist.entity.DAOUtil.createFakeListItemDAO;
import static com.justplay1.shoppist.entity.DAOUtil.createFakeListItemModel;
import static com.justplay1.shoppist.entity.DAOUtil.createFakeUnitDAO;
import static com.justplay1.shoppist.entity.DAOUtil.createFakeUnitModel;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;

/**
 * Created by Mkhytar Mkhoian.
 */
public class ListItemsDAODataMapperTest {

    private UnitsDAODataMapper unitsDAODataMapper;
    private CategoryDAODataMapper categoryDAODataMapper;
    private CurrencyDAODataMapper currencyDAODataMapper;
    private ListItemsDAODataMapper dataMapper;

    @Before
    public void setUp() throws Exception {
        unitsDAODataMapper = new UnitsDAODataMapper();
        categoryDAODataMapper = new CategoryDAODataMapper();
        currencyDAODataMapper = new CurrencyDAODataMapper();
        dataMapper = new ListItemsDAODataMapper(categoryDAODataMapper, currencyDAODataMapper, unitsDAODataMapper);
    }

    @Test
    public void transformListItemsDAO() {
        CategoryDAO categoryDAO = createFakeCategoryDAO();
        UnitDAO unitDAO = createFakeUnitDAO();
        CurrencyDAO currencyDAO = createFakeCurrencyDAO();

        CategoryModel categoryModel = categoryDAODataMapper.transformFromDAO(categoryDAO);
        UnitModel unitModel = unitsDAODataMapper.transformFromDAO(unitDAO);
        CurrencyModel currencyModel = currencyDAODataMapper.transformFromDAO(currencyDAO);
        ListItemDAO listItemDAO = createFakeListItemDAO(categoryDAO, unitDAO, currencyDAO);

        ListItemModel listItemModel = dataMapper.transformFromDAO(listItemDAO);

        assertThat(listItemModel, is(instanceOf(ListItemModel.class)));
        assertThat(listItemModel.getId(), is(FAKE_ID));
        assertThat(listItemModel.getName(), is(FAKE_NAME));
        assertThat(listItemModel.getTimeCreated(), is(FAKE_TIME_CREATED));
        assertThat(listItemModel.getNote(), is(FAKE_NOTE));
        assertThat(listItemModel.getParentListId(), is(FAKE_PARENT_LIST_ID));
        assertThat(listItemModel.getPrice(), is(FAKE_PRICE));
        assertThat(listItemModel.getPriority(), is(FAKE_PRIORITY));
        assertThat(listItemModel.getQuantity(), is(FAKE_QUANTITY));
        assertThat(listItemModel.getStatus(), is(FAKE_STATUS));
        assertThat(listItemModel.getCategory(), is(categoryModel));
        assertThat(listItemModel.getUnit(), is(unitModel));
        assertThat(listItemModel.getCurrency(), is(currencyModel));
    }

    @Test
    public void transformListItemsDAOCollection() {
        ListItemDAO mockDAOOne = mock(ListItemDAO.class);
        ListItemDAO mockDAOTwo = mock(ListItemDAO.class);

        List<ListItemDAO> list = new ArrayList<>(5);
        list.add(mockDAOOne);
        list.add(mockDAOTwo);

        Collection<ListItemModel> collection = dataMapper.transformFromDAO(list);

        assertThat(collection.toArray()[0], is(instanceOf(ListItemModel.class)));
        assertThat(collection.toArray()[1], is(instanceOf(ListItemModel.class)));
        assertThat(collection.size(), is(2));
    }

    @Test
    public void transformListItemModel() {
        CategoryModel categoryModel = createFakeCategoryModel();
        UnitModel unitModel = createFakeUnitModel();
        CurrencyModel currencyModel = createFakeCurrencyModel();

        CategoryDAO categoryDAO = categoryDAODataMapper.transformToDAO(categoryModel);
        UnitDAO unitDAO = unitsDAODataMapper.transformToDAO(unitModel);
        CurrencyDAO currencyDAO = currencyDAODataMapper.transformToDAO(currencyModel);

        ListItemModel listItemModel = createFakeListItemModel(categoryModel, unitModel, currencyModel);

        ListItemDAO listItemDAO = dataMapper.transformToDAO(listItemModel);

        assertThat(listItemDAO, is(instanceOf(ListItemDAO.class)));
        assertThat(listItemDAO.getId(), is(FAKE_ID));
        assertThat(listItemDAO.getName(), is(FAKE_NAME));
        assertThat(listItemDAO.getTimeCreated(), is(FAKE_TIME_CREATED));
        assertThat(listItemDAO.getNote(), is(FAKE_NOTE));
        assertThat(listItemDAO.getParentListId(), is(FAKE_PARENT_LIST_ID));
        assertThat(listItemDAO.getPrice(), is(FAKE_PRICE));
        assertThat(listItemDAO.getPriority(), is(FAKE_PRIORITY));
        assertThat(listItemDAO.getQuantity(), is(FAKE_QUANTITY));
        assertThat(listItemDAO.getStatus(), is(FAKE_STATUS));
        assertThat(listItemDAO.getCategory(), is(categoryDAO));
        assertThat(listItemDAO.getUnit(), is(unitDAO));
        assertThat(listItemDAO.getCurrency(), is(currencyDAO));
    }

    @Test
    public void transformListItemModelCollection() {
        ListItemModel mockModelOne = mock(ListItemModel.class);
        ListItemModel mockModelTwo = mock(ListItemModel.class);

        List<ListItemModel> list = new ArrayList<>(5);
        list.add(mockModelOne);
        list.add(mockModelTwo);

        Collection<ListItemDAO> collection = dataMapper.transformToDAO(list);

        assertThat(collection.toArray()[0], is(instanceOf(ListItemDAO.class)));
        assertThat(collection.toArray()[1], is(instanceOf(ListItemDAO.class)));
        assertThat(collection.size(), is(2));
    }
}


text:
var express = require('express'),
    routes = require('./routes'),
    http = require('http'),
    path = require('path');

var app = express();

// Configurations
app.configure(function(){
  app.set('port', process.env.PORT || 3000);
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
  app.use(express.favicon(path.join(__dirname, 'public','images','favicon.ico')));
  app.use(express.logger('dev'));
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(express.cookieParser('secret'));
  app.use(express.session());
  app.use(function(req, res, next) {
    res.locals.session = req.session;
    next();
  });

  app.use(app.router);
  app.use(require('less-middleware')(path.join(__dirname, '/public')));
  app.use(express.static(path.join(__dirname, 'public')));
});

app.configure('development', function(){
  app.use(express.errorHandler());
});

// Routes
app.get('/', routes.index);
app.get('/oauth', routes.oauth);
app.get('/oauth_callback', routes.oauth_callback);
app.get('/clear', routes.clear);

// Run
http.createServer(app).listen(app.get('port'), function(){
  console.log("Express server listening on port " + app.get('port'));
});


text:
import { nada } from "expose";
import { General } from "libcs/General";
import { niceprint } from "libcs/Essentials";
import { namespace } from "libcs/Namespace";
import { evaluate } from "libcs/Evaluator";

// CindyScript JSON
var Json = {};
Json._helper = {};

Json.turnIntoCSJson = function (a) {
    return {
        ctype: "JSON",
        value: a,
    };
};

Json._helper.ShallowClone = function (o) {
    var out, v, key;
    out = Array.isArray(o) ? [] : {};
    for (key in o) {
        v = o[key];
        out[key] = v;
    }
    return out;
};

Json.getField = function (obj, key) {
    if (obj.value && obj.value[key]) {
        return obj.value[key];
    }
    return nada;
};

Json.setField = function (where, field, what) {
    if (what.ctype === "undefined" && where[field]) {
        delete where[field];
    } else {
        where[field] = what;
    }
};

Json.GenFromUserDataEl = function (el) {
    var key = el.key;
    var obj = el.value;

    if (!key || key.ctype !== "string") {
        console.log("Error: JSON keys have to be strings.");
        return nada;
    }
    if (!obj) {
        console.log("Warning: JSON object not defined.");
        return {
            key: key.value,
            val: nada,
        };
    } else
        return {
            key: key.value,
            val: evaluate(obj),
        };
};

Json._helper.GenJSONAtom = function (key, val) {
    return {
        ctype: "JSON",
        value: {
            key: General.string(key),
            value: val,
        },
    };
};

Json._helper.forall = function (li, runVar, fct, modifs) {
    // JSON
    // default iterate over values in JSON
    var iteratorType = "value";
    var res;
    if (modifs.iterator !== undefined) {
        let it = evaluate(modifs.iterator);
        let iterTypes = ["key", "value", "pair"];
        if (it.ctype === "string" && iterTypes.indexOf(it.value) !== -1) {
            iteratorType = it.value;
        }
    }
    // iterate over key, value or pair
    if (iteratorType === "value") {
        for (let k in li) {
            namespace.setvar(runVar, li[k]);
            res = evaluate(fct);
        }
    } else if (iteratorType === "key") {
        for (let k in li) {
            namespace.setvar(runVar, General.string(k));
            res = evaluate(fct);
        }
    } else {
        // pair
        for (let k in li) {
            namespace.setvar(runVar, Json._helper.GenJSONAtom(k, li[k]));
            res = evaluate(fct);
        }
    }

    return res;
};

Json._helper.niceprint = function (a, modifs, options) {
    if (a.ctype === "JSON") {
        return Json.niceprint(a, modifs, options);
    }

    return niceprint(a);
};

Json.niceprint = function (el, modifs, options) {
    if (!options) {
        options = {};
        options.printedWarning = false;
        // track depth
        options.visitedMap = {};
        options.visitedMap.tracker = new WeakMap();
        options.visitedMap.level = 0;
        options.visitedMap.maxLevel = 1000;
        options.visitedMap.maxElVisit = 5000;

        if (modifs) {
            if (modifs.maxDepth) {
                let depth = evaluate(modifs.maxDepth);
                if (depth.ctype === "number") options.visitedMap.maxLevel = depth.value.real;
            }
        }
    }

    var visitedMap = options.visitedMap;
    // track a new recursive call
    visitedMap.newLevel = true;
    visitedMap.level += 1;

    var keys = Object.keys(el.value).sort();
    var jsonString =
        "{" +
        keys
            .map(function (key) {
                // update visitedMap
                let elValKey = el.value[key];
                if (!visitedMap.tracker.has(elValKey)) {
                    visitedMap.tracker.set(elValKey, 1);
                } else {
                    if (visitedMap[elValKey] > visitedMap.maxElVisit || visitedMap.level > visitedMap.maxLevel) {
                        //console.log([visitedMap[elValKey], visitedMap.level]);
                        if (!options.printedWarning) {
                            console.log(
                                "Warning: We visited a key-value pair very often or encountered a very deeply nested dictionary. Dictionary is probably cyclic. Output will be probably incomplete."
                            );
                            options.printedWarning = true;
                        }

                        return key + ":" + "...";
                    }
                    // update only once a recursive call
                    if (visitedMap.newLevel) {
                        visitedMap.tracker.set(elValKey, visitedMap.tracker.get(elValKey) + 1);
                        // update only once each function call
                        visitedMap.newLevel = false;
                    }
                }
                return key + ":" + Json._helper.niceprint(elValKey, modifs, options);
            })
            .join(", ") +
        "}";

    return jsonString;
};

Json._helper.handlePrintException = function (e) {
    if (e instanceof RangeError) {
        console.log("Warning: Dictionary string could not be generated! Probably large cyclic Dictionary!");
    } else if (e instanceof SyntaxError) {
        console.log("Warning: Dictionary string could not be parsed!");
    } else {
        console.log("Warning: Dictionary printing failed!");
    }
};

export { Json };


text:
layout: post
title: Using protocols to improve testability
date: "2018-02-06 05:30"
description: How to use protocols improve the testability of your code
tags: [unit-testing, protocols, mocking, testing]
---

Testing certain objects can be tough. Abstracting a classes functionality out to a protocol can make this easier.

So lets say we have a class MusicService which has a method that goes away to the network and requests songs `func getSongs(:)`.

This function has a completionBlock which is invoked when the network has responded with an error, or with the model objects it has created from the successful response.

By the use of protocols we've made the service easily testable. See below:

```swift
struct Song {
    let title: String
    let artist: String
    let album: String
}

protocol MusicService {
    func getSongs(completionBlock: (songs: [Song], error: Error?)->())
}

struct NetworkMusicService: MusicService {
    func getSongs(completionBlock: (songs: [Song], error: Error?)->()) {

        // fetch data from network
        // ....
        // ....
        completion(songs: songs, error: nil)
    }
}

struct MockMusicService: MusicService {
    func getSongs(completionBlock: (songs: [Song], error: Error?)->()) {
        completion(songs: [Song(),Song(),Song()], error: nil)
    }
}
```


text:
package io.pebbletemplates.pebble.utils;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Utility class to handle relative paths.
 *
 * @author Thomas Hunziker
 */
public final class PathUtils {

  public static final Pattern PATH_SEPARATOR_REGEX = Pattern.compile("[\\\\/]");

  /**
   * Resolves the given {@code relativePath} based on the given {@code anchorPath}.
   *
   * @param relativePath the relative path which should be resolved.
   * @param anchorPath the anchor path based on which the relative path should be resolved on.
   * @param expectedSeparator The character expected to be used as a separator; dictated by the
   * Loader.
   * @return the resolved path or {@code null} when the path could not be resolved.
   */
  public static String resolveRelativePath(String relativePath, String anchorPath,
      char expectedSeparator) {
    if (relativePath == null || relativePath.isEmpty()) {
      return null;
    }

    // ensure both paths use the same separator character
    relativePath = sanitize(relativePath, expectedSeparator);
    anchorPath = sanitize(anchorPath, expectedSeparator);

    if (relativePath.startsWith(".." + expectedSeparator) || relativePath
        .startsWith("." + expectedSeparator)) {
      return resolvePathInner(relativePath, anchorPath, expectedSeparator);
    }

    return null;
  }

  private static String sanitize(String path, char expectedSeparator) {
    return PATH_SEPARATOR_REGEX.matcher(path)
        .replaceAll(Matcher.quoteReplacement(String.valueOf(expectedSeparator)));
  }

  private static String resolvePathInner(String relativePath, String anchorPath, char separator) {
    StringBuilder resultingPath = new StringBuilder();

    for (String segment : resolvePathSegments(determineAnchorPathSegments(anchorPath, separator),
        splitBySeparator(relativePath, separator))) {
      resultingPath.append(segment).append(separator);
    }

    // remove the erroneous separator added at the end
    return resultingPath.substring(0, resultingPath.length() - 1);
  }

  private static Collection<String> determineAnchorPathSegments(String anchorPath, char separator) {
    if (anchorPath == null || anchorPath.isEmpty()) {
      return new ArrayList<>();
    }
    ArrayDeque<String> anchorPathSegments = new ArrayDeque<>(
        splitBySeparator(anchorPath, separator));
    if (anchorPath.charAt(anchorPath.length() - 1) != separator) {
      anchorPathSegments.pollLast();
    }
    return anchorPathSegments;
  }

  private static Collection<String> resolvePathSegments(Collection<String> anchorSegments,
      Collection<String> relativeSegments) {
    ArrayDeque<String> result = new ArrayDeque<>(anchorSegments);
    for (String segment : relativeSegments) {
      if (segment.equals(".")) {
        // do nothing
      } else if (segment.equals("..")) {
        result.pollLast();
      } else {
        result.add(segment);
      }
    }

    return result;
  }

  private static List<String> splitBySeparator(String path, char separator) {
    return Arrays.asList(path.split(Pattern.quote(String.valueOf(separator))));
  }

  private PathUtils() {
    throw new IllegalAccessError();
  }

}


text:
The purpose of Quotum is to allow users to store strings of texts as
quotations. Typically this would include conversations or things people have
said. In addition, the platform allows quotes to be categorised so that quotes
pertaining to particular topics can be searched.

Quotum is written in [Haskell](https://www.haskell.org/) and
[PureScript](http://www.purescript.org/) and uses
[Snap](http://snapframework.com/) as its web framework and
[acid-state](http://acid-state.seize.it/) as its database backend. Pages and
stylesheets are written using [Heist](http://hackage.haskell.org/package/heist)
and [SASS](http://sass-lang.com/) respectively. Quotum is available under the
MIT license.


text:
#ifndef XLSXCONDITIONALFORMATTING_P_H
#define XLSXCONDITIONALFORMATTING_P_H

//
//  W A R N I N G
//  -------------
//
// This file is not part of the Qt Xlsx API.  It exists for the convenience
// of the Qt Xlsx.  This header file may change from
// version to version without notice, or even be removed.
//
// We mean it.
//

#include "xlsxconditionalformatting.h"
#include "xlsxformat.h"
#include "xlsxcolor_p.h"
#include <QSharedData>
#include <QSharedPointer>
#include <QMap>

QT_BEGIN_NAMESPACE_XLSX

class XlsxCfVoData
{
public:
    XlsxCfVoData()
        :gte(true)
    {
    }

    XlsxCfVoData(ConditionalFormatting::ValueObjectType type, const QString &value, bool gte=true)
        :type(type), value(value), gte(gte)
    {
    }

    ConditionalFormatting::ValueObjectType type;
    QString value;
    bool gte;
};

class XlsxCfRuleData
{
public:
    enum Attribute {
        A_type,
        A_dxfId,
        //A_priority,
        A_stopIfTrue,
        A_aboveAverage,
        A_percent,
        A_bottom,
        A_operator,
        A_text,
        A_timePeriod,
        A_rank,
        A_stdDev,
        A_equalAverage,

        A_dxfFormat,
        A_formula1,
        A_formula2,
        A_formula3,
        A_formula1_temp,

        A_color1,
        A_color2,
        A_color3,

        A_cfvo1,
        A_cfvo2,
        A_cfvo3,

        A_hideData
    };

    XlsxCfRuleData()
        :priority(1)
    {}

    int priority;
    Format dxfFormat;
    QMap<int, QVariant> attrs;
};

class ConditionalFormattingPrivate : public QSharedData
{
public:
    ConditionalFormattingPrivate();
    ConditionalFormattingPrivate(const ConditionalFormattingPrivate &other);
    ~ConditionalFormattingPrivate();

    void writeCfVo(QXmlStreamWriter &writer, const XlsxCfVoData& cfvo) const;
    bool readCfVo(QXmlStreamReader &reader, XlsxCfVoData& cfvo);
    bool readCfRule(QXmlStreamReader &reader, XlsxCfRuleData *cfRule, Styles *styles);
    bool readCfDataBar(QXmlStreamReader &reader, XlsxCfRuleData *cfRule);
    bool readCfColorScale(QXmlStreamReader &reader, XlsxCfRuleData *cfRule);

    QList<QSharedPointer<XlsxCfRuleData> >cfRules;
    QList<CellRange> ranges;
};

QT_END_NAMESPACE_XLSX

Q_DECLARE_METATYPE(QXlsx::XlsxCfVoData)
#endif // XLSXCONDITIONALFORMATTING_P_H


text:
package org.springframework.security.cas.web;

import static junit.framework.Assert.*;

import org.junit.Test;
import org.springframework.security.cas.SamlServiceProperties;
import org.springframework.security.cas.ServiceProperties;

/**
 * Tests {@link ServiceProperties}.
 *
 * @author Ben Alex
 */
public class ServicePropertiesTests {
    //~ Methods ========================================================================================================

    @Test(expected=IllegalArgumentException.class)
    public void detectsMissingService() throws Exception {
        ServiceProperties sp = new ServiceProperties();
        sp.afterPropertiesSet();
    }

    @Test
    public void nullServiceWhenAuthenticateAllTokens() throws Exception {
        ServiceProperties sp = new ServiceProperties();
        sp.setAuthenticateAllArtifacts(true);
        try {
            sp.afterPropertiesSet();
            fail("Expected Exception");
        }catch(IllegalArgumentException success) {}
        sp.setAuthenticateAllArtifacts(false);
        try {
            sp.afterPropertiesSet();
            fail("Expected Exception");
        }catch(IllegalArgumentException success) {}
    }

    @Test
    public void testGettersSetters() throws Exception {
        ServiceProperties[] sps = {new ServiceProperties(), new SamlServiceProperties()};
        for(ServiceProperties sp : sps) {
            sp.setSendRenew(false);
            assertFalse(sp.isSendRenew());
            sp.setSendRenew(true);
            assertTrue(sp.isSendRenew());
            sp.setArtifactParameter("notticket");
            assertEquals("notticket", sp.getArtifactParameter());
            sp.setServiceParameter("notservice");
            assertEquals("notservice", sp.getServiceParameter());

            sp.setService("https://mycompany.com/service");
            assertEquals("https://mycompany.com/service", sp.getService());

            sp.afterPropertiesSet();
        }
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.13"/>
<title>Intel® Enhanced Privacy ID SDK: epid/member/include/epid/member Directory Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="navtree.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />
<link href="epidstyle.css" rel="stylesheet" type="text/css"/>

Intel® Enhanced Privacy ID SDK
 8.0.0

member Directory Reference

Member functionality.

More...

Files

file  	api.h

 	Intel(R) EPID SDK member API.

Detailed Description

Member functionality.

epid

member

include

epid

member

            © 2016-2018 Intel Corporation


text:
/* $Id$ */
/*
 * (c) copyright 1987 by the Vrije Universiteit, Amsterdam, The Netherlands.
 * See the copyright notice in the ACK home directory, in the file "Copyright".
 */
/* PREPROCESSOR: MACRO-TEXT REPLACEMENT ROUTINES */

#include <stdlib.h>
#include <string.h>
#include	"debug.h"	/* UF */
#include	"pathlength.h"	/* UF */
#include	"textsize.h"	/* UF */

#include	<alloc.h>
#include	<assert.h>
#include	"idf.h"
#include	"input.h"
#include	"macro.h"
#include	"LLlex.h"
#include	"class.h"
#include	"interface.h"

extern int InputLevel;

static struct mlist *ReplList;	/* list of currently active macros */
static char *macro2buffer(struct idf *idef, char **actpars, int *siztext);
static void macro_func(struct idf *idef);

char *long2str(long value, int base); /* External lib */

int replace(struct idf *idef)
{
	/*	replace() is called by the lexical analyzer to perform
		macro replacement.  "idef" is the description of the
		identifier which leads to the replacement.  If the
		optional actual parameters of the macro are OK, the text
		of the macro is prepared to serve as an input buffer,
		which is pushed onto the input stack.
		replace() returns 1 if the replacement succeeded and 0 if
		some error has occurred.
	*/
	struct macro *mac = idef->id_macro;
	char c;
	char **actpars;
	char *reptext;
	struct mlist *repl;
	int size;

	if (mac->mc_flag & NOREPLACE) {
		warning("macro %s is recursive", idef->id_text);
		return 0;
	}
	if (mac->mc_nps != -1) {	/* with parameter list	*/
		if (mac->mc_flag & FUNC) {
					/* must be "defined".
					   Unfortunately, the next assertion
					   will not compile ...
			assert( ! strcmp("defined", idef->id_text));
					*/
			if (! AccDefined)
				return 0;
		}
		if (++mac->mc_count > 100) {
			/* 100 must be some number in Parameters */
			warning("macro %s is assumed recursive",
				    idef->id_text);
			return 0;
		}
		LoadChar(c);
		c = skipspaces(c,! (mac->mc_flag & FUNC));
		if (c != '(') {		/* no replacement if no ()	*/
			PushBack();
			if (! (mac->mc_flag & FUNC)) {
				warning("macro %s needs arguments",
					idef->id_text);
				return 0;
			}
		}
		if (mac->mc_flag & FUNC) {
			struct idf *param;
			char *nam;

			UnknownIdIsZero = 0;
			nam = GetIdentifier();
			if (nam) {
				param = findidf(nam);
			}
			else	param = 0;
			UnknownIdIsZero = 1;
			if (c == '(') {
				LoadChar(c);
				c = skipspaces(c, 0);
				if (c != ')') error(") missing");
			}
			if (! nam) {
				error("identifier missing");
			}
			repl = new_mlist();
			if (param && param->id_macro)
				reptext = "1 ";
			else
				reptext = "0 ";
			InsertText(reptext, 2);
			InputLevel++;
			repl->m_level = InputLevel;

			repl->next = ReplList;
			ReplList = repl;
			repl->m_mac = mac;
			if (nam) free(nam);
			return 1;
		}
		actpars = getactuals(idef);	/* get act.param. list	*/
	}

	repl = new_mlist();
	repl->m_mac = mac;
	if (mac->mc_flag & FUNC) /* this macro leads to special action	*/
		macro_func(idef);
	if (mac->mc_nps <= 0) {
		reptext = mac->mc_text;
		size = mac->mc_length;
		mac->mc_flag |= NOREPLACE;	/* a file called __FILE__ ??? */
	}
	else {
		reptext = macro2buffer(idef, actpars, &size); /* create input buffer */
		repl->m_repl = reptext;
	}
	InsertText(reptext, size);
	InputLevel++;
	repl->m_level = InputLevel;
	repl->next = ReplList;
	ReplList = repl;
	return 1;
}

char FilNamBuf[PATHLENGTH];

static void macro_func(struct idf *idef)
{
	/*	macro_func() performs the special actions needed with some
		macros.  These macros are __FILE__ and __LINE__ which
		replacement texts must be evaluated at the time they are
		used.
	*/
	struct macro *mac = idef->id_macro;

	switch (idef->id_text[2]) { /* This switch is very blunt... */
	case 'F' :			/* __FILE__	*/
		mac->mc_length = strlen(FileName) + 2;
		mac->mc_text = FilNamBuf;
		mac->mc_text[0] = '"';
		strcpy(&(mac->mc_text[1]), FileName);
		strcat(mac->mc_text, "\"");
		break;
	case 'L' :			/* __LINE__	*/
	{
		mac->mc_text = long2str((long) LineNumber, 10);
		mac->mc_length = strlen(mac->mc_text);
		break;
	}
	default :
		crash("(macro_func)");
	}
}

static char *macro2buffer(struct idf *idef, char **actpars, int *siztext)
{
	/*	Macro2buffer() turns the macro replacement text, as it is
		stored, into an input buffer, while each occurrence of the
		non-ascii formal parameter mark is replaced by its
		corresponding actual parameter specified in the actual
		parameter list actpars.  A pointer to the beginning of the
		constructed text is returned, while *siztext is filled
		with its length.
		If there are no parameters, this function behaves
		the same as strcpy().
	*/
	unsigned int size = idef->id_macro->mc_length + ITEXTSIZE;
	char *text = Malloc(size);
	int pos = 0;
	char *ptr = idef->id_macro->mc_text;

	while (*ptr) {
		if (*ptr & FORMALP) {	/* non-asc formal param. mark	*/
			int n = *ptr++ & 0177;
			char *p;

			assert(n != 0);
			/*	copy the text of the actual parameter
				into the replacement text
			*/
			for (p = actpars[n - 1]; *p; p++) {
				text[pos++] = *p;
				if (pos == size)
					text = Realloc(text, size <<= 1);
			}
		}
		else {
			text[pos++] = *ptr++;
			if (pos == size)
				text = Realloc(text, size <<= 1);
		}
	}
	text[pos] = '\0';
	*siztext = pos;
	return Realloc(text, pos+1);
}

void DoUnstack()
{
	Unstacked = 1;
}

void EnableMacros()
{
	struct mlist *p = ReplList, *prev = 0;

	assert(Unstacked > 0);
	while (p) {
		struct mlist *nxt = p->next;

		if (p->m_level > InputLevel) {
			p->m_mac->mc_flag &= ~NOREPLACE;
			if (p->m_mac->mc_count) p->m_mac->mc_count--;
			if (p->m_repl) free(p->m_repl);
			if (! prev) ReplList = nxt;
			else prev->next = nxt;
			free_mlist(p);
		}
		else prev = p;
		p = nxt;
	}
	Unstacked = 0;
}


text:
package de.alpharogroup.user.service.api;

import java.util.List;

import de.alpharogroup.db.service.api.BusinessService;
import de.alpharogroup.user.entities.Permissions;

/**
 * The interface {@link PermissionsService}.
 */
public interface PermissionsService extends BusinessService<Permissions, Integer>
{

	/**
	 * Factory method to create and save a new {@link Permissions} object.
	 *
	 * @param name
	 *            the name
	 * @param description
	 *            the description
	 * @return the new {@link Permissions} object.
	 */
	Permissions createAndSavePermissions(String name, String description);

	/**
	 * Factory method to create and save a new {@link Permissions} object.
	 *
	 * @param name
	 *            the name
	 * @param description
	 *            the description
	 * @param shortcut
	 *            the shortcut
	 * @return the new {@link Permissions} object.
	 */
	Permissions createAndSavePermissions(String name, String description, String shortcut);

	/**
	 * Find all {@link Permissions} objects by the given parameters.
	 *
	 * @param description
	 *            the description
	 * @param permissionName
	 *            the permission name
	 * @param shortcut
	 *            the shortcut
	 * @return the list of the found {@link Permissions} objects.
	 */
	List<Permissions> find(String description, String permissionName, String shortcut);

	/**
	 * Find the {@link Permissions} object by the given name.
	 *
	 * @param name
	 *            the name
	 * @return the found {@link Permissions} object or null if not.
	 */
	Permissions findByName(String name);

	/**
	 * Find the {@link Permissions} object by the given shortcut.
	 *
	 * @param shortcut
	 *            the shortcut
	 * @return the found {@link Permissions} object or null if not.
	 */
	Permissions findByShortcut(String shortcut);
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE TS>

<TS version="2.0" language="tr">
    <context>
        <name>QApplication</name>
        <message>
            <source>QT_LAYOUT_DIRECTION</source>
            <comment>Translate this string to the string 'LTR' in left-to-right languages or to 'RTL' in right-to-left languages (such as Hebrew and Arabic) to get proper widget layout.</comment>
            <translation>LTR</translation>
        </message>
    </context>
    <context>
        <name>QDialogButtonBox</name>
        <message>
            <source>OK</source>
            <translation>Tamam</translation>
        </message>
        <message>
            <source>Save</source>
            <translation>Kaydet</translation>
        </message>
        <message>
            <source>&Save</source>
            <translation>&Kaydet</translation>
        </message>
        <message>
            <source>Open</source>
            <translation>Açık</translation>
        </message>
        <message>
            <source>Cancel</source>
            <translation>İptal</translation>
        </message>
        <message>
            <source>&Cancel</source>
            <translation>&İptal</translation>
        </message>
        <message>
            <source>Close</source>
            <translation>Kapat</translation>
        </message>
        <message>
            <source>&Close</source>
            <translation>&Kapat</translation>
        </message>
        <message>
            <source>Apply</source>
            <translation>Uygula</translation>
        </message>
        <message>
            <source>Reset</source>
            <translation>Sıfırla</translation>
        </message>
        <message>
            <source>Help</source>
            <translation>Kullanıcı kılavuzu</translation>
        </message>
        <message>
            <source>Don't Save</source>
            <translation>Kaydetme</translation>
        </message>
        <message>
            <source>Discard</source>
            <translation>Sil</translation>
        </message>
        <message>
            <source>&Yes</source>
            <translation>&Evet</translation>
        </message>
        <message>
            <source>Yes to &All</source>
            <translation>Tümüne E&vet</translation>
        </message>
        <message>
            <source>&No</source>
            <translation>&Hayır</translation>
        </message>
        <message>
            <source>N&o to All</source>
            <translation>Tümüne H&ayır</translation>
        </message>
        <message>
            <source>Save All</source>
            <translation>Tümünü kaydet</translation>
        </message>
        <message>
            <source>Abort</source>
            <translation>İptal</translation>
        </message>
        <message>
            <source>Retry</source>
            <translation>Tekrar deneyin</translation>
        </message>
        <message>
            <source>Ignore</source>
            <translation>Yoksay</translation>
        </message>
        <message>
            <source>Restore Defaults</source>
            <translation>Varsayılanları geri yükle</translation>
        </message>
        <message>
            <source>Close without Saving</source>
            <translation>Kaydetmeden kapat</translation>
        </message>
        <message>
            <source>&OK</source>
            <translation>&Tamam</translation>
        </message>
    </context>
    <context>
        <name>QErrorMessage</name>
        <message>
            <source>&Show this message again</source>
            <translation>Bu mesajı tekrar &göster</translation>
        </message>
        <message>
            <source>&OK</source>
            <translation>&Tamam</translation>
        </message>
        <message>
            <source>Debug Message:</source>
            <translation>Hata düzeltme mesajı:</translation>
        </message>
        <message>
            <source>Warning:</source>
            <translation>Uyarı:</translation>
        </message>
        <message>
            <source>Fatal Error:</source>
            <translation>Önemli hata:</translation>
        </message>
    </context>
    <context>
        <name>QInputDialog</name>
        <message>
            <source>Enter a value:</source>
            <translation>Bir değer girin:</translation>
        </message>
    </context>
    <context>
        <name>QMenu</name>
        <message>
            <source>Close</source>
            <translation>Kapat</translation>
        </message>
        <message>
            <source>Open</source>
            <translation>Açık</translation>
        </message>
        <message>
            <source>Execute</source>
            <translation>Kullan</translation>
        </message>
    </context>
    <context>
        <name>QMenuBar</name>
        <message>
            <source>Actions</source>
            <translation>İşlemler</translation>
        </message>
    </context>
    <context>
        <name>QMessageBox</name>
        <message>
            <source>OK</source>
            <translation>Tamam</translation>
        </message>
        <message>
            <source>
About Qt

This program uses Qt version %1.
</source>
            <translation>
Qt Hakkında

Bu program Qt sürüm %1 kullanır.
</translation>
        </message>
        <message>
            <source>About Qt</source>
            <translation>Qt hakkında</translation>
        </message>
        <message>
            <source>Help</source>
            <translation>Kullanıcı kılavuzu</translation>
        </message>
        <message>
            <source>Show Details...</source>
            <translation>Bilgileri göster</translation>
        </message>
        <message>
            <source>Hide Details...</source>
            <translation>Bilgileri gizle</translation>
        </message>
    </context>
    <context>
        <name>QProgressDialog</name>
        <message>
            <source>Cancel</source>
            <translation>İptal</translation>
        </message>
    </context>
    <context>
        <name>QSoftKeyManager</name>
        <message>
            <source>Ok</source>
            <translation>Tamam</translation>
        </message>
        <message>
            <source>Select</source>
            <translation>Seç</translation>
        </message>
        <message>
            <source>Done</source>
            <translation>Bitti</translation>
        </message>
        <message>
            <source>Options</source>
            <translation>Seçenekler</translation>
        </message>
        <message>
            <source>Cancel</source>
            <translation>İptal</translation>
        </message>
        <message>
            <source>Exit</source>
            <translation>Çıkış</translation>
        </message>
    </context>
    <context>
        <name>QTextControl</name>
        <message>
            <source>&Undo</source>
            <translation>&Geri al</translation>
        </message>
        <message>
            <source>&Redo</source>
            <translation>Yi&nele</translation>
        </message>
        <message>
            <source>Cu&t</source>
            <translation>Ke&s</translation>
        </message>
        <message>
            <source>&Copy</source>
            <translation>&Kopyala</translation>
        </message>
        <message>
            <source>Copy &Link Location</source>
            <translation>&Bağlantı konumunu kopyala</translation>
        </message>
        <message>
            <source>&Paste</source>
            <translation>&Yapıştır</translation>
        </message>
        <message>
            <source>Delete</source>
            <translation>Sil</translation>
        </message>
        <message>
            <source>Select All</source>
            <translation>Tümünü seç</translation>
        </message>
    </context>
</TS>


text:
Article 1662
----
Faute par le vendeur d'avoir exercé son action en rachat dans le terme prescrit,
l'acquéreur demeure propriétaire irrévocable.


text:
<?php

namespace Ivory\HttpAdapter\Event\Retry\Strategy;

use Ivory\HttpAdapter\Message\InternalRequestInterface;

/**
 * Constant delayed retry strategy.
 *
 * @author GeLo <geloen.eric@gmail.com>
 */
class ConstantDelayedRetryStrategy extends AbstractDelayedRetryStrategy
{
    /**
     * {@inheritdoc}
     */
    protected function doDelay(InternalRequestInterface $request)
    {
        return $this->getDelay();
    }
}


text:
<!DOCTYPE html>

    <title>"Frederick Douglass" | Lyrics of Lowly Life | Paul Laurence Dunbar | Lit2Go ETC</title>
    <link rel="stylesheet" href="http://etc.usf.edu/lit2go/css/screenless.css" type="text/css" media="screen" title="no title" charset="utf-8">
    <link rel="stylesheet" href="http://etc.usf.edu/lit2go/css/printless.css" type="text/css" media="print" title="no title" charset="utf-8">

          Lit2Go

<form action="http://etc.usf.edu/lit2go/search/"><input type="text" name="q" placeholder="Search" value=""></form>

Authors

Books

Genres

Collections

Readability

      Lyrics of Lowly Life

      by Paul Laurence Dunbar

      "Frederick Douglass"

        Additional Information

            Year Published:
            1913

            Language:
            English

            Country of Origin:
            United States of America

            Source:
            Dunbar, P.L. (1913). The Complete Poems of Paul Laurence Dunbar. New York: Dodd, Mead, and Company.

            Readability:

                Flesch–Kincaid Level:
                6.5

            Word Count:
            546

            Genre:
            Poetry

            Keywords:
            death, freedom, love

            ✎ Cite This

  Share
  |

Downloads

          Audio

          Passage PDF

Student Activity

            APA

            MLA

            Chicago

            Dunbar, P. (1913). "Frederick Douglass". Lyrics of Lowly Life (Lit2Go Edition). Retrieved February 15, 2016, from http://etc.usf.edu/lit2go/187/lyrics-of-lowly-life/3487/frederick-douglass/

            Dunbar, Paul Laurence. ""Frederick Douglass"." Lyrics of Lowly Life. Lit2Go Edition. 1913. Web. <http://etc.usf.edu/lit2go/187/lyrics-of-lowly-life/3487/frederick-douglass/>. February 15, 2016.

            Paul Laurence Dunbar, ""Frederick Douglass"," Lyrics of Lowly Life, Lit2Go Edition, (1913), accessed February 15, 2016, http://etc.usf.edu/lit2go/187/lyrics-of-lowly-life/3487/frederick-douglass/.

Back

Next

                  <audio controls style="width:99%;">
            <source src="http://etc.usf.edu/lit2go/audio/mp3/lyrics-of-lowly-life-005-frederick-douglass.3487.mp3" type="audio/mpeg" />
                          <source src="http://etc.usf.edu/lit2go/audio/ogg/lyrics-of-lowly-life-005-frederick-douglass.3487.ogg" type="audio/ogg" />
                        The embedded audio player requires a modern internet browser. You should visit Browse Happy and update your internet browser today!
          </audio>

	A hush is over all the teeming lists,

	And there is pause, a breath–space in the strife;

	A spirit brave has passed beyond the mists

	And vapors that obscure the sun of life.

	And Ethiopia, with bosom torn,

	Laments the passing of her noblest born.

	She weeps for him a mother’s burning tears—

	She loved him with a mother’s deepest love.

	He was her champion thro’ direful years,

	And held her weal all other ends above.

	When Bondage held her bleeding in the dust,

	He raised her up and whispered, “Hope and Trust.”

	For her his voice, a fearless clarion, rung

	That broke in warning on the ears of men;

	For her the strong bow of his power he strung,

	And sent his arrows to the very den

	Where grim Oppression held his bloody place

	And gloated o’er the mis’ries of a race.

	And he was no soft–tongued apologist;

	He spoke straightforward, fearlessly uncowed;

	The sunlight of his truth dispelled the mist,

	And set in bold relief each dark hued cloud;

	To sin and crime he gave their proper hue,

	And hurled at evil what was evil’s due.

	Through good and ill report he cleaved his way.

	Right onward, with his face set toward the heights,

	Nor feared to face the foeman’s dread array,—

	The lash of scorn, the sting of petty spites.

	He dared the lightning in the lightning’s track,

	And answered thunder with his thunder back.

	When men maligned him, and their torrent wrath

	In furious imprecations o’er him broke,

	He kept his counsel as he kept his path;

	‘T was for his race, not for himself he spoke.

	He knew the import of his Master’s call,

	And felt himself too mighty to be small.

	No miser in the good he held was he,—

	His kindness followed his horizon’s rim.

	His heart, his talents, and his hands were free

	To all who truly needed aught of him.

	Where poverty and ignorance were rife,

	He gave his bounty as he gave his life.

	The place and cause that first aroused his might

	Still proved its power until his latest day.

	In Freedom’s lists and for the aid of Right

	Still in the foremost rank he waged the fray;

	Wrong lived; his occupation was not gone.

	He died in action with his armor on!

	We weep for him, but we have touched his hand,

	And felt the magic of his presence nigh,

	The current that he sent throughout the land,

	The kindling spirit of his battle–cry.

	O’er all that holds us we shall triumph yet,

	And place our banner where his hopes were set!

	Oh, Douglass, thou hast passed beyond the shore,

	But still thy voice is ringing o’er the gale!

	Thou ‘st taught thy race how high her hopes may soar,

	And bade her seek the heights, nor faint, nor fail.

	She will not fail, she heeds thy stirring cry,

	She knows thy guardian spirit will be nigh,

	And, rising from beneath the chast’ning rod,

	She stretches out her bleeding hands to God!

Back

Next

            This collection of children's literature is a part of the Educational Technology Clearinghouse and is funded by various grants.

            Copyright © 2006—2016 by the Florida Center for Instructional Technology, College of Education, University of South Florida.

License

Credits

FAQ

Giving

This document was downloaded from Lit2Go, a free online collection of stories and poems in Mp3 (audiobook) format published by the Florida Center for Instructional Technology. For more information, including classroom activities, readability data, and original sources, please visit http://etc.usf.edu/lit2go/187/lyrics-of-lowly-life/3487/frederick-douglass/.

Lit2Go: Lyrics of Lowly Life

"Frederick Douglass"


text:
package checks

import (
	"testing"

	"github.com/mackerelio/mackerel-agent/config"
)

func TestChecker_Check(t *testing.T) {
	checkerOK := Checker{
		Config: &config.CheckPlugin{
			Command: config.Command{Cmd: "go run testdata/exit.go -code 0 -message OK"},
		},
	}

	checkerWarning := Checker{
		Config: &config.CheckPlugin{
			Command: config.Command{Cmd: "go run testdata/exit.go -code 1 -message something_is_going_wrong"},
		},
	}

	{
		report := checkerOK.Check()
		if report.Status != StatusOK {
			t.Errorf("status should be OK: %v", report.Status)
		}
		if report.Message != "OK\n" {
			t.Errorf("wrong message: %q", report.Message)
		}
	}

	{
		report := checkerWarning.Check()
		if report.Status != StatusWarning {
			t.Errorf("status should be WARNING: %v", report.Status)
		}
		if report.Message != "something_is_going_wrong\n" {
			t.Errorf("wrong message: %q", report.Message)
		}
	}
}


text:
.SmallImages img
{
	width: 16px;
	height: 16px;
}

.TreeNode
{

	font-family: Tahoma;
	font-size: 8pt;
	color: black;
	padding-left: 3px;
	text-decoration: none;
}

.TreeNodeOver
{
	font-family: Tahoma;
	font-size: 8pt;
	color: black;
	text-decoration: underline;
	cursor: pointer;
	cursor: hand;
	padding-left: 3px;
}

.TreeNodeSelect
{
	font-family: Tahoma;
	font-size: 8pt;
	color: white;
	background: #316AC5;
    cursor: pointer;
	cursor: hand;
	margin-left: 3px;
}

.TreeNodeDisabled
{
	font-family: Tahoma;
	font-size: 8pt;
	color: gray;
	padding-left: 3px;
	text-decoration: none;
	cursor: default;
}

.TreeContextItem
{
	font-family: Arial;
	font-size:10px;
	cursor: pointer;
	cursor: hand;
	padding-left:4px;
	height:24px;
	background-color:#fdfdfd;
	background-image:url(contextMenu.gif);
	background-repeat:repeat-y;
	width:100%;
	text-align: left;
	border-bottom: solid 1px #e3e3e3;
}

.TreeContextItemOver
{
	font-family: Arial;
	font-size:10px;
	cursor: pointer;
	cursor: hand;
	padding-left:4px;
	height:24px;
	background-color:#f3f3f3;
	background-image:url(contextMenu.gif);
	background-repeat:repeat-y;
	width:100%;
	text-align: left;
	border-bottom: solid 1px #d4d4d4;
}

.TreeNodeEdit
{
	border:1px gray solid;
	font-family: tahoma;
	font-size: 8pt;
	margin-left: 3px;
	text-align: left;
}


text:
<?php

declare(strict_types=1);

namespace BinSoul\Common\I18n\Transliteration\Locale;

/**
 * Provides transliteration for the Finnish language.
 */
class FiRule extends DefaultRule
{
    /**
     * @var string[]
     */
    private static $map = [
        'Ä' => 'A',
        'ä' => 'a',
        'Ö' => 'O',
        'ö' => 'o',
    ];

    public function apply(string $text): string
    {
        $result = strtr($text, self::$map);

        return parent::apply($result);
    }
}


text:
set -x

export ANDROID_TOOL=${ANDROID_HOME}/tools/android

# Because we cache ANDROID_HOME in Travis, we cannot test for the existence of
# the directory; it always gets created before we run.  Instead, check for the
# tool we care about, and if it doesn't exist, download the SDK.
if [ ! -x ${ANDROID_TOOL} ]; then
  wget http://dl.google.com/android/android-sdk_r23-linux.tgz
  tar -zxf android-sdk_r23-linux.tgz
  rm android-sdk_r23-linux.tgz
  rm -rf ${ANDROID_HOME}
  mv android-sdk-linux ${ANDROID_HOME}
fi

# We always update the SDK, even if it is cached, in case we change the
# versions of things we care about.
# Values from `android list sdk --extended --all`
(while :
do
    echo y
    sleep 2
 done) | ${ANDROID_TOOL} update sdk \
  --force \
  --no-ui \
  --all \
  --filter \
tools,\
platform-tools,\
build-tools-23.0.2,\
android-23,\
addon-google_apis-google-23,\
android-21,\
addon-google_apis-google-21,\
extra-android-support


text:
<?php declare(strict_types=1);

namespace Granam\DiceRolls\Templates\Dices;

use Granam\DiceRolls\Dice;
use Granam\Integer\IntegerInterface;
use Granam\Integer\IntegerObject;
use Granam\Strict\Object\StrictObject;
use Granam\Tools\ValueDescriber;

class Dices extends StrictObject implements Dice
{
    /** @var array|Dice[] */
    private $dices;
    /** @var IntegerObject */
    private $minimum;
    /** @var IntegerObject */
    private $maximum;

    /**
     * @param array|Dice[] $dices
     * @throws \LogicException
     */
    public function __construct(array $dices)
    {
        $this->checkDices($dices);
        $this->dices = $dices;
    }

    /**
     * @param array|Dice[] $dices
     * @throws \LogicException
     */
    private function checkDices(array $dices)
    {
        if (count($dices) === 0) {
            throw new \LogicException('No dice given.');
        }

        foreach ($dices as $dice) {
            if (!is_a($dice, Dice::class)) {
                throw new \LogicException(
                    'Given dices have to be DiceInterface, got ' . ValueDescriber::describe($dice)
                );
            }
        }
    }

    /**
     * @return IntegerInterface
     */
    public function getMinimum(): IntegerInterface
    {
        if ($this->minimum === null) {
            /** @noinspection ExceptionsAnnotatingAndHandlingInspection */
            $this->minimum = $this->createMinimum();
        }

        return $this->minimum;
    }

    /**
     * @return IntegerObject
     * @throws \Granam\Integer\Tools\Exceptions\WrongParameterType
     * @throws \Granam\Integer\Tools\Exceptions\ValueLostOnCast
     */
    private function createMinimum(): IntegerObject
    {
        return new IntegerObject(
            array_sum(
                array_map(
                    function (Dice $dice) {
                        return $dice->getMinimum()->getValue();
                    },
                    $this->dices
                )
            )
        );
    }

    /**
     * @return IntegerInterface
     */
    public function getMaximum(): IntegerInterface
    {
        if ($this->maximum === null) {
            /** @noinspection ExceptionsAnnotatingAndHandlingInspection */
            $this->maximum = $this->createMaximum();
        }

        return $this->maximum;
    }

    /**
     * @return IntegerObject
     * @throws \Granam\Integer\Tools\Exceptions\WrongParameterType
     * @throws \Granam\Integer\Tools\Exceptions\ValueLostOnCast
     */
    private function createMaximum(): IntegerObject
    {
        return new IntegerObject(
            array_sum(
                array_map(
                    function (Dice $dice) {
                        return $dice->getMaximum()->getValue();
                    },
                    $this->dices
                )
            )
        );
    }
}