text:
package com.yamin.reader.activity;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.geometerplus.android.fbreader.libraryService.BookCollectionShadow;
import org.geometerplus.fbreader.book.Author;
import org.geometerplus.fbreader.fbreader.FBReaderApp;
import org.geometerplus.zlibrary.core.filesystem.ZLFile;
import org.geometerplus.zlibrary.core.language.Language;
import org.geometerplus.zlibrary.core.language.ZLLanguageUtil;

import android.app.ActionBar;
import android.app.ActionBar.OnNavigationListener;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.yamin.reader.R;
import com.yamin.reader.adapter.BookHisFavAdaper;
import com.yamin.reader.adapter.BookShelfListAdaper;
import com.yamin.reader.adapter.ScanFileAdapter;
import com.yamin.reader.database.DbDataOperation;
import com.yamin.reader.database.DbTags;
import com.yamin.reader.model.Book;
import com.yamin.reader.utils.Commons;
import com.yamin.reader.utils.ToolUtils;
import com.yamin.reader.view.CustomDialog;
import com.yamin.reader.view.LoadingDialog;

/**
 *
 * @ClassName: MainActivity
 * @Description: TODO(这里用一句话描述这个类的作用)
 * @author ymcao
 * @date 2013-6-22 上午1:21:15
 *
 */
public class MainActivity extends Activity {

	/** Called when the activity is first created. */
	private ActionBar actionBar;
	//
	private FBReaderApp myFBReaderApp;
	private GridView gdlist;
	private RelativeLayout somethingRl;
	private RelativeLayout nothingRl;
	BookShelfListAdaper mABdapter;
	BookHisFavAdaper favoriteAdapter;
	EditText searchEdit;
	private ContentResolver resolver;
	private ArrayList<Book> shelfData = new ArrayList<Book>();
	private ScanFileAdapter mSearchAdatper;
	//
	private GridView scanFileGridView;
	private TextView numOfTxtFilesTxt;
	private TextView numOfBookFilesTxt;
	private RelativeLayout searchEditRl;
	private ImageView searchDone;
	private ImageView searchAll;
	private ImageView searchCancel;
	private ImageView bookDelete;
	private ImageView bookAll;
	private ImageView bookUnAll;
	//
	private RelativeLayout searchDialoglayout;
	private RelativeLayout detailDialoglayout;
	private RelativeLayout aboutDialoglayout;
	private RelativeLayout alertDialoglayout;
	private RelativeLayout eidtMenulayout;
	private TextView titleTxt;
	private TextView authorTxt;
	private TextView proessTxt;
	private TextView storageTxt;
	private ImageView coverImg;
	private TextView languageTxt;
	private Button openBtn;
	private Button shareBtn;
	private Button favBtn;
	private Button delFavBtn;
	private Button okBtn;
	private Button cancelBtn;
	//
	private ArrayList<ScanFileAdapter.FileInfo> mFileLists;
	private boolean actionModeEdit = false;
	//
	PopupWindow mPopuwindow;
	private Book book;
	private CustomDialog aboutDialog;
	private CustomDialog alertDialog;
	private static LoadingDialog loadDialog;
	private final int BOOK_SHELF = 0;
	private final int BOOK_FAVORITE = 2;
	private final int BOOK_INIT = 3;

	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			switch (msg.what) {
			case BOOK_SHELF:
				updateLayoutContent();
				break;

			case BOOK_FAVORITE:
				startActivity(new Intent(MainActivity.this,BookFavoriteActivity.class));
				break;

			case BOOK_INIT:
				mABdapter.setmData(shelfData);
				mABdapter.notifyDataSetChanged();
				updateView();
			}
			super.handleMessage(msg);
		}
	};

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

		resolver = getContentResolver();
		mABdapter=new BookShelfListAdaper(this, shelfData);
		intView();
		// handleIntent(getIntent());
	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		Log.i("MAIN", "onStart()");
		myFBReaderApp = (FBReaderApp) FBReaderApp.Instance();
		if (myFBReaderApp == null) {
			myFBReaderApp = new FBReaderApp(MainActivity.this,
					new BookCollectionShadow());
		}
		getCollection().bindToService(this, null);
		new sdScanAysnTask(3).execute();
		super.onStart();
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		new MenuInflater(getApplication()).inflate(R.menu.bookshelf_menu, menu);
		return super.onCreateOptionsMenu(menu);

	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_file:
			Intent i = new Intent(MainActivity.this, FileBrowserActivity.class);
			i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(i);
			break;
		case R.id.menu_about:
			//
			if (aboutDialog != null)
				aboutDialog.show();
			break;
		case R.id.menu_scan:
			//
			new sdScanAysnTask(0).execute();
			//
			break;
		case R.id.menu_exit:
			//
			if (alertDialog != null)
				alertDialog.show();
			//
			break;

		case R.id.menu_share:
			ToolUtils.shareWithOther(MainActivity.this, Commons.shareMsg);
			break;
		case R.id.menu_edit:
			if (mABdapter != null&&mABdapter.getCount()>0) {
				if(!mABdapter.isEditMode()){
					mABdapter.setEditMode(true);
					mABdapter.notifyDataSetChanged();
					showEditMenuWindow(0,0);
				}else{
					mABdapter.setEditMode(false);
					mABdapter.notifyDataSetChanged();
					if(mPopuwindow!=null&&mPopuwindow.isShowing()){
						mPopuwindow.dismiss();
					}
				}
			}else{
				Toast.makeText(this, "书架中还没有书籍!", Toast.LENGTH_SHORT).show();
			}
			break;
		}

		return super.onOptionsItemSelected(item);
	}

	@Override
	protected void onDestroy() {

		super.onDestroy();
		getCollection().unbind();
		if (mPopuwindow != null && mPopuwindow.isShowing()) {
			mPopuwindow.dismiss();
		}

		super.onDestroy();
	}

	public void intView() {
		actionBar = getActionBar();
		actionBar.setDisplayHomeAsUpEnabled(false);
		actionBar.setDisplayShowHomeEnabled(true);
		actionBar.setDisplayShowTitleEnabled(false);
		actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);

		gdlist = (GridView) findViewById(R.id.gdBookshelf);
		gdlist.setAdapter(mABdapter);
		somethingRl = (RelativeLayout) findViewById(R.id.bookshelf_something);
		nothingRl = (RelativeLayout) findViewById(R.id.bookshelf_nothing);

		searchDialoglayout = (RelativeLayout) LayoutInflater.from(
				MainActivity.this).inflate(R.layout.search_dialog, null);
		aboutDialoglayout = (RelativeLayout) LayoutInflater.from(
				MainActivity.this).inflate(R.layout.about_dialog, null);
		alertDialoglayout = (RelativeLayout) LayoutInflater.from(
				MainActivity.this).inflate(R.layout.alert_dialog, null);
		detailDialoglayout = (RelativeLayout) LayoutInflater.from(
				MainActivity.this).inflate(R.layout.book_details_info, null);
		eidtMenulayout= (RelativeLayout) LayoutInflater.from(
				MainActivity.this).inflate(R.layout.bookshelf_edit, null);
		numOfBookFilesTxt=(TextView)eidtMenulayout.findViewById(R.id.numOfBookFiles);
		titleTxt = (TextView) detailDialoglayout
				.findViewById(R.id.detail_title);
		authorTxt = (TextView) detailDialoglayout
				.findViewById(R.id.detail_author);
		proessTxt = (TextView) detailDialoglayout
				.findViewById(R.id.detail_progress);
		storageTxt = (TextView) detailDialoglayout
				.findViewById(R.id.detail_storage);
		coverImg = (ImageView) detailDialoglayout
				.findViewById(R.id.details_cover);
		languageTxt = (TextView) detailDialoglayout
				.findViewById(R.id.detail_language);
		okBtn = (Button) alertDialoglayout.findViewById(R.id.okBtn);
		cancelBtn = (Button) alertDialoglayout.findViewById(R.id.cancelBtn);
		//
		searchEditRl = (RelativeLayout) searchDialoglayout
				.findViewById(R.id.searchEditLayout);
		scanFileGridView = (GridView) searchDialoglayout
				.findViewById(R.id.scanFileGridView);
		numOfTxtFilesTxt = (TextView) searchDialoglayout
				.findViewById(R.id.numOfTxtFiles);
		searchDone = (ImageView) searchDialoglayout
				.findViewById(R.id.imgSearchDoneIcon);
		searchAll = (ImageView) searchDialoglayout
				.findViewById(R.id.imgSearchAllIcon);
		searchCancel = (ImageView) searchDialoglayout
				.findViewById(R.id.imgSearchUnAllIcon);
		//
		aboutDialog = new CustomDialog(MainActivity.this, aboutDialoglayout,
				R.style.Theme_dialog);
		aboutDialog.setCanceledOnTouchOutside(true);
		//
		alertDialog = new CustomDialog(MainActivity.this, alertDialoglayout,
				R.style.Theme_dialog);
		alertDialog.setCanceledOnTouchOutside(false);
		//
		mFileLists = new ArrayList<ScanFileAdapter.FileInfo>();
		// search Dialog layout
		setListener();
		//
	}

	/*
	 * private void handleIntent(Intent intent) { if
	 * (Intent.ACTION_VIEW.equals(intent.getAction())) { // handles a click on a
	 * search suggestion; launches activity to show word Intent wordIntent = new
	 * Intent(this, SearchResultActivity.class);
	 * wordIntent.setData(intent.getData()); startActivity(wordIntent); } else
	 * if (Intent.ACTION_SEARCH.equals(intent.getAction())) { // handles a
	 * search query String query = intent.getStringExtra(SearchManager.QUERY);
	 * showResults(query); } }
	 */
	private BookCollectionShadow getCollection() {
		return (BookCollectionShadow) myFBReaderApp.Collection;
	}

	private void setListener() {
		// TODO Auto-generated method stub
		ArrayAdapter<CharSequence> spinnerAdapter = ArrayAdapter
				.createFromResource(this, R.array.spinner_menu,
						android.R.layout.simple_spinner_item);
		spinnerAdapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		//
		actionBar.setListNavigationCallbacks(spinnerAdapter,
				new DropDownListenser());
		//
		okBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				MainActivity.this.finish();
			}
		});
		cancelBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				alertDialog.dismiss();
			}
		});
		// sacn GridView
		scanFileGridView.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// edit mode
				if (actionModeEdit) {
					if (mSearchAdatper != null) {
						int value = mSearchAdatper.getItemState()[position] == 1 ? 0
								: 1;
						mSearchAdatper.getItemState()[position] = value;
						// mCallback.setSeletedCountShow();
						mSearchAdatper.notifyDataSetChanged();
						updaScanSelectText(Integer.toString(mSearchAdatper
								.getCheckedItemCount()));
					}
				} else {
					//
				}
			}

		});

		scanFileGridView
				.setOnItemLongClickListener(new OnItemLongClickListener() {
					public boolean onItemLongClick(AdapterView<?> arg0,
							View arg1, int arg2, long arg3) {
						// TODO
						// Auto-generated method stub
						if (!actionModeEdit) {
							searchEditRl.setVisibility(View.VISIBLE);
							searchEditRl.startAnimation(AnimationUtils
									.loadAnimation(MainActivity.this,
											R.anim.layout_enter));
							actionModeEdit = true;
							Log.i("TAG", "OnLongClickListener()");
							return true;
						}
						return false;
					}

				});

		searchDone.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (mSearchAdatper.getCheckedItemCount() > 0) {
					if (mPopuwindow != null && mPopuwindow.isShowing()) {
						mPopuwindow.dismiss();
					}
					new sdScanAysnTask(1).execute();
				} else {
					Toast.makeText(MainActivity.this, "您还未选择书籍,请先选择书籍!",
							Toast.LENGTH_LONG).show();
				}

			}
		});
		// Select ALl
		searchAll.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (mSearchAdatper != null) {
					mSearchAdatper.checkAll();
					mSearchAdatper.notifyDataSetChanged();
					updaScanSelectText(Integer.toString(mSearchAdatper
							.getCheckedItemCount()));
					searchAll.setEnabled(false);
					searchAll.setAlpha(0.6f);
					searchCancel.setEnabled(true);
					searchCancel.setAlpha(1f);
				}
			}
		});
		// Diselect All
		searchCancel.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (mSearchAdatper != null) {
					if (mSearchAdatper.isAllChecked()) {
						mSearchAdatper.uncheckAll();
						mSearchAdatper.notifyDataSetChanged();
						updaScanSelectText(Integer.toString(mSearchAdatper
								.getCheckedItemCount()));
						searchCancel.setEnabled(false);
						searchCancel.setAlpha(0.6f);
						searchAll.setEnabled(true);
						searchAll.setAlpha(1f);
					}
				}
			}
		});

		gdlist.setOnItemClickListener(new AdapterView.OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				// TODO Auto-generated method stub
				int p = position;
				Book b = shelfData.get(position);
				// Not In Edit Mode
				if (mABdapter.isEditMode()) {
					if (mABdapter != null) {
						int value = mABdapter.getItemState()[p] == 1 ? 0 : 1;
						mABdapter.getItemState()[p] = value;
						mABdapter.notifyDataSetChanged();
						updaBookSelectText(Integer.toString(mABdapter
								.getCheckedItemCount()));
					}
				}
				// Edit Mode
				else {
					// File Exist
					if (ToolUtils.fileIsExists(b.getBookPath())) {
						//
						// openBook(b.getBookPath());
						ZLFile file = ZLFile.createFileByPath(b.getBookPath());
						org.geometerplus.fbreader.book.Book book = createBookForFile(file);
						if (book != null) {
							titleTxt.setText("书名:" + book.getTitle());
							Log.i("MAIN", b.getBookProgress() + "");
							if ("00%".equals(b.getBookProgress())) {
								proessTxt.setText("进度:未读");

							} else {
								proessTxt.setText("进度:" + b.getBookProgress());
							}
							storageTxt.setText(book.File.getPath() + "");
							String language = book.getLanguage();
							if (!ZLLanguageUtil.languageCodes().contains(
									language)) {
								language = Language.OTHER_CODE;
							}
							final StringBuilder buffer = new StringBuilder();
							final List<Author> authors = book.authors();
							for (Author a : authors) {
								if (buffer.length() > 0) {
									buffer.append(", ");
								}
								buffer.append(a.DisplayName);
							}
							Bitmap cover = ToolUtils.getCover(
									MainActivity.this, book);
							Bitmap bmp = BitmapFactory.decodeResource(
									getResources(), R.drawable.empty_icon);
							if (cover != null) {
								coverImg.setImageBitmap(cover);
							} else {
								coverImg.setImageBitmap(bmp);
							}
							// coverImg;
							authorTxt.setText("作者:" + buffer);
							languageTxt.setText("语言:"
									+ new Language(language).Name);

						}
						showDetailsPopupWindow(0, 0, book);
					} else {
						Toast.makeText(MainActivity.this, "文件已被从SD卡中移除!",
								Toast.LENGTH_LONG).show();
						DbDataOperation.deleteBook(resolver, b.getBookId());
						//
						shelfData = DbDataOperation.getBookInfo(resolver);
						mABdapter.setmData(shelfData);
						mABdapter.notifyDataSetChanged();

					}
				}
				//
			}
		});

	}

	//
	private void updaScanSelectText(String msg) {
		numOfTxtFilesTxt.setText("选中" + msg + "个文件!");
	}
	private void updaBookSelectText(String msg) {
		numOfBookFilesTxt.setText("选中" + msg + "个文件!");
	}

	public void updateView() {
		// According the data,update view!
		updateLayoutContent();
	}

	private void updateLayoutContent() {
		if (mABdapter != null && mABdapter.getCount() > 0) {
			somethingRl.setVisibility(View.VISIBLE);
			nothingRl.setVisibility(View.GONE);
			;
		} else {
			somethingRl.setVisibility(View.GONE);
			nothingRl.setVisibility(View.VISIBLE);
		}
	}

	/*
	 * private void openBook(String bookPath) { ZLFile file =
	 * ZLFile.createFileByPath(bookPath); org.geometerplus.fbreader.book.Book
	 * book = createBookForFile(file); if (book != null) {
	 * CoreReadActivity.openBookActivity(MainActivity.this, book, null);
	 * MainActivity.this.overridePendingTransition(R.anim.activity_enter,
	 * R.anim.activity_exit); } }
	 */
	private org.geometerplus.fbreader.book.Book createBookForFile(ZLFile file) {
		if (file == null) {
			return null;
		}
		org.geometerplus.fbreader.book.Book book = getCollection()
				.getBookByFile(file);
		if (book != null) {
			return book;
		}
		if (file.isArchive()) {
			for (ZLFile child : file.children()) {
				book = getCollection().getBookByFile(child);
				if (book != null) {
					return book;
				}
			}
		}
		return null;
	}

	public class sdScanAysnTask extends AsyncTask<Integer, Integer, String[]> {
		private int forWhat = 0;

		public sdScanAysnTask(int forWhat) {
			super();
			this.forWhat = forWhat;
		}

		protected void onPreExecute() {
			// 0
			if (forWhat == 0) {
				//
				showLoading(MainActivity.this, "SD卡扫描中...");
				if (mFileLists != null && mFileLists.size() > 0) {
					mFileLists.clear();
				}
			}
			// 1
			if (forWhat == 1) {
				showLoading(MainActivity.this, "正加入书架中...");
			}
			// 2
			if (forWhat == 2) {
				showLoading(MainActivity.this, "正在删除书籍...");
			}
			if (forWhat == 3) {
				// showLoading(MainActivity.this, "初始化书架...");
			}
			super.onPreExecute();
		}

		protected String[] doInBackground(Integer... params) {
			// 0
			if (forWhat == 0) {
				if (!android.os.Environment.getExternalStorageState().equals(
						android.os.Environment.MEDIA_MOUNTED)) {
				}
				GetFiles(Environment.getExternalStorageDirectory());
			}
			// 1
			if (forWhat == 1) {
				DoneScanLocal();
			}
			// 2
			if (forWhat == 2) {
				delLocalShelf();
			}
			if (forWhat == 3) {
				loadShelfData();
			}
			return null;
		}

		protected void onPostExecute(String[] result) {
			// 0
			if (forWhat == 0) {
				stopLoading();
				Toast.makeText(MainActivity.this,
						"扫描完毕,找到" + mFileLists.size() + "个文件",
						Toast.LENGTH_SHORT).show();
				showPopupWindow(0, 0);
			}
			// 1
			if (forWhat == 1) {
				stopLoading();
				shelfData = DbDataOperation.getBookInfo(resolver);
				mABdapter.setmData(shelfData);
				mABdapter.notifyDataSetChanged();
				updateView();
				Toast.makeText(MainActivity.this, "成功添加到书架!",
						Toast.LENGTH_SHORT).show();
			}
			// 2
			if (forWhat == 2) {
				stopLoading();
				shelfData = DbDataOperation.getBookInfo(resolver);
				mABdapter.setmData(shelfData);
				if(mABdapter.isEditMode()){
					mABdapter.setEditMode(false);
				}
				mABdapter.notifyDataSetChanged();
				//
				updateView();
				if (mPopuwindow != null && mPopuwindow.isShowing()) {
					mPopuwindow.dismiss();
				}
				Toast.makeText(MainActivity.this, "成功删除书籍!", Toast.LENGTH_SHORT)
						.show();
			}
			if (forWhat == 3) {
				// stopLoading();
				Message message = new Message();
				message.what = BOOK_INIT;
				mHandler.sendMessage(message);
			}
			super.onPostExecute(result);
		}
	}

	private void loadShelfData() {
		shelfData = DbDataOperation.getBookInfo(resolver);
	}

	public void delLocalShelf() {
		Log.i("MAIN", mABdapter.getItemState().length + "");
		Log.i("MAIN", shelfData.size() + "");
		if (mABdapter.getItemState() != null
				&& mABdapter.getItemState().length > 0) {
			for (int i = 0; i < mABdapter.getItemState().length; i++) {
				if (mABdapter.getItemState()[i] == 1) {
					long bookid = shelfData.get(i).getBookId();
					//
					DbDataOperation.deleteBook(resolver, bookid);
					//
					ZLFile file = ZLFile.createFileByPath(shelfData.get(i)
							.getBookPath());
					org.geometerplus.fbreader.book.Book book = createBookForFile(file);
					if (book != null) {
						myFBReaderApp.Collection.removeBook(book, false);
					}
				}
			}
		}
	}

	// search done 按钮
	public void DoneScanLocal() {
		//
		if (mSearchAdatper.getItemState() != null
				&& mSearchAdatper.getItemState().length > 0) {
			for (int i = 0; i < mSearchAdatper.getItemState().length; i++) {
				if (mSearchAdatper.getItemState()[i] == 1) {
					String filename = mFileLists.get(i).getFileName();
					String filepath = mFileLists.get(i).getFilePath();
					long filesize = mFileLists.get(i).getFileSize();
					// Local Book---Easy Book
					book = new Book();
					book.setBookName(filename);
					book.setBookProgress("00%");
					book.setBookPath(filepath);
					book.setBookSize(ToolUtils.FormetFileSize(filesize));
					Book b = DbDataOperation.queryBook(resolver,
							DbTags.FIELD_BOOK_NAME, filename);
					if (b == null) {
						DbDataOperation.insertToBookInfo(resolver, book);
					}
					//
					actionModeEdit = false;
					searchEditRl.setVisibility(View.GONE);
				}
			}
		}
		//
	}

	//
	public void GetFiles(File filePath) {
		File[] files = filePath.listFiles();
		if (files != null) {
			for (int i = 0; i < files.length; i++) {
				if (files[i].isDirectory()) {
					GetFiles(files[i]);
				} else {
					if (files[i].getName().toLowerCase().endsWith("." + "txt")
							|| files[i].getName().toLowerCase()
									.endsWith("." + "epub")
							|| files[i].getName().toLowerCase()
									.endsWith("." + "mobi")
							|| files[i].getName().toLowerCase()
									.endsWith("." + "fb2")
							|| files[i].getName().toLowerCase()
									.endsWith("." + "oeb")
							|| files[i].getName().toLowerCase()
									.endsWith("." + "html")) {
						ScanFileAdapter.FileInfo fileInfo = new ScanFileAdapter.FileInfo(
								files[i].getAbsolutePath(), files[i].getName(),
								files[i].length(), false);
						Log.i("TAG", files[i].getName());
						// String scanName = files[i].getName();
						if (fileInfo != null) {
							mFileLists.add(fileInfo);
						}
					}
				}
			}
		}
	}

	/*
	 *
	 */
	public static void showLoading(Activity activity, String msg) {
		if (loadDialog == null) {
			loadDialog = LoadingDialog.createDialog(activity, msg);
			loadDialog.setCanceledOnTouchOutside(false);
		}
		loadDialog.show();
	}

	private static void stopLoading() {
		if (loadDialog != null) {
			loadDialog.dismiss();
			loadDialog = null;
		}
	}
	//
	public void showEditMenuWindow(int x, int y) {
		bookDelete=(ImageView)eidtMenulayout.findViewById(R.id.imgDeleteIcon);
		bookAll=(ImageView)eidtMenulayout.findViewById(R.id.imgAllIcon);
	    bookUnAll=(ImageView)eidtMenulayout.findViewById(R.id.imgUnAllIcon);
	    bookDelete.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				new sdScanAysnTask(2).execute();
			}
		});
	    bookAll.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					mABdapter.checkAll();
					mABdapter.notifyDataSetChanged();
					updaBookSelectText(Integer.toString(mABdapter.getCheckedItemCount()));
				}
			});
	    bookUnAll.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					mABdapter.uncheckAll();
					mABdapter.notifyDataSetChanged();
					updaBookSelectText(Integer.toString(mABdapter.getCheckedItemCount()));
				}
			});
		mPopuwindow = new PopupWindow(eidtMenulayout,
				ViewGroup.LayoutParams.FILL_PARENT,
				ViewGroup.LayoutParams.WRAP_CONTENT);
		//
		ColorDrawable cd = new ColorDrawable(-0000);
		mPopuwindow.setBackgroundDrawable(cd);
		// mPopuwindow.setAnimationStyle(R.style.popuWindowAnimationStyle);
		mPopuwindow.setOutsideTouchable(false);
		mPopuwindow.setFocusable(false);
		mPopuwindow.showAtLocation(searchDialoglayout, Gravity.BOTTOM, x, y);
		searchDialoglayout.startAnimation(AnimationUtils.loadAnimation(
				MainActivity.this, R.anim.popu_enter));
	}
	//
	public void showPopupWindow(int x, int y) {
		//
		if (mFileLists != null && mFileLists.size() > 0) {
			mSearchAdatper = new ScanFileAdapter(MainActivity.this, mFileLists);
			scanFileGridView.setAdapter(mSearchAdatper);
			scanFileGridView.requestFocus();
		}
		//
		scanFileGridView.setOnKeyListener(new OnKeyListener() {
			// 焦点到了gridview上,所以需要监听此处的键盘事件。否则会出现不响应键盘事件的情况
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				switch (keyCode) {
				case KeyEvent.KEYCODE_MENU:
					if (mPopuwindow != null && mPopuwindow.isShowing()) {
						mPopuwindow.dismiss();
					}
					break;
				}
				return true;
			}
		});

		mPopuwindow = new PopupWindow(searchDialoglayout,
				ViewGroup.LayoutParams.FILL_PARENT,
				ViewGroup.LayoutParams.WRAP_CONTENT);
		//
		ColorDrawable cd = new ColorDrawable(-0000);
		mPopuwindow.setBackgroundDrawable(cd);
		// mPopuwindow.setAnimationStyle(R.style.popuWindowAnimationStyle);
		mPopuwindow.setOutsideTouchable(true);
		mPopuwindow.setFocusable(true);
		mPopuwindow.showAtLocation(searchDialoglayout, Gravity.TOP, x, y);
		searchDialoglayout.startAnimation(AnimationUtils.loadAnimation(
				MainActivity.this, R.anim.popu_enter));
	}

	//
	public void showDetailsPopupWindow(int x, int y,
			final org.geometerplus.fbreader.book.Book book) {
		//
		openBtn = (Button) detailDialoglayout.findViewById(R.id.openBookBtn);
		shareBtn = (Button) detailDialoglayout.findViewById(R.id.shareBtn);
		favBtn = (Button) detailDialoglayout.findViewById(R.id.favoriteBtn);
		delFavBtn = (Button) detailDialoglayout.findViewById(R.id.delFavBtn);
		delFavBtn.setVisibility(View.GONE);
		mPopuwindow = new PopupWindow(detailDialoglayout,
				ViewGroup.LayoutParams.WRAP_CONTENT,
				ViewGroup.LayoutParams.WRAP_CONTENT);
		//
		ColorDrawable cd = new ColorDrawable(-0000);
		mPopuwindow.setBackgroundDrawable(cd);
		mPopuwindow.setOutsideTouchable(true);
		mPopuwindow.setFocusable(true);
		mPopuwindow.showAtLocation(searchDialoglayout, Gravity.CENTER, x, y);
		openBtn.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (mPopuwindow != null && mPopuwindow.isShowing()) {
					mPopuwindow.dismiss();
				}
				if (book != null) {
					CoreReadActivity.openBookActivity(MainActivity.this, book,
							null);
					MainActivity.this.overridePendingTransition(
							R.anim.activity_enter, R.anim.activity_exit);
				}
			}
		});
		shareBtn.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				//
				ToolUtils.shareWithOther(MainActivity.this,
						"我觉得" + book.getTitle() + "这本书不错,现在推荐给你们!");
			}
		});
		favBtn.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				//
				// Local Book---Easy Book
				Book b = new Book();
				Log.i("MAIN", "" + book.File.getShortName());
				b.setBookName(book.File.getShortName());
				b.setBookPath(book.File.getPath());
				b.setBookProgress("00%");
				b.setBookSize(ToolUtils.FormetFileSize(book.File.size()));
				Date date = new Date();
				//
				SimpleDateFormat formatter = new SimpleDateFormat(
						"yyyy-MM-dd HH:mm");
				String bookAddTime = formatter.format(date);
				b.setBookAddTime(bookAddTime);

				Book b0 = DbDataOperation.queryBookFav(resolver,
						DbTags.FIELD_BOOK_NAME, book.File.getShortName());
				if (b0 == null) {
					DbDataOperation.insertToBookFav(resolver, b);
					Toast.makeText(MainActivity.this, "成功收藏!",
							Toast.LENGTH_LONG).show();
				}
			}
		});

	}

	/**
	 *
	 */
	class DropDownListenser implements OnNavigationListener {

		public boolean onNavigationItemSelected(int itemPosition, long itemId) {
			Message message;
			switch (itemPosition) {
			case 0:
				message = new Message();
				message.what = BOOK_SHELF;
				mHandler.sendMessage(message);
				break;

			case 1:
				message = new Message();
				message.what = BOOK_FAVORITE;
				mHandler.sendMessage(message);
				break;
			}
			return true;
		}
	}

}


text:
#include "extensions/quic_listeners/quiche/envoy_quic_server_stream.h"

#include <openssl/bio.h>
#include <openssl/evp.h>

#include <memory>

#if defined(__GNUC__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-parameter"
#pragma GCC diagnostic ignored "-Winvalid-offsetof"
#endif

#include "quiche/quic/core/http/quic_header_list.h"
#include "quiche/quic/core/quic_session.h"
#include "quiche/spdy/core/spdy_header_block.h"
#include "extensions/quic_listeners/quiche/platform/quic_mem_slice_span_impl.h"

#if defined(__GNUC__)
#pragma GCC diagnostic pop
#endif

#include "extensions/quic_listeners/quiche/envoy_quic_utils.h"
#include "extensions/quic_listeners/quiche/envoy_quic_server_session.h"

#include "common/buffer/buffer_impl.h"
#include "common/http/header_map_impl.h"
#include "common/common/assert.h"

namespace Envoy {
namespace Quic {

EnvoyQuicServerStream::EnvoyQuicServerStream(quic::QuicStreamId id, quic::QuicSpdySession* session,
                                             quic::StreamType type)
    : quic::QuicSpdyServerStreamBase(id, session, type),
      EnvoyQuicStream(
          // This should be larger than 8k to fully utilize congestion control
          // window. And no larger than the max stream flow control window for
          // the stream to buffer all the data.
          // Ideally this limit should also correlate to peer's receive window
          // but not fully depends on that.
          16 * 1024, [this]() { runLowWatermarkCallbacks(); },
          [this]() { runHighWatermarkCallbacks(); }) {}

EnvoyQuicServerStream::EnvoyQuicServerStream(quic::PendingStream* pending,
                                             quic::QuicSpdySession* session, quic::StreamType type)
    : quic::QuicSpdyServerStreamBase(pending, session, type),
      EnvoyQuicStream(
          // This should be larger than 8k to fully utilize congestion control
          // window. And no larger than the max stream flow control window for
          // the stream to buffer all the data.
          16 * 1024, [this]() { runLowWatermarkCallbacks(); },
          [this]() { runHighWatermarkCallbacks(); }) {}

void EnvoyQuicServerStream::encode100ContinueHeaders(const Http::ResponseHeaderMap& headers) {
  ASSERT(headers.Status()->value() == "100");
  encodeHeaders(headers, false);
}

void EnvoyQuicServerStream::encodeHeaders(const Http::ResponseHeaderMap& headers, bool end_stream) {
  ENVOY_STREAM_LOG(debug, "encodeHeaders (end_stream={}) {}.", *this, end_stream, headers);
  // QUICHE guarantees to take all the headers. This could cause infinite data to
  // be buffered on headers stream in Google QUIC implementation because
  // headers stream doesn't have upper bound for its send buffer. But in IETF
  // QUIC implementation this is safe as headers are sent on data stream which
  // is bounded by max concurrent streams limited.
  // Same vulnerability exists in crypto stream which can infinitely buffer data
  // if handshake implementation goes wrong.
  // TODO(#8826) Modify QUICHE to have an upper bound for header stream send buffer.
  // This is counting not serialized bytes in the send buffer.
  quic::QuicStream* writing_stream =
      quic::VersionUsesHttp3(transport_version())
          ? static_cast<quic::QuicStream*>(this)
          : (dynamic_cast<quic::QuicSpdySession*>(session())->headers_stream());
  const uint64_t bytes_to_send_old = writing_stream->BufferedDataBytes();

  WriteHeaders(envoyHeadersToSpdyHeaderBlock(headers), end_stream, nullptr);
  local_end_stream_ = end_stream;
  const uint64_t bytes_to_send_new = writing_stream->BufferedDataBytes();
  ASSERT(bytes_to_send_old <= bytes_to_send_new);
  maybeCheckWatermark(bytes_to_send_old, bytes_to_send_new, *filterManagerConnection());
}

void EnvoyQuicServerStream::encodeData(Buffer::Instance& data, bool end_stream) {
  ENVOY_STREAM_LOG(debug, "encodeData (end_stream={}) of {} bytes.", *this, end_stream,
                   data.length());
  local_end_stream_ = end_stream;
  // This is counting not serialized bytes in the send buffer.
  const uint64_t bytes_to_send_old = BufferedDataBytes();
  // QUIC stream must take all.
  WriteBodySlices(quic::QuicMemSliceSpan(quic::QuicMemSliceSpanImpl(data)), end_stream);
  if (data.length() > 0) {
    // Send buffer didn't take all the data, threshold needs to be adjusted.
    Reset(quic::QUIC_BAD_APPLICATION_PAYLOAD);
    return;
  }

  const uint64_t bytes_to_send_new = BufferedDataBytes();
  ASSERT(bytes_to_send_old <= bytes_to_send_new);
  maybeCheckWatermark(bytes_to_send_old, bytes_to_send_new, *filterManagerConnection());
}

void EnvoyQuicServerStream::encodeTrailers(const Http::ResponseTrailerMap& trailers) {
  ASSERT(!local_end_stream_);
  local_end_stream_ = true;
  ENVOY_STREAM_LOG(debug, "encodeTrailers: {}.", *this, trailers);
  quic::QuicStream* writing_stream =
      quic::VersionUsesHttp3(transport_version())
          ? static_cast<quic::QuicStream*>(this)
          : (dynamic_cast<quic::QuicSpdySession*>(session())->headers_stream());
  const uint64_t bytes_to_send_old = writing_stream->BufferedDataBytes();
  WriteTrailers(envoyHeadersToSpdyHeaderBlock(trailers), nullptr);
  const uint64_t bytes_to_send_new = writing_stream->BufferedDataBytes();
  ASSERT(bytes_to_send_old <= bytes_to_send_new);
  maybeCheckWatermark(bytes_to_send_old, bytes_to_send_new, *filterManagerConnection());
}

void EnvoyQuicServerStream::encodeMetadata(const Http::MetadataMapVector& /*metadata_map_vector*/) {
  // Metadata Frame is not supported in QUIC.
  // TODO(danzh): add stats for metadata not supported error.
}

void EnvoyQuicServerStream::resetStream(Http::StreamResetReason reason) {
  // Upper layers expect calling resetStream() to immediately raise reset callbacks.
  runResetCallbacks(reason);
  if (local_end_stream_ && !reading_stopped()) {
    // This is after 200 early response. Reset with QUIC_STREAM_NO_ERROR instead
    // of propagating original reset reason. In QUICHE if a stream stops reading
    // before FIN or RESET received, it resets the steam with QUIC_STREAM_NO_ERROR.
    StopReading();
  } else {
    Reset(envoyResetReasonToQuicRstError(reason));
  }
}

void EnvoyQuicServerStream::switchStreamBlockState(bool should_block) {
  ASSERT(FinishedReadingHeaders(),
         "Upperstream buffer limit is reached before request body is delivered.");
  if (should_block) {
    sequencer()->SetBlockedUntilFlush();
  } else {
    ASSERT(read_disable_counter_ == 0, "readDisable called in between.");
    sequencer()->SetUnblocked();
  }
}

void EnvoyQuicServerStream::OnInitialHeadersComplete(bool fin, size_t frame_len,
                                                     const quic::QuicHeaderList& header_list) {
  quic::QuicSpdyServerStreamBase::OnInitialHeadersComplete(fin, frame_len, header_list);
  ASSERT(headers_decompressed());
  request_decoder_->decodeHeaders(
      quicHeadersToEnvoyHeaders<Http::RequestHeaderMapImpl>(header_list), /*end_stream=*/fin);
  if (fin) {
    end_stream_decoded_ = true;
  }
  ConsumeHeaderList();
}

void EnvoyQuicServerStream::OnBodyAvailable() {
  ASSERT(FinishedReadingHeaders());
  ASSERT(read_disable_counter_ == 0);
  ASSERT(!in_decode_data_callstack_);
  in_decode_data_callstack_ = true;

  Buffer::InstancePtr buffer = std::make_unique<Buffer::OwnedImpl>();
  // TODO(danzh): check Envoy per stream buffer limit.
  // Currently read out all the data.
  while (HasBytesToRead()) {
    iovec iov;
    int num_regions = GetReadableRegions(&iov, 1);
    ASSERT(num_regions > 0);
    size_t bytes_read = iov.iov_len;
    Buffer::RawSlice slice;
    buffer->reserve(bytes_read, &slice, 1);
    ASSERT(slice.len_ >= bytes_read);
    slice.len_ = bytes_read;
    memcpy(slice.mem_, iov.iov_base, iov.iov_len);
    buffer->commit(&slice, 1);
    MarkConsumed(bytes_read);
  }

  // True if no trailer and FIN read.
  bool finished_reading = IsDoneReading();
  bool empty_payload_with_fin = buffer->length() == 0 && fin_received();
  // If this call is triggered by an empty frame with FIN which is not from peer
  // but synthesized by stream itself upon receiving HEADERS with FIN or
  // TRAILERS, do not deliver end of stream here. Because either decodeHeaders
  // already delivered it or decodeTrailers will be called.
  bool skip_decoding = empty_payload_with_fin && (end_stream_decoded_ || !finished_reading);
  if (!skip_decoding) {
    request_decoder_->decodeData(*buffer, finished_reading);
    if (finished_reading) {
      end_stream_decoded_ = true;
    }
  }

  if (!sequencer()->IsClosed()) {
    in_decode_data_callstack_ = false;
    if (read_disable_counter_ > 0) {
      // If readDisable() was ever called during decodeData() and it meant to disable
      // reading from downstream, the call must have been deferred. Call it now.
      switchStreamBlockState(true);
    }
    return;
  }

  if (!quic::VersionUsesHttp3(transport_version()) && !FinishedReadingTrailers()) {
    // For Google QUIC implementation, trailers may arrived earlier and wait to
    // be consumed after reading all the body. Consume it here.
    // IETF QUIC shouldn't reach here because trailers are sent on same stream.
    request_decoder_->decodeTrailers(
        spdyHeaderBlockToEnvoyHeaders<Http::RequestTrailerMapImpl>(received_trailers()));
    MarkTrailersConsumed();
  }
  OnFinRead();
  in_decode_data_callstack_ = false;
}

void EnvoyQuicServerStream::OnTrailingHeadersComplete(bool fin, size_t frame_len,
                                                      const quic::QuicHeaderList& header_list) {
  quic::QuicSpdyServerStreamBase::OnTrailingHeadersComplete(fin, frame_len, header_list);
  if (session()->connection()->connected() &&
      (quic::VersionUsesHttp3(transport_version()) || sequencer()->IsClosed()) &&
      !FinishedReadingTrailers()) {
    // Before QPack trailers can arrive before body. Only decode trailers after finishing decoding
    // body.
    request_decoder_->decodeTrailers(
        spdyHeaderBlockToEnvoyHeaders<Http::RequestTrailerMapImpl>(received_trailers()));
    MarkTrailersConsumed();
  }
}

void EnvoyQuicServerStream::OnStreamReset(const quic::QuicRstStreamFrame& frame) {
  quic::QuicSpdyServerStreamBase::OnStreamReset(frame);
  runResetCallbacks(quicRstErrorToEnvoyResetReason(frame.error_code));
}

void EnvoyQuicServerStream::OnConnectionClosed(quic::QuicErrorCode error,
                                               quic::ConnectionCloseSource source) {
  quic::QuicSpdyServerStreamBase::OnConnectionClosed(error, source);
  runResetCallbacks(quicErrorCodeToEnvoyResetReason(error));
}

void EnvoyQuicServerStream::OnClose() {
  quic::QuicSpdyServerStreamBase::OnClose();
  if (BufferedDataBytes() > 0) {
    // If the stream is closed without sending out all buffered data, regard
    // them as sent now and adjust connection buffer book keeping.
    filterManagerConnection()->adjustBytesToSend(0 - BufferedDataBytes());
  }
}

void EnvoyQuicServerStream::OnCanWrite() {
  const uint64_t buffered_data_old = BufferedDataBytes();
  quic::QuicSpdyServerStreamBase::OnCanWrite();
  const uint64_t buffered_data_new = BufferedDataBytes();
  // As long as OnCanWriteNewData() is no-op, data to sent in buffer shouldn't
  // increase.
  ASSERT(buffered_data_new <= buffered_data_old);
  maybeCheckWatermark(buffered_data_old, buffered_data_new, *filterManagerConnection());
}

uint32_t EnvoyQuicServerStream::streamId() { return id(); }

Network::Connection* EnvoyQuicServerStream::connection() { return filterManagerConnection(); }

QuicFilterManagerConnectionImpl* EnvoyQuicServerStream::filterManagerConnection() {
  return dynamic_cast<QuicFilterManagerConnectionImpl*>(session());
}

} // namespace Quic
} // namespace Envoy

redpajama_set_name: RedPajamaGithub


text:
using Mikaboshi.Locapos.Response;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;

namespace Mikaboshi.Locapos
{
    public class Users
    {
        private static readonly string usersUri = LocaposClientInternal.ApiUri + "users/";
        private static readonly string showUri = usersUri + "show";
        private static readonly string meUri = usersUri + "me";
        private static readonly string shareUri = usersUri + "share";
        private static readonly string updateNameUri = usersUri + "update";

        private readonly LocaposClient client;

        internal Users(LocaposClient client)
        {
            this.client = client;
        }

        /// <summary>
        /// 現在アクティブなユーザーの情報を取得します。<paramref name="groupId"/> を使用して、該当するグループの絞り込みをおこないます。
        /// </summary>
        /// <param name="groupId">指定した場合、該当するグループ ID でアクティブなユーザー一覧を取得します。</param>
        /// <returns></returns>
        public async Task<UsersShowResponse> Show(string groupId = "")
        {
            this.client.CheckToken();

            var http = LocaposClientInternal.GetHttpClient(this.client.ClientToken);
            var request = LocaposClientInternal.CreateGetRequest(showUri +
                (!string.IsNullOrWhiteSpace(groupId) ? "?key=" + groupId : string.Empty));
            var response = await http.SendAsync(request);
            var result = new UsersShowResponse();
            await result.SetResponseAsync(response);

            return result;
        }

        /// <summary>
        /// 自分自身の情報を取得します。
        /// </summary>
        /// <returns></returns>
        public async Task<UsersMeResponse> Me()
        {
            this.client.CheckToken();

            var http = LocaposClientInternal.GetHttpClient(this.client.ClientToken);
            var request = LocaposClientInternal.CreateGetRequest(meUri);
            var response = await http.SendAsync(request);
            var result = new UsersMeResponse();
            await result.SetResponseAsync(response);

            return result;
        }

        /// <summary>
        /// 自分自身を示す暗黙的なグループ ハッシュを取得します。
        /// </summary>
        /// <returns></returns>
        public async Task<GroupHashResponse> Share()
        {
            this.client.CheckToken();

            var http = LocaposClientInternal.GetHttpClient(this.client.ClientToken);
            var request = LocaposClientInternal.CreateGetRequest(shareUri);
            var response = await http.SendAsync(request);
            var result = new GroupHashResponse();
            await result.SetResponseAsync(response);

            return result;
        }

        public async Task<BaseResponse> Update(string screenName)
        {
            this.client.CheckToken();

            var http = LocaposClientInternal.GetHttpClient(this.client.ClientToken);
            var contentDict = new Dictionary<string, string>
                {
                    { "screen_name", screenName }
                };

            var content = new FormUrlEncodedContent(contentDict);

            var request = await LocaposClientInternal.CreatePostRequestAsync(updateNameUri, content);
            var response = await http.SendAsync(request);
            var result = new BaseResponse();
            await result.SetResponseAsync(response);

            return result;
        }
    }
}


text:
package org.drools.workbench.screens.dtablexls.backend.server.conversion.builders;

import org.drools.decisiontable.parser.ActionType;
import org.drools.decisiontable.parser.RuleSheetParserUtil;
import org.drools.workbench.models.guided.dtable.shared.conversion.ConversionResult;
import org.drools.workbench.models.guided.dtable.shared.model.AttributeCol52;
import org.drools.workbench.models.guided.dtable.shared.model.DTCellValue52;
import org.drools.workbench.models.guided.dtable.shared.model.GuidedDecisionTable52;

/**
 * Builder for AutoFocus Attribute columns
 */
public class GuidedDecisionTableAutoFocusBuilder extends AbstractGuidedDecisionTableAttributeBuilder {

    public GuidedDecisionTableAutoFocusBuilder( final int row,
                                                final int column,
                                                final ConversionResult conversionResult ) {
        super( row,
               column,
               ActionType.Code.AUTOFOCUS,
               conversionResult );
    }

    @Override
    public void populateDecisionTable( final GuidedDecisionTable52 dtable,
                                       final int maxRowCount ) {
        final AttributeCol52 column = new AttributeCol52();
        column.setAttribute( GuidedDecisionTable52.AUTO_FOCUS_ATTR );
        dtable.getAttributeCols().add( column );

        if ( this.values.size() < maxRowCount ) {
            for ( int iRow = this.values.size(); iRow < maxRowCount; iRow++ ) {
                this.values.add( new DTCellValue52( RuleSheetParserUtil.isStringMeaningTrue( "" ) ) );
            }
        }

        addColumnData( dtable,
                       column );
    }

    @Override
    public void addCellValue( final int row,
                              final int column,
                              final String value ) {
        final DTCellValue52 dcv = new DTCellValue52( RuleSheetParserUtil.isStringMeaningTrue( value ) );
        this.values.add( dcv );
    }

}


text:
package com.intellij.ui;

import com.intellij.openapi.components.ServiceManager;
import org.jetbrains.annotations.NotNull;

/**
 * @author mike
 */
public abstract class SystemNotifications {
  public static SystemNotifications getInstance() {
    return ServiceManager.getService(SystemNotifications.class);
  }

  public abstract void notify(@NotNull String notificationName, @NotNull String title, @NotNull String text);
}


text:
'use strict';

// MODULES //

var logger = require( 'debug' );
var contains = require( '@stdlib/assert/contains' );
var format = require( '@stdlib/string/format' );
var CHART_TYPES = require( './chart_types.json' );

// VARIABLES //

var debug = logger( 'sparkline:unicode:set:type' );

// MAIN //

/**
* Sets the sparkline chart type.
*
* @private
* @param {string} type - chart type
* @throws {TypeError} must be a supported chart type
*/
function set( type ) {
	/* eslint-disable no-invalid-this */
	if ( !contains( CHART_TYPES, type ) ) {
		throw new TypeError( format( 'invalid assignment. `%s` must be one of the following: "%s". Value: `%s`.', 'type', CHART_TYPES.join( '", "' ), type ) );
	}
	if ( type !== this._type ) {
		debug( 'Current value: %s.', this._type );

		this._type = type;
		debug( 'New value: %s.', this._type );

		this.emit( 'change' );
	}
}

// EXPORTS //

module.exports = set;


text:
// Copyright (c) Dapplo and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;

namespace Dapplo.Windows.Multimedia.Enums;

///
///     See PlaySound
///
[Flags]
public enum SoundSettings : uint
{
    ///
    ///     Default: Synchronous playback of a sound event. PlaySound returns after the sound event completes.
    ///
    None = 0x0000,

    ///
    ///     The sound is played asynchronously and PlaySound returns immediately after beginning the sound. To terminate an
    ///     asynchronously played waveform sound, call PlaySound with pszSound set to NULL.
    ///
    Async = 0x0001,

    ///
    ///     No default sound event is used. If the sound cannot be found, PlaySound returns silently without playing the
    ///     default sound.
    ///
    NoDefault = 0x0002,

    ///
    /// The pszSound parameter points to a sound loaded in memory.
    ///  see Playing WAVE Resources
    ///
    Memory = 0x0004,

    ///
    ///     The sound plays repeatedly until PlaySound is called again with the pszSound parameter set to NULL. You must also
    ///     specify the SND_ASYNC flag to indicate an asynchronous sound event.
    ///
    Loop = 0x0008,

    ///
    ///     The specified sound event will yield to another sound event that is already playing. If a sound cannot be played
    ///     because the resource needed to generate that sound is busy playing another sound, the function immediately returns
    ///     FALSE without playing the requested sound.
    ///     If this flag is not specified, PlaySound attempts to stop the currently playing sound so that the device can be
    ///     used to play the new sound.
    ///
    NoStop = 0x0010,

    ///
    ///     Not supported.
    ///
    NoWait = 0x00002000,
    ///
    ///     Not supported.
    ///
    Purge = 0x0040,

    ///
    ///     The pszSound parameter is a system-event alias in the registry or the WIN.INI file. Do not use with either
    ///     SND_FILENAME or SND_RESOURCE.
    ///
    Alias = 0x00010000,

    ///
    ///     The pszSound parameter is a predefined id
    ///
    AliasId = 0x00110000,

    ///
    ///     The pszSound parameter is a file name.
    ///
    Filename = 0x00020000,

    ///
    /// The pszSound parameter is a resource identifier; hmod must identify the instance that contains the resource.
    /// see Playing WAVE Resources
    ///
    Resource = 0x00040004,

    ///
    /// If this flag is set, the function triggers a SoundSentry event when the sound is played.
    /// SoundSentry is an accessibility feature that causes the computer to display a visual cue when a sound is played. If the user did not enable SoundSentry, the visual cue is not displayed.
    ///
    Sentry = 0x00080000,

    ///
    /// If this flag is set, the sound is assigned to the audio session for system notification sounds. The system volume-control program (SndVol) displays a volume slider that controls system notification sounds. Setting this flag puts the sound under the control of that volume slider
    /// If this flag is not set, the sound is assigned to the default audio session for the application's process.
    /// For more information, see the documentation for the Core Audio APIs.
    ///
    System = 0x00200000
}


text:
/**
 *
 */
package org.etagate.auth;

import io.vertx.ext.web.Router;

/**
 * @author 瞿建军       Email: troopson@163.com
 * 2017年5月19日
 */
public class AuthRoute {

	public static void addAuthRoute(Router router,AuthMgr authMgr){

		GateAuthHandler handler = new GateAuthHandler(authMgr);
		router.route().handler(handler);

	}

}


text:
package org.killbill.billing.plugin.coupon.api.user;

import org.killbill.billing.plugin.coupon.api.exception.CouponApiException;
import org.killbill.billing.plugin.coupon.api.model.Coupon;
import org.killbill.billing.plugin.coupon.dao.CouponDao;
import org.killbill.billing.util.callcontext.TenantContext;

import javax.inject.Inject;

public class DefaultCouponUserApi implements CouponUserApi {

    private static final String AGGREGATE_METRIC_NAME = "__AGGREGATE__";

    private final CouponDao couponDao;

    @Inject
    public DefaultCouponUserApi(final CouponDao couponDao) {
        this.couponDao = couponDao;
    }

    @Override
    public Coupon getCouponByCode(String couponCode, TenantContext context) throws CouponApiException {
        return couponDao.getCouponByCode(couponCode, context);
    }

//    @Override
//    public void getUsage(final OutputStream outputStream, final TimeAggregationMode timeAggregationMode,
//                         final String source, final Collection<String> categories,
//                         final DateTime fromTimestamp, final DateTime toTimestamp, final TenantContext context) throws IOException {
//        final ImmutableMap.Builder<String, Collection<String>> metricsPerCategory = new Builder<String, Collection<String>>();
//        for (final String category : categories) {
//            metricsPerCategory.put(category, ImmutableList.<String>of(AGGREGATE_METRIC_NAME));
//        }
//
//        getUsage(outputStream, timeAggregationMode, source, metricsPerCategory.build(), fromTimestamp, toTimestamp, context);
//    }
//
//    @Override
//    public void getUsage(final OutputStream outputStream, final TimeAggregationMode timeAggregationMode,
//                         final String source, final Map<String, Collection<String>> metricsPerCategory,
//                         final DateTime fromTimestamp, final DateTime toTimestamp, final TenantContext context) throws IOException {
//        final JsonSamplesOutputer outputerJson = new AccumulatingJsonSamplesOutputer(timeAggregationMode, timelineEventHandler, couponDao, context);
//        outputerJson.output(outputStream, ImmutableList.<String>of(source), metricsPerCategory, fromTimestamp, toTimestamp);
//    }
//
//    @Override
//    public void getUsage(final OutputStream outputStream, final DecimationMode decimationMode, @Nullable final Integer outputCount,
//                         final String source, final Map<String, Collection<String>> metricsPerCategory,
//                         final DateTime fromTimestamp, final DateTime toTimestamp, final TenantContext context) throws IOException {
//        final JsonSamplesOutputer outputerJson = new DecimatingJsonSamplesOutputer(decimationMode, outputCount, timelineEventHandler, couponDao, context);
//        outputerJson.output(outputStream, ImmutableList.<String>of(source), metricsPerCategory, fromTimestamp, toTimestamp);
//    }
//
//    @Override
//    public void getUsage(final OutputStream outputStream, final String source, final Collection<String> categories,
//                         final DateTime fromTimestamp, final DateTime toTimestamp, final TenantContext context) throws IOException {
//        final ImmutableMap.Builder<String, Collection<String>> metricsPerCategory = new Builder<String, Collection<String>>();
//        for (final String category : categories) {
//            metricsPerCategory.put(category, ImmutableList.<String>of(AGGREGATE_METRIC_NAME));
//        }
//
//        getUsage(outputStream, source, metricsPerCategory.build(), fromTimestamp, toTimestamp, context);
//    }
//
//    @Override
//    public void getUsage(final OutputStream outputStream, final String source, final Map<String, Collection<String>> metricsPerCategory,
//                         final DateTime fromTimestamp, final DateTime toTimestamp, final TenantContext context) throws IOException {
//        final JsonSamplesOutputer outputerJson = new DefaultJsonSamplesOutputer(timelineEventHandler, couponDao, context);
//        outputerJson.output(outputStream, ImmutableList.<String>of(source), metricsPerCategory, fromTimestamp, toTimestamp);
//    }
//
//    @Override
//    public void incrementUsage(final String source, final String categoryName, final String metricName,
//                               final DateTime timestamp, final CallContext context) {
//        recordUsage(source,
//                    ImmutableMap.<String, Map<String, Object>>of(categoryName, ImmutableMap.<String, Object>of(metricName, (short) 1)),
//                    timestamp,
//                    context);
//    }
//
//    @Override
//    public void incrementUsageAndAggregate(final String source, final String categoryName, final String metricName,
//                                           final DateTime timestamp, final CallContext context) {
//        recordUsage(source,
//                    ImmutableMap.<String, Map<String, Object>>of(categoryName, ImmutableMap.<String, Object>of(metricName, (short) 1, AGGREGATE_METRIC_NAME, (short) 1)),
//                    timestamp,
//                    context);
//    }
//
//    @Override
//    public void recordUsage(final String source, final Map<String, Map<String, Object>> samplesForCategoriesAndMetrics,
//                            final DateTime timestamp, final CallContext context) {
//        for (final String category : samplesForCategoriesAndMetrics.keySet()) {
//            timelineEventHandler.record(source, category, timestamp, samplesForCategoriesAndMetrics.get(category), context);
//        }
//    }
}


text:
namespace FickleFrostbite.SQL
{
    using System;
    using System.Collections.Generic;

    public partial class Activity
    {
        public Activity()
        {
            this.Laps = new HashSet<Lap>();
        }

        public int ActivityId { get; set; }
        public string TcxActivityId { get; set; }
        public string Sport { get; set; }

        public virtual ICollection<Lap> Laps { get; set; }
    }
}


text:
package com.davidstemmer.screenplay.stage.component;

import android.os.Parcelable;
import android.util.SparseArray;

import com.davidstemmer.screenplay.stage.Stage;

import javax.inject.Inject;

/**
 * Saves the instance state of a Scene's View when it is torn down and restores it when it
 * is set up.
 */
public class InstanceStateComponent implements Stage.Component {

    private final SparseArray<Parcelable> savedState = new SparseArray<>();

    @Inject
    public InstanceStateComponent() {}

    @Override
    public void afterSetUp(final Stage stage, boolean isStarting) {
        stage.getView().post(new Runnable() {
            @Override
            public void run() {
                if (stage.getView() != null) {
                    stage.getView().restoreHierarchyState(savedState);
                    savedState.clear();
                }
            }
        });
    }

    @Override
    public void beforeTearDown(final Stage stage, boolean isFinishing) {
        stage.getView().saveHierarchyState(savedState);
    }
}


text:
This is the entire source code of the official [F8](https://fbf8.com/) app of 2016, available on [Google Play](https://play.google.com/store/apps/details?id=com.facebook.f8) and the [App Store](https://itunes.apple.com/us/app/f8/id853467066).

## How We Build It

We've created a series of tutorials at [makeitopen.com](http://makeitopen.com/) that explain how we built the app, and that dive into how we used React Native, Redux, Relay, GraphQL, and more.

## Requirements

1. [React Native](http://facebook.github.io/react-native/docs/getting-started.html) (follow iOS and Android guides)
  - Xcode 7.3 +
2. [CocoaPods](http://cocoapods.org) (only for iOS)
  - Version 1.0+ recommended (`gem install cocoapods --pre`)
3. [MongoDB](https://www.mongodb.org/downloads) (needed to run Parse Server locally)

## Setup

1. **Clone the repo**

  ```
  $ git clone https://github.com/fbsamples/f8app.git
  $ cd f8app
  ```

2. **Install dependencies** (npm v3+):

  ```
  $ npm install
  $ (cd ios; pod install)        # only for iOS version
  ```

3. **Make sure MongoDB is running:**

  ```
  $ lsof -iTCP:27017 -sTCP:LISTEN
  ```

  NOTE: if installed with [Homebrew](http://brew.sh/) run `brew info mongo` and
  check out the Caveats section.

  If you prefer to use an external MongoDB server, set `DATABASE_URI`:

  ```
  $ export DATABASE_URI=mongodb://example-mongo-hosting.com:1337/my-awesome-database
  ```

4. **Start Parse/GraphQL servers:**

  ```
  $ npm start
  ```

5. **Import sample data** (the local Parse Server should be running):

  ```
  $ npm run import-data
  ```

  Make sure everything works by visiting:

  * Parse Dashboard: [http://localhost:8080/dashboard](http://localhost:8080/dashboard)
  * Graph*i*QL: [http://localhost:8080/graphql](http://localhost:8080/graphql?query=query+%7B%0A++schedule+%7B%0A++++title%0A++++speakers+%7B%0A++++++name%0A++++++title%0A++++%7D%0A++++location+%7B%0A++++++name%0A++++%7D%0A++%7D%0A%7D)

6. **Running on Android**:

  ```
  $ react-native run-android
  $ adb reverse tcp:8081 tcp:8081   # required to ensure the Android app can
  $ adb reverse tcp:8080 tcp:8080   # access the Packager and GraphQL server
  ```

7. **Running on iOS:**

  ```
  $ react-native run-ios
  ```

## Troubleshooting

> Could not connect to development server

In a separate terminal window run:

  ```
  $ react-native start
  ```


text:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:clickable="false"
    android:focusable="false">

    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="@color/nav_drawer_item_divider"
        android:clickable="false"
        android:focusable="false" />

</FrameLayout>


text:
<?php

namespace Ekyna\Component\Characteristics\Form\Type;

use Doctrine\ORM\EntityRepository;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

/**
 * Class ChoiceCharacteristicType
 * @package Ekyna\Component\Characteristics\Form\Type
 * @author Étienne Dauvergne <contact@ekyna.com>
 */
class ChoiceCharacteristicType extends AbstractCharacteristicType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('choice', 'entity', array(
            'label' => false,
            'required' => false,
            'empty_value' => 'Undefined',
            'empty_data'  => null,
            'class' => 'Ekyna\Component\Characteristics\Entity\ChoiceCharacteristicValue',
            'property' => 'value',
            'query_builder' => function(EntityRepository $er) use ($options) {
                return $er
                    ->createQueryBuilder('c')
                    ->where('c.identifier = :identifier')
                    ->setParameter('identifier', $options['identifier'])
                    ->orderBy('c.value', 'ASC')
                ;
            }
        ));
    }

    /**
     * {@inheritDoc}
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        parent::setDefaultOptions($resolver);

        $resolver
            ->setDefaults(array(
                'data_class' => 'Ekyna\Component\Characteristics\Entity\ChoiceCharacteristic',
                'identifier' => null
            ))
            ->setAllowedTypes(array(
                'identifier' => 'string'
            ))
            ->setRequired(array('identifier'))
        ;
    }

    /**
     * {@inheritDoc}
     */
    public function getName()
    {
        return 'ekyna_choice_characteristic';
    }
}


text:
package com.vaadin.v7.data.util;

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

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

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

public class NestedMethodPropertyTest {

    public static class Address implements Serializable {
        private String street;
        private int postalCodePrimitive;
        private Integer postalCodeObject;

        public Address(String street, int postalCode) {
            this.street = street;
            postalCodePrimitive = postalCode;
            postalCodeObject = postalCode;
        }

        public void setStreet(String street) {
            this.street = street;
        }

        public String getStreet() {
            return street;
        }

        public void setPostalCodePrimitive(int postalCodePrimitive) {
            this.postalCodePrimitive = postalCodePrimitive;
        }

        public int getPostalCodePrimitive() {
            return postalCodePrimitive;
        }

        public void setPostalCodeObject(Integer postalCodeObject) {
            this.postalCodeObject = postalCodeObject;
        }

        public Integer getPostalCodeObject() {
            return postalCodeObject;
        }

        // read-only boolean property
        public boolean isBoolean() {
            return true;
        }
    }

    public static class Person implements Serializable {
        private String name;
        private Address address;
        private int age;

        public Person(String name, Address address) {
            this.name = name;
            this.address = address;
        }

        public Person(String name, Address address, int age) {
            this.name = name;
            this.address = address;
            this.age = age;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getName() {
            return name;
        }

        public void setAddress(Address address) {
            this.address = address;
        }

        public Address getAddress() {
            return address;
        }

        public int getAge() {
            return age;
        }

        public void setAge(int age) {
            this.age = age;
        }
    }

    public static class Team implements Serializable {
        private String name;
        private Person manager;

        public Team(String name, Person manager) {
            this.name = name;
            this.manager = manager;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getName() {
            return name;
        }

        public void setManager(Person manager) {
            this.manager = manager;
        }

        public Person getManager() {
            return manager;
        }
    }

    private Address oldMill;
    private Person joonas;
    private Team vaadin;

    @Before
    public void setUp() {
        oldMill = new Address("Ruukinkatu 2-4", 20540);
        joonas = new Person("Joonas", oldMill);
        vaadin = new Team("Vaadin", joonas);
    }

    @Test
    public void testSingleLevelNestedSimpleProperty() {
        NestedMethodProperty<String> nameProperty = new NestedMethodProperty<String>(
                vaadin, "name");

        Assert.assertEquals(String.class, nameProperty.getType());
        Assert.assertEquals("Vaadin", nameProperty.getValue());
    }

    @Test
    public void testSingleLevelNestedObjectProperty() {
        NestedMethodProperty<Person> managerProperty = new NestedMethodProperty<Person>(
                vaadin, "manager");

        Assert.assertEquals(Person.class, managerProperty.getType());
        Assert.assertEquals(joonas, managerProperty.getValue());
    }

    @Test
    public void testMultiLevelNestedProperty() {
        NestedMethodProperty<String> managerNameProperty = new NestedMethodProperty<String>(
                vaadin, "manager.name");
        NestedMethodProperty<Address> addressProperty = new NestedMethodProperty<Address>(
                vaadin, "manager.address");
        NestedMethodProperty<String> streetProperty = new NestedMethodProperty<String>(
                vaadin, "manager.address.street");
        NestedMethodProperty<Integer> postalCodePrimitiveProperty = new NestedMethodProperty<Integer>(
                vaadin, "manager.address.postalCodePrimitive");
        NestedMethodProperty<Integer> postalCodeObjectProperty = new NestedMethodProperty<Integer>(
                vaadin, "manager.address.postalCodeObject");
        NestedMethodProperty<Boolean> booleanProperty = new NestedMethodProperty<Boolean>(
                vaadin, "manager.address.boolean");

        Assert.assertEquals(String.class, managerNameProperty.getType());
        Assert.assertEquals("Joonas", managerNameProperty.getValue());

        Assert.assertEquals(Address.class, addressProperty.getType());
        Assert.assertEquals(oldMill, addressProperty.getValue());

        Assert.assertEquals(String.class, streetProperty.getType());
        Assert.assertEquals("Ruukinkatu 2-4", streetProperty.getValue());

        Assert.assertEquals(Integer.class,
                postalCodePrimitiveProperty.getType());
        Assert.assertEquals(Integer.valueOf(20540),
                postalCodePrimitiveProperty.getValue());

        Assert.assertEquals(Integer.class, postalCodeObjectProperty.getType());
        Assert.assertEquals(Integer.valueOf(20540),
                postalCodeObjectProperty.getValue());

        Assert.assertEquals(Boolean.class, booleanProperty.getType());
        Assert.assertEquals(Boolean.TRUE, booleanProperty.getValue());
    }

    @Test
    public void testEmptyPropertyName() {
        try {
            new NestedMethodProperty<Object>(vaadin, "");
            fail();
        } catch (IllegalArgumentException e) {
            // should get exception
        }

        try {
            new NestedMethodProperty<Object>(vaadin, " ");
            fail();
        } catch (IllegalArgumentException e) {
            // should get exception
        }
    }

    @Test
    public void testInvalidPropertyName() {
        try {
            new NestedMethodProperty<Object>(vaadin, ".");
            fail();
        } catch (IllegalArgumentException e) {
            // should get exception
        }
        try {
            new NestedMethodProperty<Object>(vaadin, ".manager");
            fail();
        } catch (IllegalArgumentException e) {
            // should get exception
        }
        try {
            new NestedMethodProperty<Object>(vaadin, "manager.");
            fail();
        } catch (IllegalArgumentException e) {
            // should get exception
        }
        try {
            new NestedMethodProperty<Object>(vaadin, "manager..name");
            fail();
        } catch (IllegalArgumentException e) {
            // should get exception
        }
    }

    @Test
    public void testInvalidNestedPropertyName() {
        try {
            new NestedMethodProperty<Object>(vaadin, "member");
            fail();
        } catch (IllegalArgumentException e) {
            // should get exception
        }

        try {
            new NestedMethodProperty<Object>(vaadin, "manager.pet");
            fail();
        } catch (IllegalArgumentException e) {
            // should get exception
        }

        try {
            new NestedMethodProperty<Object>(vaadin, "manager.address.city");
            fail();
        } catch (IllegalArgumentException e) {
            // should get exception
        }
    }

    @Test
    public void testNullNestedProperty() {
        NestedMethodProperty<String> managerNameProperty = new NestedMethodProperty<String>(
                vaadin, "manager.name");
        NestedMethodProperty<String> streetProperty = new NestedMethodProperty<String>(
                vaadin, "manager.address.street");

        joonas.setAddress(null);
        assertNull(streetProperty.getValue());

        vaadin.setManager(null);
        assertNull(managerNameProperty.getValue());
        assertNull(streetProperty.getValue());

        vaadin.setManager(joonas);
        Assert.assertEquals("Joonas", managerNameProperty.getValue());
        Assert.assertNull(streetProperty.getValue());

    }

    @Test
    public void testMultiLevelNestedPropertySetValue() {
        NestedMethodProperty<String> managerNameProperty = new NestedMethodProperty<String>(
                vaadin, "manager.name");
        NestedMethodProperty<Address> addressProperty = new NestedMethodProperty<Address>(
                vaadin, "manager.address");
        NestedMethodProperty<String> streetProperty = new NestedMethodProperty<String>(
                vaadin, "manager.address.street");
        NestedMethodProperty<Integer> postalCodePrimitiveProperty = new NestedMethodProperty<Integer>(
                vaadin, "manager.address.postalCodePrimitive");
        NestedMethodProperty<Integer> postalCodeObjectProperty = new NestedMethodProperty<Integer>(
                vaadin, "manager.address.postalCodeObject");

        managerNameProperty.setValue("Joonas L");
        Assert.assertEquals("Joonas L", joonas.getName());
        streetProperty.setValue("Ruukinkatu");
        Assert.assertEquals("Ruukinkatu", oldMill.getStreet());
        postalCodePrimitiveProperty.setValue(0);
        postalCodeObjectProperty.setValue(1);
        Assert.assertEquals(0, oldMill.getPostalCodePrimitive());
        Assert.assertEquals(Integer.valueOf(1), oldMill.getPostalCodeObject());

        postalCodeObjectProperty.setValue(null);
        Assert.assertNull(oldMill.getPostalCodeObject());

        Address address2 = new Address("Other street", 12345);
        addressProperty.setValue(address2);
        Assert.assertEquals("Other street", streetProperty.getValue());
    }

    @Test
    public void testSerialization() throws IOException, ClassNotFoundException {
        NestedMethodProperty<String> streetProperty = new NestedMethodProperty<String>(
                vaadin, "manager.address.street");
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        new ObjectOutputStream(baos).writeObject(streetProperty);
        @SuppressWarnings("unchecked")
        NestedMethodProperty<String> property2 = (NestedMethodProperty<String>) new ObjectInputStream(
                new ByteArrayInputStream(baos.toByteArray())).readObject();

        Assert.assertEquals("Ruukinkatu 2-4", property2.getValue());
    }

    @Test
    public void testSerializationWithIntermediateNull()
            throws IOException, ClassNotFoundException {
        vaadin.setManager(null);
        NestedMethodProperty<String> streetProperty = new NestedMethodProperty<String>(
                vaadin, "manager.address.street");
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        new ObjectOutputStream(baos).writeObject(streetProperty);
        @SuppressWarnings("unchecked")
        NestedMethodProperty<String> property2 = (NestedMethodProperty<String>) new ObjectInputStream(
                new ByteArrayInputStream(baos.toByteArray())).readObject();

        Assert.assertNull(property2.getValue());
    }

    @Test
    public void testIsReadOnly() {
        NestedMethodProperty<String> streetProperty = new NestedMethodProperty<String>(
                vaadin, "manager.address.street");
        NestedMethodProperty<Boolean> booleanProperty = new NestedMethodProperty<Boolean>(
                vaadin, "manager.address.boolean");

        Assert.assertFalse(streetProperty.isReadOnly());
        Assert.assertTrue(booleanProperty.isReadOnly());
    }

    @Test
    public void testChangeInstance() {
        NestedMethodProperty<String> streetProperty = new NestedMethodProperty<String>(
                vaadin, "manager.address.street");

        Address somewhere = new Address("The street", 1234);
        Person someone = new Person("Someone", somewhere);
        Team someteam = new Team("The team", someone);
        streetProperty.setInstance(someteam);

        Assert.assertEquals("The street", streetProperty.getValue());
        Assert.assertEquals("Ruukinkatu 2-4", vaadin.getManager().getAddress()
                .getStreet());
    }

    @Test(expected = IllegalArgumentException.class)
    public void testChangeInstanceToIncompatible() {
        NestedMethodProperty<String> streetProperty = new NestedMethodProperty<String>(
                vaadin, "manager.address.street");

        streetProperty.setInstance("bar");
    }

}


text:
package simpledb;

import java.io.*;

/**
 * Instance of Field that stores a single String of a fixed length.
 */
public class StringField implements Field {

	private static final long serialVersionUID = 1L;

	private final String value;
	private final int maxSize;

	public String getValue() {
		return value;
	}

	/**
	 * Constructor.
	 *
	 * @param s
	 *            The value of this field.
	 * @param maxSize
	 *            The maximum size of this string
	 */
	public StringField(String s, int maxSize) {
		this.maxSize = maxSize;

		if (s.length() > maxSize)
			value = s.substring(0, maxSize);
		else
			value = s;
	}

	public String toString() {
		return value;
	}

	public int hashCode() {
		return value.hashCode();
	}

	public boolean equals(Object field) {
		return ((StringField) field).value.equals(value);
	}

	/**
	 * Write this string to dos. Always writes maxSize + 4 bytes to the passed
	 * in dos. First four bytes are string length, next bytes are string, with
	 * remainder padded with 0 to maxSize.
	 *
	 * @param dos
	 *            Where the string is written
	 */
	public void serialize(DataOutputStream dos) throws IOException {
		String s = value;
		int overflow = maxSize - s.length();
		if (overflow < 0) {
			String news = s.substring(0, maxSize);
			s = news;
		}
		dos.writeInt(s.length());
		dos.writeBytes(s);
		while (overflow-- > 0)
			dos.write((byte) 0);
	}

	/**
	 * Compare the specified field to the value of this Field. Return semantics
	 * are as specified by Field.compare
	 *
	 * @throws IllegalCastException
	 *             if val is not a StringField
	 * @see Field#compare
	 */
	public boolean compare(Predicate.Op op, Field val) {

		StringField iVal = (StringField) val;
		int cmpVal = value.compareTo(iVal.value);

		switch (op) {
		case EQUALS:
			return cmpVal == 0;

		case NOT_EQUALS:
			return cmpVal != 0;

		case GREATER_THAN:
			return cmpVal > 0;

		case GREATER_THAN_OR_EQ:
			return cmpVal >= 0;

		case LESS_THAN:
			return cmpVal < 0;

		case LESS_THAN_OR_EQ:
			return cmpVal <= 0;

		case LIKE:
			return value.indexOf(iVal.value) >= 0;
		}

		return false;
	}

	/**
	 * @return the Type for this Field
	 */
	public Type getType() {

		return Type.STRING_TYPE;
	}
}


text:
"""
This package contains the API. You may use it to embed the conda package
manager inside your own PyQt application.
"""
#from .editor import RegexEditorWidget
#from .quick_ref import QuickRefWidget
#rom .match_highlighter import MatchHighlighter


text:
package com.box.sdk;

/**
 * The interface for intercepting requests to the Box API.
 *
 *
An interceptor may handle a request in any way it sees fit. It may update a request before it's sent, or it may
 * choose to return a custom response. If an interceptor returns a null response, then the request will continue to be
 * sent to the API along with any changes that the interceptor may have made to it.

 *
 *
public BoxAPIResponse onRequest(BoxAPIRequest request) {
 *    request.addHeader("My-Header", "My-Value");
 *
 *    // Returning null means the request will be sent along with our new header.
 *    return null;
 * }

 *
 *
However, if a response is returned, then the request won't be sent and the interceptor's response will take the
 * place of the normal response.

 *
 *
public BoxAPIResponse onRequest(BoxAPIRequest request) {
 *    // Returning our own response means the request won't be sent at all.
 *    return new BoxAPIResponse();
 * }

 *
 *
A RequestInterceptor can be very useful for testing purposes. Requests to the Box API can be intercepted and fake
 * responses can be returned, allowing you to effectively test your code without needing to actually communicate with
 * the Box API.

 */
public interface RequestInterceptor {
    /**
     * Invoked when a request is about to be sent to the API.
     *
     * @param request the request that is about to be sent.
     * @return an optional response to the request. If the response is null, then the request will continue to
     * be sent to the Box API.
     */
    BoxAPIResponse onRequest(BoxAPIRequest request);
}


text:
 "use strict";
//var STAGE_MAX = 1;
import * as sfg from '../../js/global';
import * as util from '../../js/util';
import * as audio from '../../js/audio';
//import * as song from './song';
import * as graphics from '../../js/graphics';
import * as io from '../../js/io';
import * as comm from '../../js/comm';
import * as text from '../../js/text';
import * as gameobj from '../../js/gameobj';
import * as myship from '../../js/myship';
import * as enemies from '../../js/enemies';
import * as effectobj from '../../js/effectobj';
import { DevTool } from './devtool';
import { Game } from '../../js/game';

/// メイン
window.onload = function () {
  sfg.game = new Game();
  sfg.devTool = new DevTool(sfg.game);
  sfg.game.exec();
};


text:
"""Throttle calls to a method."""

import time

from . contextdecorator import ContextDecorator

class throttle(ContextDecorator):

    """Throttle calls to a method by a factor.

    The call to the inner function is timed, and a delay equivalent to
    that time multiplied by factor is executed before exiting. If
    error_only is set, delay only when an exception has been raised.

    This can be used either as a decorator or context manager.

    with throttle(3):
        pass

    @throttle(3)
    def method():
        pass
    """

    def __init__(self, factor, error_only=False):
        self.factor = factor
        self.error_only = error_only
        self.timer = timer()
        self.time = None

    def __enter__(self):
        """Enter the nested context."""
        self.time = self.timer.__enter__()

    def __exit__(self, type, value, traceback):
        """Exit the nested context."""
        self.timer.__exit__(type, value, traceback)
        if not self.error_only or (self.error_only and type):
            time.sleep(self.factor * self.time[-1])
        return False


text:
addpath './DOAToolbox'
addpath './wav'
%% Initializations
%Variables:
%Fixed:
% l: distance between sensors in m
% m: number of sensors
% fs: sampling frequency
%Tunables:
% wlen: affects frequency precision, is the most important parameter
% bins: number of samples for the narrowband algo to work with
% wlen and bins set the total number of necessary samples, N
% olf: overlapping factor, integer between 0 and wlen-1
% L: precision/ resolution, how many slices to divide the angle domain
l = 0.04;        %distance between sensors in m
m = 8;           %num of sensors
fs = 8820;       %sampling frequency
wlen = 512;      %fft order, or window size
bins = 10;       %num of windows
olf = wlen/2;    %overlapping factor for stft( fft_separate)
L = 180;         %num of divisions for [-pi/2, pi/2]
sig = 0.1;
%% Generate data
[highb,Fs ] = wavread('mono_highpitch.wav');
n = 1;
doa = [12];
[Y, ~] = simsound_planar(doa(1) * pi/180, m, l, highb(:, 1), Fs);
[Y, Fs] = downsample(Y,Fs, 5);
Y = addnoise(Y, sig);
%% Wideband DOA
[N, phicapon, phimusic , thetaesprit, f] = wideband_doa(Y, l, fs, n, wlen, bins, olf, L);

%% Spectrum
highbfft = fft(highb(:,1), length(f)*2);
figure(3);
plot(f,2*abs(Y(1:length(f))))

%% Plotting
% figure(3)
% plot(t, real(Y));
% xlabel('Time');
% ylabel('Value');
% title('Data set');
% legend('Sensor 1','Sensor 2','Sensor 3','Sensor 4','Sensor 5','Sensor 6','Sensor 7','Sensor 8');
% grid on

%% Plot the spatial spectrum
figure(1)
x = ((0:(L-1)) .* pi/L - pi/2); % x in radians
x = x * 180/pi; %x in degrees
imagesc(x,f, phicapon.');
xlabel('Degrees');
ylabel('Frequency');
title('Capon estimation');
grid on

figure(2)
x = ((0:(L-1)) .* pi/L - pi/2); % x in radians
x = x * 180/pi; %x in degrees
imagesc(x,f, phimusic.');
xlabel('Degrees');
ylabel('Frequency');
title('MUSIC estimation');
grid on

%% Clean-up
rmpath './DOAToolbox'
rmpath './wav'
clear Fs L N Y bins f fs l m n olf phicapon phimusic thetaesprit wlen x doa highb highbfft sig


text:
{-# LANGUAGE QuasiQuotes #-}

module Ch24.Logfile where

import Control.Applicative
import Text.Trifecta
import Text.RawString.QQ
import Data.Time
import qualified Data.Map as M
import Data.Map (Map)
import Safe (headMay, lastMay)

newtype Activity =
  Activity String
  deriving (Eq, Show)

data DayLog =
  DayLog Day (Map UTCTime Activity)
  deriving (Eq, Show)

logFileEx :: String
logFileEx = [r|
-- wheee a comment

# 2025-02-05
08:00 Breakfast
09:00 Sanitizing moisture collector
11:00 Exercising in high-grav gym
12:00 Lunch
13:00 Programming
17:00 Commuting home in rover
17:30 R&R
19:00 Dinner
21:00 Shower
21:15 Read
22:00 Sleep

# 2025-02-07 -- dates not nececessarily sequential
08:00 Breakfast -- should I try skippin bfast?
09:00 Bumped head, passed out
13:36 Wake up, headache
13:37 Go to medbay
13:40 Patch self up
13:45 Commute home for rest
14:15 Read
21:00 Dinner
21:15 Read
22:00 Sleep
|]

totalTimePerDay :: DayLog -> Maybe NominalDiffTime
totalTimePerDay (DayLog _ activities) =
  let times = map fst . M.toList $ activities
      start = headMay times
      end   = lastMay times
  in
    liftA2 diffUTCTime end start

averageActivityTime :: [DayLog] -> Maybe NominalDiffTime
averageActivityTime daylogs =
    fmap (calcAvg . sum) $ traverse averageActivityTimePerDay daylogs
    where
      calcAvg total = total / (fromIntegral $ length daylogs)

averageActivityTimePerDay :: DayLog -> Maybe NominalDiffTime
averageActivityTimePerDay daylog@(DayLog _ activities) =
  let timeDiff = totalTimePerDay daylog
      numberOfActivities = fromIntegral . M.size $ activities
  in
    fmap (\t -> t / numberOfActivities) timeDiff

logFile :: Parser [DayLog]
logFile = some dayLog

dayLog :: Parser DayLog
dayLog = do
  _  <- skipNewlines
  _  <- skipMany comment
  d  <- dateLine
  xs <- some (activity d)
  _  <- skipNewlines
  return $ DayLog d (M.fromList xs)

activity :: Day -> Parser (UTCTime, Activity)
activity day = do
  h  <- integer
  _  <- char ':'
  m  <- integer
  xs <- activityContent
  _  <- skipNewlines
  let time = UTCTime day $ timeOfDay h m
      act  = Activity xs
  return $ (time, act)

activityContent :: Parser String
activityContent = do
  try (manyTill exceptNewLine comment) <|> many exceptNewLine

timeOfDay :: Integer -> Integer -> DiffTime
timeOfDay h m =
  60 * 60 * (fromInteger h) + 60 * (fromInteger m)

dateLine :: Parser Day
dateLine = do
  _ <- string "# "
  y <- integer
  _ <- char '-'
  m <- integer
  _ <- char '-'
  d <- integer
  _ <- skipMany comment
  return $ fromGregorian y (fromInteger m) (fromInteger d)

comment :: Parser ()
comment = do
  _ <- skipMany (oneOf " ")
  _ <- string "-- "
  _ <- skipMany exceptNewLine
  _ <- skipNewlines
  return ()

exceptNewLine :: Parser Char
exceptNewLine = noneOf "\n"

skipNewlines :: Parser ()
skipNewlines = skipMany (oneOf "\n")

main :: IO ()
main = do
  print $ parseString comment mempty "-- a comment \n"
  print $ parseString dateLine mempty "# 2025-02-05\n"
  print $ parseString (activity $ fromGregorian 2015 2 1) mempty "08:00 hello world"
  let parsedLog = parseString logFile mempty logFileEx
  print $ parsedLog
  print $ (fmap . fmap) totalTimePerDay parsedLog
  print $ (fmap . fmap) averageActivityTimePerDay parsedLog
  print $ fmap averageActivityTime parsedLog


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.facebook.presto.plugin.memory;

import com.facebook.presto.spi.ColumnHandle;
import com.facebook.presto.spi.ColumnMetadata;
import com.facebook.presto.spi.ConnectorInsertTableHandle;
import com.facebook.presto.spi.ConnectorNewTableLayout;
import com.facebook.presto.spi.ConnectorOutputTableHandle;
import com.facebook.presto.spi.ConnectorSession;
import com.facebook.presto.spi.ConnectorTableHandle;
import com.facebook.presto.spi.ConnectorTableLayout;
import com.facebook.presto.spi.ConnectorTableLayoutHandle;
import com.facebook.presto.spi.ConnectorTableLayoutResult;
import com.facebook.presto.spi.ConnectorTableMetadata;
import com.facebook.presto.spi.Constraint;
import com.facebook.presto.spi.Node;
import com.facebook.presto.spi.NodeManager;
import com.facebook.presto.spi.SchemaTableName;
import com.facebook.presto.spi.SchemaTablePrefix;
import com.facebook.presto.spi.connector.ConnectorMetadata;
import com.facebook.presto.spi.connector.ConnectorOutputMetadata;
import com.facebook.presto.spi.predicate.TupleDomain;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import io.airlift.slice.Slice;

import javax.annotation.concurrent.ThreadSafe;
import javax.inject.Inject;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Function;
import java.util.stream.Collectors;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
import static java.util.Objects.requireNonNull;
import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toMap;

@ThreadSafe
public class MemoryMetadata
        implements ConnectorMetadata
{
    public static final String SCHEMA_NAME = "default";

    private final NodeManager nodeManager;
    private final String connectorId;
    private final AtomicLong nextTableId = new AtomicLong();
    private final Map<String, Long> tableIds = new ConcurrentHashMap<>();
    private final Map<Long, MemoryTableHandle> tables = new ConcurrentHashMap<>();

    @Inject
    public MemoryMetadata(NodeManager nodeManager, MemoryConnectorId connectorId)
    {
        this.nodeManager = requireNonNull(nodeManager, "nodeManager is null");
        this.connectorId = requireNonNull(connectorId, "connectorId is null").toString();
    }

    @Override
    public synchronized List<String> listSchemaNames(ConnectorSession session)
    {
        return ImmutableList.of(SCHEMA_NAME);
    }

    @Override
    public synchronized ConnectorTableHandle getTableHandle(ConnectorSession session, SchemaTableName tableName)
    {
        Long tableId = tableIds.get(tableName.getTableName());
        if (tableId == null) {
            return null;
        }
        return tables.get(tableId);
    }

    @Override
    public synchronized ConnectorTableMetadata getTableMetadata(ConnectorSession session, ConnectorTableHandle tableHandle)
    {
        MemoryTableHandle memoryTableHandle = (MemoryTableHandle) tableHandle;
        return memoryTableHandle.toTableMetadata();
    }

    @Override
    public synchronized List<SchemaTableName> listTables(ConnectorSession session, String schemaNameOrNull)
    {
        if (schemaNameOrNull != null && !schemaNameOrNull.equals(SCHEMA_NAME)) {
            return ImmutableList.of();
        }
        return tables.values().stream()
                .map(MemoryTableHandle::toSchemaTableName)
                .collect(toList());
    }

    @Override
    public synchronized Map<String, ColumnHandle> getColumnHandles(ConnectorSession session, ConnectorTableHandle tableHandle)
    {
        MemoryTableHandle memoryTableHandle = (MemoryTableHandle) tableHandle;
        return memoryTableHandle.getColumnHandles().stream()
                .collect(toMap(MemoryColumnHandle::getName, Function.identity()));
    }

    @Override
    public synchronized ColumnMetadata getColumnMetadata(ConnectorSession session, ConnectorTableHandle tableHandle, ColumnHandle columnHandle)
    {
        MemoryColumnHandle memoryColumnHandle = (MemoryColumnHandle) columnHandle;
        return memoryColumnHandle.toColumnMetadata();
    }

    @Override
    public synchronized Map<SchemaTableName, List<ColumnMetadata>> listTableColumns(ConnectorSession session, SchemaTablePrefix prefix)
    {
        return tables.values().stream()
                .filter(table -> prefix.matches(table.toSchemaTableName()))
                .collect(toMap(MemoryTableHandle::toSchemaTableName, handle -> handle.toTableMetadata().getColumns()));
    }

    @Override
    public synchronized void dropTable(ConnectorSession session, ConnectorTableHandle tableHandle)
    {
        MemoryTableHandle handle = (MemoryTableHandle) tableHandle;
        Long tableId = tableIds.remove(handle.getTableName());
        if (tableId != null) {
            tables.remove(tableId);
        }
    }

    @Override
    public synchronized void renameTable(ConnectorSession session, ConnectorTableHandle tableHandle, SchemaTableName newTableName)
    {
        MemoryTableHandle oldTableHandle = (MemoryTableHandle) tableHandle;
        MemoryTableHandle newTableHandle = new MemoryTableHandle(
                oldTableHandle.getConnectorId(),
                oldTableHandle.getSchemaName(),
                newTableName.getTableName(),
                oldTableHandle.getTableId(),
                oldTableHandle.getColumnHandles(),
                oldTableHandle.getHosts());
        tableIds.remove(oldTableHandle.getTableName());
        tableIds.put(newTableName.getTableName(), oldTableHandle.getTableId());
        tables.remove(oldTableHandle.getTableId());
        tables.put(oldTableHandle.getTableId(), newTableHandle);
    }

    @Override
    public synchronized void createTable(ConnectorSession session, ConnectorTableMetadata tableMetadata)
    {
        ConnectorOutputTableHandle outputTableHandle = beginCreateTable(session, tableMetadata, Optional.empty());
        finishCreateTable(session, outputTableHandle, ImmutableList.of());
    }

    @Override
    public synchronized MemoryOutputTableHandle beginCreateTable(ConnectorSession session, ConnectorTableMetadata tableMetadata, Optional<ConnectorNewTableLayout> layout)
    {
        long nextId = nextTableId.getAndIncrement();
        Set<Node> nodes = nodeManager.getRequiredWorkerNodes();
        checkState(!nodes.isEmpty(), "No Memory nodes available");

        tableIds.put(tableMetadata.getTable().getTableName(), nextId);
        MemoryTableHandle table = new MemoryTableHandle(
                connectorId,
                nextId,
                tableMetadata,
                nodes.stream().map(Node::getHostAndPort).collect(Collectors.toList()));
        tables.put(table.getTableId(), table);

        return new MemoryOutputTableHandle(table, ImmutableSet.copyOf(tableIds.values()));
    }

    @Override
    public synchronized Optional<ConnectorOutputMetadata> finishCreateTable(ConnectorSession session, ConnectorOutputTableHandle tableHandle, Collection<Slice> fragments)
    {
        return Optional.empty();
    }

    @Override
    public synchronized MemoryInsertTableHandle beginInsert(ConnectorSession session, ConnectorTableHandle tableHandle)
    {
        MemoryTableHandle memoryTableHandle = (MemoryTableHandle) tableHandle;
        return new MemoryInsertTableHandle(memoryTableHandle, ImmutableSet.copyOf(tableIds.values()));
    }

    @Override
    public synchronized Optional<ConnectorOutputMetadata> finishInsert(ConnectorSession session, ConnectorInsertTableHandle insertHandle, Collection<Slice> fragments)
    {
        return Optional.empty();
    }

    @Override
    public synchronized List<ConnectorTableLayoutResult> getTableLayouts(
            ConnectorSession session,
            ConnectorTableHandle handle,
            Constraint<ColumnHandle> constraint,
            Optional<Set<ColumnHandle>> desiredColumns)
    {
        requireNonNull(handle, "handle is null");
        checkArgument(handle instanceof MemoryTableHandle);

        MemoryTableLayoutHandle layoutHandle = new MemoryTableLayoutHandle((MemoryTableHandle) handle);
        return ImmutableList.of(new ConnectorTableLayoutResult(getTableLayout(session, layoutHandle), constraint.getSummary()));
    }

    @Override
    public synchronized ConnectorTableLayout getTableLayout(ConnectorSession session, ConnectorTableLayoutHandle handle)
    {
        return new ConnectorTableLayout(
                handle,
                Optional.empty(),
                TupleDomain.all(),
                Optional.empty(),
                Optional.empty(),
                Optional.empty(),
                ImmutableList.of());
    }
}