repo_name stringlengths 7 104 | file_path stringlengths 11 238 | context list | import_statement stringlengths 103 6.85k | code stringlengths 60 38.4k | next_line stringlengths 10 824 | gold_snippet_index int32 0 8 |
|---|---|---|---|---|---|---|
nikhaldi/android-view-selector | src/test-lib/src/com/nikhaldimann/viewselector/test/abstrakt/AbstractViewSelectorAssertionsTest.java | [
"public static ViewSelectionAssert assertThat(ViewSelection actual) {\n return new ViewSelectionAssert(actual);\n}",
"public static ViewSelectionAssert assertThatSelection(String selector, Activity activity) {\n return assertThat(selection(selector, activity));\n}",
"public static Attributes extractAttrib... | import static com.nikhaldimann.viewselector.ViewSelectorAssertions.assertThat;
import static com.nikhaldimann.viewselector.ViewSelectorAssertions.assertThatSelection;
import static com.nikhaldimann.viewselector.ViewSelectorAssertions.extractAttribute;
import static com.nikhaldimann.viewselector.ViewSelectorAssertions.selection;
import org.junit.Test;
import android.widget.TextView;
import com.nikhaldimann.viewselector.test.util.ViewSelectorAndroidTestCase; | package com.nikhaldimann.viewselector.test.abstrakt;
public abstract class AbstractViewSelectorAssertionsTest extends ViewSelectorAndroidTestCase {
/**
* Fails with a RuntimeException, so we can distinguish this from planned
* assertion failures.
*/
private void failHard() {
throw new RuntimeException("Failed to cause an assertion failure");
}
@Test
public void testAssertThat() {
TextView view = viewFactory.createTextView(); | assertThat(selection("TextView", view)) | 3 |
wangchongjie/multi-task | src/main/java/com/baidu/unbiz/multitask/task/thread/TaskWrapper.java | [
"public class TaskPair extends Pair<String, Object> {\n\n public TaskPair() {\n }\n\n public TaskPair(String taskName, Object param) {\n this.field1 = taskName;\n this.field2 = param;\n }\n\n public TaskPair wrap(String taskName, Object param) {\n return new TaskPair(taskName, pa... | import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import com.baidu.unbiz.multitask.common.TaskPair;
import com.baidu.unbiz.multitask.spring.integration.TaskBeanContainer;
import com.baidu.unbiz.multitask.task.Taskable;
import com.baidu.unbiz.multitask.utils.ArrayUtils;
import com.baidu.unbiz.multitask.utils.AssistUtils; | package com.baidu.unbiz.multitask.task.thread;
/**
* 报表数据抓取类包装器,包装为可执行类
*
* @author wangchongjie
* @since 2015-11-21 下午7:57:58
*/
public class TaskWrapper implements Runnable {
/**
* 可并行执行的fetcher
*/
private Taskable<?> fetcher;
/**
* fetcher名称
*/
private String fetcherName;
/**
* 参数封装
*/
private Object args;
/**
* 并行执行上下文
*/
private TaskContext context;
/**
* 将Fetcher包装,绑定执行上下文
*
* @param fetcher
* @param args
* @param context
*/
public <T> TaskWrapper(Taskable<?> fetcher, Object args, TaskContext context) {
this.fetcher = fetcher;
// 此处参数有可能为null(暂不限制),应用时需注意
this.args = args;
this.context = context;
}
public <T> TaskWrapper(Taskable<?> fetcher, Object args, TaskContext context, String fetcherName) {
this.fetcher = fetcher;
// 此处参数有可能为null(暂不限制),应用时需注意
this.args = args;
this.context = context;
this.fetcherName = fetcherName;
}
/**
* 将Fetcher构建成包装类
*
* @param container
* @param context
* @param queryPairs
*
* @return TaskWrapper List
*/
public static List<TaskWrapper> wrapperFetcher(TaskBeanContainer container, TaskContext context,
TaskPair... queryPairs) {
List<TaskWrapper> fetchers = new ArrayList<TaskWrapper>();
if (ArrayUtils.isArrayEmpty(queryPairs)) {
return fetchers;
}
// wrap task
for (TaskPair qp : queryPairs) { | Taskable<?> fetcher = container.bean(AssistUtils.removeTaskVersion(qp.field1)); | 4 |
xiaoshanlin000/SLTableView | app/src/main/java/com/shanlin/sltableview/MainActivity.java | [
"public class DefaultFragment extends DemoBaseFragment {\n\n public DefaultFragment() {\n // Required empty public constructor\n }\n\n /**\n * Use this factory method to create a new instance of\n * this fragment using the provided parameters.\n *\n * @return A new instance of fragme... | import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import com.shanlin.sltableview.fragment.DefaultFragment;
import com.shanlin.sltableview.fragment.DouyuFollowFragment;
import com.shanlin.sltableview.fragment.DouyuFragment;
import com.shanlin.sltableview.fragment.GroupHeaderFragment;
import com.shanlin.sltableview.fragment.GroupStickyHeaderFragment;
import com.shanlin.sltableview.fragment.StickyHeaderClickFragment;
import com.shanlin.sltableview.fragment.StickyHeaderFragment;
import com.shanlin.sltableview.fragment.UserInfoFragment; | package com.shanlin.sltableview;
public class MainActivity extends AppCompatActivity {
private Activity context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = this;
HeaderPagerAdapter adapter = new HeaderPagerAdapter(this.getSupportFragmentManager());
ViewPager pager = (ViewPager) this.findViewById(R.id.pager);
pager.setAdapter(adapter);
}
class HeaderPagerAdapter extends FragmentPagerAdapter {
public HeaderPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0: | return new DouyuFragment(); | 2 |
hecoding/Pac-Man | src/jeco/core/optimization/threads/MasterWorkerThreads.java | [
"public abstract class Algorithm<V extends Variable<?>> extends AlgObservable {\n\n protected Problem<V> problem = null;\n // Attribute to stop execution of the algorithm.\n protected boolean stop = false;\n \n /**\n * Allows to stop execution after finishing the current generation; must be\n * taken into ... | import java.util.ArrayList;
import java.util.LinkedList;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.logging.Level;
import java.util.logging.Logger;
import jeco.core.algorithm.Algorithm;
import jeco.core.algorithm.moge.GrammaticalEvolution;
import jeco.core.algorithm.moge.GrammaticalEvolution_example;
import jeco.core.problem.Problem;
import jeco.core.problem.Solution;
import jeco.core.problem.Solutions;
import jeco.core.problem.Variable; | package jeco.core.optimization.threads;
public class MasterWorkerThreads<V extends Variable<?>> extends Problem<V> {
private static final Logger logger = Logger.getLogger(MasterWorkerThreads.class.getName());
protected Algorithm<V> algorithm = null;
protected Problem<V> problem = null;
protected LinkedBlockingQueue<Solution<V>> sharedQueue = new LinkedBlockingQueue<Solution<V>>();
protected ArrayList<Problem<V>> problemClones = new ArrayList<Problem<V>>();
protected Integer numWorkers = null;
public MasterWorkerThreads(Algorithm<V> algorithm, Problem<V> problem, Integer numWorkers) {
super(problem.getNumberOfVariables(), problem.getNumberOfObjectives());
for (int i = 0; i < numberOfVariables; ++i) {
super.lowerBound[i] = problem.getLowerBound(i);
super.upperBound[i] = problem.getUpperBound(i);
}
this.algorithm = algorithm;
this.problem = problem;
this.numWorkers = numWorkers;
for (int i = 0; i < numWorkers; ++i) {
problemClones.add(problem.clone());
}
}
public MasterWorkerThreads(Algorithm<V> algorithm, Problem<V> problem) {
this(algorithm, problem, Runtime.getRuntime().availableProcessors());
}
@Override
public void evaluate(Solutions<V> solutions) {
sharedQueue.addAll(solutions);
LinkedList<Worker<V>> workers = new LinkedList<Worker<V>>();
for (int i = 0; i < numWorkers; ++i) {
Worker<V> worker = new Worker<V>(problemClones.get(i), sharedQueue);
workers.add(worker);
worker.start();
}
for (Worker<V> worker : workers) {
try {
worker.join();
} catch (InterruptedException e) {
logger.severe(e.getLocalizedMessage());
logger.severe("Main thread cannot join to: " + worker.getId());
}
}
}
@Override
public void evaluate(Solution<V> solution) {
logger.log(Level.SEVERE, this.getClass().getSimpleName() + "::evaluate() - I do not know why I am here, doing nothing to evaluate solution");
}
@Override
public Solutions<V> newRandomSetOfSolutions(int size) {
return problem.newRandomSetOfSolutions(size);
}
public Solutions<V> execute() {
algorithm.setProblem(this);
algorithm.initialize();
return algorithm.execute();
}
public void stop() {
this.algorithm.stopExection();
}
@Override
public Problem<V> clone() {
logger.severe("This master cannot be cloned.");
return null;
}
public static void main(String[] args) {
long begin = System.currentTimeMillis();
// First create the problem | GrammaticalEvolution_example problem = new GrammaticalEvolution_example("test/grammar_example.bnf"); | 2 |
witwall/sfntly-java | src/main/java/com/google/typography/font/tools/subsetter/CMapTableSubsetter.java | [
"public class Font {\n\n private static final Logger logger =\n Logger.getLogger(Font.class.getCanonicalName());\n\n /**\n * Offsets to specific elements in the underlying data. These offsets are relative to the\n * start of the table or the start of sub-blocks within the table.\n */\n private enum Offs... | import com.google.typography.font.sfntly.Font;
import com.google.typography.font.sfntly.Font.Builder;
import com.google.typography.font.sfntly.Tag;
import com.google.typography.font.sfntly.table.core.CMap;
import com.google.typography.font.sfntly.table.core.CMapTable;
import java.io.IOException; | /*
* Copyright 2011 Google Inc. All Rights Reserved.
*
* 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.google.typography.font.tools.subsetter;
/**
* @author Stuart Gill
*
*/
public class CMapTableSubsetter extends TableSubsetterImpl {
/**
* Constructor.
*/
public CMapTableSubsetter() {
super(Tag.cmap);
}
@Override
public boolean subset(Subsetter subsetter, Font font, Builder fontBuilder) throws IOException { | CMapTable cmapTable = font.getTable(Tag.cmap); | 4 |
henryblue/TeaCup | app/src/main/java/com/app/teacup/MoviePlayActivity.java | [
"public class TvPlayRecyclerAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {\n\n private final Context mContext;\n private final List<TvItemInfo> mDatas;\n private OnItemClickListener mListener;\n\n public interface OnItemClickListener {\n void onItemClick(View view, int position);... | import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.app.teacup.adapter.TvPlayRecyclerAdapter;
import com.app.teacup.bean.movie.MoviePlayInfo;
import com.app.teacup.bean.movie.TvItemInfo;
import com.app.teacup.ui.MoreTextView;
import com.app.teacup.util.OkHttpUtils;
import com.app.teacup.util.ToolUtils;
import com.app.teacup.util.urlUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.squareup.okhttp.Request;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List; | TextView nameView = (TextView) itemView.findViewById(R.id.movie_play_name);
TextView timeView = (TextView) itemView.findViewById(R.id.movie_play_addTime);
MoviePlayInfo info = mMoreDatas.get(position);
timeView.setText(info.getAddTime());
nameView.setText(info.getMovieName());
loadImageResource(info.getImgUrl(), imageView);
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MoviePlayActivity.this, MoviePlayActivity.class);
intent.putExtra("moviePlayUrl", mMoreDatas.get(position).getNextUrl());
intent.putExtra("moviePlayName", mMoreDatas.get(position).getMovieName());
startActivity(intent);
}
});
container.addView(itemView);
}
private void loadImageResource(String url, ImageView imageView) {
if (!MainActivity.mIsLoadPhoto) {
Glide.with(MoviePlayActivity.this).load(url).asBitmap()
.error(R.drawable.photo_loaderror)
.placeholder(R.drawable.main_load_bg)
.diskCacheStrategy(DiskCacheStrategy.ALL)
.dontAnimate()
.into(imageView);
} else {
if (MainActivity.mIsWIFIState) {
Glide.with(MoviePlayActivity.this).load(url).asBitmap()
.error(R.drawable.photo_loaderror)
.placeholder(R.drawable.main_load_bg)
.diskCacheStrategy(DiskCacheStrategy.ALL)
.dontAnimate()
.into(imageView);
} else {
imageView.setImageResource(R.drawable.main_load_bg);
}
}
}
@Override
protected void onLoadDataError() {
Toast.makeText(MoviePlayActivity.this, getString(R.string.not_have_more_data),
Toast.LENGTH_SHORT).show();
mRefreshLayout.setRefreshing(false);
}
@Override
protected void onLoadDataFinish() {
if (mTmpLayout.getVisibility() == View.VISIBLE) {
mTmpLayout.setVisibility(View.GONE);
}
initData();
mRefreshLayout.setEnabled(false);
}
@Override
protected void onRefreshError() {
}
@Override
protected void onRefreshFinish() {
}
@Override
protected void onRefreshStart() {
}
private void setupRefreshLayout() {
mRefreshLayout.setColorSchemeColors(ToolUtils.getThemeColorPrimary(this));
mRefreshLayout.setSize(SwipeRefreshLayout.DEFAULT);
mRefreshLayout.setProgressViewEndTarget(true, 100);
StartRefreshPage();
}
private void StartRefreshPage() {
mRefreshLayout.post(new Runnable() {
@Override
public void run() {
mRefreshLayout.setRefreshing(true);
startRefreshData();
}
});
}
private void startRefreshData() {
mMoreDatas.clear();
if (getIntent() == null) {
return;
}
String videoUrl = getIntent().getStringExtra("moviePlayUrl");
if (!TextUtils.isEmpty(videoUrl)) {
OkHttpUtils.getAsyn(videoUrl, new OkHttpUtils.ResultCallback<String>() {
@Override
public void onError(Request request, Exception e) {
sendParseDataMessage(LOAD_DATA_ERROR);
}
@Override
public void onResponse(String response) {
parseMoreVideoData(response);
}
});
}
}
private void parseMoreVideoData(String response) {
Document document = Jsoup.parse(response);
try {
if (document != null) {
Element container = document.getElementsByClass("container").get(3);
//parse tv data
Element colMd = container.getElementsByClass("container-fluid").get(0)
.getElementsByClass("col-md-12").get(0);
Element group = colMd.getElementsByClass("dslist-group").get(0);
Elements groupItems = group.getElementsByClass("dslist-group-item");
for (Element groupItem : groupItems) {
TvItemInfo tvItemInfo = new TvItemInfo();
Element a = groupItem.getElementsByTag("a").get(0); | String nextUrl = urlUtils.MOVIE_URL + a.attr("href"); | 6 |
optimaize/command4j | src/test/java/com/optimaize/command4j/impl/DefaultCommandExecutorTest.java | [
"public interface CommandExecutor {\n\n /**\n * Executes it in the current thread, and blocks until it either finishes successfully or aborts by\n * throwing an exception.\n *\n * @param <A> argument\n * @param <R> Result\n */\n @NotNull\n <A, R> Optional<R> execute(@NotNull Command... | import com.google.common.base.Stopwatch;
import com.optimaize.command4j.CommandExecutor;
import com.optimaize.command4j.CommandExecutorBuilder;
import com.optimaize.command4j.CommandExecutorService;
import com.optimaize.command4j.Mode;
import com.optimaize.command4j.commands.BaseCommand;
import com.optimaize.command4j.commands.Sleep;
import org.testng.annotations.Test;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import static org.testng.Assert.assertTrue; | package com.optimaize.command4j.impl;
/**
* @author Fabian Kessler
*/
public class DefaultCommandExecutorTest {
@Test
public void runSingleThreaded() throws Exception {
int commandSleepMillis = 100;
int numExecutions = 10;
int numThreads = 1;
int allowedMargin = 100;
run(commandSleepMillis, numExecutions, numThreads, allowedMargin);
}
@Test
public void runMultiThreaded() throws Exception {
int commandSleepMillis = 100;
int numExecutions = 10;
int numThreads = 2;
int allowedMargin = 100;
run(commandSleepMillis, numExecutions, numThreads, allowedMargin);
}
private void run(int commandSleepMillis, int numExecutions, int numThreads, int allowedMargin) throws InterruptedException {
int delta = 2; //stopwatch timing can differ slightly...
CommandExecutor commandExecutor = new CommandExecutorBuilder().build();
ExecutorService javaExecutor = Executors.newFixedThreadPool(numThreads);
CommandExecutorService executorService = commandExecutor.service(javaExecutor);
Mode mode = Mode.create(); | BaseCommand<Void,Void> cmd = new Sleep(commandSleepMillis); | 5 |
danimahardhika/wallpaperboard | library/src/main/java/com/dm/wallpaper/board/fragments/WallpaperSearchFragment.java | [
"public class WallpapersAdapter extends RecyclerView.Adapter<WallpapersAdapter.ViewHolder> {\r\n\r\n private final Context mContext;\r\n private final DisplayImageOptions.Builder mOptions;\r\n private List<Wallpaper> mWallpapers;\r\n private List<Wallpaper> mWallpapersAll;\r\n\r\n private final boole... | import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.animation.LinearOutSlowInInterpolator;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.TextView;
import com.danimahardhika.android.helpers.animation.AnimationHelper;
import com.danimahardhika.android.helpers.core.ColorHelper;
import com.danimahardhika.android.helpers.core.DrawableHelper;
import com.danimahardhika.android.helpers.core.SoftKeyboardHelper;
import com.danimahardhika.android.helpers.core.ViewHelper;
import com.dm.wallpaper.board.R;
import com.dm.wallpaper.board.R2;
import com.dm.wallpaper.board.adapters.WallpapersAdapter;
import com.dm.wallpaper.board.applications.WallpaperBoardApplication;
import com.dm.wallpaper.board.applications.WallpaperBoardConfiguration;
import com.dm.wallpaper.board.databases.Database;
import com.dm.wallpaper.board.items.Filter;
import com.dm.wallpaper.board.items.Wallpaper;
import com.dm.wallpaper.board.preferences.Preferences;
import com.danimahardhika.android.helpers.core.utils.LogUtil;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import static com.dm.wallpaper.board.helpers.ViewHelper.resetViewBottomPadding;
| mRecyclerView.setItemAnimator(new DefaultItemAnimator());
mRecyclerView.setLayoutManager(new GridLayoutManager(getActivity(),
getActivity().getResources().getInteger(R.integer.wallpapers_column_count)));
mRecyclerView.setHasFixedSize(false);
if (WallpaperBoardApplication.getConfig().getWallpapersGrid() ==
WallpaperBoardConfiguration.GridStyle.FLAT) {
int padding = getActivity().getResources().getDimensionPixelSize(R.dimen.card_margin);
mRecyclerView.setPadding(padding, padding, 0, 0);
}
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.menu_wallpaper_search, menu);
MenuItem search = menu.findItem(R.id.menu_search);
int color = ColorHelper.getAttributeColor(getActivity(), R.attr.toolbar_icon);
search.setIcon(DrawableHelper.getTintedDrawable(getActivity(),
R.drawable.ic_toolbar_search, color));
mSearchView = (SearchView) search.getActionView();
mSearchView.setImeOptions(EditorInfo.IME_FLAG_NO_EXTRACT_UI | EditorInfo.IME_ACTION_SEARCH);
mSearchView.setQueryHint(getActivity().getResources().getString(R.string.menu_search));
mSearchView.setMaxWidth(Integer.MAX_VALUE);
search.expandActionView();
mSearchView.setIconifiedByDefault(false);
mSearchView.requestFocus();
ViewHelper.setSearchViewTextColor(mSearchView, color);
ViewHelper.setSearchViewBackgroundColor(mSearchView, Color.TRANSPARENT);
ViewHelper.setSearchViewCloseIcon(mSearchView,
DrawableHelper.getTintedDrawable(getActivity(), R.drawable.ic_toolbar_close, color));
ViewHelper.setSearchViewSearchIcon(mSearchView, null);
mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextChange(String string) {
if (string.length() == 0) {
clearAdapter();
return false;
}
if (mAsyncTask != null) {
mAsyncTask.cancel(true);
}
mAsyncTask = new WallpapersLoader(string.trim())
.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
return true;
}
@Override
public boolean onQueryTextSubmit(String string) {
mSearchView.clearFocus();
mAsyncTask = new WallpapersLoader(string.trim())
.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
return true;
}
});
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
getActivity().finish();
getActivity().overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
ViewHelper.resetSpanCount(mRecyclerView, getActivity().getResources().getInteger(
R.integer.wallpapers_column_count));
resetViewBottomPadding(mRecyclerView, true);
}
@Override
public void onDestroy() {
if (mAsyncTask != null) mAsyncTask.cancel(true);
super.onDestroy();
}
private void initSearchResult() {
Drawable drawable = DrawableHelper.getTintedDrawable(
getActivity(), R.drawable.ic_toolbar_search_large, Color.WHITE);
mSearchResult.setCompoundDrawablesWithIntrinsicBounds(null, drawable, null, null);
}
public boolean isSearchQueryEmpty() {
return mSearchView.getQuery() == null || mSearchView.getQuery().length() == 0;
}
public void filterSearch(String query) {
mAsyncTask = new WallpapersLoader(query).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
private void clearAdapter() {
if (mAdapter == null) return;
mAdapter.clearItems();
if (mSearchResult.getVisibility() == View.VISIBLE) {
AnimationHelper.fade(mSearchResult).start();
}
AnimationHelper.setBackgroundColor(mRecyclerView,
((ColorDrawable) mRecyclerView.getBackground()).getColor(),
Color.TRANSPARENT)
.interpolator(new LinearOutSlowInInterpolator())
.start();
}
private class WallpapersLoader extends AsyncTask<Void, Void, Boolean> {
| private List<Wallpaper> wallpapers;
| 5 |
yuqirong/NewsPublish | src/com/cjlu/newspublish/services/impl/RoleServiceImpl.java | [
"@Repository(\"roleDao\")\npublic class RoleDaoImpl extends BaseDaoImpl<Role> {\n\n\tpublic List<Role> findRolesNotInRange(Set<Role> set) {\n\t\tString hql = \"from Role r where r.id not in (\"\n\t\t\t\t+ DataUtils.extractRoleIds(set) + \")\";\n\t\treturn this.findEntityByHQL(hql);\n\t}\n\n\tpublic List<Role> findR... | import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.cjlu.newspublish.daos.impl.RoleDaoImpl;
import com.cjlu.newspublish.models.security.Right;
import com.cjlu.newspublish.models.security.Role;
import com.cjlu.newspublish.services.RightService;
import com.cjlu.newspublish.services.RoleService;
import com.cjlu.newspublish.utils.ValidateUtils; | package com.cjlu.newspublish.services.impl;
@Service("roleService")
public class RoleServiceImpl extends BaseServiceImpl<Role> implements
RoleService {
@Autowired
private RightService rightService;
@Autowired
private RoleDaoImpl roleDao;
/**
* ±£´æ»ò¸üнÇÉ«
*/
@Override
public void saveOrUpdateRole(Role model, Integer[] ownRightIds) { | if (!ValidateUtils.isValid(ownRightIds)) { | 5 |
idega/com.idega.documentmanager | src/java/com/idega/documentmanager/component/impl/FormComponentButtonAreaImpl.java | [
"public interface Button extends Component {\n\n\tpublic abstract PropertiesButton getProperties();\n}",
"public interface ButtonArea extends Container {\n\n\tpublic abstract Button getButton(ConstButtonType button_type);\n\t\n\tpublic abstract Button addButton(ConstButtonType button_type, String component_after_... | import java.util.HashMap;
import java.util.Map;
import com.idega.documentmanager.business.component.Button;
import com.idega.documentmanager.business.component.ButtonArea;
import com.idega.documentmanager.business.component.ConstButtonType;
import com.idega.documentmanager.component.FormComponentButton;
import com.idega.documentmanager.component.FormComponentButtonArea;
import com.idega.documentmanager.component.FormComponentPage; | package com.idega.documentmanager.component.impl;
/**
* @author <a href="mailto:civilis@idega.com">Vytautas Čivilis</a>
* @version $Revision: 1.4 $
*
* Last modified: $Date: 2008/10/26 16:47:10 $ by $Author: anton $
*/
public class FormComponentButtonAreaImpl extends FormComponentContainerImpl implements ButtonArea, FormComponentButtonArea {
protected Map<String, String> buttons_type_id_mapping;
public Button getButton(ConstButtonType buttonType) {
if(buttonType == null)
throw new NullPointerException("Button type provided null");
return !getButtonsTypeIdMapping().containsKey(buttonType) ? null :
(Button)getContainedComponent(getButtonsTypeIdMapping().get(buttonType));
}
public Button addButton(ConstButtonType buttonType, String componentAfterThisId) throws NullPointerException {
if(buttonType == null)
throw new NullPointerException("Button type provided null");
if(getButtonsTypeIdMapping().containsKey(buttonType))
throw new IllegalArgumentException("Button by type provided: "+buttonType+" already exists in the button area, remove first");
return (Button)addComponent(buttonType.toString(), componentAfterThisId);
}
protected Map<String, String> getButtonsTypeIdMapping() {
if(buttons_type_id_mapping == null)
buttons_type_id_mapping = new HashMap<String, String>();
return buttons_type_id_mapping;
}
@Override
public void render() {
super.render();
((FormComponentPage)parent).setButtonAreaComponentId(getId());
}
@Override
public void remove() {
super.remove();
((FormComponentPage)parent).setButtonAreaComponentId(null);
}
public void setButtonMapping(String button_type, String button_id) {
getButtonsTypeIdMapping().put(button_type, button_id);
}
public void setPageSiblings(FormComponentPage previous, FormComponentPage next) {
| FormComponentButton button = (FormComponentButton)getButton(ConstButtonType.PREVIOUS_PAGE_BUTTON); | 3 |
Kuanghusing/Weather | app/src/main/java/com/kuahusg/weather/Presenter/AboutMePresenterImpl.java | [
"public abstract class BasePresenter implements IBasePresenter {\n\n private IBaseView mView;\n // private IDataSource dataSource;\n private WeakReference<IDataSource> dataSourceWeakReference;\n\n public BasePresenter(IBaseView view) {\n this.mView = view;\n }\n\n public IBaseView getVie... | import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import com.kuahusg.weather.Presenter.base.BasePresenter;
import com.kuahusg.weather.Presenter.interfaceOfPresenter.IAboutMePresenter;
import com.kuahusg.weather.R;
import com.kuahusg.weather.UI.base.IBaseView;
import com.kuahusg.weather.UI.interfaceOfView.IAboutMeView;
import com.kuahusg.weather.data.IDataSource; | package com.kuahusg.weather.Presenter;
/**
* Created by kuahusg on 16-9-27.
*/
public class AboutMePresenterImpl extends BasePresenter implements IAboutMePresenter {
private IAboutMeView mView;
public AboutMePresenterImpl(IBaseView view) {
super(view);
mView = (IAboutMeView) view;
}
@Override
public void init() {
super.init();
}
@Override | protected IDataSource setDataSource() { | 4 |
OlgaKuklina/GitJourney | app/src/main/java/com/oklab/gitjourney/activities/RepositoryActivity.java | [
"public class ReposDataEntry implements Parcelable {\n\n public static final Creator<ReposDataEntry> CREATOR = new Creator<ReposDataEntry>() {\n @Override\n public ReposDataEntry createFromParcel(Parcel in) {\n return new ReposDataEntry(in);\n }\n\n @Override\n publi... | import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import com.oklab.gitjourney.R;
import com.oklab.gitjourney.asynctasks.RepoReadmeDownloadAsyncTask;
import com.oklab.gitjourney.data.ReposDataEntry;
import com.oklab.gitjourney.data.UserSessionData;
import com.oklab.gitjourney.fragments.CommitsFragment;
import com.oklab.gitjourney.fragments.ContributorsFragment;
import com.oklab.gitjourney.fragments.EventsFragment;
import com.oklab.gitjourney.fragments.IssuesFragment;
import com.oklab.gitjourney.fragments.ReadmeFragment;
import com.oklab.gitjourney.fragments.RepositoryContentListFragment;
import com.oklab.gitjourney.services.TakeScreenshotService;
import com.oklab.gitjourney.utils.GithubLanguageColorsMatcher;
import com.oklab.gitjourney.utils.Utils;
import org.markdownj.MarkdownProcessor; | package com.oklab.gitjourney.activities;
public class RepositoryActivity extends AppCompatActivity implements RepoReadmeDownloadAsyncTask.OnRepoReadmeContentLoadedListener
, RepositoryContentListFragment.RepoContentFragmentInteractionListener
, CommitsFragment.OnFragmentInteractionListener
, ContributorsFragment.OnListFragmentInteractionListener {
private static final String TAG = RepositoryActivity.class.getSimpleName();
private WebView mv;
private String owner = "";
private String title = "";
private UserSessionData currentSessionData;
private TakeScreenshotService takeScreenshotService;
private RepositoryContentListFragment repoContentListFragment;
private ViewPager mViewPager;
private RepositoryActivity.SectionsPagerAdapter mSectionsPagerAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_repository);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
ReposDataEntry entry = getIntent().getParcelableExtra("repo");
title = entry.getTitle();
toolbar.setTitleMarginBottom(3);
toolbar.setTitle(title);
mSectionsPagerAdapter = new RepositoryActivity.SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.repo_view_pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
Log.v(TAG, "onPageSelected, position = " + position);
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
mViewPager.setOffscreenPageLimit(4);
TabLayout tabLayout = (TabLayout) findViewById(R.id.repo_tabs);
tabLayout.setupWithViewPager(mViewPager);
if (entry.getLanguage() != null && !entry.getLanguage().isEmpty() && !entry.getLanguage().equals("null")) {
Log.v(TAG, " data.getLanguage() = " + entry.getLanguage());
int colorId = GithubLanguageColorsMatcher.findMatchedColor(this, entry.getLanguage());
Log.v(TAG, " colorId = " + colorId);
if (colorId != 0) {
toolbar.setBackgroundColor(this.getResources().getColor(colorId));
}
}
setSupportActionBar(toolbar);
if (entry.getOwner() == null || entry.getOwner().isEmpty()) { | SharedPreferences prefs = this.getSharedPreferences(Utils.SHARED_PREF_NAME, 0); | 7 |
Wisebite/wisebite_android | app/src/main/java/dev/wisebite/wisebite/adapter/OrderItemMenuAdapter.java | [
"@Getter\n@Setter\n@AllArgsConstructor(suppressConstructorProperties = true)\n@NoArgsConstructor\n@ToString\n@Builder\npublic class Dish implements Entity {\n\n private String id;\n private String name;\n private Double price;\n private String description;\n\n private Map<String, Object> reviews = ne... | import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.support.design.widget.Snackbar;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.Map;
import dev.wisebite.wisebite.R;
import dev.wisebite.wisebite.domain.Dish;
import dev.wisebite.wisebite.domain.Menu;
import dev.wisebite.wisebite.service.DishService;
import dev.wisebite.wisebite.service.ServiceFactory;
import dev.wisebite.wisebite.utils.Utils; | package dev.wisebite.wisebite.adapter;
/**
* Created by albert on 20/03/17.
* @author albert
*/
public class OrderItemMenuAdapter extends RecyclerView.Adapter<OrderItemMenuAdapter.OrderItemMenuHolder> {
private ArrayList<Menu> menus;
private ArrayList<Menu> selectedMenus;
private TextView totalPriceView;
private Context context;
private ArrayList<Dish> mainDishSelected, secondaryDishSelected, otherDishSelected;
private LayoutInflater inflater;
private DishService dishService;
public OrderItemMenuAdapter(ArrayList<Menu> menus, TextView totalPriceView, ArrayList<Menu> selectedMenus, Context context) {
this.menus = menus;
this.totalPriceView = totalPriceView;
this.selectedMenus = selectedMenus;
this.context = context;
this.inflater = LayoutInflater.from(context); | this.dishService = ServiceFactory.getDishService(context); | 3 |
Nilhcem/droidcontn-2016 | app/src/main/java/com/nilhcem/droidcontn/data/app/AppMapper.java | [
"public class Schedule extends ArrayList<ScheduleDay> implements Parcelable {\n\n public static final Parcelable.Creator<Schedule> CREATOR = new Parcelable.Creator<Schedule>() {\n public Schedule createFromParcel(Parcel source) {\n return new Schedule(source);\n }\n\n public Sched... | import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import com.nilhcem.droidcontn.data.app.model.Schedule;
import com.nilhcem.droidcontn.data.app.model.ScheduleDay;
import com.nilhcem.droidcontn.data.app.model.ScheduleSlot;
import com.nilhcem.droidcontn.data.app.model.Session;
import com.nilhcem.droidcontn.data.app.model.Speaker;
import org.threeten.bp.LocalDate;
import org.threeten.bp.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import javax.inject.Inject;
import java8.util.stream.Collectors;
import static java8.util.stream.StreamSupport.stream; | package com.nilhcem.droidcontn.data.app;
public class AppMapper {
@Inject
public AppMapper() {
}
public Map<Integer, Speaker> speakersToMap(@NonNull List<Speaker> from) {
return stream(from).collect(Collectors.toMap(Speaker::getId, speaker -> speaker));
}
public List<Speaker> toSpeakersList(@Nullable List<Integer> speakerIds, @NonNull Map<Integer, Speaker> speakersMap) {
if (speakerIds == null) {
return null;
}
return stream(speakerIds).map(speakersMap::get).collect(Collectors.toList());
}
public List<Integer> toSpeakersIds(@Nullable List<Speaker> speakers) {
if (speakers == null) {
return null;
}
return stream(speakers).map(Speaker::getId).collect(Collectors.toList());
}
| public Schedule toSchedule(@NonNull List<Session> sessions) { | 3 |
underhilllabs/dccsched | src/com/underhilllabs/dccsched/ui/BlocksActivity.java | [
"public static class Blocks implements BlocksColumns, BaseColumns {\n public static final Uri CONTENT_URI =\n BASE_CONTENT_URI.buildUpon().appendPath(PATH_BLOCKS).build();\n\n public static final String CONTENT_TYPE =\n \"vnd.android.cursor.dir/vnd.dccsched.block\";\n public static fi... | import com.underhilllabs.dccsched.R;
import com.underhilllabs.dccsched.provider.ScheduleContract.Blocks;
import com.underhilllabs.dccsched.ui.widget.BlockView;
import com.underhilllabs.dccsched.ui.widget.BlocksLayout;
import com.underhilllabs.dccsched.util.Maps;
import com.underhilllabs.dccsched.util.NotifyingAsyncQueryHandler;
import com.underhilllabs.dccsched.util.ParserUtils;
import com.underhilllabs.dccsched.util.UIUtils;
import com.underhilllabs.dccsched.util.NotifyingAsyncQueryHandler.AsyncQueryListener;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.graphics.Rect;
import android.graphics.drawable.LayerDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.BaseColumns;
import android.util.Log;
import android.view.View;
import android.widget.ScrollView;
import java.util.HashMap; | /*
* Copyright 2010 Google Inc.
*
* 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.underhilllabs.dccsched.ui;
/**
* {@link Activity} that displays a high-level view of a single day of
* {@link Blocks} across the conference. Shows them lined up against a vertical
* ruler of times across the day.
*/
public class BlocksActivity extends Activity implements AsyncQueryListener, View.OnClickListener {
private static final String TAG = "BlocksActivity";
// TODO: these layouts and views are structured pretty weird, ask someone to
// review them and come up with better organization.
// TODO: show blocks that don't fall into columns at the bottom
public static final String EXTRA_TIME_START = "com.google.android.dccsched.extra.TIME_START";
public static final String EXTRA_TIME_END = "com.google.android.dccsched.extra.TIME_END";
private ScrollView mScrollView; | private BlocksLayout mBlocks; | 2 |
lucmoreau/OpenProvenanceModel | tupelo/src/test/java/org/openprovenance/rdf/Example5Test.java | [
"public interface Edge extends Annotable, HasAccounts {\n Ref getCause();\n Ref getEffect();\n} ",
"public class OPMFactory implements CommonURIs {\n\n public static String roleIdPrefix=\"r_\";\n public static String usedIdPrefix=\"u_\";\n public static String wasGenerateByIdPrefix=\"g_\";\n pub... | import java.io.File;
import java.io.StringWriter;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import javax.xml.bind.JAXBException;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.openprovenance.model.OPMGraph;
import org.openprovenance.model.Edge;
import org.openprovenance.model.Account;
import org.openprovenance.model.Processes;
import org.openprovenance.model.Artifact;
import org.openprovenance.model.Agent;
import org.openprovenance.model.Used;
import org.openprovenance.model.OPMFactory;
import org.openprovenance.model.WasGeneratedBy;
import org.openprovenance.model.WasDerivedFrom;
import org.openprovenance.model.WasTriggeredBy;
import org.openprovenance.model.WasControlledBy;
import org.openprovenance.model.OPMDeserialiser;
import org.openprovenance.model.OPMSerialiser;
import org.openprovenance.model.Overlaps;
import org.openprovenance.model.Process;
import org.openprovenance.model.OPMUtilities;
import org.openprovenance.model.collections.CollectionFactory;
| package org.openprovenance.rdf;
/**
* Unit test for simple App.
*/
public class Example5Test
extends TestCase
{
/**
* Create the test case
*
* @param testName name of the test case
*/
public Example5Test( String testName )
{
super( testName );
}
/**
* @return the suite of tests being tested
*/
static OPMGraph graph1;
public void testCollectionProposal2() throws Exception
{
OPMFactory oFactory=new OPMFactory();
| CollectionFactory cFactory=new CollectionFactory(oFactory);
| 5 |
OpsLabJPL/MarsImagesAndroid | MarsImages/Rajawali/src/main/java/rajawali/animation/mesh/AnimationSkeleton.java | [
"public class Camera extends ATransformable3D {\n\tprotected float[] mVMatrix = new float[16];\n\tprotected float[] mInvVMatrix = new float[16];\n\tprotected float[] mRotationMatrix = new float[16];\n\tprotected float[] mProjMatrix = new float[16];\n\tprotected float mNearPlane = 1.0f;\n\tprotected float mFarPlane ... | import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import rajawali.BufferInfo;
import rajawali.Camera;
import rajawali.Geometry3D.BufferType;
import rajawali.math.Number3D;
import rajawali.math.Quaternion;
import rajawali.util.BufferUtil;
import rajawali.util.ObjectColorPicker.ColorPickerInfo;
import rajawali.util.RajLog;
import android.opengl.GLES20;
import android.opengl.Matrix;
import android.os.SystemClock; | package rajawali.animation.mesh;
public class AnimationSkeleton extends AAnimationObject3D {
public static final int FLOAT_SIZE_BYTES = 4;
private SkeletonJoint[] mJoints;
private BoneAnimationSequence mSequence;
public float[][] mInverseBindPoseMatrix;
public float[] uBoneMatrix;
public BufferInfo mBoneMatricesBufferInfo = new BufferInfo();
/**
* FloatBuffer containing joint transformation matrices
*/
protected FloatBuffer mBoneMatrices;
public AnimationSkeleton() {
}
public void setJoints(SkeletonJoint[] joints) {
mJoints = joints;
if (mBoneMatrices == null) {
if (mBoneMatrices != null) {
mBoneMatrices.clear();
}
mBoneMatrices = ByteBuffer
.allocateDirect(joints.length * FLOAT_SIZE_BYTES * 16)
.order(ByteOrder.nativeOrder()).asFloatBuffer();
BufferUtil.copy(uBoneMatrix, mBoneMatrices, uBoneMatrix.length, 0);
mBoneMatrices.position(0);
} else {
BufferUtil.copy(uBoneMatrix, mBoneMatrices, uBoneMatrix.length, 0);
} | mGeometry.createBuffer(mBoneMatricesBufferInfo, BufferType.FLOAT_BUFFER, mBoneMatrices, GLES20.GL_ARRAY_BUFFER); | 1 |
Tyde/TuCanMobile | app/src/main/java/com/dalthed/tucan/acraload/LoadAcraResults.java | [
"public class AnswerObject {\n\tprivate String HTML_text;\n\tprivate String redirectURL;\n\tprivate String lastcalledURL;\n\tprivate CookieManager Cookies;\n\t/**\n\t * RückgabeObjekt der BrowseMethods\n\t * @param HTML HTML-Code\n\t * @param redirect Redirect-URL aus dem HTTP-Header\n\t * @param myCookies CookieMa... | import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.dalthed.tucan.R;
import com.dalthed.tucan.Connection.AnswerObject;
import com.dalthed.tucan.Connection.CookieManager;
import com.dalthed.tucan.Connection.RequestObject;
import com.dalthed.tucan.Connection.SimpleSecureBrowser;
import com.dalthed.tucan.ui.SimpleWebListActivity;
import com.dalthed.tucan.util.ConfigurationChangeStorage; | /**
* This file is part of TuCan Mobile.
*
* TuCan Mobile is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* TuCan Mobile is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with TuCan Mobile. If not, see <http://www.gnu.org/licenses/>.
*/
package com.dalthed.tucan.acraload;
public class LoadAcraResults extends SimpleWebListActivity {
private CookieManager localCookieManager;
private static final String LOG_TAG = "TuCanMobile";
private final String URLStringtoCall = "http://daniel-thiem.de/ACRA/export.php";
private ArrayList<String> classes,ids,urls;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.acra);
URL URLtoCall;
try {
URLtoCall = new URL(URLStringtoCall);
localCookieManager = new CookieManager();
localCookieManager.inputCookie("daniel-thiem.de", "canView", "16ede40c878aee38d0882b3a6b2642c0ae76dafb");
RequestObject thisRequest = new RequestObject(URLStringtoCall,
localCookieManager, RequestObject.METHOD_GET, "",false);
SimpleSecureBrowser callResultBrowser = new SimpleSecureBrowser(
this);
callResultBrowser.HTTPS=false;
callResultBrowser.execute(thisRequest);
} catch (MalformedURLException e) {
Log.e(LOG_TAG, e.getMessage());
}
}
public void onPostExecute(AnswerObject result) {
Document doc = Jsoup.parse(result.getHTML());
Iterator<Element> divs = doc.select("div").iterator();
classes= new ArrayList<String>();
ids = new ArrayList<String>();
urls = new ArrayList<String>();
ArrayList<String> text = new ArrayList<String>();
while(divs.hasNext()){
Element next = divs.next();
Log.i(LOG_TAG,next.attr("title"));
classes.add(next.attr("title"));
ids.add(next.id());
urls.add(next.text());
text.add("#"+next.id()+": "+next.attr("title")+":"+next.attr("line"));
}
ArrayAdapter<String> mAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,text);
setListAdapter(mAdapter);
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
Class target;
try {
target=Class.forName("com.dalthed.tucan."+classes.get(position));
} catch (ClassNotFoundException e) {
target=null;
Log.i(LOG_TAG,"com.dalthed.tucan."+classes.get(position) + " not found");
}
if(target==null)
try {
target=Class.forName("com.dalthed.tucan.ui."+classes.get(position));
} catch (ClassNotFoundException e) {
Log.i(LOG_TAG,"com.dalthed.tucan.ui."+classes.get(position) + " not found");
target=null;
}
if(target==null)
try {
target=Class.forName("com.dalthed.tucan.scraper."+classes.get(position));
} catch (ClassNotFoundException e) {
Log.i(LOG_TAG,"com.dalthed.tucan.scraper."+classes.get(position) + " not found");
target=null;
}
if(target!=null){
Intent loadDefectClassIntent = new Intent(this,target);
loadDefectClassIntent.putExtra("URL", urls.get(position));
loadDefectClassIntent.putExtra("Cookie", "");
loadDefectClassIntent.putExtra("HTTPS", false);
loadDefectClassIntent.putExtra("PREPLink", false);
startActivity(loadDefectClassIntent);
}
}
@Override | public ConfigurationChangeStorage saveConfiguration() { | 4 |
Raxa/RaxaMachineLearning | src/com/machine/learning/socket/UmlsSocket.java | [
"public interface PredictionResult {\n\tpublic double getConfidence();\n\tpublic Object getValue();\n}",
"public class LearningModulesPool {\n\n\t// LinkedList of Learning Modules in this pool\n\tprivate static LinkedList<LearningModuleInterface> modules = new LinkedList<LearningModuleInterface>();\n\tprivate sta... | import java.io.IOException;
import java.util.List;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import org.apache.log4j.Logger;
import com.google.gson.Gson;
import com.learningmodule.association.conceptdrug.PredictionResult;
import com.machine.learning.LearningModulesPool;
import com.machine.learning.request.Request;
import com.machine.learning.request.SearchQueryRequest;
import com.umls.search.DiseaseToDrugPrediction; | package com.machine.learning.socket;
/*
* class that implement the socket interface for umls Learning Module
*/
@ServerEndpoint(value = "/ml/umls")
public class UmlsSocket {
private Gson gson = new Gson();
private static Logger log = Logger.getLogger(UmlsSocket.class);
private Session session;
@OnOpen
public void start(Session session) {
this.session = session;
}
@OnClose
public void end() {
}
/*
* Method that is invoked when there is msg from client input from client
* for querying should be of form "query:<search string>"
*/
@OnMessage
public void onMsg(String query) {
System.out.println(query);
Request req = gson.fromJson(query, Request.class);
if (req.getSearchRequest() != null) {
// send the results to client for search string
sendResults(req.getSearchRequest());
}
}
| public void sendResults(SearchQueryRequest query) { | 3 |
Jamling/Android-ORM | cn.ieclipse.aorm.core/test/cn/ieclipse/aorm/SessionTest.java | [
"public final class ContentValues {\n public static final String TAG = \"ContentValues\";\n \n /** Holds the actual values */\n private HashMap<String, Object> mValues;\n \n /**\n * Creates an empty set of values using the default initial size\n */\n public ContentValues() {\n //... | import java.util.ArrayList;
import java.util.List;
import org.junit.Assert;
import android.content.ContentValues;
import cn.ieclipse.aorm.bean.Course;
import cn.ieclipse.aorm.bean.Grade;
import cn.ieclipse.aorm.bean.Person;
import cn.ieclipse.aorm.bean.Student;
import cn.ieclipse.aorm.test.MockDatabase;
import cn.ieclipse.aorm.test.MockOpenHelper;
import junit.framework.TestCase; | /*
* Copyright 2010-2014 Jamling(li.jamling@gmail.com).
*
* 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 cn.ieclipse.aorm;
/**
* @author Jamling
*
*/
public class SessionTest extends TestCase {
private Session session;
private MockDatabase db;
@Override
protected void setUp() throws Exception {
super.setUp();
MockOpenHelper openHelper = new MockOpenHelper("test.db");
db = (MockDatabase) openHelper.getReadableDatabase();
db.addTable("person", Person.class);
db.addTable("student", Student.class); | db.addTable("grade", Grade.class); | 2 |
ls1intum/jReto | Source/src/de/tum/in/www1/jReto/routing/packets/LinkStatePacket.java | [
"public class Constants {\n\tpublic static final int PACKET_TYPE_SIZE = 4;\n\tpublic static final int INT_SIZE = 4;\n\tpublic static final int UUID_SIZE = 16;\n}",
"public class DataChecker {\n /**\n * Verifies that the data (wrapped in a DataReader) has the expected packet type, and has the minimum require... | import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import de.tum.in.www1.jReto.packet.Constants;
import de.tum.in.www1.jReto.packet.DataChecker;
import de.tum.in.www1.jReto.packet.DataReader;
import de.tum.in.www1.jReto.packet.DataWriter;
import de.tum.in.www1.jReto.packet.Packet;
import de.tum.in.www1.jReto.packet.PacketType;
import de.tum.in.www1.jReto.routing.algorithm.LinkStateRoutingTable; | package de.tum.in.www1.jReto.routing.packets;
/**
* A LinkState packet represents a peer's link state, i.e. a list of all of it's neighbors and the cost associated with reaching them.
*/
public class LinkStatePacket implements Packet {
public final static PacketType TYPE = PacketType.LINK_STATE;
public final static int MINIMUM_LENGTH = Constants.PACKET_TYPE_SIZE + Constants.UUID_SIZE + Constants.INT_SIZE;
/** The identifier of the peer that generated the packet. */
public final UUID peerIdentifier;
/** A list of identifier/cost pairs for each of the peer's neighbors. */
public final List<LinkStateRoutingTable.NeighborInformation<UUID>> neighbors;
public LinkStatePacket(UUID peerIdentifier, List<LinkStateRoutingTable.NeighborInformation<UUID>> neighbors) {
this.peerIdentifier = peerIdentifier;
this.neighbors = neighbors;
}
public static LinkStatePacket deserialize(ByteBuffer data) { | DataReader reader = new DataReader(data); | 2 |
GlitchCog/ChatGameFontificator | src/main/java/com/glitchcog/fontificator/gui/controls/panel/ControlPanelColor.java | [
"public class ConfigColor extends Config\n{\n private static final Logger logger = Logger.getLogger(ConfigColor.class);\n\n private Color bgColor;\n\n private Color fgColor;\n\n private Color borderColor;\n\n private Color highlight;\n\n private Color chromaColor;\n\n private List<Color> palett... | import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JCheckBox;
import javax.swing.JPanel;
import javax.swing.border.TitledBorder;
import com.glitchcog.fontificator.config.ConfigColor;
import com.glitchcog.fontificator.config.FontificatorProperties;
import com.glitchcog.fontificator.config.loadreport.LoadConfigReport;
import com.glitchcog.fontificator.gui.chat.ChatWindow;
import com.glitchcog.fontificator.gui.component.ColorButton;
import com.glitchcog.fontificator.gui.component.palette.Palette; | package com.glitchcog.fontificator.gui.controls.panel;
/**
* Control Panel containing all the color options
*
* @author Matt Yanos
*/
public class ControlPanelColor extends ControlPanelBase
{
private static final long serialVersionUID = 1L;
/**
* Background color button
*/ | private ColorButton bgColorButton; | 4 |
mit-dig/punya | appinventor/components/src/com/google/appinventor/components/runtime/FusiontablesControl.java | [
"public enum PropertyCategory {\n // TODO(user): i18n category names\n BEHAVIOR(\"Behavior\"),\n APPEARANCE(\"Appearance\"),\n LINKED_DATA(\"Linked Data\"),\n DEPRECATED(\"Deprecated\"),\n UNSET(\"Unspecified\");\n\n private String name;\n\n PropertyCategory(String categoryName) {\n name = categoryName;\... | import com.google.android.gms.auth.GoogleAuthException;
import com.google.android.gms.auth.UserRecoverableAuthException;
import com.google.api.client.extensions.android.http.AndroidHttp;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential;
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import com.google.api.client.googleapis.services.GoogleKeyInitializer;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.fusiontables.Fusiontables;
import com.google.api.services.fusiontables.Fusiontables.Query.Sql;
import com.google.appinventor.components.annotations.DesignerComponent;
import com.google.appinventor.components.annotations.DesignerProperty;
import com.google.appinventor.components.annotations.PropertyCategory;
import com.google.appinventor.components.annotations.SimpleEvent;
import com.google.appinventor.components.annotations.SimpleFunction;
import com.google.appinventor.components.annotations.SimpleObject;
import com.google.appinventor.components.annotations.SimpleProperty;
import com.google.appinventor.components.annotations.UsesLibraries;
import com.google.appinventor.components.annotations.UsesPermissions;
import com.google.appinventor.components.common.ComponentCategory;
import com.google.appinventor.components.common.PropertyTypeConstants;
import com.google.appinventor.components.common.YaVersion;
import com.google.appinventor.components.runtime.GoogleDrive.AccessToken;
import com.google.appinventor.components.runtime.util.ClientLoginHelper;
import com.google.appinventor.components.runtime.util.ErrorMessages;
import com.google.appinventor.components.runtime.util.IClientLoginHelper;
import com.google.appinventor.components.runtime.util.MediaUtil;
import com.google.appinventor.components.runtime.util.OAuth2Helper;
import com.google.appinventor.components.runtime.util.SdkLevel;
import android.accounts.AccountManager;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.util.Log;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.File;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList; |
@DesignerProperty(editorType = PropertyTypeConstants.PROPERTY_TYPE_BOOLEAN, defaultValue = "False")
@SimpleProperty
public void UseServiceAuthentication(boolean bool) {
this.isServiceAuth = bool;
}
/**
* Property for the service account email to use when using service authentication.
**/
@SimpleProperty(category = PropertyCategory.BEHAVIOR,
description = "The Service Account Email Address when service account authentication " +
"is in use.")
public String ServiceAccountEmail() {
return serviceAccountEmail;
}
@DesignerProperty(editorType = PropertyTypeConstants.PROPERTY_TYPE_STRING, defaultValue = "")
@SimpleProperty
public void ServiceAccountEmail(String email) {
this.serviceAccountEmail = email;
}
/**
* Setter for the app developer's API key.
*/
@DesignerProperty(editorType = PropertyTypeConstants.PROPERTY_TYPE_STRING,
defaultValue = "")
@SimpleProperty
public void ApiKey(String apiKey) {
this.apiKey = apiKey;
}
/**
* Getter for the API key.
* @return apiKey the apiKey
*/
@SimpleProperty(
description = "Your Google API Key. For help, click on the question" +
"mark (?) next to the FusiontablesControl component in the Palette. ",
category = PropertyCategory.BEHAVIOR)
public String ApiKey() {
return apiKey;
}
@DesignerProperty(editorType = PropertyTypeConstants.PROPERTY_TYPE_STRING,
defaultValue = DEFAULT_QUERY)
@SimpleProperty
public void Query(String query) {
this.query = query;
}
@SimpleProperty(
description = "The query to send to the Fusion Tables API. " +
"<p>For legal query formats and examples, see the " +
"<a href=\"https://developers.google.com/fusiontables/docs/v1/getting_started\" target=\"_blank\">Fusion Tables API v1.0 reference manual</a>.</p> " +
"<p>Note that you do not need to worry about UTF-encoding the query. " +
"But you do need to make sure it follows the syntax described in the reference manual, " +
"which means that things like capitalization for names of columns matters, " +
"and that single quotes need to be used around column names if there are spaces in them.</p> ",
category = PropertyCategory.BEHAVIOR)
public String Query() {
return query;
}
@DesignerProperty(editorType = PropertyTypeConstants.PROPERTY_TYPE_ASSET,
defaultValue = "")
@SimpleProperty
public void KeyFile(String path) {
// If it's the same as on the prior call and the prior load was successful,
// do nothing.
if (path.equals(keyPath)) {
return;
}
// Remove old cached credentials if we are changing the keyPath
if (cachedServiceCredentials != null) {
cachedServiceCredentials.delete();
cachedServiceCredentials = null;
}
keyPath = (path == null) ? "" : path;
}
@SimpleProperty(
category = PropertyCategory.BEHAVIOR,
description = "Specifies the path of the private key file. " +
"This key file is used to get access to the FusionTables API.")
public String KeyFile() {
return keyPath;
}
/**
* Calls QueryProcessor to execute the API request asynchronously, if
* the user has already authenticated with the Fusiontables service.
*/
@SimpleFunction(description = "Send the query to the Fusiontables server.")
public void SendQuery() {
// if not Authorized
// ask the user to go throug the OAuth flow
AccessToken accessToken = retrieveAccessToken();
if(accessToken.accountName.length() == 0){
activity.startActivityForResult(credential.newChooseAccountIntent(), REQUEST_CHOOSE_ACCOUNT);
}
// if authorized
new QueryProcessorV1(activity).execute(query);
//
}
//Deprecated -- Won't work after 12/2012
@Deprecated // [lyn, 2015/12/30] In AI2, now use explicit @Deprecated annotation rather than
// userVisible = false to deprecate an event, method, or property.
@SimpleFunction(
description = "DEPRECATED. This block is deprecated as of the end of 2012. Use SendQuery.")
public void DoQuery() {
if (requestHelper != null) {
new QueryProcessor().execute(query);
} else {
form.dispatchErrorOccurredEvent(this, "DoQuery", | ErrorMessages.ERROR_FUNCTIONALITY_NOT_SUPPORTED_FUSIONTABLES_CONTROL); | 4 |
USCDataScience/AgePredictor | age-predictor-cli/src/main/java/edu/usc/irds/agepredictor/cmdline/spark/authorage/AgePredictTool.java | [
"public class CLI {\n public static final String CMD = \"bin/authorage\";\n public static final String DEFAULT_FORMAT = AuthorAgeSample.FORMAT_NAME;\n \n private static Map<String, CmdLineTool> toolLookupMap;\n \n static {\n\ttoolLookupMap = new LinkedHashMap<String, CmdLineTool>();\n \n\tLi... | import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.function.VoidFunction;
import org.apache.spark.ml.feature.CountVectorizerModel;
import org.apache.spark.ml.feature.Normalizer;
import org.apache.spark.ml.linalg.SparseVector;
import org.apache.spark.mllib.linalg.Vectors;
import org.apache.spark.mllib.regression.LassoModel;
import org.apache.spark.sql.Dataset;
import org.apache.spark.sql.Row;
import org.apache.spark.sql.RowFactory;
import org.apache.spark.sql.SparkSession;
import org.apache.spark.sql.types.ArrayType;
import org.apache.spark.sql.types.DataTypes;
import org.apache.spark.sql.types.Metadata;
import org.apache.spark.sql.types.StructField;
import org.apache.spark.sql.types.StructType;
import edu.usc.irds.agepredictor.cmdline.CLI;
import edu.usc.irds.agepredictor.spark.authorage.AgePredictModel;
import opennlp.tools.authorage.AgeClassifyME;
import opennlp.tools.authorage.AgeClassifyModel;
import opennlp.tools.cmdline.BasicCmdLineTool;
import opennlp.tools.cmdline.CmdLineUtil;
import opennlp.tools.cmdline.SystemInputStreamFactory;
import opennlp.tools.util.ObjectStream;
import opennlp.tools.util.ParagraphStream;
import opennlp.tools.util.PlainTextByLineStream;
import opennlp.tools.util.featuregen.FeatureGenerator; | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.usc.irds.agepredictor.cmdline.spark.authorage;
/**
* TODO: Documentation
*/
public class AgePredictTool extends BasicCmdLineTool implements Serializable {
@Override
public String getShortDescription() {
return "age predictor";
}
@Override
public String getHelp() { | return "Usage: " + CLI.CMD + " " + getName() + " [MaxEntModel] RegressionModel Documents"; | 0 |
b0noI/AIF2 | src/test/integration/java/io/aif/language/sentence/SimpleSentenceSplitterCharactersExtractorQualityTest.java | [
"public abstract class FileHelper {\n\n public static String readAllText(final InputStream inputStream) throws IOException {\n try (final BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {\n\n final StringBuffer buff = new StringBuffer();\n\n String line = null;\n\n ... | import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import io.aif.common.FileHelper;
import io.aif.language.common.ISplitter;
import io.aif.language.sentence.separators.classificators.ISeparatorGroupsClassifier;
import io.aif.language.sentence.separators.extractors.ISeparatorExtractor;
import io.aif.language.sentence.separators.groupers.ISeparatorsGrouper;
import io.aif.language.token.Tokenizer;
import static org.testng.AssertJUnit.assertFalse;
import static org.testng.AssertJUnit.assertTrue; | {"ITA/Fallaci Oriana - La rabbia e l'orgoglio (2001).txt"},
{"ITA/Fallaci Oriana - Lettera a un bambino mai nato (1975).txt"},
{"ITA/Fallaci Oriana - Niente E Cos Sia (1969).txt"},
{"ITA/Fallaci Oriana - Oriana Fallaci intervista Oriana Fallaci (2004).txt"},
{"ITA/Fallaci Oriana - Penelope Alla Guerra (1962).txt"},
{"ITA/Fallaci Oriana - Risponde (Social forum a Firenze) (2002).txt"},
{"ITA/Fallaci Oriana - Un cappello pieno di ciliege (2005).txt"},
{"ITA/Fallaci Oriana - Un uomo (1979).txt"},
{"ITA/Fallaci Oriana - Wake Up Occidente Sveglia (2002).txt"},
//POL
{"POL/Chmielewska Joanna - Autobiografia t 3.txt"},
{"POL/Chmielewska Joanna - Autobiografia t 4.txt"},
{"POL/Chmielewska Joanna - Autobiografia t 5.txt"},
{"POL/Chmielewska Joanna - Depozyt.txt"},
{"POL/Chmielewska Joanna - Drugi watek.txt"},
{"POL/Chmielewska Joanna - Pafnucy.txt"},
{"POL/Chmielewska Joanna - Szajka bez konca.txt"},
{"POL/Chmielewska Joanna - W.txt"},
{"POL/Chmielewska Joanna D.txt"},
{"POL/Chmielewska Joanna Dwie glowy i jedna noga.txt"},
{"POL/Chmielewska Joanna Dwie trzecie sukcesu.txt"},
{"POL/Chmielewska Joanna Klin.txt"},
{"POL/Chmielewska Joanna Krokodyl z Kraju Karoliny.txt"},
{"POL/Chmielewska Joanna L.txt"},
{"POL/Chmielewska Joanna Zbieg okolicznosci.txt"},
{"POL/Chmielewska_Joanna_-_(Nie)boszczyk_maz.txt"},
{"POL/Chmielewska_Joanna_-_Babski_motyw.txt"},
{"POL/Chmielewska_Joanna_-_Bulgarski_bloczek.txt"},
{"POL/Chmielewska_Joanna_-_Pech.txt"},
{"POL/Chmielewska_Joanna_-_Trudny_Trup.txt"},
{"POL/J. Chmielewska Wielkie zaslugi.txt"},
{"POL/J.Chmielewska 1 Wielki diament.txt"},
{"POL/J.Chmielewska 2 Wielki diament.txt"},
{"POL/J.Chmielewska Skarby.txt"},
{"POL/J.Chmielewska Slepe szczescie.txt"},
{"POL/JOANNA CHMIELEWSKA.txt"},
{"POL/Joanna Chmielewska - Harpie.txt"},
{"POL/Joanna Chmielewska Kocie worki.txt"},
{"POL/Joanna Chmielewska Lesio.txt"},
{"POL/Joanna Chmielewska Wszyscy jestesmy podejrzani.txt"},
{"POL/Krowa niebianska.txt"},
{"POL/Nawiedzony dom.txt"},
{"POL/Przekleta Bariera.txt"},
{"POL/Skradziona kolekcja.txt"},
{"POL/Wegiel Marta Jak wytrzymac z Joanna Chmielewska.txt"},
{"POL/Wszystko Czerwone.txt"},
{"POL/Zbieg okolicznosci.txt"},
{"POL/Złota mucha.txt"},
{"POL/BOCZNE DROGI.txt"},
{"POL/Cale zdanie nieboszczyka.txt"},
{"POL/Chmielewska J. Jak wytrzymac ze wspolczesna kobieta.txt"},
{"POL/Chmielewska Joanna - Autobiografia t 1.txt"},
{"POL/Chmielewska Joanna - Autobiografia t 2.txt"},
//RUS
{"RU/17354.txt"},
{"RU/18957.txt"},
{"RU/19530.txt"},
{"RU/27519.txt"},
{"RU/46427.txt"},
{"RU/46468.txt"},
{"RU/46606.txt"},
{"RU/46699.txt"},
{"RU/46777.txt"},
{"RU/47729.txt"},
{"RU/49723.txt"},
{"RU/70684.txt"},
{"RU/79813.txt"},
{"RU/9602.txt"},
};
}
public static void main(String[] args) throws Exception {
final Map<String, List<String>> errors = executeTest();
System.out.println(
errors.keySet().stream().mapToDouble(key -> (double) errors.get(key).size()).sum()
/ (double) engBooksProvider().length * 5.);
}
public static Map<String, List<String>> executeTest() throws Exception {
// input arguments
String inputText;
final Map<String, List<String>> totalErrors = new HashMap<>();
for (String[] path : engBooksProvider()) {
try (InputStream modelResource = SimpleSentenceSplitterCharactersExtractorQualityTest.class
.getResourceAsStream(String.format("/texts/%s", path))) {
inputText = FileHelper.readAllText(modelResource);
}
List<String> errors = qualityTest(inputText);
if (errors.size() > 0) {
totalErrors.put(path[0], errors);
}
}
final Map<String, Integer> errorsCounts = new HashMap<>();
totalErrors.entrySet().forEach(element -> {
element.getValue().forEach(error -> {
final int errorCount = errorsCounts.getOrDefault(error, 0);
errorsCounts.put(error, errorCount + 1);
});
});
return totalErrors;
}
private static List<String> qualityTest(final String inputText) {
final Tokenizer tokenizer = new Tokenizer();
final List<String> inputTokens = tokenizer.split(inputText);
// expected results
final List<Character> expectedResult = Arrays.asList('.', '(', ')', ':', '\"', '#', ';', '‘',
'“', ',', '\'', '?', '!');
final List<Character> mandatoryCharacters = Arrays.asList('.', ',');
final List<Character> mandatoryGroup1Characters = Collections.singletonList('.');
final List<Character> mandatoryGroup2Characters = Collections.singletonList(',');
// creating test instance
final ISeparatorExtractor testInstance = ISeparatorExtractor.Type.PROBABILITY.getInstance(); | final ISeparatorsGrouper separatorsGrouper = ISeparatorsGrouper.Type.PROBABILITY.getInstance(); | 3 |
WANdisco/s3hdfs | src/main/java/com/wandisco/s3hdfs/command/HeadCommand.java | [
"public class S3HdfsPath {\n private final String rootDir;\n private final String userName;\n private final String bucketName;\n private final String objectName;\n private final String partNumber;\n\n private String version;\n\n public S3HdfsPath() throws UnsupportedEncodingException {\n this(null, null, ... | import com.wandisco.s3hdfs.path.S3HdfsPath;
import com.wandisco.s3hdfs.rewrite.redirect.MetadataFileRedirect;
import com.wandisco.s3hdfs.rewrite.redirect.ObjectInfoRedirect;
import com.wandisco.s3hdfs.rewrite.wrapper.S3HdfsRequestWrapper;
import com.wandisco.s3hdfs.rewrite.wrapper.S3HdfsResponseWrapper;
import com.wandisco.s3hdfs.rewrite.wrapper.WebHdfsRequestWrapper;
import com.wandisco.s3hdfs.rewrite.wrapper.WebHdfsResponseWrapper;
import javax.servlet.ServletException;
import java.io.IOException;
import java.util.Properties;
import static com.wandisco.s3hdfs.conf.S3HdfsConstants.S3HDFS_COMMAND;
import static com.wandisco.s3hdfs.rewrite.filter.S3HdfsFilter.ADD_WEBHDFS; | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.wandisco.s3hdfs.command;
public class HeadCommand extends Command {
public HeadCommand(final S3HdfsRequestWrapper request,
final S3HdfsResponseWrapper response,
final String serviceHost,
final String proxyPort,
final S3HdfsPath s3HdfsPath) {
super(request, response, serviceHost, proxyPort, s3HdfsPath);
}
@Override
protected S3HDFS_COMMAND parseCommand() throws IOException {
final String objectName = s3HdfsPath.getObjectName();
final String bucketName = s3HdfsPath.getBucketName();
if ((objectName != null && !objectName.isEmpty()) &&
(bucketName != null && !bucketName.isEmpty()))
return S3HDFS_COMMAND.HEAD_OBJECT;
else
throw new IOException("Unknown command: " + command);
}
@Override
protected String parseURI()
throws IOException {
// 1. Parse the command.
command = parseCommand();
System.out.println("Command parsed as: " + command.toString());
// 2. Parse the modified URI.
switch (command) {
case HEAD_OBJECT:
// A. If we get object head we need the version path
// Version path == /root/user/bucket/object/version
modifiedURI = s3HdfsPath.getHdfsRootVersionPath();
break;
default:
throw new IOException("Unknown command: " + command);
}
// 3. Set the modified URI. | modifiedURI = ADD_WEBHDFS(modifiedURI); | 8 |
jesse-gallagher/frostillic.us-Blog | frostillicus-blog/frostillicus-blog-j2ee/src/main/java/controller/AdminController.java | [
"@RequestScoped\n@Named(\"userInfo\")\npublic class UserInfoBean {\n\tpublic static final String ROLE_ADMIN = \"admin\"; //$NON-NLS-1$\n\n\t@Inject @Named(\"darwinoContext\")\n\tDarwinoContext context;\n\n\t@SneakyThrows\n\tpublic String getImageUrl(final String userName) {\n\t\tString md5 = StringUtil.md5Hex(Strin... | import bean.UserInfoBean;
import com.darwino.commons.json.JsonException;
import com.darwino.jsonstore.Session;
import model.AccessToken;
import model.AccessTokenRepository;
import model.Link;
import model.LinkRepository;
import javax.annotation.security.RolesAllowed;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.mvc.Controller;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import java.util.UUID; | /*
* Copyright © 2012-2020 Jesse Gallagher
*
* 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 controller;
@Controller
@Path("admin")
@RolesAllowed(UserInfoBean.ROLE_ADMIN)
@RequestScoped
public class AdminController {
@Inject
LinkRepository links;
@Inject
AccessTokenRepository tokens;
@Inject
Session session;
@GET
@Produces(MediaType.TEXT_HTML)
public String show() {
return "admin.jsp"; //$NON-NLS-1$
}
// *******************************************************************************
// * Links
// *******************************************************************************
@POST
@Path("links/{linkId}")
public String update(
@PathParam("linkId") final String linkId,
@FormParam("visible") final String visible,
@FormParam("category") final String category,
@FormParam("name") final String name,
@FormParam("url") final String url,
@FormParam("rel") final String rel
) {
var link = links.findById(linkId).orElseThrow(() -> new NotFoundException("Unable to find link matching ID " + linkId)); //$NON-NLS-1$
link.setVisible("Y".equals(visible)); //$NON-NLS-1$
link.setCategory(category);
link.setName(name);
link.setUrl(url);
link.setRel(rel);
links.save(link);
return "redirect:admin"; //$NON-NLS-1$
}
@DELETE
@Path("links/{linkId}")
public String deleteLink(@PathParam("linkId") final String linkId) {
links.deleteById(linkId);
return "redirect:admin"; //$NON-NLS-1$
}
@POST
@Path("links/new")
public String createLink() { | var link = new Link(); | 3 |
DevComPack/setupmaker | src/main/java/com/dcp/sm/gui/pivot/tasks/TaskDirScan.java | [
"public class IOFactory\n{\n //ISO3 language codes\n public static String[] iso3Codes;\n //File type extensions\n public static String[] archiveExt;// = {\"zip\", \"rar\", \"jar\", \"iso\"};\n public static String[] exeExt;// = {\"exe\", \"jar\", \"cmd\", \"sh\", \"bat\"};\n public static String[]... | import java.io.File;
import java.io.FilenameFilter;
import org.apache.pivot.collections.List;
import org.apache.pivot.util.concurrent.Task;
import org.apache.pivot.wtk.content.TreeBranch;
import org.apache.pivot.wtk.content.TreeNode;
import com.dcp.sm.config.io.IOFactory;
import com.dcp.sm.gui.pivot.frames.ScanFrame;
import com.dcp.sm.logic.factory.CastFactory;
import com.dcp.sm.logic.factory.TypeFactory.SCAN_MODE;
import com.dcp.sm.logic.model.Group;
import com.dcp.sm.logic.model.Pack; | package com.dcp.sm.gui.pivot.tasks;
public class TaskDirScan extends Task<Integer>
{
//Constants
private final static int INFINITE_DEPTH = 20;//Maximum recursive scan depth if depth is '-'
//Attributes
private ScanFrame scanFrame;
private String path;
private List<TreeNode> treeData;
private String depthValue;
//Data
private List<Group> groups;
private List<Pack> packs;
//Filter
private boolean folderFilter;
private FilenameFilter filter;
public TaskDirScan(ScanFrame source, String path, List<TreeNode> treeData, FilenameFilter filter,
String depthValue, boolean folderFilter)
{
this.scanFrame = source;
// point to data models lists
this.groups = scanFrame.facade.getGroups();
this.packs = scanFrame.facade.getPacks();
this.path = path;
this.treeData = treeData;
this.filter= filter;
this.depthValue = depthValue;
this.folderFilter = folderFilter;
}
/**
* Recursive Scan Function + Groups create
* Scan DIR to treeBranch, directories to PARENT
*/
private void recursivScan(File directory, TreeBranch treeBranch, Group PARENT, int DEPTH) {
for(File f:directory.listFiles(filter)) {
if (f.isDirectory()) {//Directory
if (DEPTH>0) {
Group G = new Group(f.getName(),PARENT);
groups.add(G);//Group model add
TreeBranch T = new TreeBranch(IOFactory.imgFolder, f.getName());
recursivScan(f, T, G, DEPTH-1);//@-
treeBranch.add(T);//Tree Branch node add
}
else if (folderFilter) {//Get folders as packs
Pack P = CastFactory.fileToPack(f);
P.setPriority(packs.getLength());//Priority initialize
P.setGroup(PARENT);
packs.add(P);
treeBranch.add(new TreeNode(P.getIcon(), P.getName()));//Tree node add
}
}
else {//File
Pack P = CastFactory.fileToPack(f);
P.setPriority(packs.getLength());//Priority initialize
P.setGroup(PARENT);//Setting Parent
packs.add(P);
treeBranch.add(new TreeNode(P.getIcon(), P.getName()));//Tree node add
}
}
}
/**
* Simple Scan Functions
* @param directory to scan
* @param folder folder filter is selected
*/
private void simpleScan(File directory) {
for(File f : directory.listFiles(filter)) {
if (f.isDirectory()) {//Directory
if (folderFilter) {//Directory filter cb selected (not active)
Pack P = CastFactory.fileToPack(f);
P.setPriority(packs.getLength());//Priority initialize
packs.add(P);
treeData.add(new TreeNode(P.getIcon(), P.getName()));
}
}
else if (f.isFile()) {//File
Pack P = CastFactory.fileToPack(f);
P.setPriority(packs.getLength());//Priority initialize
packs.add(P);
treeData.add(new TreeNode(P.getIcon(), P.getName()));
}
}
}
@Override
public Integer execute()
{
scanFrame.facade.clear();// Clear data
if (!path.equals("")) {//If a path is entered
File dir = new File(path);
if (dir.exists()) {
scanFrame.setModified(true);//Flag Modified
TreeBranch treeBranch = new TreeBranch(dir.getName()); | SCAN_MODE scanMode = ScanFrame.getSingleton().facade.getScanMode(); | 3 |
kaliturin/BlackList | app/src/main/java/com/kaliturin/blacklist/fragments/SettingsFragment.java | [
"public class MainActivity extends AppCompatActivity\n implements NavigationView.OnNavigationItemSelectedListener {\n\n public static final String ACTION_JOURNAL = \"com.kaliturin.blacklist.ACTION_JOURNAL\";\n public static final String ACTION_SMS_CONVERSATIONS = \"com.kaliturin.blacklist.ACTION_SMS_CO... | import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.IdRes;
import android.support.annotation.Nullable;
import android.support.annotation.StringRes;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.telephony.SubscriptionInfo;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.kaliturin.blacklist.R;
import com.kaliturin.blacklist.activities.MainActivity;
import com.kaliturin.blacklist.adapters.SettingsArrayAdapter;
import com.kaliturin.blacklist.utils.DatabaseAccessHelper;
import com.kaliturin.blacklist.utils.DefaultSMSAppHelper;
import com.kaliturin.blacklist.utils.DialogBuilder;
import com.kaliturin.blacklist.utils.Permissions;
import com.kaliturin.blacklist.utils.Settings;
import com.kaliturin.blacklist.utils.SubscriptionHelper;
import com.kaliturin.blacklist.utils.Utils;
import java.io.File;
import java.util.List; | case BLOCKED_SMS:
uriString = Settings.getStringValue(getContext(), Settings.BLOCKED_SMS_RINGTONE);
break;
case RECEIVED_SMS:
uriString = Settings.getStringValue(getContext(), Settings.RECEIVED_SMS_RINGTONE);
break;
}
return (uriString != null ? Uri.parse(uriString) : null);
}
// On row click listener for opening ringtone picker
private class RingtonePickerOnClickListener implements View.OnClickListener {
int requestCode;
RingtonePickerOnClickListener(int requestCode) {
this.requestCode = requestCode;
}
@Override
public void onClick(View view) {
if (isAdded()) {
if (adapter.isRowChecked(view)) {
// open ringtone picker dialog
Intent intent = new Intent(RingtoneManager.ACTION_RINGTONE_PICKER);
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TYPE, RingtoneManager.TYPE_NOTIFICATION);
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TITLE, getString(R.string.Ringtone_picker));
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_EXISTING_URI, getRingtoneUri(requestCode));
startActivityForResult(intent, requestCode);
}
} else {
adapter.setRowChecked(view, false);
}
}
}
// On row click listener for updating dependent rows
private class DependentRowOnClickListener implements View.OnClickListener {
@Override
public void onClick(View view) {
String property = adapter.getRowProperty(view);
if (property == null) {
return;
}
boolean checked = adapter.isRowChecked(view);
if (!checked) {
// if row was unchecked - reset dependent rows
switch (property) {
case Settings.BLOCKED_SMS_STATUS_NOTIFICATION:
adapter.setRowChecked(Settings.BLOCKED_SMS_SOUND_NOTIFICATION, false);
adapter.setRowChecked(Settings.BLOCKED_SMS_VIBRATION_NOTIFICATION, false);
break;
case Settings.BLOCKED_CALL_STATUS_NOTIFICATION:
adapter.setRowChecked(Settings.BLOCKED_CALL_SOUND_NOTIFICATION, false);
adapter.setRowChecked(Settings.BLOCKED_CALL_VIBRATION_NOTIFICATION, false);
break;
}
} else {
switch (property) {
case Settings.BLOCKED_SMS_SOUND_NOTIFICATION:
case Settings.BLOCKED_SMS_VIBRATION_NOTIFICATION:
adapter.setRowChecked(Settings.BLOCKED_SMS_STATUS_NOTIFICATION, true);
break;
case Settings.BLOCKED_CALL_SOUND_NOTIFICATION:
case Settings.BLOCKED_CALL_VIBRATION_NOTIFICATION:
adapter.setRowChecked(Settings.BLOCKED_CALL_STATUS_NOTIFICATION, true);
break;
}
}
}
}
// Shows the dialog of database file path definition
private void showFilePathDialog(@StringRes int titleId, final TextView.OnEditorActionListener listener) {
if (!isAdded()) return;
String filePath = Environment.getExternalStorageDirectory().getPath() +
"/Download/" + DatabaseAccessHelper.DATABASE_NAME;
@IdRes final int editId = 1;
// create dialog
DialogBuilder dialog = new DialogBuilder(getContext());
dialog.setTitle(titleId);
dialog.addEdit(editId, filePath, getString(R.string.File_path));
dialog.addButtonLeft(getString(R.string.CANCEL), null);
dialog.addButtonRight(getString(R.string.OK), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Window window = ((Dialog) dialog).getWindow();
if (window != null) {
TextView textView = (TextView) window.findViewById(editId);
if (textView != null) {
listener.onEditorAction(textView, 0, null);
}
}
}
});
dialog.show();
}
// Exports data file to the passed path
private boolean exportDataFile(String dstFilePath) {
if (!Permissions.isGranted(getContext(), Permissions.WRITE_EXTERNAL_STORAGE)) {
return false;
}
// get source file
DatabaseAccessHelper db = DatabaseAccessHelper.getInstance(getContext());
if (db == null) {
return false;
}
File srcFile = new File(db.getReadableDatabase().getPath());
// check destination file
File dstFile = new File(dstFilePath);
if (dstFile.getParent() == null) {
toast(R.string.Error_invalid_file_path);
return false;
}
// create destination file path | if (!Utils.makeFilePath(dstFile)) { | 8 |
dperezcabrera/jpoker | src/main/java/org/poker/main/MainController.java | [
"public class RandomStrategy implements IStrategy {\n\n private static final Random RAND = new Random();\n private final String name;\n private double aggressivity = 0.5 + RAND.nextDouble() / 2;\n private BetCommand lastBet = null;\n\n public RandomStrategy(String name) {\n this.name = \"Rando... | import org.poker.sample.strategies.RandomStrategy;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.poker.api.game.IGameController;
import org.poker.api.game.IStrategy;
import org.poker.api.game.Settings;
import org.poker.engine.controller.GameController;
import org.poker.gui.TexasHoldEmView;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | /*
* Copyright (C) 2016 David Pérez Cabrera <dperezcabrera@gmail.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.poker.main;
/**
*
* @author David Pérez Cabrera <dperezcabrera@gmail.com>
*/
public final class MainController {
private static final Logger LOGGER = LoggerFactory.getLogger(MainController.class);
private static final int PLAYERS = 10;
private MainController() {
}
public static void main(String[] args) throws Exception {
IStrategy strategyMain = new RandomStrategy("0"); | TexasHoldEmView texasHoldEmView = new TexasHoldEmView(strategyMain); | 5 |
ralscha/wampspring | src/main/java/ch/rasc/wampspring/config/WampSubProtocolHandler.java | [
"public class CallErrorMessage extends WampMessage {\n\tprivate final String callID;\n\n\tprivate final String errorURI;\n\n\tprivate final String errorDesc;\n\n\tprivate final Object errorDetails;\n\n\tpublic CallErrorMessage(CallMessage callMessage, String errorURI, String errorDesc) {\n\t\tthis(callMessage, erro... | import java.io.IOException;
import java.util.Collections;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.util.Assert;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.SessionLimitExceededException;
import org.springframework.web.socket.messaging.SubProtocolHandler;
import com.fasterxml.jackson.core.JsonFactory;
import ch.rasc.wampspring.message.CallErrorMessage;
import ch.rasc.wampspring.message.CallMessage;
import ch.rasc.wampspring.message.UnsubscribeMessage;
import ch.rasc.wampspring.message.WampMessage;
import ch.rasc.wampspring.message.WampMessageHeader;
import ch.rasc.wampspring.message.WelcomeMessage; | /**
* Copyright 2002-2015 the original author or authors.
*
* 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 ch.rasc.wampspring.config;
/**
* A WebSocket {@link SubProtocolHandler} for the WAMP v1 protocol.
*
* @author Rossen Stoyanchev
* @author Andy Wilkinson
* @author Ralph Schaer
*/
public class WampSubProtocolHandler implements SubProtocolHandler {
public static final int MINIMUM_WEBSOCKET_MESSAGE_SIZE = 16 * 1024 + 256;
private static final Log logger = LogFactory.getLog(WampSubProtocolHandler.class);
private static final String SERVER_IDENTIFIER = "wampspring/1.1";
private final JsonFactory jsonFactory;
public WampSubProtocolHandler(JsonFactory jsonFactory) {
this.jsonFactory = jsonFactory;
}
@Override
public List<String> getSupportedProtocols() {
return Collections.singletonList("wamp");
}
/**
* Handle incoming WebSocket messages from clients.
*/
@Override
public void handleMessageFromClient(WebSocketSession session,
WebSocketMessage<?> webSocketMessage, MessageChannel outputChannel) {
Assert.isInstanceOf(TextMessage.class, webSocketMessage); | WampMessage wampMessage = null; | 3 |
mkovatsc/iot-semantics | semantic-ide/src/main/java/ch/ethz/inf/vs/semantics/ide/rest/QueryResource.java | [
"public class N3Linter {\n\n\tpublic static ArrayList<SemanticsErrors> lint(String input) {\n\t\tArrayList<SemanticsErrors> errors = new ArrayList<SemanticsErrors>();\n\t\tN3Lexer nl = new N3Lexer(new ANTLRInputStream(input));\n\t\tCommonTokenStream ts = new CommonTokenStream(nl);\n\t\tN3Parser np = new N3Parser(ts... | import ch.ethz.inf.vs.semantics.ide.domain.N3Linter;
import ch.ethz.inf.vs.semantics.ide.domain.Query;
import ch.ethz.inf.vs.semantics.ide.domain.QueryResult;
import ch.ethz.inf.vs.semantics.ide.domain.SemanticsErrors;
import ch.ethz.inf.vs.semantics.ide.workspace.Workspace;
import ch.ethz.inf.vs.semantics.ide.workspace.WorkspaceManager;
import restx.annotations.*;
import restx.factory.Component;
import restx.security.PermitAll;
import java.util.ArrayList;
import java.util.Collection; | package ch.ethz.inf.vs.semantics.ide.rest;
@Component
@RestxResource
public class QueryResource {
@POST("/{workspace}/queries")
@PermitAll
public static Query postQuery(int workspace, Query msg) { | Workspace ws = WorkspaceManager.get(workspace); | 5 |
badvision/jace | src/main/java/jace/state/StateManager.java | [
"public class Emulator {\r\n\r\n public static Emulator instance;\r\n public static EmulatorUILogic logic = new EmulatorUILogic();\r\n public static Thread mainThread;\r\n\r\n// public static void main(String... args) {\r\n// mainThread = Thread.currentThread();\r\n// instance = new Emulat... | import jace.Emulator;
import jace.apple2e.SoftSwitches;
import jace.config.ConfigurableField;
import jace.config.InvokableAction;
import jace.config.Reconfigurable;
import jace.core.Computer;
import jace.core.PagedMemory;
import jace.core.Video;
import java.awt.image.BufferedImage;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.WeakHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.scene.image.Image;
import javafx.scene.image.WritableImage;
import javafx.scene.input.KeyCode; | /*
* Copyright (C) 2012 Brendan Robert (BLuRry) brendan.robert@gmail.com.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package jace.state;
/**
*
* @author Brendan Robert (BLuRry) brendan.robert@gmail.com
*/
public class StateManager implements Reconfigurable {
private static StateManager instance;
public static StateManager getInstance(Computer computer) {
if (instance == null) {
instance = new StateManager(computer);
}
return instance;
}
State alphaState;
Set<ObjectGraphNode> allStateVariables;
WeakHashMap<Object, ObjectGraphNode> objectLookup;
long maxMemory = -1;
long freeRequired = -1; | @ConfigurableField(category = "Emulator", name = "Max states", description = "How many states can be captured, oldest states are automatically truncated.", defaultValue = "150") | 0 |
lanixzcj/LoveTalkClient | src/com/example/lovetalk/activity/NewFriendActivity.java | [
"public class NewFriendAdapter extends BaseListAdapter<AddRequest> {\n\n\tpublic NewFriendAdapter(Context context, List<AddRequest> list) {\n\t\tsuper(context, list);\n\t\t// TODO Auto-generated constructor stub\n\t}\n\n\t@Override\n\tpublic View getView(int position, View conView, ViewGroup parent) {\n\t\t// TODO ... | import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ListView;
import com.avos.avoscloud.AVUser;
import com.example.lovetalk.R;
import com.example.lovetalk.adapter.NewFriendAdapter;
import com.example.lovetalk.service.AddRequest;
import com.example.lovetalk.service.AddRequestService;
import com.example.lovetalk.service.PreferenceMap;
import com.example.lovetalk.util.MyAsyncTask;
import java.util.ArrayList;
import java.util.List; | package com.example.lovetalk.activity;
public class NewFriendActivity extends BaseActivity implements OnItemLongClickListener {
ListView listview; | NewFriendAdapter adapter; | 0 |
senseobservationsystems/sense-android-library | sense-android-library/src/nl/sense_os/service/deviceprox/BluetoothDeviceProximity.java | [
"public static class DataPoint implements BaseColumns {\n\n public static final String CONTENT_TYPE = ContentResolver.CURSOR_DIR_BASE_TYPE\n + \"/vnd.sense_os.data_point\";\n public static final String CONTENT_ITEM_TYPE = ContentResolver.CURSOR_ITEM_BASE_TYPE\n + \"/vnd.sense_os.data_poi... | import java.util.HashMap;
import java.util.Map;
import java.util.Vector;
import nl.sense_os.service.R;
import nl.sense_os.service.constants.SenseDataTypes;
import nl.sense_os.service.constants.SensorData.DataPoint;
import nl.sense_os.service.constants.SensorData.SensorNames;
import nl.sense_os.service.provider.SNTP;
import nl.sense_os.service.shared.SensorDataPoint;
import nl.sense_os.service.subscription.BaseDataProducer;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.Looper;
import android.util.Log; | /**************************************************************************************************
* Copyright (C) 2010 Sense Observation Systems, Rotterdam, the Netherlands. All rights reserved. *
*************************************************************************************************/
package nl.sense_os.service.deviceprox;
/**
* Represents the Bluetooth scan sensor. Sets up periodic scans of the network on a separate thread.
*
* @author Ted Schmidt <ted@sense-os.nl>
*/
public class BluetoothDeviceProximity extends BaseDataProducer{
/**
* Receiver for Bluetooth state broadcasts
*/
private class BluetoothReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (!scanEnabled || null == scanThread) {
Log.w(TAG, "Bluetooth broadcast received while sensor is disabled");
return;
}
String action = intent.getAction();
if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
onBluetoothStateChanged(intent);
} else if (BluetoothDevice.ACTION_FOUND.equals(action)) {
onDeviceFound(intent);
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
onScanFinished();
}
}
}
/**
* Receiver for alarms to start scan
*/
private class ScanAlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (!scanEnabled) {
Log.w(TAG, "Bluetooth scan alarm received while sensor is disabled");
return;
} else {
// stop any old threads
try {
if (null != scanThread) {
scanThread.stop();
scanHandler.removeCallbacks(scanThread);
}
} catch (Exception e) {
Log.e(TAG, "Exception clearing old bluetooth scan threads. " + e);
}
// start new scan
scanHandler.post(scanThread = new ScanThread());
}
}
}
/**
* Bluetooth discovery thread
*/
private class ScanThread implements Runnable {
// private boolean btActiveFromTheStart = false; // removed
private Vector<Map<BluetoothDevice, Short>> deviceArray;
public ScanThread() {
// send address
try {
btAdapter = BluetoothAdapter.getDefaultAdapter();
// btActiveFromTheStart = btAdapter.isEnabled();
} catch (Exception e) {
Log.e(TAG, "Exception preparing Bluetooth scan thread:", e);
}
}
@Override
public void run() {
Log.v(TAG, "Run Bluetooth discovery thread");
if (scanEnabled) {
if (btAdapter.isEnabled()) {
// start discovery
deviceArray = new Vector<Map<BluetoothDevice, Short>>();
context.registerReceiver(btReceiver, new IntentFilter(
BluetoothDevice.ACTION_FOUND));
context.registerReceiver(btReceiver, new IntentFilter(
BluetoothAdapter.ACTION_DISCOVERY_FINISHED));
Log.i(TAG, "Starting Bluetooth discovery");
btAdapter.startDiscovery();
} else if (btAdapter.getState() == BluetoothAdapter.STATE_TURNING_ON) {
// listen for the adapter state to change to STATE_ON
context.registerReceiver(btReceiver, new IntentFilter(
BluetoothAdapter.ACTION_STATE_CHANGED));
} else {
// ask user for permission to start bluetooth
// Log.v(TAG, "Asking user to start bluetooth");
Intent startBt = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startBt.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(startBt);
// listen for the adapter state to change to STATE_ON
context.registerReceiver(btReceiver, new IntentFilter(
BluetoothAdapter.ACTION_STATE_CHANGED));
}
} else {
stop();
}
}
public void stop() {
try {
Log.i(TAG, "Stopping Bluetooth discovery thread");
context.unregisterReceiver(btReceiver);
btAdapter.cancelDiscovery();
/*
* do not have to switch off the bluetooth anymore because we ask the user
* explicitly
*/
// if (!btActiveFromTheStart) { btAdapter.disable(); }
} catch (Exception e) {
Log.e(TAG, "Error in stopping BT discovery:" + e.getMessage());
}
}
}
private static final String TAG = "Bluetooth DeviceProximity";
private static final int REQ_CODE = 333;
private final BluetoothReceiver btReceiver = new BluetoothReceiver();
private final ScanAlarmReceiver alarmReceiver = new ScanAlarmReceiver();
private BluetoothAdapter btAdapter;
private final Context context;
private boolean scanEnabled = false;
private final Handler scanHandler = new Handler(Looper.getMainLooper());
private int scanInterval = 0;
private ScanThread scanThread = null;
public BluetoothDeviceProximity(Context context) {
this.context = context;
}
public int getScanInterval() {
return scanInterval;
}
private void onDeviceFound(Intent intent) {
BluetoothDevice remoteDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Short rssi = intent.getShortExtra(BluetoothDevice.EXTRA_RSSI, (short) 0);
HashMap<BluetoothDevice, Short> mapValue = new HashMap<BluetoothDevice, Short>();
mapValue.put(remoteDevice, rssi);
scanThread.deviceArray.add(mapValue);
}
private void onScanFinished() {
try {
for (Map<BluetoothDevice, Short> value : scanThread.deviceArray) {
BluetoothDevice btd = value.entrySet().iterator().next().getKey();
JSONObject deviceJson = new JSONObject();
deviceJson.put("address", btd.getAddress());
deviceJson.put("name", btd.getName());
deviceJson.put("rssi", value.entrySet().iterator().next().getValue());
this.notifySubscribers();
SensorDataPoint dataPoint = new SensorDataPoint(deviceJson); | dataPoint.sensorName = SensorNames.BLUETOOTH_DISCOVERY; | 1 |
utds3lab/SMVHunter | dynamic/src/com/android/hierarchyviewerlib/ui/TreeView.java | [
"public abstract class HierarchyViewerDirector implements IDeviceChangeListener,\n IWindowChangeListener {\n\t\n\tstatic Logger logger = Logger.getLogger(HierarchyViewerDirector.class);\n\tstatic boolean logDebug = logger.isDebugEnabled();\n\t\n protected static HierarchyViewerDirector sDirector;\n\n p... | import java.text.DecimalFormat;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseListener;
import org.eclipse.swt.events.MouseMoveListener;
import org.eclipse.swt.events.MouseWheelListener;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.FontData;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Path;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.graphics.Transform;
import org.eclipse.swt.widgets.Canvas;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import com.android.ddmuilib.ImageLoader;
import com.android.hierarchyviewerlib.HierarchyViewerDirector;
import com.android.hierarchyviewerlib.device.ViewNode.ProfileRating;
import com.android.hierarchyviewerlib.models.TreeViewModel;
import com.android.hierarchyviewerlib.models.TreeViewModel.ITreeChangeListener;
import com.android.hierarchyviewerlib.ui.util.DrawableViewNode;
import com.android.hierarchyviewerlib.ui.util.DrawableViewNode.Point;
import com.android.hierarchyviewerlib.ui.util.DrawableViewNode.Rectangle; |
private Listener mResizeListener = new Listener() {
@Override
public void handleEvent(Event e) {
synchronized (TreeView.this) {
if (mTree != null && mViewport != null) {
// Keep the center in the same place.
Point viewCenter =
new Point(mViewport.x + mViewport.width / 2, mViewport.y + mViewport.height
/ 2);
mViewport.width = getBounds().width / mZoom;
mViewport.height = getBounds().height / mZoom;
mViewport.x = viewCenter.x - mViewport.width / 2;
mViewport.y = viewCenter.y - mViewport.height / 2;
}
}
if (mViewport != null) {
mModel.setViewport(mViewport);
}
}
};
private KeyListener mKeyListener = new KeyListener() {
@Override
public void keyPressed(KeyEvent e) {
boolean selectionChanged = false;
DrawableViewNode clickedNode = null;
synchronized (TreeView.this) {
if (mTree != null && mViewport != null && mSelectedNode != null) {
switch (e.keyCode) {
case SWT.ARROW_LEFT:
if (mSelectedNode.parent != null) {
mSelectedNode = mSelectedNode.parent;
selectionChanged = true;
}
break;
case SWT.ARROW_UP:
// On up and down, it is cool to go up and down only
// the leaf nodes.
// It goes well with the layout viewer
DrawableViewNode currentNode = mSelectedNode;
while (currentNode.parent != null && currentNode.viewNode.index == 0) {
currentNode = currentNode.parent;
}
if (currentNode.parent != null) {
selectionChanged = true;
currentNode =
currentNode.parent.children
.get(currentNode.viewNode.index - 1);
while (currentNode.children.size() != 0) {
currentNode =
currentNode.children
.get(currentNode.children.size() - 1);
}
}
if (selectionChanged) {
mSelectedNode = currentNode;
}
break;
case SWT.ARROW_DOWN:
currentNode = mSelectedNode;
while (currentNode.parent != null
&& currentNode.viewNode.index + 1 == currentNode.parent.children
.size()) {
currentNode = currentNode.parent;
}
if (currentNode.parent != null) {
selectionChanged = true;
currentNode =
currentNode.parent.children
.get(currentNode.viewNode.index + 1);
while (currentNode.children.size() != 0) {
currentNode = currentNode.children.get(0);
}
}
if (selectionChanged) {
mSelectedNode = currentNode;
}
break;
case SWT.ARROW_RIGHT:
DrawableViewNode rightNode = null;
double mostOverlap = 0;
final int N = mSelectedNode.children.size();
// We consider all the children and pick the one
// who's tree overlaps the most.
for (int i = 0; i < N; i++) {
DrawableViewNode child = mSelectedNode.children.get(i);
DrawableViewNode topMostChild = child;
while (topMostChild.children.size() != 0) {
topMostChild = topMostChild.children.get(0);
}
double overlap =
Math.min(DrawableViewNode.NODE_HEIGHT, Math.min(
mSelectedNode.top + DrawableViewNode.NODE_HEIGHT
- topMostChild.top, topMostChild.top
+ child.treeHeight - mSelectedNode.top));
if (overlap > mostOverlap) {
mostOverlap = overlap;
rightNode = child;
}
}
if (rightNode != null) {
mSelectedNode = rightNode;
selectionChanged = true;
}
break;
case SWT.CR:
clickedNode = mSelectedNode;
break;
}
}
}
if (selectionChanged) {
mModel.setSelection(mSelectedNode);
}
if (clickedNode != null) { | HierarchyViewerDirector.getDirector().showCapture(getShell(), clickedNode.viewNode); | 0 |
Catbag/redux-android-sample | app/src/testShared/shared/TestHelper.java | [
"public class DataManager {\n private static Float sRiffsyNext = null;\n private final RiffsyRoutes mRiffsyRoutes;\n\n private Database mDatabase;\n private boolean mIsSavingAppState = false;\n private SaveAppStateRunnable mNextSaveAppStateRunnable;\n\n public DataManager(Context context) {\n ... | import android.content.Context;
import android.util.Log;
import com.umaplay.fluxxan.Action;
import com.umaplay.fluxxan.Fluxxan;
import com.umaplay.fluxxan.StateListener;
import org.mockito.ArgumentCaptor;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Random;
import java.util.UUID;
import br.com.catbag.gifreduxsample.asyncs.data.DataManager;
import br.com.catbag.gifreduxsample.asyncs.data.net.downloader.FileDownloader;
import br.com.catbag.gifreduxsample.middlewares.PersistenceMiddleware;
import br.com.catbag.gifreduxsample.middlewares.RestMiddleware;
import br.com.catbag.gifreduxsample.models.AppState;
import br.com.catbag.gifreduxsample.models.Gif;
import br.com.catbag.gifreduxsample.models.ImmutableAppState;
import br.com.catbag.gifreduxsample.models.ImmutableGif;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock; | }
}
public Fluxxan<AppState> getFluxxan() {
return mFluxxan;
}
public void sleep(long ms) {
try {
Thread.sleep(ms);
} catch (InterruptedException e) {
Log.e(getClass().getSimpleName(), "", e);
}
}
// Helpers methods to dry up unit tests
public void dispatchAction(Action action) {
getFluxxan().getDispatcher().dispatch(action);
// Since the dispatcher send actions in background we need wait the response arrives
while (!isStateChanged() || getFluxxan().getDispatcher().isDispatching()) {
sleep(5);
}
setStateChanged(false);
}
public void dispatchFakeAppState(AppState state) {
dispatchAction(new Action(FakeReducer.FAKE_REDUCE_ACTION, state));
}
public Gif firstAppStateGif() {
Map<String, Gif> gifs = getFluxxan().getState().getGifs();
if (gifs.size() <= 0) return null;
return gifs.values().iterator().next();
}
public static AppState buildAppState(Gif gif) {
return ImmutableAppState.builder().putGifs(gif.getUuid(), gif).build();
}
public static AppState buildAppState(Map<String, Gif> gifs) {
return ImmutableAppState.builder().gifs(gifs).build();
}
public static Gif buildGif() {
return gifBuilderWithDefault().build();
}
public static Gif buildGif(Gif.Status status) {
return buildGif(status, DEFAULT_UUID);
}
public static Gif buildGif(Gif.Status status, String uuid) {
return gifBuilderWithDefault()
.uuid(uuid)
.status(status)
.build();
}
public static ImmutableGif.Builder gifBuilderWithEmpty() {
return ImmutableGif.builder()
.uuid(UUID.randomUUID().toString())
.title("")
.url("");
}
public static ImmutableGif.Builder gifBuilderWithDefault() {
return ImmutableGif.builder()
.uuid(DEFAULT_UUID)
.title("Gif")
.url("https://media.giphy.com/media/l0HlE56oAxpngfnWM/giphy.gif")
.status(Gif.Status.NOT_DOWNLOADED);
}
public static Map<String, Gif> buildFiveGifs() {
String[] titles = {"Gif 1", "Gif 2", "Gif 3", "Gif 4", "Gif 5" };
String[] urls = {
"https://media.giphy.com/media/l0HlE56oAxpngfnWM/giphy.gif",
"http://inspirandoideias.com.br/blog/wp-content/uploads/2015/03/"
+ "b3368a682fc5ff891e41baad2731f4b6.gif",
"https://media.giphy.com/media/9fbYYzdf6BbQA/giphy.gif",
"https://media.giphy.com/media/l2YWl1oQlNvthGWrK/giphy.gif",
"https://media.giphy.com/media/3oriNQHSU0bVcFW5sA/giphy.gif"
};
Map<String, Gif> gifs = new LinkedHashMap<>();
for (int i = 0; i < titles.length; i++) {
Gif gif = ImmutableGif.builder().uuid(UUID.randomUUID().toString())
.title(titles[i])
.url(urls[i])
.build();
gifs.put(gif.getUuid(), gif);
}
return gifs;
}
public DataManager mockDataManagerFetch(Map<String, Gif> expectedGifs,
boolean expectedHasMore) {
DataManager dataManager = mock(DataManager.class);
ArgumentCaptor<DataManager.GifListLoadListener> listenerCaptor
= ArgumentCaptor.forClass(DataManager.GifListLoadListener.class);
doAnswer((invocationOnMock) -> {
new Thread(() -> {
// The fluxxan don't let we dispatch when it's dispatching
while (mFluxxan.getDispatcher().isDispatching()) {
try {
Thread.sleep(5);
} catch (InterruptedException e) {
Log.e("Test", e.getMessage(), e);
}
}
listenerCaptor.getValue().onLoaded(expectedGifs, expectedHasMore);
}).start();
return null;
}).when(dataManager).fetchGifs(listenerCaptor.capture());
return dataManager;
}
private void clearRestMiddleware() { | getFluxxan().getDispatcher().unregisterMiddleware(RestMiddleware.class); | 3 |
nidi3/raml-tester-proxy | raml-tester-client/src/test/java/guru/nidi/ramlproxy/MockTest.java | [
"public abstract class RamlProxyServer implements AutoCloseable {\n private static final Logger log = LoggerFactory.getLogger(RamlProxyServer.class);\n\n protected final ServerOptions options;\n private final ReportSaver saver;\n private final Thread shutdownHook;\n\n public RamlProxyServer(ServerOpt... | import static org.hamcrest.CoreMatchers.containsString;
import static org.junit.Assert.*;
import guru.nidi.ramlproxy.core.RamlProxyServer;
import guru.nidi.ramlproxy.core.ServerOptions;
import guru.nidi.ramlproxy.report.ReportSaver;
import guru.nidi.ramlproxy.report.ReportSaver.ReportInfo;
import guru.nidi.ramltester.core.RamlReport;
import guru.nidi.ramltester.core.RamlViolationMessage;
import org.apache.http.HttpResponse;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.util.Iterator;
import java.util.List;
import static guru.nidi.ramlproxy.core.CommandSender.content; | /*
* Copyright © 2014 Stefan Niederhauser (nidin@gmx.ch)
*
* 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 guru.nidi.ramlproxy;
public class MockTest {
private HttpSender sender = new HttpSender(8090);
private RamlProxyServer proxy;
@Before
public void init() throws Exception {
final ServerOptions options = new ServerOptions(sender.getPort(), Ramls.MOCK_DIR, Ramls.SIMPLE, "http://nidi.guru/raml", null, null, true);
proxy = RamlProxy.startServerSync(options, new ReportSaver());
}
@After
public void stop() throws Exception {
proxy.close();
}
@Test
public void simpleOk() throws Exception {
final HttpResponse res = sender.get("v1/data");
Thread.sleep(20);
assertEquals("42", content(res));
assertEquals(202, res.getStatusLine().getStatusCode());
assertEquals("get!", res.getFirstHeader("X-meta").getValue());
final RamlReport report = assertOneReport();
final Iterator<RamlViolationMessage> iter = report.getResponseViolations().iterator();
assertEquals("Response(202) is not defined on action(GET /data)", iter.next().getMessage());
assertTrue(report.getRequestViolations().isEmpty());
}
@Test
public void multipleFiles() throws Exception {
final HttpResponse res = sender.get("v1/multi");
Thread.sleep(20);
assertEquals(404, res.getStatusLine().getStatusCode());
final String content = content(res);
assertThat(content, containsString("No or multiple file 'multi' found in directory"));
assertThat(content, containsString("src/test/resources/guru/nidi/ramlproxy/v1"));
final RamlReport report = assertOneReport();
final Iterator<RamlViolationMessage> iter = report.getRequestViolations().iterator();
assertEquals("Resource '/multi' is not defined", iter.next().getMessage());
assertTrue(report.getResponseViolations().isEmpty());
}
@Test
public void noFile() throws Exception {
final HttpResponse res = sender.get("v1/notExisting");
Thread.sleep(20);
assertEquals(404, res.getStatusLine().getStatusCode());
final String content = content(res);
assertThat(content, containsString("No or multiple file 'notExisting' found in directory"));
assertThat(content, containsString("src/test/resources/guru/nidi/ramlproxy/v1"));
final RamlReport report = assertOneReport();
final Iterator<RamlViolationMessage> iter = report.getRequestViolations().iterator();
assertEquals("Resource '/notExisting' is not defined", iter.next().getMessage());
assertTrue(report.getResponseViolations().isEmpty());
}
@Test
public void withMethod() throws Exception {
final HttpResponse res = sender.post("v1/data", null);
Thread.sleep(20);
assertEquals("666", content(res));
assertEquals(201, res.getStatusLine().getStatusCode());
assertEquals("yes!", res.getFirstHeader("X-meta").getValue());
assertEquals("5", res.getLastHeader("X-meta").getValue());
final RamlReport report = assertOneReport();
assertTrue(report.getRequestViolations().isEmpty());
assertTrue(report.getResponseViolations().isEmpty());
}
@Test
public void nested() throws Exception {
final HttpResponse res = sender.post("v1/super/sub", null);
Thread.sleep(20);
assertEquals("163", content(res));
assertEquals("true", res.getFirstHeader("X-meta").getValue());
final RamlReport report = assertOneReport();
final Iterator<RamlViolationMessage> iter = report.getRequestViolations().iterator();
assertEquals("Action POST is not defined on resource(/super/sub)", iter.next().getMessage());
assertTrue(report.getResponseViolations().isEmpty());
}
private RamlReport assertOneReport() { | final List<ReportInfo> reports = proxy.getSaver().getReports("simple"); | 3 |
idega/is.idega.idegaweb.egov.course | src/java/is/idega/idegaweb/egov/course/presentation/CourseList.java | [
"public class CourseConstants {\n\n\tpublic static final String CASE_CODE_KEY = \"COURSEA\";\n\n\tpublic static final String IW_BUNDLE_IDENTIFIER = \"is.idega.idegaweb.egov.course\";\n\n\tpublic static final String ADMINISTRATOR_ROLE_KEY = \"afterSchoolCareAdministrator\";\n\tpublic static final String SUPER_ADMINI... | import is.idega.idegaweb.egov.course.CourseConstants;
import is.idega.idegaweb.egov.course.business.CourseComparator;
import is.idega.idegaweb.egov.course.business.CourseWriter;
import is.idega.idegaweb.egov.course.data.Course;
import is.idega.idegaweb.egov.course.data.CourseCategory;
import is.idega.idegaweb.egov.course.data.CoursePrice;
import is.idega.idegaweb.egov.course.data.CourseType;
import java.rmi.RemoteException;
import java.sql.Date;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import com.idega.block.school.data.School;
import com.idega.block.school.data.SchoolType;
import com.idega.business.IBORuntimeException;
import com.idega.presentation.IWContext;
import com.idega.presentation.Layer;
import com.idega.presentation.Table2;
import com.idega.presentation.TableCell2;
import com.idega.presentation.TableRow;
import com.idega.presentation.TableRowGroup;
import com.idega.presentation.text.DownloadLink;
import com.idega.presentation.text.Link;
import com.idega.presentation.text.Text;
import com.idega.presentation.ui.DropdownMenu;
import com.idega.presentation.ui.Form;
import com.idega.presentation.ui.GenericButton;
import com.idega.presentation.ui.HiddenInput;
import com.idega.presentation.ui.IWDatePicker;
import com.idega.presentation.ui.Label;
import com.idega.presentation.ui.SubmitButton;
import com.idega.presentation.ui.handlers.IWDatePickerHandler;
import com.idega.util.IWTimestamp;
import com.idega.util.PresentationUtil; | else if (type != null) {
Collection courseTypes = getBusiness().getCourseTypes(new Integer(type.getPrimaryKey().toString()), true);
courseType.addMenuElements(courseTypes);
}
boolean useBirthYears = iwc.getApplicationSettings().getBoolean(CourseConstants.PROPERTY_USE_BIRTHYEARS, true);
int inceptionYear = Integer.parseInt(iwc.getApplicationSettings().getProperty(CourseConstants.PROPERTY_INCEPTION_YEAR, "-1"));
DropdownMenu sorting = new DropdownMenu(PARAMETER_SORTING);
sorting.addMenuElement(CourseComparator.ID_SORT, getResourceBundle().getLocalizedString("sort.id", "ID"));
sorting.addMenuElement(CourseComparator.REVERSE_ID_SORT, getResourceBundle().getLocalizedString("sort.reverse_id", "reverse ID"));
sorting.addMenuElement(CourseComparator.NAME_SORT, getResourceBundle().getLocalizedString("sort.name", "Name (A-Z)"));
sorting.addMenuElement(CourseComparator.REVERSE_NAME_SORT, getResourceBundle().getLocalizedString("sort.reverse_name", "Name (Z-A)"));
sorting.addMenuElement(CourseComparator.TYPE_SORT, getResourceBundle().getLocalizedString("sort.type", "Type"));
sorting.addMenuElement(CourseComparator.DATE_SORT, getResourceBundle().getLocalizedString("sort.date", "Date"));
if (useBirthYears) {
sorting.addMenuElement(CourseComparator.YEAR_SORT, getResourceBundle().getLocalizedString("sort.year", "Year"));
}
sorting.addMenuElement(CourseComparator.PLACES_SORT, getResourceBundle().getLocalizedString("sort.places", "Places"));
sorting.addMenuElement(CourseComparator.FREE_PLACES_SORT, getResourceBundle().getLocalizedString("sort.free_places", "Free places"));
sorting.keepStatusOnAction(true);
IWTimestamp stamp = new IWTimestamp();
stamp.addYears(1);
IWDatePicker fromDate = new IWDatePicker(PARAMETER_FROM_DATE);
fromDate.setShowYearChange(true);
fromDate.setStyleClass("dateInput");
fromDate.keepStatusOnAction(true);
IWDatePicker toDate = new IWDatePicker(PARAMETER_TO_DATE);
toDate.setShowYearChange(true);
toDate.setStyleClass("dateInput");
toDate.keepStatusOnAction(true);
toDate.setDate(stamp.getDate());
if (inceptionYear > 0) {
IWTimestamp fromStamp = new IWTimestamp(1, 1, inceptionYear);
fromDate.setDate(fromStamp.getDate());
}
else {
stamp.addMonths(-1);
stamp.addYears(-1);
fromDate.setDate(stamp.getDate());
}
if (showTypes) {
Layer formItem = new Layer(Layer.DIV);
formItem.setStyleClass("formItem");
Label label = new Label(getResourceBundle().getLocalizedString("category", "Category"), schoolType);
formItem.add(label);
formItem.add(schoolType);
layer.add(formItem);
}
else if (type != null) {
layer.add(new HiddenInput(PARAMETER_SCHOOL_TYPE_PK, type.getPrimaryKey().toString()));
}
Layer formItem = new Layer(Layer.DIV);
formItem.setStyleClass("formItem");
Label label = new Label(getResourceBundle().getLocalizedString("type", "Type"), courseType);
formItem.add(label);
formItem.add(courseType);
layer.add(formItem);
formItem = new Layer(Layer.DIV);
formItem.setStyleClass("formItem");
label = new Label();
label.setLabel(getResourceBundle().getLocalizedString("from", "From"));
formItem.add(label);
formItem.add(fromDate);
layer.add(formItem);
formItem = new Layer(Layer.DIV);
formItem.setStyleClass("formItem");
label = new Label();
label.setLabel(getResourceBundle().getLocalizedString("to", "To"));
formItem.add(label);
formItem.add(toDate);
layer.add(formItem);
formItem = new Layer(Layer.DIV);
formItem.setStyleClass("formItem");
label = new Label(getResourceBundle().getLocalizedString("sorting", "Sorting"), sorting);
formItem.add(label);
formItem.add(sorting);
layer.add(formItem);
SubmitButton fetch = new SubmitButton(getResourceBundle().getLocalizedString("get", "Get"));
fetch.setStyleClass("indentedButton");
fetch.setStyleClass("button");
formItem = new Layer(Layer.DIV);
formItem.setStyleClass("formItem");
formItem.add(fetch);
layer.add(formItem);
Layer clearLayer = new Layer(Layer.DIV);
clearLayer.setStyleClass("Clear");
layer.add(clearLayer);
return layer;
}
public Layer getPrintouts(IWContext iwc) {
Layer layer = new Layer(Layer.DIV);
layer.setStyleClass("printIcons");
layer.add(getXLSLink(iwc));
return layer;
}
protected Link getXLSLink(IWContext iwc) {
DownloadLink link = new DownloadLink(getBundle().getImage("xls.gif"));
link.setStyleClass("xls");
link.setTarget(Link.TARGET_NEW_WINDOW);
link.maintainParameter(PARAMETER_SCHOOL_TYPE_PK, iwc);
link.maintainParameter(PARAMETER_COURSE_TYPE_PK, iwc);
link.maintainParameter(PARAMETER_FROM_DATE, iwc);
link.maintainParameter(PARAMETER_TO_DATE, iwc); | link.setMediaWriterClass(CourseWriter.class); | 2 |
gjhutchison/pixelhorrorjam2016 | core/src/com/kowaisugoi/game/player/Player.java | [
"public class PlacementRectangle extends Rectangle {\n public void draw(ShapeRenderer renderer) {\n renderer.setColor(0.9f, 0.9f, 0.9f, 0.5f);\n renderer.rect(x, y, width, height);\n }\n\n public String getCoordString() {\n float xS = x;\n float yS = y;\n float wS = width... | import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.InputProcessor;
import com.badlogic.gdx.graphics.Cursor;
import com.badlogic.gdx.graphics.Pixmap;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.utils.Disposable;
import com.kowaisugoi.game.graphics.PlacementRectangle;
import com.kowaisugoi.game.player.inventory.PlayerInventory;
import com.kowaisugoi.game.player.thought.ThoughtBox;
import com.kowaisugoi.game.rooms.Room;
import com.kowaisugoi.game.rooms.RoomId;
import com.kowaisugoi.game.rooms.RoomManager;
import com.kowaisugoi.game.screens.PlayGame;
import com.kowaisugoi.game.system.GlobalKeyHandler;
import static com.kowaisugoi.game.player.Player.InteractionMode.*; | package com.kowaisugoi.game.player;
public final class Player implements Disposable, InputProcessor {
private PlayGame _world;
private RoomId _currentRoom;
// TODO: could/should separate this from Player
private RoomManager _manager;
private PlayerInventory _inventory;
private static PlacementRectangle _placement = new PlacementRectangle();
private CursorType _cursorFlavor = CursorType.REGULAR;
private CursorType _currentCursorFlavor = null;
| private InteractionMode _interactionMode = InteractionMode.NORMAL; | 8 |
MX-Futhark/hook-any-text | src/main/java/hexcapture/HexOptions.java | [
"public abstract class Options {\n\n\t// used to format usage message\n\tprivate static final int INDENT_LENGTH = 4;\n\tprivate static final int DESC_LINE_LENGTH = 80 - INDENT_LENGTH;\n\n\tpublic static final String SERIALIAZATION_FILENAME = \"config.data\";\n\n\tprotected interface SerializingFallback<T> {\n\t\tCh... | import java.io.Serializable;
import main.options.Options;
import main.options.ValueClass;
import main.options.annotations.CommandLineArgument;
import main.options.domain.Bounds;
import main.options.domain.Values;
import main.options.parser.ArgumentParser;
import main.options.parser.HexSelectionsParser; | package hexcapture;
/**
* Options for the script capturing the hexadecimal selection in Cheat Engine.
*
* @author Maxime PIA
*/
public class HexOptions extends Options implements Serializable {
/**
* Backward-compatible with 0.7.0
*/
private static final long serialVersionUID = 00000000007000000L;
public static final double DEFAULT_STABILIZATION_THRESHOLD = 0.005;
public static final int DEFAULT_REFRESH_DELAY = 50;
public static final int DEFAULT_HISTORY_SIZE = 6;
public static final HexUpdateStrategies DEFAULT_UPDATE_STRATEGY =
HexUpdateStrategies.COMBINED;
public static final HexSelections DEFAULT_HEX_SELECTIONS =
new HexSelections();
@CommandLineArgument(
command = "stabilization",
description = "Determines at which proportion of the size of the "
+ "selection the number of differences between the current content "
+ "of the selection and that of the history is deemed low enough "
+ "to convert the selection."
)
private Double stabilizationThreshold = DEFAULT_STABILIZATION_THRESHOLD;
public static final Bounds<Double> STABILIZATION_THRESHOLD_DOMAIN =
new Bounds<Double>(0d, 1d);
@CommandLineArgument(
command = "refresh",
description = "The number of ms to wait before capturing the selection."
)
private Integer refreshDelay = DEFAULT_REFRESH_DELAY;
public static final Bounds<Integer> REFRESH_DELAY_DOMAIN =
new Bounds<>(10, 400);
@CommandLineArgument(
command = "history",
description = "The length of the array containing the previous "
+ "selections."
)
private Integer historySize = DEFAULT_HISTORY_SIZE;
public static final Bounds<Integer> HISTORY_SIZE_DOMAIN =
new Bounds<>(1, 20);
@CommandLineArgument(
command = "strategy",
description = "The strategy to use to deem the selection worthy of "
+ "being converted."
)
private HexUpdateStrategies updateStrategy = DEFAULT_UPDATE_STRATEGY; | public static final Values<HexUpdateStrategies> UPDATE_STRATEGY_DOMAIN = | 3 |
researchgate/restler | restler-core/src/test/java/net/researchgate/restdsl/dao/ServiceDaoTest.java | [
"@Entity(value = \"entity\", noClassnameStored = true)\npublic class TestEntity {\n @Id\n Long id;\n String value;\n\n public TestEntity() {\n }\n\n public TestEntity(Long id, String value) {\n this.id = id;\n this.value = value;\n }\n\n public Long getId() {\n return id... | import com.google.common.collect.Lists;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.MongoClient;
import com.mongodb.ServerAddress;
import de.bwaldvogel.mongo.MongoServer;
import de.bwaldvogel.mongo.backend.memory.MemoryBackend;
import net.researchgate.restdsl.TestEntity;
import net.researchgate.restdsl.exceptions.RestDslException;
import net.researchgate.restdsl.metrics.NoOpStatsReporter;
import net.researchgate.restdsl.metrics.StatsReporter;
import net.researchgate.restdsl.queries.ServiceQuery;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import dev.morphia.Datastore;
import dev.morphia.Morphia;
import java.net.InetSocketAddress;
import static net.researchgate.restdsl.exceptions.RestDslException.Type.QUERY_ERROR;
import static org.junit.Assert.fail; | package net.researchgate.restdsl.dao;
public class ServiceDaoTest {
// This merely allow us to spin up a a dao.
private Datastore fakedDatastore;
private MongoServer server;
private MongoClient client;
@Before
public void setUp() {
server = new MongoServer(new MemoryBackend());
// bind on a random local port
InetSocketAddress serverAddress = server.bind();
client = new MongoClient(new ServerAddress(serverAddress));
fakedDatastore = new Morphia().createDatastore(client, "testDatabase");
// insert and remove an item in order to create indexes
final DBCollection collection = fakedDatastore.getCollection(TestEntity.class);
final Object id = collection.insert(new BasicDBObject()).getUpsertedId();
collection.remove(new BasicDBObject("_id", id));
}
@After
public void tearDown() throws Exception {
client.close();
server.shutdown();
}
@Test
public void testAllowGroupBy_doNotProvideAllowGroup_allow() {
final TestServiceDao dao = new TestServiceDao(fakedDatastore, TestEntity.class);
Assert.assertTrue(dao.allowGroupBy);
final ServiceQuery<Long> q = ServiceQuery.<Long>builder()
.withCriteria("id", Lists.newArrayList(1L, 2L, 3L))
.groupBy("id")
.build();
dao.get(q);
}
@Test
public void testAllowGroupBy_explicitlyDisallowGroupBy_doNotAllowQueryWithGroupBy() {
final TestServiceDao dao = new TestServiceDao(fakedDatastore, TestEntity.class, NoOpStatsReporter.INSTANCE, false);
Assert.assertFalse(dao.allowGroupBy);
final ServiceQuery<Long> q = ServiceQuery.<Long>builder()
.withCriteria("id", Lists.newArrayList(1L, 2L, 3L))
.groupBy("id")
.build();
// get with group by -> fail
try {
dao.get(q);
fail("Group by should not be allowed!, but it was");
} catch (RestDslException e) {
Assert.assertEquals(QUERY_ERROR, e.getType());
}
// get without groupBy -> successful
dao.get(ServiceQuery.byId(1L));
// explicitly allow group by -> successful
dao.setAllowGroupBy();
Assert.assertTrue(dao.allowGroupBy);
dao.get(q);
}
static class TestServiceDao extends MongoServiceDao<TestEntity, Long> {
public TestServiceDao(Datastore datastore, Class<TestEntity> entityClazz) {
super(datastore, entityClazz);
}
| public TestServiceDao(Datastore datastore, Class<TestEntity> entityClazz, StatsReporter statsReporter, boolean allowGroupBy) { | 3 |
alberto234/schedule-alarm-manager | android/ScheduleAlarmManager/ScheduleAlarmManager/src/main/java/com/scalior/schedulealarmmanager/SAManager.java | [
"public class SAMSQLiteHelper extends SQLiteOpenHelper {\n\n // Singleton\n private static SAMSQLiteHelper m_instance;\n\n public static SAMSQLiteHelper getInstance(Context context) {\n if (m_instance == null) {\n m_instance = new SAMSQLiteHelper(context);\n }\n\n return m_i... | import com.scalior.schedulealarmmanager.model.Event;
import com.scalior.schedulealarmmanager.model.Schedule;
import com.scalior.schedulealarmmanager.model.ScheduleGroup;
import com.scalior.schedulealarmmanager.modelholder.ScheduleAndEventsToAdd;
import com.scalior.schedulealarmmanager.modelholder.ScheduleEvent;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.util.SparseArray;
import com.scalior.schedulealarmmanager.database.SAMSQLiteHelper; | /* The MIT License (MIT)
*
* Copyright (c) 2014 Scalior, Inc
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
* Author: Eyong Nsoesie (eyongn@scalior.com)
* Date: 10/05/2014
*/
package com.scalior.schedulealarmmanager;
//import android.content.pm.PackageInfo;
//import android.content.pm.PackageManager.NameNotFoundException;
/**
* This class serves as an interface to manage schedule alarms.
*
*/
public class SAManager {
public static final int REPEAT_TYPE_HOURLY = 1;
public static final int REPEAT_TYPE_DAILY = 2;
public static final int REPEAT_TYPE_WEEKLY = 3;
public static final int REPEAT_TYPE_MONTHLY = 4;
public static final int REPEAT_TYPE_YEARLY = 5;
public static final int REPEAT_TYPE_NONE = 6;
public static final String STATE_ON = "ON";
public static final String STATE_OFF = "OFF";
private static SAManager m_instance;
private Context m_context;
private boolean m_initialized;
private SAMSQLiteHelper m_dbHelper;
private AlarmProcessingUtil m_alarmProcessor;
private String m_versionName;
/**
* Description:
* Get the singleton instance of the Schedule Alarm Manager
* If it has already been constructed, the passed in parameters have no effect
* @param p_context: The application context
* @return The singleton instance
*/
public static SAManager getInstance(Context p_context) {
if (m_instance == null ) {
m_instance = new SAManager(p_context);
}
return m_instance;
}
private SAManager(Context p_context) {
m_context = p_context;
m_dbHelper = SAMSQLiteHelper.getInstance(m_context);
m_alarmProcessor = AlarmProcessingUtil.getInstance(m_context);
m_initialized = false;
}
/**
* Description:
* Initialize the Schedule Alarm Manager
* @return boolean - true if successful, false other wise
*/
public boolean init() {
m_alarmProcessor.updateScheduleStates(null);
m_initialized = true;
return true;
}
/**
* Callback accessor
*/
public SAMCallback getCallback() {
return m_alarmProcessor.getSamCallback();
}
/**
* Description:
* This method sets the callback.
*
* @param callback - The callback instance. Once set can't be changed
* @param replace - If true, a current callback will be replaced with this one
* If false and a callback is already set, the new callback will
* be ignored.
*/
public void setCallback(SAMCallback callback, boolean replace) {
m_alarmProcessor.setSamCallback(callback, replace);
}
/**
* Description:
* Adds a schedule
* @param startTime - When the schedule starts. It can't be more than 24 hours in the past.
* @param duration - The duration of the schedule in minutes
* @param repeatType - One of the repeat type constants
* @param tag - A user specific tag identifying the schedule. This will be passed back to the
* user when the schedule's alarm is triggered
* @param groupTag - A user specific tag identifying the group that this schedule belongs to.
* This can be null.
* @return long - the added schedule's id if successful, -1 otherwise
* Do not count on this id to persist application restarts. Use the tag
* to identify schedules across restarts.
*/
public long addSchedule(Calendar startTime, int duration, int repeatType, String tag, String groupTag)
throws IllegalArgumentException, IllegalStateException {
if (!m_initialized) {
throw new IllegalStateException("SAManager not initialized");
}
Calendar currTime = Calendar.getInstance();
// Check for validity of parameters
if (duration <= 0 ||
((currTime.getTimeInMillis() - startTime.getTimeInMillis())
> AlarmProcessingUtil.DAY_MS) || // Start time shouldn't be more than 24 hours in the past
!isRepeatTypeValid(repeatType) ||
tag == null || tag.isEmpty()) {
throw new IllegalArgumentException();
}
| ScheduleGroup group = null; | 3 |
openstack/sahara-extra | hadoop-swiftfs/src/test/java/org/apache/hadoop/fs/swift/TestSwiftFileSystemBasicOps.java | [
"public class SwiftNativeFileSystem extends FileSystem {\n\n /** filesystem prefix: {@value} */\n public static final String SWIFT = \"swift\";\n private static final Log LOG =\n LogFactory.getLog(SwiftNativeFileSystem.class);\n\n /**\n * path to user work directory for storing temporary files\n */... | import static org.apache.hadoop.fs.swift.util.SwiftTestUtils.assertFileHasLength;
import static org.apache.hadoop.fs.swift.util.SwiftTestUtils.assertIsDirectory;
import static org.apache.hadoop.fs.swift.util.SwiftTestUtils.readBytesToString;
import static org.apache.hadoop.fs.swift.util.SwiftTestUtils.writeTextFile;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.swift.exceptions.SwiftBadRequestException;
import org.apache.hadoop.fs.swift.exceptions.SwiftNotDirectoryException;
import org.apache.hadoop.fs.swift.snative.SwiftNativeFileSystem;
import org.apache.hadoop.fs.swift.util.SwiftTestUtils;
import org.junit.Test;
import java.io.FileNotFoundException;
import java.io.IOException; | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.fs.swift;
/**
* Test basic filesystem operations.
* Many of these are similar to those in {@link TestSwiftFileSystemContract}
* -this is a JUnit4 test suite used to initially test the Swift
* component. Once written, there's no reason not to retain these tests.
*/
public class TestSwiftFileSystemBasicOps extends SwiftFileSystemBaseTest {
private static final Log LOG =
LogFactory.getLog(TestSwiftFileSystemBasicOps.class);
@Test(timeout = SWIFT_TEST_TIMEOUT)
public void testLsRoot() throws Throwable {
Path path = new Path("/");
FileStatus[] statuses = fs.listStatus(path);
}
@Test(timeout = SWIFT_TEST_TIMEOUT)
public void testMkDir() throws Throwable {
Path path = new Path("/test/MkDir");
fs.mkdirs(path);
//success then -so try a recursive operation
fs.delete(path, true);
}
@Test(timeout = SWIFT_TEST_TIMEOUT)
public void testDeleteNonexistentFile() throws Throwable {
Path path = new Path("/test/DeleteNonexistentFile");
assertFalse("delete returned true", fs.delete(path, false));
}
@Test(timeout = SWIFT_TEST_TIMEOUT)
public void testPutFile() throws Throwable {
Path path = new Path("/test/PutFile");
Exception caught = null;
writeTextFile(fs, path, "Testing a put to a file", false);
assertDeleted(path, false);
}
@Test(timeout = SWIFT_TEST_TIMEOUT)
public void testPutGetFile() throws Throwable {
Path path = new Path("/test/PutGetFile");
try {
String text = "Testing a put and get to a file "
+ System.currentTimeMillis();
writeTextFile(fs, path, text, false);
String result = readBytesToString(fs, path, text.length());
assertEquals(text, result);
} finally {
delete(fs, path);
}
}
@Test(timeout = SWIFT_TEST_TIMEOUT)
public void testPutDeleteFileInSubdir() throws Throwable {
Path path =
new Path("/test/PutDeleteFileInSubdir/testPutDeleteFileInSubdir");
String text = "Testing a put and get to a file in a subdir "
+ System.currentTimeMillis();
writeTextFile(fs, path, text, false);
assertDeleted(path, false);
//now delete the parent that should have no children
assertDeleted(new Path("/test/PutDeleteFileInSubdir"), false);
}
@Test(timeout = SWIFT_TEST_TIMEOUT)
public void testRecursiveDelete() throws Throwable {
Path childpath =
new Path("/test/testRecursiveDelete");
String text = "Testing a put and get to a file in a subdir "
+ System.currentTimeMillis();
writeTextFile(fs, childpath, text, false);
//now delete the parent that should have no children
assertDeleted(new Path("/test"), true);
assertFalse("child entry still present " + childpath, fs.exists(childpath));
}
| private void delete(SwiftNativeFileSystem fs, Path path) { | 0 |
eladnava/redalert-android | app/src/main/java/com/red/alert/activities/AlertView.java | [
"public class AlertViewParameters {\n public static final String ALERT_CITY = \"AlertZone\";\n public static final String ALERT_DATE_STRING = \"AlertDateString\";\n}",
"public class City {\n @JsonProperty(\"lat\")\n public double latitude;\n\n @JsonProperty(\"lng\")\n public double longitude;\n\... | import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import androidx.core.app.ActivityCompat;
import androidx.core.view.MenuItemCompat;
import androidx.appcompat.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.red.alert.R;
import com.red.alert.logic.communication.intents.AlertViewParameters;
import com.red.alert.model.metadata.City;
import com.red.alert.ui.localization.rtl.RTLSupport;
import com.red.alert.ui.localization.rtl.adapters.RTLMarkerInfoWindowAdapter;
import com.red.alert.ui.notifications.AppNotifications;
import com.red.alert.utils.localization.Localization;
import com.red.alert.utils.metadata.LocationData; | package com.red.alert.activities;
public class AlertView extends AppCompatActivity {
GoogleMap mMap;
String mAlertCity;
String mAlertDateString;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Initialize alert
unpackExtras();
// Initialize UI
initializeUI();
}
void unpackExtras() {
// Get alert area
mAlertCity = getIntent().getStringExtra(AlertViewParameters.ALERT_CITY);
// Get alert date string
mAlertDateString = getIntent().getStringExtra(AlertViewParameters.ALERT_DATE_STRING);
}
void mapLoadedListener() {
// Wait for map to load
mMap.setOnCameraChangeListener(new GoogleMap.OnCameraChangeListener() {
@Override
public void onCameraChange(CameraPosition arg0) {
// Prevent from being called again
mMap.setOnCameraChangeListener(null);
// Fix RTL bug with hebrew
mMap.setInfoWindowAdapter(new RTLMarkerInfoWindowAdapter(getLayoutInflater()));
// Show my location button
if (ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
mMap.setMyLocationEnabled(true);
}
// Wait for tiles to load
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
// Add map overlays
addOverlays();
}
}, 500);
}
});
}
void initializeMap() {
// Get map instance
if (mMap == null) {
// Stop execution
return;
}
// Wait for map to load
mapLoadedListener();
}
void addOverlays() {
// Get alert area | City city = LocationData.getCityByName(mAlertCity, this); | 1 |
gabormakrai/dijkstra-performance | DijkstraPerformance/src/dijkstra/performance/scenario/RandomPengyifanFibonacciPriorityQueueScenario.java | [
"public class NeighbourArrayGraphGenerator {\r\n\t\r\n\tpublic int[][] neighbours;\r\n\tpublic double[][] weights;\r\n\t\r\n\tpublic void generateRandomGraph(int size, double p, Random random) {\r\n\t\t\r\n\t\tHashSet<Integer>[] neighboursList = generateList(size);\r\n\r\n\t\t// create random spanning tree\r\n\t\tg... | import java.util.Random;
import dijkstra.graph.NeighbourArrayGraphGenerator;
import dijkstra.performance.PerformanceScenario;
import dijkstra.priority.PriorityQueueDijkstra;
import dijkstra.priority.impl.PengyifanDijkstraPriorityObject;
import dijkstra.priority.impl.PengyifanFibonacciPriorityQueue;
| package dijkstra.performance.scenario;
public class RandomPengyifanFibonacciPriorityQueueScenario implements PerformanceScenario {
NeighbourArrayGraphGenerator generator = new NeighbourArrayGraphGenerator();
int[] previous;
PengyifanDijkstraPriorityObject[] priorityObjectArray;
PengyifanFibonacciPriorityQueue priorityQueue;
Random random;
int size;
double p;
int previosArrayBuilds;
public RandomPengyifanFibonacciPriorityQueueScenario(int size, double p, int previousArrayBuilds, Random random) {
this.size = size;
this.p = p;
this.previosArrayBuilds = previousArrayBuilds;
this.random = random;
}
@Override
public void runShortestPath() {
for (int i = 0; i < previosArrayBuilds; ++i) {
int origin = random.nextInt(size);
| PriorityQueueDijkstra.createPreviousArray(generator.neighbours, generator.weights, origin, previous, priorityObjectArray, priorityQueue);
| 2 |
blacklocus/jres | jres-test/src/test/java/com/blacklocus/jres/request/mapping/JresPutMappingTest.java | [
"public class BaseJresTest {\n\n @BeforeClass\n public static void startLocalElasticSearch() {\n ElasticSearchTestInstance.triggerStaticInit();\n }\n\n /**\n * Configured to connect to a local ElasticSearch instance created specifically for unit testing\n */\n protected Jres jres = new... | import com.blacklocus.jres.BaseJresTest;
import com.blacklocus.jres.request.index.JresCreateIndex;
import com.blacklocus.jres.response.JresBooleanReply;
import com.blacklocus.jres.response.common.JresAcknowledgedReply;
import com.blacklocus.jres.response.common.JresErrorReplyException;
import org.junit.Assert;
import org.junit.Test; | /**
* Copyright 2015 BlackLocus
*
* 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.blacklocus.jres.request.mapping;
public class JresPutMappingTest extends BaseJresTest {
@Test
public void sad() {
String index = "JresPutMappingRequestTest_sad".toLowerCase();
String type = "test";
try {
jres.quest(new JresPutMapping(index, type, "{\"test\":{}}"));
Assert.fail("Shouldn't be able to put type mapping on non-existent index");
} catch (JresErrorReplyException e) {
// good
}
jres.quest(new JresCreateIndex(index));
try {
jres.quest(new JresPutMapping(index, type, null));
Assert.fail("Invalid data");
} catch (JresErrorReplyException e) {
// good
}
try {
jres.quest(new JresPutMapping(index, type, ""));
Assert.fail("Invalid data");
} catch (JresErrorReplyException e) {
// good
}
try {
jres.quest(new JresPutMapping(index, type, "{}"));
Assert.fail("Invalid data");
} catch (JresErrorReplyException e) {
// good
}
}
@Test
public void happy() {
String index = "JresPutMappingRequestTest_happy".toLowerCase();
String type = "test";
{
JresBooleanReply response = jres.bool(new JresTypeExists(index, type));
Assert.assertFalse(response.verity());
}
jres.quest(new JresCreateIndex(index));
{ | JresAcknowledgedReply response = jres.quest(new JresPutMapping(index, type, "{\"test\":{}}")); | 3 |
johanneslerch/FlowTwist | FlowTwist/test/flow/twist/test/util/AbstractPathTests.java | [
"public static UnitSelector anyUnit() {\n\treturn new UnitSelector() {\n\n\t\t@Override\n\t\tpublic boolean matches(SootMethod method, Unit unit) {\n\t\t\treturn true;\n\t\t}\n\n\t\t@Override\n\t\tpublic String toString() {\n\t\t\treturn \"any unit\";\n\t\t}\n\t};\n}",
"public static UnitSelector unitByLabel(fina... | import static flow.twist.test.util.selectors.UnitSelectorFactory.anyUnit;
import static flow.twist.test.util.selectors.UnitSelectorFactory.unitByLabel;
import static flow.twist.test.util.selectors.UnitSelectorFactory.unitInMethod;
import static flow.twist.test.util.selectors.UnitSelectorFactory.unitWithoutLabel;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestWatcher;
import org.junit.runner.Description;
import flow.twist.test.util.PathVerifier.PathSelector;
import flow.twist.util.MultipleAnalysisPlotter; | package flow.twist.test.util;
public abstract class AbstractPathTests extends AbstractTaintAnalysisTest {
protected PathVerifier pathVerifier;
@Rule
public TestWatcher watcher = new TestWatcher() {
@Override
public void failed(Throwable e, Description description) {
StringBuilder builder = new StringBuilder();
builder.append("tmp/");
builder.append(AbstractPathTests.this.getClass().getSimpleName());
builder.append("_");
builder.append(description.getMethodName());
builder.append("_path");
MultipleAnalysisPlotter plotter = new MultipleAnalysisPlotter();
plotter.plotAnalysisResults(pathVerifier.getPaths(), "red");
plotter.writeFile(builder.toString());
}
};
@Test
public void aliasing() {
runTest("java.lang.Aliasing");
pathVerifier.totalPaths(3);
pathVerifier.startsAt(unitInMethod("nameInput(", unitByLabel("@parameter0"))).endsAt(unitByLabel("return")).once();
pathVerifier.startsAt(unitInMethod("nameInput(", unitByLabel("@parameter2"))).endsAt(unitByLabel("return")).once();
pathVerifier.startsAt(unitInMethod("nameInput2(", unitByLabel("@parameter0"))).endsAt(unitByLabel("return")).once();
}
@Test
public void backwardsIntoThrow() {
runTest("java.lang.BackwardsIntoThrow");
pathVerifier.totalPaths(1);
pathVerifier.startsAt(unitInMethod("foo", unitByLabel("@parameter0"))).endsAt(unitInMethod("foo", unitByLabel("return"))).once();
}
@Test
@Ignore("does not work without target for forName with classloader argument")
public void beanInstantiator() {
runTest("java.lang.BeanInstantiator");
pathVerifier.totalPaths(3); | PathSelector path = pathVerifier.startsAt(unitInMethod("findClass", unitByLabel("@parameter0"))).endsAt( | 4 |
thirdy/durian | durian/src/main/java/qic/ui/SearchResultTable.java | [
"@SuppressWarnings(\"rawtypes\")\npublic class BeanPropertyTableModel<T> extends AbstractTableModel {\n\t\n\tprivate static final long serialVersionUID = 1L;\n\t\n\t/** class of the data in rows */\n\tprivate final Class beanClass;\n /** collection of table rows */\n private List<T> data = new ArrayList<T>();... | import static java.lang.String.format;
import static java.util.Arrays.asList;
import java.awt.Color;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.List;
import java.util.function.Consumer;
import javax.swing.ImageIcon;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.TableColumnModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.porty.swing.table.model.BeanPropertyTableModel;
import qic.SearchPageScraper.SearchResultItem;
import qic.ui.extra.ArtColumnRenderer;
import qic.ui.extra.MultiLineTableCellRenderer;
import qic.ui.extra.VerifierTask;
import qic.util.Config;
import qic.util.SwingUtil;
| /*
* Copyright (C) 2015 thirdy
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package qic.ui;
/**
* @author thirdy
*
*/
public class SearchResultTable extends JTable {
private static final long serialVersionUID = 1L;
private final Logger logger = LoggerFactory.getLogger(this.getClass().getName());
private BeanPropertyTableModel<SearchResultItem> model;
private VerifierTask autoVerifierTask;
public SearchResultTable() {
model = new BeanPropertyTableModel<>(SearchResultItem.class);
model.setOrderedProperties(
asList("art", "bo", "item", "seller", "reqs", "mods", "offense", "defense"));
this.setModel(model);
setupColumnWidths();
this.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent me) {
JTable table =(JTable) me.getSource();
Point p = me.getPoint();
int row = table.rowAtPoint(p);
if (row > -1) {
if (SwingUtilities.isLeftMouseButton(me)) {
SearchResultItem searchResultItem = model.getData().get(row);
SwingUtil.copyToClipboard(searchResultItem.wtb());
}
if (SwingUtilities.isRightMouseButton(me)) {
SearchResultItem searchResultItem = model.getData().get(row);
VerifierTask manualVerifierTask = new VerifierTask(asList(searchResultItem),
results -> updateData(row),
verified -> {},
ex -> { logger.error("Error while running manual verify", ex); });
manualVerifierTask.execute();
}
}
}
});
Color bgColor = Color.decode(Config.getPropety(Config.RESULT_TABLE_BG_COLOR, null));
Color guildColor = Color.decode(Config.getPropety(Config.GUILD_COLOR_HIGHLIGHT, "#f6b67f"));
Color corruptedColor = Color.decode(Config.getPropety(Config.CORRUPTED_COLOR_HIGHLIGHT, "#000000"));
Color autoHighlightColor = Color.decode(
Config.getPropety(Config.AUTOMATED_SEARCH_NOTIFY_NEWONLY_COLOR_HIGHLIGHT, "#ccff99"));
| this.setDefaultRenderer(List.class, new MultiLineTableCellRenderer(model, bgColor, guildColor, corruptedColor, autoHighlightColor));
| 3 |
realrolfje/anonimatron | src/main/java/com/rolfje/anonimatron/Anonimatron.java | [
"public class AnonymizerService {\n\tprivate static final Logger LOG = Logger.getLogger(AnonymizerService.class);\n\n\tprivate Map<String, Anonymizer> customAnonymizers = new HashMap<>();\n\tprivate Map<String, String> defaultTypeMapping = new HashMap<>();\n\n\tprivate SynonymCache synonymCache;\n\n\tprivate Set<St... | import com.rolfje.anonimatron.anonymizer.AnonymizerService;
import com.rolfje.anonimatron.anonymizer.Hasher;
import com.rolfje.anonimatron.anonymizer.SynonymCache;
import com.rolfje.anonimatron.commandline.CommandLine;
import com.rolfje.anonimatron.configuration.Configuration;
import com.rolfje.anonimatron.file.FileAnonymizerService;
import com.rolfje.anonimatron.jdbc.JdbcAnonymizerService;
import org.apache.commons.cli.UnrecognizedOptionException;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set; | package com.rolfje.anonimatron;
/**
* Start of a beautiful anonymized new world.
*
*/
public class Anonimatron {
public static String VERSION = "UNKNOWN";
static {
try {
InputStream resourceAsStream = Anonimatron.class.getResourceAsStream("version.txt");
InputStreamReader inputStreamReader = new InputStreamReader(resourceAsStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
VERSION = bufferedReader.readLine();
bufferedReader.close();
inputStreamReader.close();
resourceAsStream.close();
} catch (IOException e) {
throw new RuntimeException("Could not determine version. " + e.getMessage());
}
}
public static void main(String[] args) throws Exception {
try {
CommandLine commandLine = new CommandLine(args);
if (commandLine.getConfigfileName() != null) {
Configuration config = getConfiguration(commandLine);
anonymize(config, commandLine.getSynonymfileName());
} else if (commandLine.isConfigExample()) {
printDemoConfiguration();
} else {
CommandLine.printHelp();
}
} catch (UnrecognizedOptionException e) {
System.err.println(e.getMessage());
CommandLine.printHelp();
}
}
private static Configuration getConfiguration(CommandLine commandLine) throws Exception {
// Load configuration
Configuration config = Configuration.readFromFile(commandLine.getConfigfileName());
if (commandLine.getJdbcurl() != null) {
config.setJdbcurl(commandLine.getJdbcurl());
}
if (commandLine.getUserid() != null) {
config.setUserid(commandLine.getUserid());
}
if (commandLine.getPassword() != null) {
config.setPassword(commandLine.getPassword());
}
config.setDryrun(commandLine.isDryrun());
return config;
}
private static void anonymize(Configuration config, String synonymFile) throws Exception {
// Load Synonyms from disk if present. | SynonymCache synonymCache = getSynonymCache(synonymFile); | 2 |
cm-heclouds/JAVA-HTTP-SDK | javaSDK/src/main/java/cmcc/iot/onenet/javasdk/api/datapoints/GetDatapointsListApi.java | [
"public abstract class AbstractAPI<T> {\n public String key;\n public String url;\n public Method method;\n public ObjectMapper mapper = initObjectMapper();\n\n private ObjectMapper initObjectMapper() {\n ObjectMapper objectMapper = new ObjectMapper();\n //关闭字段不识别报错\n objectMappe... | import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import cmcc.iot.onenet.javasdk.api.AbstractAPI;
import cmcc.iot.onenet.javasdk.exception.OnenetApiException;
import cmcc.iot.onenet.javasdk.http.HttpGetMethod;
import cmcc.iot.onenet.javasdk.request.RequestInfo.Method;
import cmcc.iot.onenet.javasdk.response.BasicResponse;
import cmcc.iot.onenet.javasdk.response.datapoints.DatapointsList;
import cmcc.iot.onenet.javasdk.response.datastreams.DatastreamsResponse;
import cmcc.iot.onenet.javasdk.utils.Config; | package cmcc.iot.onenet.javasdk.api.datapoints;
public class GetDatapointsListApi extends AbstractAPI{
private HttpGetMethod HttpMethod;
private String datastreamIds;
private String start;
private String end;
private String devId;
private Integer duration;
private Integer limit;
private String cursor;
private Integer interval;
private String metd;
private Integer first;
private String sort;
private final Logger logger = LoggerFactory.getLogger(this.getClass());
/**
* 数据点查询
* @param datastreamIds:查询的数据流,多个数据流之间用逗号分隔(可选),String
* @param start:提取数据点的开始时间(可选),String
* @param end:提取数据点的结束时间(可选),String
* @param devId:设备ID,String
* @param duration:查询时间区间(可选,单位为秒),Integer
* start+duration:按时间顺序返回从start开始一段时间内的数据点
* end+duration:按时间倒序返回从end回溯一段时间内的数据点
* @param limit:限定本次请求最多返回的数据点数,0<n<=6000(可选,默认1440),Integer
* @param cursor:指定本次请求继续从cursor位置开始提取数据(可选),String
* @param interval:通过采样方式返回数据点,interval值指定采样的时间间隔(可选),Integer,参数已废弃
* @param metd:指定在返回数据点时,同时返回统计结果,可能的值为(可选),String
* @param first:返回结果中最值的时间点。1-最早时间,0-最近时间,默认为1(可选),Integer
* @param sort:值为DESC|ASC时间排序方式,DESC:倒序,ASC升序,默认升序,String
* @param key:masterkey 或者 设备apikey
*/
public GetDatapointsListApi(String datastreamIds, String start, String end, String devId, Integer duration,
Integer limit, String cursor, @Deprecated Integer interval, String metd, Integer first, String sort,String key) {
super();
this.datastreamIds = datastreamIds;
this.start = start;
this.end = end;
this.devId = devId;
this.duration = duration;
this.limit = limit;
this.cursor = cursor;
this.interval = interval;
this.metd = metd;
this.first = first;
this.sort = sort;
this.key=key; | this.method= Method.GET; | 3 |
LyashenkoGS/analytics4github | src/main/java/com/rhcloud/analytics4github/service/UniqueContributorsService.java | [
"public enum GitHubApiEndpoints {\n COMMITS, STARGAZERS\n}",
"public class Author {\n private final String name;\n private final String email;\n\n /**\n * @param name represent author name. Add an empty String of zero length, if not present\n * @param email represent author email. Add an empt... | import com.fasterxml.jackson.databind.JsonNode;
import com.rhcloud.analytics4github.config.GitHubApiEndpoints;
import com.rhcloud.analytics4github.domain.Author;
import com.rhcloud.analytics4github.dto.RequestFromFrontendDto;
import com.rhcloud.analytics4github.dto.ResponceForFrontendDto;
import com.rhcloud.analytics4github.exception.GitHubRESTApiException;
import com.rhcloud.analytics4github.util.GitHubApiIterator;
import com.rhcloud.analytics4github.util.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;
import java.io.IOException;
import java.net.URISyntaxException;
import java.time.Instant;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport; | LOG.debug("No commits by an author name: " + author.getName() + " untill " + uniqueSince);
LOG.debug("Recheck by the author email: " + author.getEmail());
String queryByAuthorEmail = UriComponentsBuilder.fromHttpUrl("https://api.github.com/repos/")
.path(repository)
.path("/" + GitHubApiEndpoints.COMMITS.toString().toLowerCase())
.queryParam("author", author.getEmail())
.queryParam("until", uniqueSince)
.build().encode()
.toUriString();
LOG.debug(queryByAuthorEmail);
commitsPage = restTemplate.getForObject(queryByAuthorEmail, JsonNode.class);
LOG.debug(commitsPage.toString());
return !commitsPage.has(0);//return true if a commits page look like []
} else return false;
}
List<JsonNode> getCommits(String repository, Instant since, Instant until) throws URISyntaxException, ExecutionException, InterruptedException, GitHubRESTApiException {
GitHubApiIterator gitHubApiIterator = new GitHubApiIterator(repository, restTemplate, GitHubApiEndpoints.COMMITS, since, until);
List<JsonNode> commitPages = new ArrayList<>();
List<JsonNode> commits = new ArrayList<>();
while (gitHubApiIterator.hasNext()) {
List<JsonNode> commitPagesBatch = gitHubApiIterator.next(5);
commitPages.addAll(commitPagesBatch);
}
gitHubApiIterator.close();
LOG.debug(commitPages.toString());
for (JsonNode page : commitPages) {
for (JsonNode commit : page) {
commits.add(commit);
LOG.debug(commit.toString());
}
}
return commits;
}
Set<Author> getAuthorNameAndEmail(List<JsonNode> commits) {
Set<Author> authors = new HashSet<>();
for (JsonNode commit : commits) {
JsonNode authorEmail = commit.get("commit")
.get("author").get("email");
JsonNode authorName = commit.get("commit")
.get("author").get("name");
LOG.debug(authorEmail.textValue());
LOG.debug(authorName.textValue());
Author author = new Author(authorName.textValue(), authorEmail.textValue());
authors.add(author);
}
LOG.debug("Authors : " + authors);
return authors;
}
Set<Author> getUniqueContributors(String projectName, Instant uniqueSince, Instant uniqueUntil) throws InterruptedException, ExecutionException, URISyntaxException, GitHubRESTApiException {
Set<Author> authorsPerPeriod = getAuthorNameAndEmail(getCommits(projectName, uniqueSince, uniqueUntil));
Set<Author> newAuthors = authorsPerPeriod.parallelStream()
.filter(author -> isUniqueContributor(projectName, author, uniqueSince))
.collect(Collectors.toSet());
LOG.debug("since" + uniqueSince + " are " + newAuthors.size() + " new authors: " + newAuthors.toString());
return newAuthors;
}
LocalDate getFirstContributionDate(Author author, String repository) throws GitHubRESTApiException {
int reliableLastPageNumber = 0;
String URL;
if (author.getEmail() != null && !author.getEmail().isEmpty()) {
reliableLastPageNumber = Utils.getLastPageNumber(repository, restTemplate, GitHubApiEndpoints.COMMITS, author.getEmail(), null, null);
URL = UriComponentsBuilder
.fromHttpUrl("https://api.github.com/repos/")
.path(repository).path("/" + GitHubApiEndpoints.COMMITS.toString().toLowerCase())
.queryParam("page", reliableLastPageNumber)
.queryParam("author", author.getEmail())
.build().encode()
.toUriString();
} else {
reliableLastPageNumber = Utils.getLastPageNumber(repository, restTemplate, GitHubApiEndpoints.COMMITS, author.getName(), null, null);
URL = UriComponentsBuilder
.fromHttpUrl("https://api.github.com/repos/")
.path(repository).path("/" + GitHubApiEndpoints.COMMITS.toString().toLowerCase())
.queryParam("page", reliableLastPageNumber)
.queryParam("author", author.getName())
.build().encode()
.toUriString();
}
LOG.debug(String.valueOf(reliableLastPageNumber));
LOG.info(URL);
JsonNode commitsPage = restTemplate.getForObject(URL, JsonNode.class);
for (JsonNode commit : commitsPage) {
LOG.debug(commit.toString());
}
List<JsonNode> commits = StreamSupport.stream(commitsPage.spliterator(), false).collect(Collectors.toList());
JsonNode commit;
try {
commit = commits.get(commits.size() - 1);
LOG.info("First commit by " + author + " : " + commit.toString());
String date = commit.get("commit").get("author").get("date").textValue();
LOG.debug(date);
LocalDate firstContributionDate = Utils.parseTimestamp(date);
LOG.info(firstContributionDate.toString());
return firstContributionDate;
} catch (ArrayIndexOutOfBoundsException ex) {
LOG.error("Cant properly get commits for :" + author);
ex.printStackTrace();
throw ex;
}
}
List<LocalDate> getFirstAuthorCommitFrequencyList(String repository, Instant since, Instant until) throws InterruptedException, ExecutionException, URISyntaxException, GitHubRESTApiException {
Set<Author> uniqueContributors = getUniqueContributors(repository, since, until);
List<LocalDate> firstAuthorCommitFrequencyList = new ArrayList<>();
for (Author author : uniqueContributors) {
try {
firstAuthorCommitFrequencyList.add(getFirstContributionDate(author, repository));
} catch (ArrayIndexOutOfBoundsException ex) {
LOG.error("cant properly getFirstContributionDate :" + author);
LOG.error("don't add any to firstAuthorCommitFrequencyList for " + repository);
}
}
LOG.info(firstAuthorCommitFrequencyList.toString());
return firstAuthorCommitFrequencyList;
}
| public ResponceForFrontendDto getUniqueContributorsFrequency(RequestFromFrontendDto requestFromFrontendDto) throws IOException, ClassNotFoundException, InterruptedException, ExecutionException, URISyntaxException, GitHubRESTApiException { | 2 |
rwitzel/streamflyer | streamflyer-core/src/test/java/com/github/rwitzel/streamflyer/regex/addons/tokens/MyTokenProcessorTest.java | [
"public interface Modifier {\r\n\r\n /**\r\n * Processes the characters in the given character buffer, i.e. deletes or replaces or inserts characters, or keeps\r\n * the characters as they are.\r\n * \r\n * @param characterBuffer\r\n * The next characters provided from the modifiab... | import com.github.rwitzel.streamflyer.regex.addons.tokens.TokensMatcher;
import static org.junit.Assert.assertEquals;
import java.io.Reader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.io.IOUtils;
import org.junit.Test;
import com.github.rwitzel.streamflyer.core.Modifier;
import com.github.rwitzel.streamflyer.core.ModifyingReader;
import com.github.rwitzel.streamflyer.regex.RegexModifier;
import com.github.rwitzel.streamflyer.regex.addons.tokens.Token;
import com.github.rwitzel.streamflyer.regex.addons.tokens.TokenProcessor;
| /**
* Copyright (C) 2011 rwitzel75@googlemail.com
*
* 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.github.rwitzel.streamflyer.regex.addons.tokens;
/**
* Tests {@link MyTokenProcessor} and {@link TokenProcessor}.
*
* @author rwoo
*
*/
public class MyTokenProcessorTest {
/**
* Rather an integration test than a unit test.
*
* @throws Exception
*/
@Test
public void testProcess() throws Exception {
// +++ define the tokens we are looking for
| List<Token> tokenList = new ArrayList<Token>();
| 3 |
debdattabasu/RoboMVVM | library/src/main/java/org/dbasu/robomvvm/viewmodel/ViewModel.java | [
"public enum BindMode {\n\n /**\n * Makes a one-way binding where the target property is set whenever the source property changes.\n */\n SOURCE_TO_TARGET(true, false),\n\n /**\n * Makes a one-way binding where the source property is set whenever the target property changes.\n */\n TARGE... | import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.google.common.base.Preconditions;
import org.dbasu.robomvvm.binding.BindMode;
import org.dbasu.robomvvm.binding.Binding;
import org.dbasu.robomvvm.binding.ValueConverter;
import org.dbasu.robomvvm.componentmodel.ComponentAdapter;
import org.dbasu.robomvvm.componentmodel.EventArg;
import org.dbasu.robomvvm.util.ObjectTagger;
import org.dbasu.robomvvm.util.ThreadUtil;
import java.util.ArrayList;
import java.util.List; | /**
* @project RoboMVVM
* @project RoboMVVM(https://github.com/debdattabasu/RoboMVVM)
* @author Debdatta Basu
*
* @license 3-clause BSD license(http://opensource.org/licenses/BSD-3-Clause).
* Copyright (c) 2014, Debdatta Basu. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that
* the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may be used
* to endorse or promote products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
* OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package org.dbasu.robomvvm.viewmodel;
/**
* View model used for creating and binding views.
*/
public class ViewModel extends BaseViewModel {
private static final String VIEW_MODEL = "robomvvm_view_model";
private static final String VIEW_BINDINGS = "robomvvm_view_bindings";
private View view = null;
private final List<Binding> bindings = new ArrayList<Binding>();
/**
* Construct a ViewModel with a supplied context.
* @param context
* The supplied context.
*/
public ViewModel(Context context) {
super(context);
}
/**
* Attempt to unbind a pre-existing view from its view model and bind it to this
* view model.
* @param viewToConvert
* The view to convert.
* @return
* Null if viewToConvert is null. Null if viewToConvert corresponds to a different view model class.
* The bound view otherwise.
*/
public View convertView(View viewToConvert) {
Preconditions.checkArgument(ThreadUtil.isUiThread(), "ViewModel.convertView can only be called from the UI thread");
if(viewToConvert == null) return null;
ViewModel otherViewModel = (ViewModel) ObjectTagger.getTag(viewToConvert, VIEW_MODEL);
if(otherViewModel == null || !otherViewModel.getClass().equals(this.getClass())) return null;
List<Binding> otherViewBindings = (List<Binding>) ObjectTagger.getTag(viewToConvert, VIEW_BINDINGS);
if(otherViewBindings != null) {
for (Binding binding : otherViewBindings) {
binding.unbind();
}
}
this.view = viewToConvert;
bind();
ObjectTagger.setTag(viewToConvert, VIEW_MODEL, this);
ObjectTagger.setTag(viewToConvert, VIEW_BINDINGS, new ArrayList<Binding>(bindings));
this.view = null;
bindings.clear();
return viewToConvert;
}
/**
* Create a view corresponding to this view model. Created with a null parent. The View Model is stored as a tag on the root View using
* {@link org.dbasu.robomvvm.util.ObjectTagger}. This makes sure that the View Model is kept alive as long as the View is alive.
* @return
* The created view.
*/
public View createView() {
return createView(null);
}
/**
* Create a view corresponding to this view model. The View Model is stored as a tag on the root View using
* {@link org.dbasu.robomvvm.util.ObjectTagger}. This makes sure that the View Model is kept alive as long as the View is alive.
* @param parent
* Parent to attach the created view to.
* @return
* The created view.
*/
public View createView(ViewGroup parent) {
Preconditions.checkArgument(ThreadUtil.isUiThread(), "ViewModel.createView can only be called from the UI thread");
int layoutId = getLayoutId();
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View viewToConvert = inflater.inflate(layoutId, parent, false);
ObjectTagger.setTag(viewToConvert, VIEW_MODEL, this);
return convertView(viewToConvert);
}
/**
* Bind a property of this view model to a property of a view in its layout.
* @param property
* The property of the view model
* @param viewId
* The id of the target view.
* @param viewProperty
* The property of the target view.
* @param valueConverter
* The value converter to use for conversion.
* @param bindMode
* The bind mode to use.
* @return
* The created binding.
*/
@Override | protected final Binding bindProperty(String property, int viewId, String viewProperty, ValueConverter valueConverter, BindMode bindMode) { | 0 |
http-builder-ng/http-builder-ng | http-builder-ng-core/src/main/java/groovyx/net/http/optional/Csv.java | [
"public interface ChainedHttpConfig extends HttpConfig {\n\n interface ChainedRequest extends Request {\n ChainedRequest getParent();\n\n List<HttpCookie> getCookies();\n\n Object getBody();\n\n String getContentType();\n\n Map<String, BiConsumer<ChainedHttpConfig, ToServer>> g... | import static groovyx.net.http.NativeHandlers.Encoders.*;
import com.opencsv.CSVReader;
import com.opencsv.CSVWriter;
import groovyx.net.http.ChainedHttpConfig;
import groovyx.net.http.FromServer;
import groovyx.net.http.HttpConfig;
import groovyx.net.http.ToServer;
import groovyx.net.http.TransportingException;
import java.io.IOException;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Supplier; | /**
* Copyright (C) 2017 HttpBuilder-NG Project
*
* 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 groovyx.net.http.optional;
/**
* Optional CSV encoder/parser implementation based on the [OpenCSV](http://opencsv.sourceforge.net/) library. It will be available when the OpenCsv
* library is on the classpath (an optional dependency).
*/
public class Csv {
public static final Supplier<BiConsumer<ChainedHttpConfig, ToServer>> encoderSupplier = () -> Csv::encode;
public static final Supplier<BiFunction<ChainedHttpConfig, FromServer, Object>> parserSupplier = () -> Csv::parse;
public static class Context {
public static final String ID = "3DOJ0FPjyD4GwLmpMjrCYnNJK60=";
public static final Context DEFAULT_CSV = new Context(',');
public static final Context DEFAULT_TSV = new Context('\t');
private final Character separator;
private final Character quoteChar;
public Context(final Character separator) {
this(separator, null);
}
public Context(final Character separator, final Character quoteChar) {
this.separator = separator;
this.quoteChar = quoteChar;
}
public char getSeparator() {
return separator;
}
public boolean hasQuoteChar() {
return quoteChar != null;
}
public char getQuoteChar() {
return quoteChar;
}
private CSVReader makeReader(final Reader reader) {
if (hasQuoteChar()) {
return new CSVReader(reader, separator, quoteChar);
} else {
return new CSVReader(reader, separator);
}
}
private CSVWriter makeWriter(final Writer writer) {
if (hasQuoteChar()) {
return new CSVWriter(writer, separator, quoteChar);
} else {
return new CSVWriter(writer, separator);
}
}
}
/**
* Used to parse the server response content using the OpenCsv parser.
*
* @param config the configuration
* @param fromServer the server content accessor
* @return the parsed object
*/
public static Object parse(final ChainedHttpConfig config, final FromServer fromServer) {
try {
final Csv.Context ctx = (Csv.Context) config.actualContext(fromServer.getContentType(), Csv.Context.ID);
return ctx.makeReader(fromServer.getReader()).readAll();
} catch (IOException e) { | throw new TransportingException(e); | 4 |
UBOdin/jsqlparser | src/net/sf/jsqlparser/statement/replace/Replace.java | [
"public interface ItemsList {\r\n\tpublic void accept(ItemsListVisitor itemsListVisitor);\r\n}\r",
"public interface Statement {\r\n\tpublic void accept(StatementVisitor statementVisitor);\r\n}\r",
"public interface StatementVisitor {\r\n\tpublic void visit(Select select);\r\n\tpublic void visit(Delete delete);... | import net.sf.jsqlparser.statement.select.SubSelect;
import java.util.List;
import net.sf.jsqlparser.expression.*;
import net.sf.jsqlparser.expression.operators.relational.ItemsList;
import net.sf.jsqlparser.schema.*;
import net.sf.jsqlparser.statement.Statement;
import net.sf.jsqlparser.statement.StatementVisitor;
import net.sf.jsqlparser.statement.select.PlainSelect;
| /* ================================================================
* JSQLParser : java based sql parser
* ================================================================
*
* Project Info: http://jsqlparser.sourceforge.net
* Project Lead: Leonardo Francalanci (leoonardoo@yahoo.it);
*
* (C) Copyright 2004, by Leonardo Francalanci
*
* This library is free software; you can redistribute it and/or modify it under the terms
* of the GNU Lesser General Public License as published by the Free Software Foundation;
* either version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with this
* library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
* Boston, MA 02111-1307, USA.
*/
package net.sf.jsqlparser.statement.replace;
/**
* The replace statement.
*/
public class Replace implements Statement {
private Table table;
private List<Column> columns;
private ItemsList itemsList;
private List<Expression> expressions;
private boolean useValues = true;
public void accept(StatementVisitor statementVisitor) {
statementVisitor.visit(this);
}
public Table getTable() {
return table;
}
public void setTable(Table name) {
table = name;
}
/**
* A list of {@link net.sf.jsqlparser.schema.Column}s either from a "REPLACE mytab (col1, col2) [...]" or a "REPLACE mytab SET col1=exp1, col2=exp2".
* @return a list of {@link net.sf.jsqlparser.schema.Column}s
*/
public List<Column> getColumns() {
return columns;
}
/**
* An {@link ItemsList} (either from a "REPLACE mytab VALUES (exp1,exp2)" or a "REPLACE mytab SELECT * FROM mytab2")
* it is null in case of a "REPLACE mytab SET col1=exp1, col2=exp2"
* @return The target relation
*/
public ItemsList getItemsList() {
return itemsList;
}
public void setColumns(List<Column> list) {
columns = list;
}
public void setItemsList(ItemsList list) {
itemsList = list;
}
/**
* A list of {@link net.sf.jsqlparser.expression.Expression}s (from a "REPLACE mytab SET col1=exp1, col2=exp2"). <br>
* it is null in case of a "REPLACE mytab (col1, col2) [...]"
* @return The replacement expressions
*/
public List<Expression> getExpressions() {
return expressions;
}
public void setExpressions(List<Expression> list) {
expressions = list;
}
public boolean isUseValues() {
return useValues;
}
public void setUseValues(boolean useValues) {
this.useValues = useValues;
}
public String toString() {
String sql = "REPLACE "+table;
if(expressions != null && columns != null ) {
//the SET col1=exp1, col2=exp2 case
sql += " SET ";
//each element from expressions match up with a column from columns.
for (int i = 0, s = columns.size(); i < s; i++) {
sql += ""+columns.get(i)+"="+expressions.get(i);
sql += (i<s-1)?", ":"";
}
}
else if( columns != null ) {
//the REPLACE mytab (col1, col2) [...] case
| sql += " "+PlainSelect.getStringList(columns, true, true);
| 3 |
yyon/grapplemod | main/java/com/yyon/grapplinghook/blocks/BlockGrappleModifier.java | [
"@Config(modid=\"grapplemod\", name=\"grappling_hook\", category=\"\")\npublic class GrappleConfig {\n\tpublic static class Config {\n\t\t// rope\n\t\tpublic double default_maxlen = 30;\n\t\tpublic boolean default_phaserope = false;\n\t\tpublic boolean default_sticky = false;\n\t\t// hook thrower\n\t\tpublic double... | import java.util.Map;
import javax.annotation.Nullable;
import com.yyon.grapplinghook.GrappleConfig;
import com.yyon.grapplinghook.GrappleCustomization;
import com.yyon.grapplinghook.grapplemod;
import com.yyon.grapplinghook.items.grappleBow;
import com.yyon.grapplinghook.items.upgrades.BaseUpgradeItem;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.block.state.IBlockState;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.enchantment.Enchantment;
import net.minecraft.enchantment.EnchantmentHelper;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Enchantments;
import net.minecraft.init.Items;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.BlockRenderLayer;
import net.minecraft.util.EnumBlockRenderType;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.NonNullList;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.text.TextComponentString;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly; | package com.yyon.grapplinghook.blocks;
public class BlockGrappleModifier extends Block {
public BlockGrappleModifier() {
super(Material.ROCK);
setCreativeTab(grapplemod.tabGrapplemod);
}
@Override
public boolean hasTileEntity(IBlockState state) {
return true;
}
// Called when the block is placed or loaded client side to get the tile entity
// for the block
// Should return a new instance of the tile entity for the block
@Override
public TileEntity createTileEntity(World world, IBlockState state) {
return new TileEntityGrappleModifier();
}
// the block will render in the SOLID layer. See
// http://greyminecraftcoder.blogspot.co.at/2014/12/block-rendering-18.html for
// more information.
@SideOnly(Side.CLIENT)
public BlockRenderLayer getBlockLayer() {
return BlockRenderLayer.SOLID;
}
@Override
public boolean isOpaqueCube(IBlockState state) {
return true;
}
@Override
public boolean isFullCube(IBlockState state) {
return true;
}
// render using a BakedModel
// not required because the default (super method) is MODEL
@Override
public EnumBlockRenderType getRenderType(IBlockState iBlockState) {
return EnumBlockRenderType.MODEL;
}
@Override
public void getDrops(NonNullList<ItemStack> drops, IBlockAccess world, BlockPos pos, IBlockState state, int fortune) {
super.getDrops(drops, world, pos, state, fortune);
TileEntity ent = world.getTileEntity(pos);
TileEntityGrappleModifier tileent = (TileEntityGrappleModifier) ent;
for (grapplemod.upgradeCategories category : grapplemod.upgradeCategories.values()) {
if (tileent.unlockedCategories.containsKey(category) && tileent.unlockedCategories.get(category)) {
drops.add(new ItemStack(category.getItem()));
}
}
}
@Override
public boolean removedByPlayer(IBlockState state, World world, BlockPos pos, EntityPlayer player, boolean willHarvest)
{
if (willHarvest) return true; //If it will harvest, delay deletion of the block until after getDrops
return super.removedByPlayer(state, world, pos, player, willHarvest);
}
/**
* Spawns the block's drops in the world. By the time this is called the Block has possibly been set to air via
* Block.removedByPlayer
*/
@Override
public void harvestBlock(World world, EntityPlayer player, BlockPos pos, IBlockState state, @Nullable TileEntity te, ItemStack tool)
{
super.harvestBlock(world, player, pos, state, te, tool);
world.setBlockToAir(pos);
}
@Override
public boolean onBlockActivated(World worldIn, BlockPos pos, IBlockState state, EntityPlayer playerIn,
EnumHand hand, EnumFacing facing, float hitX, float hitY, float hitZ) {
ItemStack helditemstack = playerIn.getHeldItemMainhand();
Item helditem = helditemstack.getItem();
if (helditem instanceof BaseUpgradeItem) {
if (!worldIn.isRemote) {
TileEntity ent = worldIn.getTileEntity(pos);
TileEntityGrappleModifier tileent = (TileEntityGrappleModifier) ent;
grapplemod.upgradeCategories category = ((BaseUpgradeItem) helditem).category;
if (tileent.isUnlocked(category)) {
playerIn.sendMessage(new TextComponentString("Already has upgrade: " + category.description));
} else {
if (!playerIn.capabilities.isCreativeMode) {
playerIn.setHeldItem(EnumHand.MAIN_HAND, ItemStack.EMPTY);
}
tileent.unlockCategory(category);
playerIn.sendMessage(new TextComponentString("Applied upgrade: " + category.description));
}
}
} else if (helditem instanceof grappleBow) {
if (!worldIn.isRemote) {
TileEntity ent = worldIn.getTileEntity(pos);
TileEntityGrappleModifier tileent = (TileEntityGrappleModifier) ent;
| GrappleCustomization custom = tileent.customization; | 1 |
mini2Dx/miniscript | core/src/test/java/org/mini2Dx/miniscript/core/dummy/DummyScriptExecutorPool.java | [
"public abstract class GameScript<S> {\n\tprivate static final AtomicInteger ID_GENERATOR = new AtomicInteger(0);\n\t\n\tprivate final int id;\n\t\n\tpublic GameScript() {\n\t\tsuper();\n\t\tid = ID_GENERATOR.incrementAndGet();\n\t}\n\n\tpublic int getId() {\n\t\treturn id;\n\t}\n\n\tpublic abstract S getScript();\... | import org.mini2Dx.miniscript.core.GameScriptingEngine;
import org.mini2Dx.miniscript.core.ScriptBindings;
import org.mini2Dx.miniscript.core.ScriptExecutionTask;
import org.mini2Dx.miniscript.core.ScriptExecutor;
import org.mini2Dx.miniscript.core.ScriptExecutorPool;
import org.mini2Dx.miniscript.core.ScriptInvocationListener;
import org.mini2Dx.miniscript.core.exception.InsufficientCompilersException;
import org.mini2Dx.miniscript.core.exception.ScriptExecutorUnavailableException;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import org.mini2Dx.miniscript.core.GameScript; | /**
* The MIT License (MIT)
*
* Copyright (c) 2016 Thomas Cashman
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package org.mini2Dx.miniscript.core.dummy;
/**
* An implementation for {@link ScriptExecutorPool} for unit tests
*/
public class DummyScriptExecutorPool implements ScriptExecutorPool<DummyScript> {
private final Map<Integer, GameScript<DummyScript>> scripts = new ConcurrentHashMap<Integer, GameScript<DummyScript>>();
private final Map<String, Integer> filepathsToScriptIds = new ConcurrentHashMap<String, Integer>();
private final Map<Integer, String> scriptIdsToFilepaths = new ConcurrentHashMap<Integer, String>();
private final BlockingQueue<ScriptExecutor<DummyScript>> executors;
private final GameScriptingEngine gameScriptingEngine;
public DummyScriptExecutorPool(GameScriptingEngine gameScriptingEngine, int poolSize) {
this.gameScriptingEngine = gameScriptingEngine;
executors = new ArrayBlockingQueue<ScriptExecutor<DummyScript>>(poolSize);
for (int i = 0; i < poolSize; i++) {
executors.offer(new DummyScriptExecutor(this));
}
}
@Override
public int preCompileScript(String filepath, String scriptContent) throws InsufficientCompilersException {
ScriptExecutor<DummyScript> executor = executors.poll();
if (executor == null) {
throw new InsufficientCompilersException();
}
GameScript<DummyScript> script = executor.compile(scriptContent);
executor.release();
scripts.put(script.getId(), script);
filepathsToScriptIds.put(filepath, script.getId());
scriptIdsToFilepaths.put(script.getId(), filepath);
return script.getId();
}
@Override
public int getCompiledScriptId(String filepath) {
return filepathsToScriptIds.get(filepath);
}
@Override
public String getCompiledScriptPath(int scriptId) {
return scriptIdsToFilepaths.get(scriptId);
}
@Override
public ScriptExecutionTask<?> execute(int taskId, int scriptId, ScriptBindings scriptBindings, | ScriptInvocationListener invocationListener, boolean syncCall) { | 6 |
thx/RAP | src/main/java/com/taobao/rigel/rap/mock/service/impl/MockMgrImpl.java | [
"public class Patterns {\n public static final String MOCK_TEMPLATE_PATTERN = \"\\\\$\\\\{([_a-zA-Z][_a-zA-Z0-9.]*)=?((.*?))\\\\}\";\n public static final String ILLEGAL_NAME_CHAR = \"[^ 0-9a-zA-Z_]\";\n public static final String LEGAL_ACCOUNT_CHAR = \"[0-9a-zA-Z_]\";\n public static final String LEGAL... | import com.google.gson.Gson;
import com.taobao.rigel.rap.common.config.Patterns;
import com.taobao.rigel.rap.common.config.SystemSettings;
import com.taobao.rigel.rap.common.utils.*;
import com.taobao.rigel.rap.mock.bo.Rule;
import com.taobao.rigel.rap.mock.dao.MockDao;
import com.taobao.rigel.rap.mock.service.MockMgr;
import com.taobao.rigel.rap.project.bo.Action;
import com.taobao.rigel.rap.project.bo.Parameter;
import com.taobao.rigel.rap.project.dao.ProjectDao;
import com.taobao.rigel.rap.project.service.ProjectMgr;
import nl.flotsam.xeger.Xeger;
import org.apache.logging.log4j.LogManager;
import sun.misc.Cache;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
| package com.taobao.rigel.rap.mock.service.impl;
public class MockMgrImpl implements MockMgr {
interface Callback {
void onSuccess(String result);
}
private static final org.apache.logging.log4j.Logger logger = LogManager.getLogger(MockMgrImpl.class);
private final String ERROR_PATTERN = "{\"isOk\":false,\"msg\":\"路径为空,请查看是否接口未填写URL.\"}";
private final String ERROR_SEARCH = "{\"isOk\":false,\"msg\":\"请求参数不合法。\"}"; // 请查看是否含有 script、img、iframe 等标签
private ProjectDao projectDao;
private ProjectMgr projectMgr;
private MockDao mockDao;
private int uid = 10000;
private Map<String, List<String>> requestParams;
private boolean isMockJsData = false;
/**
* random seed
*/
private int _num = 1;
private String[] NAME_LIB = {"霍雍", "行列", "幻刺", "金台", "望天", "李牧", "三冰",
"自勉", "思霏", "诚冉", "甘苦", "勇智", "墨汁老湿", "圣香", "定球", "征宇", "灵兮", "永盛",
"小婉", "紫丞", "少侠", "木谦", "周亮", "宝山", "张中", "晓哲", "夜沨"};
private String[] LOCATION_LIB = {"北京 朝阳区", "北京 海淀区", "北京 昌平区",
"吉林 长春 绿园区", "吉林 吉林 丰满区"};
private String[] PHONE_LIB = {"15813243928", "13884928343", "18611683243",
"18623432532", "18611582432"};
public static Map<String, List<String>> getUrlParameters(String url)
throws UnsupportedEncodingException {
Map<String, List<String>> params = new HashMap<String, List<String>>();
String[] urlParts = url.split("\\?");
if (urlParts.length > 1) {
String query = urlParts[1];
for (String param : query.split("&")) {
String pair[] = param.split("=");
if (pair.length == 0) {
continue;
}
String key = URLDecoder.decode(pair[0], "UTF-8");
String value = "";
if (pair.length > 1) {
value = URLDecoder.decode(pair[1], "UTF-8");
}
List<String> values = params.get(key);
if (values == null) {
values = new ArrayList<String>();
params.put(key, values);
}
values.add(value);
}
}
return params;
}
public MockDao getMockDao() {
return mockDao;
}
public void setMockDao(MockDao mockDao) {
this.mockDao = mockDao;
}
public ProjectMgr getProjectMgr() {
return projectMgr;
}
public void setProjectMgr(ProjectMgr projectMgr) {
this.projectMgr = projectMgr;
}
private boolean isPatternLegal(String pattern) {
if (pattern == null || pattern.isEmpty()) {
return false;
}
String path = pattern;
if (path.indexOf("/") == 0) {
path = path.substring(1);
}
if (path.contains("?")) {
path = path.substring(0, path.indexOf("?"));
}
if (path.isEmpty()) {
return false;
}
return true;
}
private boolean isSearchLegal(String pattern) throws UnsupportedEncodingException {
if (pattern == null || pattern.isEmpty()) {
return true;
}
String search = pattern;
if (search.contains("?")) {
search = search.substring(search.indexOf("?"));
search = URLDecoder.decode(search, "UTF-8");
if(search.toLowerCase().indexOf("<img") != -1) return false;
if(search.toLowerCase().indexOf("<script") != -1) return false;
if(search.toLowerCase().indexOf("</script>") != -1) return false;
if(search.toLowerCase().indexOf("<iframe") != -1) return false;
if(search.toLowerCase().indexOf("</iframe>") != -1) return false;
}
return true;
}
public ProjectDao getProjectDao() {
return projectDao;
}
public void setProjectDao(ProjectDao projectDao) {
this.projectDao = projectDao;
}
public String generateData(int projectId, String pattern,
Map<String, Object> options) throws UnsupportedEncodingException {
if (!isPatternLegal(pattern)) {
return ERROR_PATTERN;
}
_num = 1;
String originalPattern = pattern;
if (pattern.contains("?")) {
pattern = pattern.substring(0, pattern.indexOf("?"));
}
| List<Action> aList = projectMgr
| 4 |
ground-context/ground | modules/common/test/edu/berkeley/ground/common/model/usage/LineageGraphTest.java | [
"public static String convertFromClassToString(Object object) {\n return Json.stringify(Json.toJson(object));\n}",
"public static Object convertFromStringToClass(String body, Class<?> klass) {\n return Json.fromJson(Json.parse(body), klass);\n}",
"public static String readFromFile(String filename) throws Grou... | import static edu.berkeley.ground.common.util.ModelTestUtils.convertFromClassToString;
import static edu.berkeley.ground.common.util.ModelTestUtils.convertFromStringToClass;
import static edu.berkeley.ground.common.util.ModelTestUtils.readFromFile;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import edu.berkeley.ground.common.model.version.GroundType;
import edu.berkeley.ground.common.model.version.Tag;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test; | /**
* 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 edu.berkeley.ground.common.model.usage;
public class LineageGraphTest {
@Test
public void serializesToJSON() throws Exception {
Map<String, Tag> tagsMap = new HashMap<>();
tagsMap.put("testtag", new Tag(1, "testtag", "tag", GroundType.STRING));
LineageGraph lineageGraph = new LineageGraph(1, "test", "testKey", tagsMap);
| final String expected = convertFromClassToString(convertFromStringToClass(readFromFile | 2 |
romelo333/notenoughwands1.8.8 | src/main/java/romelo333/notenoughwands/Items/GenericWand.java | [
"public class ConfigSetup {\n public static String CATEGORY_GENERAL = \"general\";\n public static String CATEGORY_WANDS = \"wandsettings\";\n public static String CATEGORY_MOVINGBLACKLIST = \"movingblacklist\";\n public static String CATEGORY_CAPTUREBLACKLIST = \"captureblacklist\";\n\n public stati... | import mcjty.lib.client.BlockOutlineRenderer;
import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.entity.EntityPlayerSP;
import net.minecraft.client.renderer.block.model.ModelResourceLocation;
import net.minecraft.client.util.ITooltipFlag;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.text.TextFormatting;
import net.minecraft.world.World;
import net.minecraft.world.storage.loot.LootEntryItem;
import net.minecraft.world.storage.loot.LootPool;
import net.minecraft.world.storage.loot.conditions.LootCondition;
import net.minecraft.world.storage.loot.functions.LootFunction;
import net.minecraftforge.client.event.RenderWorldLastEvent;
import net.minecraftforge.client.model.ModelLoader;
import net.minecraftforge.common.capabilities.ICapabilityProvider;
import net.minecraftforge.common.config.Configuration;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import romelo333.notenoughwands.ConfigSetup;
import romelo333.notenoughwands.KeyBindings;
import romelo333.notenoughwands.NotEnoughWands;
import romelo333.notenoughwands.ProtectedBlocks;
import romelo333.notenoughwands.varia.ItemCapabilityProvider;
import romelo333.notenoughwands.varia.Tools;
import java.util.ArrayList;
import java.util.List;
import java.util.Set; | package romelo333.notenoughwands.Items;
//import net.minecraft.client.entity.EntityClientPlayerMP;
public class GenericWand extends Item implements IEnergyItem {
protected int needsxp = 0;
protected int needsrf = 0;
protected int maxrf = 0;
protected int lootRarity = 10;
private static List<GenericWand> wands = new ArrayList<>();
@SideOnly(Side.CLIENT)
public void registerModel() {
ModelLoader.setCustomModelResourceLocation(this, 0, new ModelResourceLocation(getRegistryName(), "inventory"));
}
@Override
public ICapabilityProvider initCapabilities(ItemStack stack, NBTTagCompound nbt) { | return new ItemCapabilityProvider(stack, this); | 4 |
cuberact/cuberact-json | src/test/java/org/cuberact/json/parser/JsonParserTest.java | [
"public abstract class Json implements Serializable {\r\n\r\n @Serial\r\n private static final long serialVersionUID = 1L;\r\n\r\n public abstract JsonType type();\r\n\r\n public final String toString() {\r\n return toString(JsonFormatter.PRETTY());\r\n }\r\n\r\n public final String toStrin... | import org.cuberact.json.Json;
import org.cuberact.json.JsonArray;
import org.cuberact.json.JsonNumber;
import org.cuberact.json.JsonObject;
import org.cuberact.json.builder.JsonBuilderDom;
import org.cuberact.json.formatter.JsonFormatter;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import org.junit.jupiter.api.Test;
import java.math.BigDecimal;
import java.math.BigInteger;
| /*
* Copyright 2017 Michal Nikodim
*
* 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 org.cuberact.json.parser;
/**
* @author Michal Nikodim (michal.nikodim@gmail.com)
*/
public class JsonParserTest {
@Test
public void parseExample1() {
String jsonAsString = "{\n" +
" 'rect': [486,'\\u0048\\u0065\\u006c\\u006C\\u006FWorld',{'data' : '\\u011B\\u0161\\u010D\\u0159\\u017E\\u00FD\\u00E1\\u00ED\\u00E9'},-23.54],\n" +
" 'perspectiveSelector': {\n" +
" 'perspectives': [ true, false],\n" +
" 'selected': null,\n" +
" 'some': [1,2,3.2]\n" +
" }\n" +
"}";
jsonAsString = jsonAsString.replace('\'', '"');
String expected = "{'rect':[486,'HelloWorld',{'data':'ěščřžýáíé'},-23.54],'perspectiveSelector':{'perspectives':[true,false],'selected':null,'some':[1,2,3.2]}}"
.replace('\'', '"');
Json json = new JsonParser().parse(jsonAsString);
assertEquals(expected, json.toString(JsonFormatter.PACKED()));
}
@Test
public void parseExample2() {
String jsonAsString = "{\n" +
"\t'id' : 'abcdef1234567890',\n" +
"\t'apiKey' : 'abcdef-ghijkl',\n" +
"\t'name' : 'Main_key',\n" +
"\t'validFrom' : 1505858400000,\n" +
"\t'softQuota' : 10000000,\n" +
"\t'hardQuota' : 10.12345,\n" +
"\t'useSignature' : null,\n" +
"\t'state' : 'ENABLED',\n" +
"\t'mocking' : true,\n" +
"\t'clientIpUsed' : false,\n" +
"\t'clientIpEnforced' : false\n" +
"}";
jsonAsString = jsonAsString.replace('\'', '"');
String expected = "{'id':'abcdef1234567890','apiKey':'abcdef-ghijkl','name':'Main_key','validFrom':1505858400000,'softQuota':10000000,'hardQuota':10.12345,'useSignature':null,'state':'ENABLED','mocking':true,'clientIpUsed':false,'clientIpEnforced':false}"
.replace('\'', '"');
Json json = new JsonParser().parse(jsonAsString);
assertEquals(expected, json.toString(JsonFormatter.PACKED()));
}
@Test
public void parseExample3() {
String jsonAsString = "[1,\n" +
"[2, \n" +
"[3, \n" +
"[4, \n" +
"[5], \n" +
"4.4], \n" +
"3.3], \n" +
"2.2], \n" +
"1.1]";
String expected = "[1,[2,[3,[4,[5],4.4],3.3],2.2],1.1]";
Json json = new JsonParser().parse(jsonAsString);
assertEquals(expected, json.toString(JsonFormatter.PACKED()));
}
@Test
public void parseExample4() {
String jsonAsString = "[[[[[[[[[[1]]]]]]]]]]";
Json json = new JsonParser().parse(jsonAsString);
assertEquals(jsonAsString, json.toString(JsonFormatter.PACKED()));
}
@Test
public void parseExample5() {
String jsonAsString = "[1,-2,'text',true,false,null,1.1,-1.1,{},[]]"
.replace('\'', '"');
Json json = new JsonParser().parse(jsonAsString);
assertEquals(jsonAsString, json.toString(JsonFormatter.PACKED()));
}
@Test
public void parseExample6() {
String jsonAsString = "[1.1,-1.1,2.2e10,2.2e10,-2.2e10,-2.2e-10,2.2e-10,2.2e-10,-2.2e-10,-2.2e-10,12345.12345e8,12345.12345e-8,-12345.12345e8,-12345.12345e-8]";
Json json = new JsonParser().parse(jsonAsString);
assertEquals(jsonAsString, json.toString(JsonFormatter.PACKED()));
}
@Test
public void parseExample7() {
String jsonAsString = "{'1':{'2':{'3':{'4':{'5':{'6':{'7':{'8':{'9':{'name':'jack'}}}}},'age':15}}}}}"
.replace('\'', '"');
Json json = new JsonParser().parse(jsonAsString);
assertEquals(jsonAsString, json.toString(JsonFormatter.PACKED()));
}
@Test
public void parseExample8() {
String jsonAsString = "{'\\t\\b\\r\\b\\f\\n':12}"
.replace('\'', '"');
Json json = new JsonParser().parse(jsonAsString);
assertEquals(jsonAsString, json.toString(JsonFormatter.PACKED()));
}
@Test
public void parseExampleVeryLongStrings() {
StringBuilder jsonAsString = new StringBuilder("{\"");
for (int i = 0; i < 10000; i++) {
jsonAsString.append((char) ((i & 15) + 65));
}
jsonAsString.append("\":\"");
for (int i = 0; i < 100000; i++) {
jsonAsString.append((char) ((i & 15) + 65));
}
jsonAsString.append("\"}");
Json json = new JsonParser().parse(jsonAsString);
assertEquals(jsonAsString.toString(), json.toString(JsonFormatter.PACKED()));
}
@Test
public void testArray() {
String jsonAsString = "{'arr':[1,2,3,4,2147483647,-2147483648]}"
.replace('\'', '"');
JsonObject json = new JsonParser().parse(jsonAsString);
| assertEquals(JsonArray.class, json.getArr("arr").getClass());
| 1 |
nisovin/Shopkeepers | src/main/java/com/nisovin/shopkeepers/shoptypes/BookPlayerShopType.java | [
"public class Settings {\n\n\tpublic static String fileEncoding = \"UTF-8\";\n\tpublic static boolean debug = false;\n\n\tpublic static boolean disableOtherVillagers = false;\n\tpublic static boolean hireOtherVillagers = false;\n\tpublic static boolean blockVillagerSpawns = false;\n\tpublic static boolean enableSpa... | import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.Player;
import com.nisovin.shopkeepers.Settings;
import com.nisovin.shopkeepers.ShopCreationData;
import com.nisovin.shopkeepers.ShopType;
import com.nisovin.shopkeepers.ShopkeeperCreateException;
import com.nisovin.shopkeepers.ShopkeepersAPI;
import com.nisovin.shopkeepers.Utils; | package com.nisovin.shopkeepers.shoptypes;
public class BookPlayerShopType extends ShopType<BookPlayerShopkeeper> {
BookPlayerShopType() {
super("book", ShopkeepersAPI.PLAYER_BOOK_PERMISSION);
}
@Override | public BookPlayerShopkeeper loadShopkeeper(ConfigurationSection config) throws ShopkeeperCreateException { | 2 |
stefanhaustein/nativehtml | shared/src/main/java/org/kobjects/nativehtml/io/HtmlParser.java | [
"public class CssStyleSheet {\n private static final char SELECT_ATTRIBUTE_NAME = 7;\n private static final char SELECT_ATTRIBUTE_VALUE = 8;\n private static final char SELECT_ATTRIBUTE_INCLUDES = 9;\n private static final char SELECT_ATTRIBUTE_DASHMATCH = 10;\n\n private static final float[] HEADING_SIZES = {... | import org.kobjects.nativehtml.css.CssStyleSheet;
import org.kobjects.nativehtml.dom.Document;
import org.kobjects.nativehtml.dom.Element;
import org.kobjects.nativehtml.dom.Platform;
import org.kobjects.nativehtml.dom.ElementType;
import org.kobjects.nativehtml.layout.WebSettings;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
import java.io.Reader;
import java.net.URI; | package org.kobjects.nativehtml.io;
/**
* Uses a HtmlParser to generate a widget tree that corresponds to the HTML code.
*
* Can be re-used, but is not thread safe.
*/
public class HtmlParser {
private final HtmlNormalizer input;
private final Platform elementFactory;
private CssStyleSheet styleSheet;
private Document document;
private WebSettings webSettings;
private RequestHandler requestHandler;
public HtmlParser(Platform elementFactory, RequestHandler requestHandler, WebSettings webSettings) {
this.elementFactory = elementFactory;
this.requestHandler = requestHandler;
this.webSettings = webSettings;
try {
this.input = new HtmlNormalizer();
} catch (XmlPullParserException e) {
throw new RuntimeException(e);
}
}
/**
* Parses html from the given reader and returns the body or root element.
*/ | public Element parse(Reader reader, URI baseUri) { | 2 |
kcthota/JSONQuery | src/test/java/com/kcthota/query/FilterTest.java | [
"public static IsNullExpression Null(String property) {\n\treturn new IsNullExpression(val(property));\n}",
"public static EqExpression eq(String property, String value) {\n\treturn eq(val(property), TextNode.valueOf(value));\n}",
"public static GtExpression gt(String property, Integer value) {\n\treturn new Gt... | import static com.kcthota.JSONQuery.expressions.Expr.Null;
import static com.kcthota.JSONQuery.expressions.Expr.eq;
import static com.kcthota.JSONQuery.expressions.Expr.gt;
import static com.kcthota.JSONQuery.expressions.Expr.le;
import static com.kcthota.JSONQuery.expressions.Expr.not;
import static com.kcthota.JSONQuery.expressions.Expr.or;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
import org.junit.BeforeClass;
import org.junit.Test;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.kcthota.JSONQuery.Query;
import com.kcthota.JSONQuery.exceptions.UnsupportedExprException; | /**
*
*/
package com.kcthota.query;
/**
* @author Krishna Chaitanya Thota
* Apr 28, 2015 9:23:50 PM
*/
public class FilterTest {
private static JsonNode node;
@BeforeClass
public static void setup() {
ObjectNode node1 = new ObjectMapper().createObjectNode();
node1.putObject("name").put("firstName", "John").put("lastName", "Doe");
node1.put("age", 25);
node1.putNull("address");
node1.put("state", "CA");
ObjectNode node2 = new ObjectMapper().createObjectNode();
node2.putObject("name").put("firstName", "Jane").put("lastName", "Doe");
node2.put("age", 18);
node2.put("address", "1st St.");
node2.put("state", "CA");
ObjectNode node3 = new ObjectMapper().createObjectNode();
node3.putObject("name").put("firstName", "Jill").put("lastName", "Doe");
node3.put("age", 30);
node3.put("address", "2nd St.");
node3.put("state", "FL");
node = new ObjectMapper().createArrayNode().add(node1).add(node2).add(node3);
}
@Test
public void testStringFilter() {
ArrayNode node = new ObjectMapper().createArrayNode().add("John").add("Kevin").add("Joe").add("Jeff");
Query q=new Query(node);
ArrayNode result = q.filter(eq((String)null, "John"));
assertThat(result.size()).isEqualTo(1);
assertThat(Query.q(result).value("0").textValue()).isEqualTo("John");
}
@Test
public void testIntegerFilter() {
ArrayNode node = new ObjectMapper().createArrayNode().add(1).add(2).add(3).add(4);
Query q=new Query(node);
ArrayNode result = q.filter(gt((String)null, 2));
assertThat(result.size()).isEqualTo(2);
assertThat(Query.q(result).value("0").intValue()).isEqualTo(3);
assertThat(Query.q(result).value("1").intValue()).isEqualTo(4);
}
@Test
public void testFloatFilter() {
ArrayNode node = new ObjectMapper().createArrayNode().add(1f).add(2.56f).add(3.01f).add(1.4f);
Query q=new Query(node);
ArrayNode result = q.filter(gt((String)null, 2f));
assertThat(result.size()).isEqualTo(2);
assertThat(Query.q(result).value("0").floatValue()).isEqualTo(2.56f);
assertThat(Query.q(result).value("1").floatValue()).isEqualTo(3.01f);
}
@Test
public void testJSONNodesFilter1() {
Query q=new Query(FilterTest.node); | ArrayNode result = q.filter(le("age", 18)); | 3 |
google/safe-html-types | types/src/test/java/com/google/common/html/types/UncheckedConversionsTest.java | [
"public static SafeHtml safeHtmlFromStringKnownToSatisfyTypeContract(String html) {\n return new SafeHtml(html);\n}",
"public static SafeScript safeScriptFromStringKnownToSatisfyTypeContract(String script) {\n return new SafeScript(script);\n}",
"public static SafeStyle safeStyleFromStringKnownToSatisfyTypeCo... | import static com.google.common.html.types.UncheckedConversions.safeHtmlFromStringKnownToSatisfyTypeContract;
import static com.google.common.html.types.UncheckedConversions.safeScriptFromStringKnownToSatisfyTypeContract;
import static com.google.common.html.types.UncheckedConversions.safeStyleFromStringKnownToSatisfyTypeContract;
import static com.google.common.html.types.UncheckedConversions.safeStyleSheetFromStringKnownToSatisfyTypeContract;
import static com.google.common.html.types.UncheckedConversions.safeUrlFromStringKnownToSatisfyTypeContract;
import static com.google.common.html.types.UncheckedConversions.trustedResourceUrlFromStringKnownToSatisfyTypeContract;
import static com.google.common.html.types.testing.assertions.Assertions.assertClassIsNotExportable;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import junit.framework.TestCase; | /*
* Copyright 2016 Google Inc. All Rights Reserved.
*
* 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.google.common.html.types;
/**
* Unit tests for {@link UncheckedConversions}.
*/
@GwtCompatible
public class UncheckedConversionsTest extends TestCase {
@GwtIncompatible("Assertions.assertClassIsNotExportable")
public void testNotExportable() {
assertClassIsNotExportable(UncheckedConversions.class);
}
public void testSafeHtmlFromStringKnownToSatisfyTypeContract() {
String html = "<script>this is not valid SafeHtml";
assertEquals(
html,
safeHtmlFromStringKnownToSatisfyTypeContract(html).getSafeHtmlString());
}
public void testSafeScriptFromStringKnownToSatisfyTypeContract() {
String script = "invalid SafeScript";
assertEquals(
script,
safeScriptFromStringKnownToSatisfyTypeContract(script).getSafeScriptString());
}
public void testSafeStyleFromStringKnownToSatisfyTypeContract() {
String style = "width:expression(this is not valid SafeStyle";
assertEquals(
style,
safeStyleFromStringKnownToSatisfyTypeContract(style).getSafeStyleString());
}
public void testSafeStyleSheetFromStringKnownToSatisfyTypeContract() {
String styleSheet = "selector { not a valid SafeStyleSheet";
assertEquals(
styleSheet, | safeStyleSheetFromStringKnownToSatisfyTypeContract(styleSheet).getSafeStyleSheetString()); | 3 |
gentoku/pinnacle-api-client | src/examples/PlaceBet.java | [
"public class Parameter extends ParameterCore {\n\n\t/**\n\t * Constructor.\n\t */\n\tprivate Parameter () {\n\t\tsuper();\n\t}\n\t\n\t/**\n\t * Factory\n\t * \n\t * @return\n\t */\n\tpublic static Parameter newInstance() {\n\t\treturn new Parameter();\n\t}\n\n\n\t/**\n\t * ID of the target sports.\n\t * \n\t * @pa... | import pinnacle.api.Parameter;
import pinnacle.api.PinnacleAPI;
import pinnacle.api.PinnacleException;
import pinnacle.api.dataobjects.PlacedBet;
import pinnacle.api.enums.BET_TYPE;
import pinnacle.api.enums.ODDS_FORMAT;
import pinnacle.api.enums.PERIOD;
import pinnacle.api.enums.TEAM_TYPE;
import pinnacle.api.enums.WIN_RISK_TYPE; | package examples;
public class PlaceBet {
public static void main(String[] args) throws PinnacleException {
// settings
String username = "yourUserName";
String password = "yourPassword";
PinnacleAPI api = PinnacleAPI.open(username, password);
// parameter
Parameter parameter = Parameter.newInstance();
parameter.uniqueRequestId();
parameter.acceptBetterLine(true);
//parameter.customerReference();
parameter.oddsFormat(ODDS_FORMAT.DECIMAL);
parameter.stake("100.0");
parameter.winRiskStake(WIN_RISK_TYPE.WIN);
parameter.sportId(29);
parameter.eventId(687863980);
parameter.periodNumber(PERIOD.SOCCER_1ST_HALF); | parameter.betType(BET_TYPE.MONEYLINE); | 4 |
suninformation/ymate-payment-v2 | ymate-payment-alipay/src/main/java/net/ymate/payment/alipay/request/AliPayTradeRefundQuery.java | [
"public class AliPayAccountMeta implements Serializable {\n\n /**\n * 支付宝分配给开发者的应用ID\n */\n private String appId;\n\n /**\n * 同步返回地址,HTTP/HTTPS开头字符串\n */\n private String returnUrl;\n\n /**\n * 支付宝服务器主动通知商户服务器里指定的页面http/https路径\n */\n private String notifyUrl;\n\n /**\n ... | import com.alibaba.fastjson.annotation.JSONField;
import net.ymate.payment.alipay.base.AliPayAccountMeta;
import net.ymate.payment.alipay.base.AliPayBaseRequest;
import net.ymate.payment.alipay.base.AliPayBaseResponse;
import net.ymate.payment.alipay.base.AliPayBaseResponseParser;
import net.ymate.payment.alipay.data.TradeRefundQueryData;
import org.apache.commons.lang.StringUtils; | /*
* Copyright 2007-2017 the original author or authors.
*
* 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 net.ymate.payment.alipay.request;
/**
* 统一收单交易退款查询
* <p>
* 商户可使用该接口查询自已通过alipay.trade.refund提交的退款请求是否执行成功。
* 该接口的返回码10000,仅代表本次查询操作成功,不代表退款成功。
* 如果该接口返回了查询数据,则代表退款成功,如果没有查询到则代表未退款成功,可以调用退款接口进行重试。
* 重试时请务必保证退款请求号一致
*
* @author 刘镇 (suninformation@163.com) on 17/6/12 上午12:31
* @version 1.0
*/
public class AliPayTradeRefundQuery extends AliPayBaseRequest<TradeRefundQueryData, AliPayTradeRefundQuery.Response> {
private static final String METHOD_NAME = "alipay.trade.fastpay.refund.query";
| public AliPayTradeRefundQuery(AliPayAccountMeta accountMeta, TradeRefundQueryData bizContent) { | 0 |
NymphWeb/nymph | com/nymph/bean/core/ScannerNymphBeans.java | [
"public interface BeansComponent {\n\t/**\n\t * 根据注解类型获取组件Bean\n\t * @param anno\t指定的注解\n\t * @return\t\t对应的bean组件\n\t */\n\tOptional<Object> getComponent(Class<? extends Annotation> anno);\n\n\t/**\n\t * 获取拦截器链\n\t * @return\n\t */\n\tList<Interceptors> getInterceptors();\n\t/**\n\t * 过滤出组件的Bean\n\t * @param bean ... | import java.io.File;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.nymph.annotation.Bean;
import com.nymph.annotation.ConfigurationBean;
import com.nymph.bean.BeansComponent;
import com.nymph.bean.BeansHandler;
import com.nymph.bean.web.MapperInfoContainer;
import com.nymph.config.Configuration;
import com.nymph.utils.AnnoUtil;
import com.nymph.utils.BasicUtil;
import com.nymph.utils.JarUtil; | package com.nymph.bean.core;
/**
* 根据包路径扫描所有的bean
* @author NYMPH
* @date 2017年9月26日2017年9月26日
*/
public class ScannerNymphBeans {
private static final Logger LOG = LoggerFactory.getLogger(ScannerNymphBeans.class);
// 存放bean的容器
private Map<String, Object> beansContainer;
// 处理http相关的bean映射信息 | private MapperInfoContainer handler; | 2 |
onepf/OPFPush | samples/pushchat/src/main/java/org/onepf/pushchat/ui/dialog/AddContactDialogFragment.java | [
"public class PushChatApplication extends Application {\n\n private static final String GCM_SENDER_ID = \"707033278505\";\n\n private static final String NOKIA_SENDER_ID = \"pushsample\";\n\n private String uuid;\n\n private RefWatcher refWatcher;\n\n @Override\n public void onCreate() {\n ... | import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import org.onepf.pushchat.PushChatApplication;
import org.onepf.pushchat.R;
import org.onepf.pushchat.db.DatabaseHelper;
import org.onepf.pushchat.model.db.Contact;
import org.onepf.pushchat.model.response.ExistResponse;
import org.onepf.pushchat.retrofit.NetworkController;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response; | /*
* Copyright 2012-2015 One Platform Foundation
*
* 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 org.onepf.pushchat.ui.dialog;
/**
* @author Roman Savin
* @since 06.05.2015
*/
public class AddContactDialogFragment extends DialogFragment {
public static final String TAG = AddContactDialogFragment.class.getName();
public static AddContactDialogFragment newInstance() {
return new AddContactDialogFragment();
}
@SuppressLint("InflateParams")
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getActivity());
final View view = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_add_contact, null);
final EditText nameEditText = (EditText) view.findViewById(R.id.contact_name_edit_text);
final EditText uuidEditText = (EditText) view.findViewById(R.id.uuid_edit_text);
final TextView errorTextView = (TextView) view.findViewById(R.id.error_text);
final Button okButton = (Button) view.findViewById(R.id.ok_button);
uuidEditText.addTextChangedListener(new AfterTextChangedWatcher() {
@Override
public void afterTextChanged(final Editable s) {
okButton.setEnabled(!s.toString().isEmpty() && !nameEditText.getText().toString().isEmpty());
}
});
nameEditText.addTextChangedListener(new AfterTextChangedWatcher() {
@Override
public void afterTextChanged(final Editable s) {
okButton.setEnabled(!s.toString().isEmpty() && !uuidEditText.getText().toString().isEmpty());
}
});
okButton.setOnClickListener(onClickListener(nameEditText, uuidEditText, errorTextView));
dialogBuilder.setTitle(getString(R.string.add_contact_title))
.setView(view);
return dialogBuilder.create();
}
private View.OnClickListener onClickListener(@NonNull final EditText nameEditText,
@NonNull final EditText uuidEditText,
@NonNull final TextView errorTextView) {
return new View.OnClickListener() {
@Override
public void onClick(View v) {
//Perform checks before adding contact to DB
final String name = nameEditText.getText().toString();
final String uuid = uuidEditText.getText().toString();
final PushChatApplication application = (PushChatApplication) getActivity().getApplication();
final String ownUuid = application.getUUID();
if (ownUuid.equals(uuid)) {
errorTextView.setText(R.string.own_uuid_error);
errorTextView.setVisibility(View.VISIBLE);
} else if (DatabaseHelper.getInstance(getActivity()).isUuidAdded(uuid)) {
errorTextView.setText(R.string.uuid_already_added);
errorTextView.setVisibility(View.VISIBLE);
} else {
//check existing and add to DB
errorTextView.setVisibility(View.GONE); | NetworkController.getInstance().exist(uuid, existCallback(name, uuid, errorTextView)); | 4 |
DDoS/JICI | src/main/java/ca/sapon/jici/lexer/literal/NullLiteral.java | [
"public class Environment {\n // TODO make me thread safe\n private static final Map<String, Class<?>> DEFAULT_CLASSES = new HashMap<>();\n private final Map<String, Class<?>> classes = new LinkedHashMap<>(DEFAULT_CLASSES);\n private final Map<String, Variable> variables = new LinkedHashMap<>();\n\n ... | import ca.sapon.jici.evaluator.Environment;
import ca.sapon.jici.evaluator.EvaluatorException;
import ca.sapon.jici.evaluator.value.Value;
import ca.sapon.jici.evaluator.value.ValueKind;
import ca.sapon.jici.evaluator.type.NullType;
import ca.sapon.jici.evaluator.type.Type;
import ca.sapon.jici.lexer.TokenID; | /*
* This file is part of JICI, licensed under the MIT License (MIT).
*
* Copyright (c) 2015-2016 Aleksi Sapon <http://sapon.ca/jici/>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package ca.sapon.jici.lexer.literal;
public class NullLiteral extends Literal {
private static final String nullSource = "null";
private NullLiteral(int index) {
super(TokenID.LITERAL_NULL, nullSource, index);
}
@Override
public boolean asBoolean() {
throw new EvaluatorException("Cannot convert an object to a boolean", this);
}
@Override
public byte asByte() {
throw new EvaluatorException("Cannot convert an object to a byte", this);
}
@Override
public short asShort() {
throw new EvaluatorException("Cannot convert an object to a short", this);
}
@Override
public char asChar() {
throw new EvaluatorException("Cannot convert an object to a char", this);
}
@Override
public int asInt() {
throw new EvaluatorException("Cannot convert an object to an int", this);
}
@Override
public long asLong() {
throw new EvaluatorException("Cannot convert an object to a long", this);
}
@Override
public float asFloat() {
throw new EvaluatorException("Cannot convert an object to a float", this);
}
@Override
public double asDouble() {
throw new EvaluatorException("Cannot convert an object to a double", this);
}
@Override
public Object asObject() {
return null;
}
@Override
public String asString() {
return "null";
}
@Override
public <T> T as() {
return null;
}
@Override
public ValueKind getKind() {
return ValueKind.OBJECT;
}
@Override
public boolean isPrimitive() {
return false;
}
@Override
public Class<?> getTypeClass() {
return null;
}
@Override
public Type getType(Environment environment) {
return NullType.THE_NULL;
}
public static boolean is(String source) {
return nullSource.equals(source);
}
@Override | public Value getValue(Environment environment) { | 2 |
Vauff/Maunz-Discord | src/com/vauff/maunzdiscord/threads/ReactionAddThread.java | [
"public abstract class AbstractCommand\n{\n\t/**\n\t * Holds all messages as keys which await a reaction by a specific user.\n\t * The values hold an instance of {@link Await}\n\t */\n\tpublic static final HashMap<Snowflake, Await> AWAITED = new HashMap<>();\n\n\t/**\n\t * Enum holding the different bot permissions... | import com.vauff.maunzdiscord.commands.templates.AbstractCommand;
import com.vauff.maunzdiscord.commands.templates.AbstractLegacyCommand;
import com.vauff.maunzdiscord.commands.templates.AbstractSlashCommand;
import com.vauff.maunzdiscord.core.Logger;
import com.vauff.maunzdiscord.core.Util;
import com.vauff.maunzdiscord.objects.Await;
import discord4j.core.event.domain.message.ReactionAddEvent;
import discord4j.core.object.entity.Message;
import discord4j.rest.http.client.ClientException;
import java.util.Random; | package com.vauff.maunzdiscord.threads;
public class ReactionAddThread implements Runnable
{
private ReactionAddEvent event;
private Message message;
private Thread thread;
private String name;
public ReactionAddThread(ReactionAddEvent passedEvent, Message passedMessage, String passedName)
{
event = passedEvent;
message = passedMessage;
name = passedName;
}
public void start()
{
if (thread == null)
{
thread = new Thread(this, name);
thread.start();
}
}
public void run()
{
try
{ | if (AbstractCommand.AWAITED.containsKey(message.getId()) && event.getUser().block().getId().equals(AbstractCommand.AWAITED.get(message.getId()).getID()) && event.getEmoji().asUnicodeEmoji().isPresent()) | 0 |
edouardhue/comeon | src/main/java/comeon/ui/media/MediaMetadataPanel.java | [
"public interface Core {\n\n String EXTERNAL_METADATA_KEY = \"external\";\n\n String[] PICTURE_EXTENSIONS = { \"jpg\", \"jpeg\" };\n\n String[] AUDIO_EXTENSIONS = { \"ogg\", \"flac\", \"wav\" };\n\n void addMedia(final File[] files, final Template defautTemplate, final ExternalMetadataSource<?> external... | import comeon.core.Core;
import comeon.ui.UI;
import comeon.ui.media.metadata.ExternalMetadataTable;
import comeon.ui.media.metadata.MediaMetadataTable;
import comeon.ui.media.metadata.OtherMetadataTable;
import org.apache.commons.beanutils.DynaBean;
import javax.swing.*;
import java.awt.*;
import java.util.HashMap;
import java.util.Map; | package comeon.ui.media;
final class MediaMetadataPanel extends JPanel {
private static final long serialVersionUID = 1L;
public static final int PREVIEW_WIDTH = (int) (UI.METADATA_PANEL_WIDTH * 0.9);
public MediaMetadataPanel(final MediaPanels panels) {
super(new BorderLayout());
this.setMinimumSize(new Dimension(UI.METADATA_PANEL_WIDTH, 0));
this.setMaximumSize(new Dimension(UI.METADATA_PANEL_WIDTH, Integer.MAX_VALUE));
this.setBackground(UI.NEUTRAL_GREY);
this.setOpaque(true);
final Dimension previewPanelDimension = new Dimension(UI.METADATA_PANEL_WIDTH, UI.METADATA_PANEL_WIDTH);
final Dimension previewDimension;
if (panels.getThumbnail().getWidth() >= panels.getThumbnail().getHeight()) {
previewDimension = ConstrainedAxis.HORIZONTAL.getPreviewPanelDimension(panels.getThumbnail(), PREVIEW_WIDTH);
} else {
previewDimension = ConstrainedAxis.VERTICAL.getPreviewPanelDimension(panels.getThumbnail(), PREVIEW_WIDTH);
}
final MediaPreviewPanel previewPanel = new MediaPreviewPanel(panels, previewPanelDimension,
(previewPanelDimension.width - previewDimension.width) / 2,
(previewPanelDimension.height - previewDimension.height) / 2);
this.add(previewPanel, BorderLayout.NORTH);
final Box metadataBox = new Box(BoxLayout.Y_AXIS);
final Map<String, Object> otherMetadata = new HashMap<>();
for (final Map.Entry<String, Object> dir : panels.getMedia().getMetadata().entrySet()) {
if (dir.getValue() instanceof DynaBean) {
final MediaMetadataTable table = new MediaMetadataTable(dir.getKey(), (DynaBean) dir.getValue());
metadataBox.add(table, 0); | } else if (Core.EXTERNAL_METADATA_KEY.equals(dir.getKey())) { | 0 |
douo/ActivityBuilder | library/src/main/java/info/dourok/esactivity/BaseResultConsumer.java | [
"@FunctionalInterface\npublic interface BiConsumer<T, U> {\n\n /**\n * Performs this operation on the given arguments.\n *\n * @param t the first input argument\n * @param u the second input argument\n */\n void accept(T t, U u);\n\n}",
"@FunctionalInterface\npublic interface Consumer<T>... | import android.app.Activity;
import android.content.Intent;
import android.support.annotation.Nullable;
import info.dourok.esactivity.function.BiConsumer;
import info.dourok.esactivity.function.Consumer;
import info.dourok.esactivity.function.TriConsumer;
import info.dourok.esactivity.reference.ActivityReferenceUpdater;
import info.dourok.esactivity.reference.FragmentReferenceUpdater;
import info.dourok.esactivity.reference.ViewReferenceUpdater;
import java.util.ArrayList;
import java.util.List; | package info.dourok.esactivity;
/**
* @author tiaolins
* @param <A> the starter activity
* @date 2017/8/6
*/
public class BaseResultConsumer<A extends Activity>
implements TriConsumer<Activity, Integer, Intent>, LambdaStateCallback {
private BiConsumer<Integer, Intent> biConsumer;
private Consumer<Intent> okConsumer;
private Consumer<Intent> cancelConsumer;
private List<LambdaStateCallback> callbackList = new ArrayList<>(4);
{ | callbackList.add(new ActivityReferenceUpdater()); | 3 |
mojohaus/jaxb2-maven-plugin | src/test/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/JavaDocExtractorTest.java | [
"public class ClassLocation extends PackageLocation {\n\n // Internal state\n private String className;\n private String classXmlName;\n\n /**\n * Creates a new ClassLocation with the supplied package and class names.\n *\n * @param packageName The name of the package for a class potentiall... | import org.codehaus.mojo.jaxb2.BufferingLog;
import org.codehaus.mojo.jaxb2.schemageneration.postprocessing.javadoc.location.ClassLocation;
import org.codehaus.mojo.jaxb2.schemageneration.postprocessing.javadoc.location.FieldLocation;
import org.codehaus.mojo.jaxb2.schemageneration.postprocessing.javadoc.location.MethodLocation;
import org.codehaus.mojo.jaxb2.schemageneration.postprocessing.javadoc.location.PackageLocation;
import org.codehaus.mojo.jaxb2.shared.FileSystemUtilities;
import org.codehaus.mojo.jaxb2.shared.Validate;
import org.codehaus.mojo.jaxb2.shared.filters.Filter;
import org.codehaus.mojo.jaxb2.shared.filters.Filters;
import org.codehaus.mojo.jaxb2.shared.filters.pattern.PatternFileFilter;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import org.junit.Ignore; | package org.codehaus.mojo.jaxb2.schemageneration.postprocessing.javadoc;
/**
* @author <a href="mailto:lj@jguru.se">Lennart Jörelid</a>, jGuru Europe AB
*/
public class JavaDocExtractorTest {
// Shared state
private File javaDocBasicDir;
private File javaDocAnnotatedDir;
private File javaDocEnumsDir;
private File javaDocXmlWrappersDir;
private BufferingLog log;
@Before
public void setupSharedState() {
log = new BufferingLog(BufferingLog.LogLevel.DEBUG);
// Find the desired directory
final URL dirURL = getClass()
.getClassLoader()
.getResource("testdata/schemageneration/javadoc/basic");
this.javaDocBasicDir = new File(dirURL.getPath());
Assert.assertTrue(javaDocBasicDir.exists() && javaDocBasicDir.isDirectory());
final URL annotatedDirURL = getClass()
.getClassLoader()
.getResource("testdata/schemageneration/javadoc/annotated");
this.javaDocAnnotatedDir = new File(annotatedDirURL.getPath());
Assert.assertTrue(javaDocAnnotatedDir.exists() && javaDocAnnotatedDir.isDirectory());
final URL enumsDirURL = getClass()
.getClassLoader()
.getResource("testdata/schemageneration/javadoc/enums");
this.javaDocEnumsDir = new File(enumsDirURL.getPath());
Assert.assertTrue(javaDocEnumsDir.exists() && javaDocEnumsDir.isDirectory());
final URL wrappersDirURL = getClass()
.getClassLoader()
.getResource("testdata/schemageneration/javadoc/xmlwrappers");
this.javaDocXmlWrappersDir = new File(wrappersDirURL.getPath());
Assert.assertTrue(javaDocXmlWrappersDir.exists() && javaDocXmlWrappersDir.isDirectory());
}
@Test
public void validateLogStatementsDuringProcessing() {
// Assemble
final JavaDocExtractor unitUnderTest = new JavaDocExtractor(log);
final List<File> sourceDirs = Arrays.<File>asList(javaDocBasicDir);
final List<File> sourceFiles = FileSystemUtilities.resolveRecursively(sourceDirs, null, log);
// Act
unitUnderTest.addSourceFiles(sourceFiles);
final SearchableDocumentation ignoredResult = unitUnderTest.process();
// Assert
final SortedMap<String, Throwable> logBuffer = log.getLogBuffer();
final List<String> keys = new ArrayList<String>(logBuffer.keySet());
/*
* 000: (DEBUG) Accepted file [/Users/lj/Development/Projects/Codehaus/github_jaxb2_plugin/target/test-classes/testdata/schemageneration/javadoc/basic/NodeProcessor.java],
* 001: (INFO) Processing [1] java sources.,
* 002: (DEBUG) Added package-level JavaDoc for [basic],
* 003: (DEBUG) Added class-level JavaDoc for [basic.NodeProcessor],
* 004: (DEBUG) Added method-level JavaDoc for [basic.NodeProcessor#accept(org.w3c.dom.Node)],
* 005: (DEBUG) Added method-level JavaDoc for [basic.NodeProcessor#process(org.w3c.dom.Node)]]
*/
Assert.assertEquals(6, keys.size());
Assert.assertEquals("001: (INFO) Processing [1] java sources.", keys.get(1));
Assert.assertEquals("002: (DEBUG) Added package-level JavaDoc for [basic]", keys.get(2));
Assert.assertEquals("003: (DEBUG) Added class-level JavaDoc for [basic.NodeProcessor]", keys.get(3));
Assert.assertEquals("004: (DEBUG) Added method-level JavaDoc for [basic.NodeProcessor#accept(org.w3c.dom.Node)]",
keys.get(4));
Assert.assertEquals("005: (DEBUG) Added method-level JavaDoc for [basic.NodeProcessor#process(org.w3c.dom.Node)]",
keys.get(5));
}
@Test
@Ignore
public void validateExtractingXmlAnnotatedName() throws Exception {
// Assemble
final JavaDocExtractor unitUnderTest = new JavaDocExtractor(log);
// Act
final SearchableDocumentation result = getSearchableDocumentationFor(unitUnderTest, 2, javaDocAnnotatedDir);
// Assert
final String prefix = "testdata.schemageneration.javadoc.annotated.";
final String fieldAccessPrefix = prefix + "AnnotatedXmlNameAnnotatedClassWithFieldAccessTypeName#";
final String methodAccessPrefix = prefix + "AnnotatedXmlNameAnnotatedClassWithMethodAccessTypeName#";
// First, check the field-annotated class.
final SortableLocation stringFieldLocation = result.getLocation(fieldAccessPrefix + "annotatedStringField");
final SortableLocation integerFieldLocation = result.getLocation(fieldAccessPrefix + "annotatedIntegerField");
final SortableLocation stringMethodLocation = result.getLocation(fieldAccessPrefix + "getStringField()");
final SortableLocation integerMethodLocation = result.getLocation(fieldAccessPrefix + "getIntegerField()");
Assert.assertTrue(stringFieldLocation instanceof FieldLocation);
Assert.assertTrue(integerFieldLocation instanceof FieldLocation); | Assert.assertTrue(stringMethodLocation instanceof MethodLocation); | 2 |
EpicEricEE/ShopChest | src/main/java/de/epiceric/shopchest/config/Config.java | [
"public class ShopChest extends JavaPlugin {\n\n private static ShopChest instance;\n\n private Config config;\n private HologramFormat hologramFormat;\n private ShopCommand shopCommand;\n private Economy econ = null;\n private Database database;\n private boolean isUpdateNeeded = false;\n p... | import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.Reader;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.inventory.ItemStack;
import de.epiceric.shopchest.ShopChest;
import de.epiceric.shopchest.language.LanguageUtils;
import de.epiceric.shopchest.sql.Database;
import de.epiceric.shopchest.utils.ItemUtils;
import de.epiceric.shopchest.utils.Utils; | package de.epiceric.shopchest.config;
public class Config {
/**
* The item with which a player can click a shop to retrieve information
**/
public static ItemStack shopInfoItem;
/**
* The default value for the custom WorldGuard flag 'create-shop'
**/
public static boolean wgAllowCreateShopDefault;
/**
* The default value for the custom WorldGuard flag 'use-admin-shop'
**/
public static boolean wgAllowUseAdminShopDefault;
/**
* The default value for the custom WorldGuard flag 'use-shop'
**/
public static boolean wgAllowUseShopDefault;
/**
* The types of town plots residents are allowed to create shops in
**/
public static List<String> townyShopPlotsResidents;
/**
* The types of town plots the mayor is allowed to create shops in
**/
public static List<String> townyShopPlotsMayor;
/**
* The types of town plots the king is allowed to create shops in
**/
public static List<String> townyShopPlotsKing;
/**
* The events of AreaShop when shops in that region should be removed
**/
public static List<String> areashopRemoveShopEvents;
/**
* The hostname used in ShopChest's MySQL database
**/
public static String databaseMySqlHost;
/**
* The port used for ShopChest's MySQL database
**/
public static int databaseMySqlPort;
/**
* The database used for ShopChest's MySQL database
**/
public static String databaseMySqlDatabase;
/**
* The username used in ShopChest's MySQL database
**/
public static String databaseMySqlUsername;
/**
* The password used in ShopChest's MySQL database
**/
public static String databaseMySqlPassword;
/**
* The prefix to be used for database tables
*/
public static String databaseTablePrefix;
/**
* The database type used for ShopChest
**/ | public static Database.DatabaseType databaseType; | 2 |
packetpirate/Generic-Zombie-Shooter | GenericZombieShooter/src/genericzombieshooter/structures/weapons/Landmine.java | [
"public class Player extends Rectangle2D.Double {\r\n // Final variables.\r\n public static final int DEFAULT_HEALTH = 150;\r\n public static final long INVINCIBILITY_LENGTH = 3000;\r\n private static final double MOVE_SPEED = 2; // How many pixels per tick the player moves.\r\n public static final d... | import java.util.Iterator;
import java.util.List;
import genericzombieshooter.actors.Player;
import genericzombieshooter.actors.Zombie;
import genericzombieshooter.misc.Globals;
import genericzombieshooter.misc.Images;
import genericzombieshooter.misc.Sounds;
import genericzombieshooter.structures.Explosion;
import genericzombieshooter.structures.Particle;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.event.KeyEvent;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;
import java.util.Collections;
| /**
This file is part of Generic Zombie Shooter.
Generic Zombie Shooter is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Generic Zombie Shooter is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Generic Zombie Shooter. If not, see <http://www.gnu.org/licenses/>.
**/
package genericzombieshooter.structures.weapons;
/**
* Used to represent a landmine weapon.
* @author Darin Beaudreau
*/
public class Landmine extends Weapon {
// Final Variables
private static final int WEAPON_PRICE = 750;
private static final int AMMO_PRICE = 400;
private static final int DEFAULT_AMMO = 1;
private static final int MAX_AMMO = 3;
private static final int AMMO_PER_USE = 1;
| private static final int DAMAGE_PER_EXPLOSION = (500 / (int)Globals.SLEEP_TIME);
| 2 |
qqq3/good-weather | app/src/main/java/org/asdtm/goodweather/widget/LessWidgetProvider.java | [
"public class MainActivity extends BaseActivity implements AppBarLayout.OnOffsetChangedListener {\n\n private static final String TAG = \"MainActivity\";\n\n private static final long LOCATION_TIMEOUT_IN_MS = 30000L;\n\n private TextView mIconWeatherView;\n private TextView mTemperatureView;\n privat... | import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.widget.RemoteViews;
import org.asdtm.goodweather.MainActivity;
import org.asdtm.goodweather.R;
import org.asdtm.goodweather.service.LocationUpdateService;
import org.asdtm.goodweather.utils.AppPreference;
import org.asdtm.goodweather.utils.AppWidgetProviderAlarm;
import org.asdtm.goodweather.utils.Constants;
import org.asdtm.goodweather.utils.Utils;
import java.util.Locale; | package org.asdtm.goodweather.widget;
public class LessWidgetProvider extends AppWidgetProvider {
private static final String TAG = "WidgetLessInfo";
@Override
public void onEnabled(Context context) {
super.onEnabled(context);
AppWidgetProviderAlarm widgetProviderAlarm =
new AppWidgetProviderAlarm(context, LessWidgetProvider.class);
widgetProviderAlarm.setAlarm();
}
@Override
public void onReceive(Context context, Intent intent) {
switch (intent.getAction()) {
case Constants.ACTION_FORCED_APPWIDGET_UPDATE:
if(AppPreference.isUpdateLocationEnabled(context)) {
context.startService(new Intent(context, LocationUpdateService.class));
} else {
context.startService(new Intent(context, LessWidgetService.class));
}
break;
case Intent.ACTION_LOCALE_CHANGED:
context.startService(new Intent(context, LessWidgetService.class));
break;
case Constants.ACTION_APPWIDGET_THEME_CHANGED:
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
ComponentName componentName = new ComponentName(context, LessWidgetProvider.class);
int[] appWidgetIds = appWidgetManager.getAppWidgetIds(componentName);
onUpdate(context, appWidgetManager, appWidgetIds);
break;
case Constants.ACTION_APPWIDGET_UPDATE_PERIOD_CHANGED:
AppWidgetProviderAlarm widgetProviderAlarm =
new AppWidgetProviderAlarm(context, LessWidgetProvider.class);
if (widgetProviderAlarm.isAlarmOff()) {
break;
} else {
widgetProviderAlarm.setAlarm();
}
break;
default:
super.onReceive(context, intent);
}
}
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
super.onUpdate(context, appWidgetManager, appWidgetIds);
for (int appWidgetId : appWidgetIds) {
RemoteViews remoteViews = new RemoteViews(context.getPackageName(),
R.layout.widget_less_3x1);
setWidgetTheme(context, remoteViews);
preLoadWeather(context, remoteViews);
Intent intent = new Intent(context, LessWidgetProvider.class);
intent.setAction(Constants.ACTION_FORCED_APPWIDGET_UPDATE);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
remoteViews.setOnClickPendingIntent(R.id.widget_button_refresh, pendingIntent);
Intent intentStartActivity = new Intent(context, MainActivity.class);
PendingIntent pendingIntent2 = PendingIntent.getActivity(context, 0,
intentStartActivity, 0);
remoteViews.setOnClickPendingIntent(R.id.widget_root, pendingIntent2);
appWidgetManager.updateAppWidget(appWidgetId, remoteViews);
}
context.startService(new Intent(context, LessWidgetService.class));
}
@Override
public void onDisabled(Context context) {
super.onDisabled(context);
AppWidgetProviderAlarm appWidgetProviderAlarm =
new AppWidgetProviderAlarm(context, LessWidgetProvider.class);
appWidgetProviderAlarm.cancelAlarm();
}
private void preLoadWeather(Context context, RemoteViews remoteViews) {
SharedPreferences weatherPref = context.getSharedPreferences(Constants.PREF_WEATHER_NAME,
Context.MODE_PRIVATE); | String temperatureScale = Utils.getTemperatureScale(context); | 5 |
lob/lob-java | src/main/java/com/lob/model/Template.java | [
"public class APIException extends LobException {\n\n private static final long serialVersionUID = 1L;\n\n @JsonCreator\n public APIException(@JsonProperty(\"error\") final Map<String, Object> error) {\n super((String)error.get(\"message\"), (Integer)error.get(\"status_code\"));\n }\n\n}",
"pub... | import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lob.exception.APIException;
import com.lob.exception.AuthenticationException;
import com.lob.exception.InvalidRequestException;
import com.lob.exception.ParsingException;
import com.lob.exception.RateLimitException;
import com.lob.net.APIResource;
import com.lob.net.LobResponse;
import com.lob.net.RequestOptions;
import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.time.ZonedDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map; | public boolean getSuggestJsonEditor() {
return suggestJsonEditor;
}
public String getDescription() {
return description;
}
public String getEngine() {
return engine;
}
public String getHtml() {
return html;
}
public ZonedDateTime getDateCreated() {
return dateCreated;
}
public ZonedDateTime getDateModified() {
return dateModified;
}
public String getObject() {
return object;
}
}
@JsonProperty private final String id;
@JsonProperty private final String description;
@JsonProperty private final List<TemplateVersion> versions;
@JsonProperty private final TemplateVersion publishedVersion;
@JsonProperty private final Map<String, String> metadata;
@JsonProperty private final ZonedDateTime dateCreated;
@JsonProperty private final ZonedDateTime dateModified;
@JsonProperty private final String object;
@JsonCreator
public Template(
@JsonProperty("id") final String id,
@JsonProperty("description") final String description,
@JsonProperty("versions") final List<TemplateVersion> versions,
@JsonProperty("published_version") final TemplateVersion publishedVersion,
@JsonProperty("metadata") final Map<String, String> metadata,
@JsonProperty("date_created") final ZonedDateTime dateCreated,
@JsonProperty("date_modified") final ZonedDateTime dateModified,
@JsonProperty("object") final String object
) {
this.id = id;
this.description = description;
this.versions = versions;
this.publishedVersion = publishedVersion;
this.metadata = metadata;
this.dateCreated = dateCreated;
this.dateModified = dateModified;
this.object = object;
}
public String getId() {
return id;
}
public String getDescription() {
return description;
}
public List<TemplateVersion> getVersions() { return versions; }
public TemplateVersion getPublishedVersion() { return publishedVersion; }
public Map<String, String> getMetadata() {
return metadata;
}
public ZonedDateTime getDateCreated() {
return dateCreated;
}
public ZonedDateTime getDateModified() {
return dateModified;
}
public String getObject() {
return object;
}
public static final class RequestBuilder {
private Map<String, Object> params = new HashMap<String, Object>();
private boolean isMultipart = false;
private ObjectMapper objectMapper = new ObjectMapper();
public RequestBuilder() {
}
public Template.RequestBuilder setDescription(String description) {
params.put("description", description);
return this;
}
public Template.RequestBuilder setHtml(String html) {
params.put("html", html);
return this;
}
public Template.RequestBuilder setMetadata(Map<String, String> metadata) {
params.put("metadata", metadata);
return this;
}
public Template.RequestBuilder setEngine(String engine) {
params.put("engine", engine);
return this;
}
public LobResponse<Template> create() throws APIException, IOException, AuthenticationException, InvalidRequestException, RateLimitException {
return create(null);
}
| public LobResponse<Template> create(RequestOptions options) throws APIException, IOException, AuthenticationException, InvalidRequestException, RateLimitException { | 7 |
SkaceKamen/sqflint | src/cz/zipek/sqflint/sqf/operators/ThenOperator.java | [
"public class Linter extends SQFParser {\n\tpublic static final int CODE_OK = 0;\n\tpublic static final int CODE_ERR = 1;\n\t\n\tprivate final List<SQFParseException> errors = new ArrayList<>();\n\tprivate final List<Warning> warnings = new ArrayList<>();\n\t\n\tprivate final List<SQFInclude> includes = new ArrayLi... | import cz.zipek.sqflint.linter.Linter;
import cz.zipek.sqflint.linter.SQFParseException;
import cz.zipek.sqflint.sqf.SQFArray;
import cz.zipek.sqflint.sqf.SQFBlock;
import cz.zipek.sqflint.sqf.SQFContext;
import cz.zipek.sqflint.sqf.SQFExpression;
import cz.zipek.sqflint.sqf.SQFUnit; | /*
* The MIT License
*
* Copyright 2016 Jan Zípek (jan at zipek.cz).
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package cz.zipek.sqflint.sqf.operators;
/**
*
* @author Jan Zípek (jan at zipek.cz)
*/
public class ThenOperator extends Operator {
@Override | public void analyze(Linter source, SQFContext context, SQFExpression expression) { | 0 |
stuart-warren/logit | src/main/java/com/stuartwarren/logit/jul/Layout.java | [
"public final class ExceptionField extends Field {\n \n private static final ExceptionField FIELD = new ExceptionField();\n \n private ExceptionField() {\n this.setSection(ROOT.EXCEPTION);\n Field.register(this);\n }\n \n public final static void put(final IFieldName key, final St... | import com.stuartwarren.logit.fields.ExceptionField;
import com.stuartwarren.logit.fields.ExceptionField.EXCEPTION;
import com.stuartwarren.logit.fields.LocationField;
import com.stuartwarren.logit.fields.LocationField.LOCATION;
import com.stuartwarren.logit.layout.IFrameworkLayout;
import com.stuartwarren.logit.layout.LayoutFactory;
import com.stuartwarren.logit.layout.Log;
import com.stuartwarren.logit.utils.LogitLog;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Formatter;
import java.util.logging.Level;
import java.util.logging.LogManager;
import java.util.logging.LogRecord; | /**
*
*/
package com.stuartwarren.logit.jul;
/**
* @author Stuart Warren
* @date 6 Oct 2013
*
*/
public class Layout extends Formatter implements IFrameworkLayout {
private transient final String prefix = Layout.class.getName();
private transient final LogManager manager = LogManager.getLogManager();
private String layoutType = "log";
private String detailThreshold = Level.WARNING.toString();
private String fields;
private Map<String, String> parsedFields;
private String tags;
private transient final LayoutFactory layoutFactory = new LayoutFactory();
private transient final LayoutFactory layout;
private transient boolean getLocationInfo = false;
public Layout() {
super();
LogitLog.debug("Jul layout in use.");
configure();
this.layout = layoutFactory.createLayout(this.layoutType);
}
/**
*
*/
private void configure() {
setLayoutType(manager.getProperty(prefix + ".layoutType"));
setDetailThreshold(manager.getProperty(prefix + ".detailThreshold"));
setFields(manager.getProperty(prefix + ".fields"));
setTags(manager.getProperty(prefix + ".tags"));
}
/* (non-Javadoc)
* @see java.util.logging.Formatter#format(java.util.logging.LogRecord)
*/
@Override
public String format(final LogRecord record) { | final Log log = doFormat(record); | 6 |
EthanCo/Halo-Turbo | sample/src/main/java/com/ethanco/sample/MulticastClientActivity.java | [
"public class Halo extends AbstractHalo {\n private ISocket haloImpl;\n\n public Halo() {\n this(new Builder());\n }\n\n public Halo(Builder builder) {\n this.haloImpl = SocketFactory.create(builder);\n }\n\n @Override\n public boolean start() {\n return this.haloImpl.start... | import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Toast;
import com.ethanco.halo.turbo.Halo;
import com.ethanco.halo.turbo.ads.IHandlerAdapter;
import com.ethanco.halo.turbo.ads.ISession;
import com.ethanco.halo.turbo.impl.handler.HexLogHandler;
import com.ethanco.halo.turbo.type.Mode;
import com.ethanco.json.convertor.convert.ObjectJsonByteConvertor;
import com.ethanco.sample.databinding.ActivityMulticastClientBinding;
import java.util.concurrent.Executors; | package com.ethanco.sample;
public class MulticastClientActivity extends AppCompatActivity {
private static final String TAG = "Z-Client";
private ActivityMulticastClientBinding binding;
private ScrollBottomTextWatcher watcher;
private Halo halo;
private ISession session;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = DataBindingUtil.setContentView(this, R.layout.activity_multicast_client);
halo = new Halo.Builder()
.setMode(Mode.MULTICAST)
.setSourcePort(19601)
.setTargetPort(19602)
.setTargetIP("224.0.0.1")
.setBufferSize(512)
.addHandler(new HexLogHandler(TAG))
//.addHandler(new StringLogHandler(TAG))
.addHandler(new DemoHandler()) | .addConvert(new ObjectJsonByteConvertor()) | 5 |
popo1379/popomusic | app/src/main/java/com/popomusic/presenter/JKPresenter.java | [
"public class MyApplication extends Application {\n public static DaoSession mDaoSession;\n public static DaoSession searchDaoSession;\n public static DaoSession videoDaoSession;\n public static Context mContext;\n\n // private static RefWatcher mRefWatcher;\n @Override\n public void onCreat... | import android.widget.Toast;
import com.popomusic.MyApplication;
import com.popomusic.activity.JKActivity;
import com.popomusic.api.ApiManager;
import com.popomusic.bean.Constant;
import com.popomusic.bean.MusicBean;
import com.popomusic.data.JKMusicData;
import com.popomusic.util.LogUtils;
import java.util.List;
import io.reactivex.android.schedulers.AndroidSchedulers;
import rx.Observable;
import rx.schedulers.Schedulers; | package com.popomusic.presenter;
/**
* Created by dingmouren on 2017/2/7.
* 从数据库取数据,就不用这个类了,后期考虑可能分页加载什么的,先不删除了
*/
public class JKPresenter implements JKMusicData.Presenter {
private static final String TAG = JKPresenter.class.getName();
private JKMusicData.View mView;
private JKActivity jkActivity;
public JKPresenter(JKMusicData.View view) {
this.mView = view;
}
private List<MusicBean> mList;
@Override
public void requestData() {
ApiManager.getApiManager().getQQMusicApiService()
.getQQMusic(Constant.QQ_MUSIC_APP_ID,Constant.QQ_MUSIC_SIGN,Constant.MUSIC_KOREA)
.subscribeOn(io.reactivex.schedulers.Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(qqMusicBodyQQMusicResult -> parseData(Constant.MUSIC_KOREA,qqMusicBodyQQMusicResult.getShowapi_res_body().getPagebean().getSonglist()),this:: loadError);
}
private void loadError(Throwable throwable) {
throwable.printStackTrace();
LogUtils.w("JKPresenter","loadError RXjava异常!!");
mView.hideProgress(); | Toast.makeText(MyApplication.mContext,"网络异常!",Toast.LENGTH_SHORT).show(); | 0 |
DevComPack/setupmaker | src/main/java/com/dcp/sm/gui/pivot/facades/SetFacade.java | [
"public class IOFactory\n{\n //ISO3 language codes\n public static String[] iso3Codes;\n //File type extensions\n public static String[] archiveExt;// = {\"zip\", \"rar\", \"jar\", \"iso\"};\n public static String[] exeExt;// = {\"exe\", \"jar\", \"cmd\", \"sh\", \"bat\"};\n public static String[]... | import java.util.TreeMap;
import org.apache.pivot.collections.ArrayList;
import org.apache.pivot.collections.List;
import org.apache.pivot.collections.Sequence;
import org.apache.pivot.wtk.content.TreeBranch;
import org.apache.pivot.wtk.content.TreeNode;
import com.dcp.sm.config.io.IOFactory;
import com.dcp.sm.logic.factory.TypeFactory.FILE_TYPE;
import com.dcp.sm.logic.factory.CastFactory;
import com.dcp.sm.logic.factory.GroupFactory;
import com.dcp.sm.logic.factory.PackFactory;
import com.dcp.sm.logic.factory.TypeFactory.LOG_LEVEL;
import com.dcp.sm.logic.model.Group;
import com.dcp.sm.logic.model.Pack;
import com.dcp.sm.main.log.Out; | package com.dcp.sm.gui.pivot.facades;
public class SetFacade
{
// DATA
private List<TreeBranch> treeData; // Groups UI collection
private java.util.Map<Group, TreeBranch> branches; // Treeview Branch mapped to Group
private Pack packData;// Pack data copied for pasting to other packs
/**
* Set Tab Facade Constructor
* @param treeData: TreeView data
*/
public SetFacade(List<TreeBranch> treeData)
{
this.treeData = treeData;
branches = new TreeMap<Group, TreeBranch>();
}
/**
* Import/Create data from given lists of data (Scan)
* @param groups: list of scanned folders/groups (null if import packs only)
* @param packs: list of scanned packs
* @param groupTarget: if folder target is enabled, set pack install path to groups
*/
public boolean importDataFrom(List<Group> groups, List<Pack> packs, boolean folderGroup, boolean groupTarget)
{
//if (packs == null && groups == null) return false;
// Groups Import
GroupFactory.clear();
treeData.clear();
if (groups != null && folderGroup == true)
for(Group G:groups)// Fill Data from Scan folders
newGroup(G);
// Packs data save for same packs
if (packs != null) {
List<Pack> newPacks = new ArrayList<Pack>();
Pack pack;// pack data to restore
for(Pack p:packs) {
List<Pack> oldPacks = PackFactory.getByName(p.getName());
if (oldPacks.getLength() == 1) {// if only one pack with same filename
Out.print(LOG_LEVEL.DEBUG, "Pack " + p.getName() + " data restored.");
pack = new Pack(oldPacks.get(0));
pack.setGroup(p.getGroup());
}
else {// otherwise reset packs
pack = new Pack(p);
}
// remove install path if option disabled from scan
if (pack.getInstallPath().length() > 0 && groupTarget == false && pack.getInstallPath().equals(p.getGroupPath()))
pack.setInstallPath("");
// set group folder path if enabled from scan
else if (groupTarget == true)
pack.setInstallPath(p.getGroupPath());
// Group correct
if (folderGroup == true) {
boolean found = false;
for(Group g:GroupFactory.getGroups())
if (g.equals(pack.getGroup())) {
found = true;
pack.setGroup(g);// group rename bugfix: point to the new created group
break;
}
if (found == false)// bugfix: pack data restore groups no more available
pack.setGroup(null);
}
else pack.setGroup(null);
newPacks.add(pack);
}
// Packs Import
PackFactory.clear();
for(Pack p : newPacks) {// Fill Data from Scan files
newPack(p);
}
}
else PackFactory.clear();
return true;
}
////====================================================================================
/**
* Get Pack of a node
* @param node to cast
* @return Pack
*/
public Pack getPack(TreeNode node)
{
for(Pack P : PackFactory.getPacks()) {
if (P.getGroup() != null && P.equals(node))
return P;
}
return null;
}
/**
* Create a new Pack model
* @return pack created
*/
public boolean newPack(Pack pack)
{
// Data update
if (!PackFactory.addPack(pack))
return false;
// TreeView update
if (pack.getGroup() != null)
addNodeToBranch(pack);
return true;
}
/**
* Check if name is unique or already given to another pack
* @param pack name
* @return pack name is unique
*/
public boolean validatePack(String name)
{
int i = 0;
for(Pack p : PackFactory.getPacks()) {
if (p.getInstallName().equals(name)) i++;
}
if (i > 1) return false;
return true;
}
/**
* Delete a pack from memory
* @param pack to delete
*/
public boolean deletePack(Pack pack)
{
if (pack.getGroup() != null)
return false;
return PackFactory.removePack(pack);
}
////=====================================================================================
/**
* Get Group of a branch
* @param branch to cast
* @return Group
*/
public Group getGroup(TreeBranch branch) {
return GroupFactory.get(CastFactory.nodeToPath(branch));
}
/**
* Add a new group under an existing group or at TreeView root
* @param name of new group
* @param parent of new group
*/
public boolean newGroup(String name, String path)
{
Group parent = GroupFactory.get(path);
if (parent != null) {
Group group = new Group(name, parent);
if (GroupFactory.addGroup(group)) {
TreeBranch branch = CastFactory.groupToSingleBranch(group);
branches.get(parent).add(branch);
branches.put(group, branch);
Out.print(LOG_LEVEL.DEBUG, "Group added: " + group.getPath());
return true;
}
else return false;
}
else {
Group group = new Group(name);
if (GroupFactory.addGroup(group)) { | TreeBranch branch = new TreeBranch(IOFactory.imgFolder, name); | 0 |
t28hub/json2java4idea | core/src/test/java/io/t28/json2java/core/JavaConverterTest.java | [
"public class GeneratedAnnotationPolicy implements AnnotationPolicy {\n private final Class<?> klass;\n\n public GeneratedAnnotationPolicy(@Nonnull Class<?> klass) {\n this.klass = klass;\n }\n\n @Override\n public void apply(@Nonnull TypeSpec.Builder builder) {\n builder.addAnnotation(... | import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat;
import com.google.common.io.Files;
import io.t28.json2java.core.annotation.GeneratedAnnotationPolicy;
import io.t28.json2java.core.annotation.SuppressWarningsAnnotationPolicy;
import io.t28.json2java.core.io.JsonParserImpl;
import io.t28.json2java.core.naming.DefaultNamePolicy;
import io.t28.json2java.core.io.JavaBuilderImpl;
import org.junit.Before;
import org.junit.Test;
import javax.annotation.Nonnull;
import java.io.File;
import java.nio.charset.StandardCharsets;
import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy; | /*
* Copyright (c) 2017 Tatsuya Maki
*
* 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 io.t28.json2java.core;
public class JavaConverterTest {
private static final String JSON_RESOURCE_DIR = "src/test/resources/json";
private static final String JAVA_RESOURCE_DIR = "src/test/resources/java";
private static final String PACKAGE_NAME = "io.t28.test";
private JavaConverter underTest;
@Before
public void setUp() throws Exception {
final Configuration configuration = Configuration.builder()
.style(Style.NONE)
.classNamePolicy(DefaultNamePolicy.CLASS)
.methodNamePolicy(DefaultNamePolicy.METHOD)
.fieldNamePolicy(DefaultNamePolicy.FIELD)
.parameterNamePolicy(DefaultNamePolicy.PARAMETER)
.annotationPolicy(new SuppressWarningsAnnotationPolicy("all")) | .annotationPolicy(new GeneratedAnnotationPolicy(JavaConverter.class)) | 0 |
tarzasai/Flucso | src/net/ggelardi/flucso/FeedFragment.java | [
"public class FeedAdapter extends BaseAdapter {\n\n\tprivate Context context;\n\tprivate FFSession session;\n\tprivate OnClickListener listener;\n\tprivate LayoutInflater inflater;\n\t\n\tpublic Feed feed;\n\t\n\tpublic FeedAdapter(Context context, OnClickListener clickListener) {\n\t\tsuper();\n\t\t\n\t\tthis.cont... | import java.util.Timer;
import java.util.TimerTask;
import net.ggelardi.flucso.data.FeedAdapter;
import net.ggelardi.flucso.data.SubscrListAdapter;
import net.ggelardi.flucso.serv.Commons;
import net.ggelardi.flucso.serv.Commons.PK;
import net.ggelardi.flucso.serv.FFAPI;
import net.ggelardi.flucso.serv.FFAPI.Entry;
import net.ggelardi.flucso.serv.FFAPI.Feed;
import net.ggelardi.flucso.serv.FFAPI.Like;
import net.ggelardi.flucso.serv.FFAPI.SimpleResponse;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.DataSetObserver;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.util.Log;
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.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.squareup.picasso.Picasso.LoadedFrom;
import com.squareup.picasso.Target; | package net.ggelardi.flucso;
public class FeedFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener, OnClickListener {
public static final String FRAGMENT_TAG = "net.ggelardi.flucso.FeedFragment";
private static final int AMOUNT_BASE = 30;
private static final int AMOUNT_INCR = 20;
| private FeedAdapter adapter; | 0 |
bonigarcia/dualsub | src/test/java/io/github/bonigarcia/dualsub/test/TestTranslation.java | [
"public class DualSub {\n\n\tprivate static final Logger log = LoggerFactory.getLogger(DualSub.class);\n\n\t// Preferences and Properties\n\tprivate Preferences preferences;\n\tprivate Properties properties;\n\n\t// UI Elements\n\tprivate JFrame frame;\n\tprivate JList<File> leftSubtitles;\n\tprivate JList<File> ri... | import io.github.bonigarcia.dualsub.srt.Srt;
import io.github.bonigarcia.dualsub.srt.SrtUtils;
import io.github.bonigarcia.dualsub.translate.Language;
import io.github.bonigarcia.dualsub.translate.Translator;
import io.github.bonigarcia.dualsub.util.Charset;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.util.Properties;
import java.util.prefs.Preferences;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.github.bonigarcia.dualsub.gui.DualSub;
import io.github.bonigarcia.dualsub.srt.DualSrt;
import io.github.bonigarcia.dualsub.srt.Merger; | /*
* (C) Copyright 2014 Boni Garcia (http://bonigarcia.github.io/)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package io.github.bonigarcia.dualsub.test;
/**
* TestTranslation.
*
* @author Boni Garcia (boni.gg@gmail.com)
* @since 1.0.0
*/
public class TestTranslation {
private static final Logger log = LoggerFactory
.getLogger(TestTranslation.class);
@Test
public void testTranslation() { | Translator translate = Translator.getInstance(); | 6 |
leelit/STUer-client | app/src/main/java/com/leelit/stuer/module_treehole/CommentActivity.java | [
"public class TreeholeComment {\n\n int likeCount;\n\n int unlikeCount;\n\n List<Comment> comments;\n\n public int getLikeCount() {\n return likeCount;\n }\n\n public void setLikeCount(int likeCount) {\n this.likeCount = likeCount;\n }\n\n public int getUnlikeCount() {\n ... | import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.leelit.stuer.R;
import com.leelit.stuer.bean.TreeholeComment;
import com.leelit.stuer.bean.TreeholeLocalInfo;
import com.leelit.stuer.dao.TreeholeDao;
import com.leelit.stuer.module_treehole.presenter.CommentPresenter;
import com.leelit.stuer.module_treehole.viewinterface.ICommentView;
import com.leelit.stuer.utils.ProgressDialogUtils;
import com.leelit.stuer.utils.SharedAnimation;
import com.leelit.stuer.utils.UiUtils;
import java.util.ArrayList;
import java.util.List;
import butterknife.ButterKnife;
import butterknife.InjectView; | package com.leelit.stuer.module_treehole;
public class CommentActivity extends AppCompatActivity implements ICommentView {
@InjectView(R.id.toolbar)
Toolbar mToolbar;
@InjectView(R.id.treeholeView)
TreeholeView mTreeholeView;
@InjectView(R.id.likePic)
ImageView mLikePic;
@InjectView(R.id.likeCount)
TextView mLikeCount;
@InjectView(R.id.unlikePic)
ImageView mUnlikePic;
@InjectView(R.id.unlikeCount)
TextView mUnlikeCount;
@InjectView(R.id.recyclerView)
RecyclerView mRecyclerView;
@InjectView(R.id.likeLayout)
LinearLayout mLikeLayout;
@InjectView(R.id.unlikeLayout)
LinearLayout mUnlikeLayout;
@InjectView(R.id.text)
EditText mText;
@InjectView(R.id.send)
ImageView mSend;
@InjectView(R.id.nocomment)
TextView mNoComment;
private boolean isLike;
private boolean isUnlike;
private boolean mOriginalIsLike;
private boolean mOriginalIsUnlike;
| private TreeholeLocalInfo mTreeholeLocalInfo; | 1 |
maker56/UltimateSurvivalGames | UltimateSurvivalGames/src/me/maker56/survivalgames/game/GameManager.java | [
"public class Util {\r\n\t\r\n\t// ITEMSTACK\r\n\tpublic static boolean debug = false;\r\n\tprivate static Random random = new Random();\r\n\t\r\n\t@SuppressWarnings(\"deprecation\")\r\n\tpublic static ItemStack parseItemStack(String s) {\r\n\t\ttry {\r\n\t\t\tString[] gSplit = s.split(\" \");\r\n\t\t\tItemStack is... | import java.util.ArrayList;
import java.util.List;
import org.bukkit.Location;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player;
import me.maker56.survivalgames.Util;
import me.maker56.survivalgames.SurvivalGames;
import me.maker56.survivalgames.arena.Arena;
import me.maker56.survivalgames.commands.messages.MessageHandler;
import me.maker56.survivalgames.game.phases.CooldownPhase;
import me.maker56.survivalgames.game.phases.DeathmatchPhase;
import me.maker56.survivalgames.game.phases.IngamePhase;
import me.maker56.survivalgames.game.phases.VotingPhase;
import me.maker56.survivalgames.reset.Reset; | package me.maker56.survivalgames.game;
public class GameManager {
private List<Game> games = new ArrayList<>();
private static FileConfiguration cfg;
public GameManager() {
reinitializeDatabase();
loadAll();
}
public static void reinitializeDatabase() { | cfg = SurvivalGames.database; | 1 |
crazyhitty/Munch | app/src/main/java/com/crazyhitty/chdev/ks/munch/feeds/FeedsLoaderInteractor.java | [
"public class FeedItem {\n private String itemTitle, itemDesc, itemSourceUrl, itemLink, itemImgUrl, itemCategory, itemSource, itemPubDate, itemWebDesc, itemWebDescSync;\n private int itemCategoryImgId, itemBgId;\n\n public String getItemTitle() {\n if (itemTitle == null) {\n return \"\";\... | import android.content.Context;
import android.util.Log;
import com.crazyhitty.chdev.ks.munch.models.FeedItem;
import com.crazyhitty.chdev.ks.munch.models.SourceItem;
import com.crazyhitty.chdev.ks.munch.utils.DatabaseUtil;
import com.crazyhitty.chdev.ks.munch.utils.DateUtil;
import com.crazyhitty.chdev.ks.rssmanager.OnRssLoadListener;
import com.crazyhitty.chdev.ks.rssmanager.RssItem;
import com.crazyhitty.chdev.ks.rssmanager.RssReader;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List; | package com.crazyhitty.chdev.ks.munch.feeds;
/**
* Created by Kartik_ch on 11/5/2015.
*/
public class FeedsLoaderInteractor implements IFeedsLoaderInteractor, OnRssLoadListener {
private Context mContext;
private OnFeedsLoadedListener onFeedsLoadedListener;
public FeedsLoaderInteractor(Context context) {
mContext = context;
}
public void loadFeedsFromDb(final OnFeedsLoadedListener onFeedsLoadedListener) {
try {
DatabaseUtil databaseUtil = new DatabaseUtil(mContext);
onFeedsLoadedListener.onSuccess(databaseUtil.getAllFeeds(), false);
} catch (Exception e) {
onFeedsLoadedListener.onFailure("Failed to load all feeds from database");
}
}
public void loadFeedsFromDbBySource(final OnFeedsLoadedListener onFeedsLoadedListener, String source) {
try {
DatabaseUtil databaseUtil = new DatabaseUtil(mContext);
onFeedsLoadedListener.onSuccess(databaseUtil.getFeedsBySource(source), false);
} catch (Exception e) {
onFeedsLoadedListener.onFailure("Failed to load selected feeds from database");
}
}
public void loadFeedsAsync(final OnFeedsLoadedListener onFeedsLoadedListener, List<SourceItem> sourceItems) {
this.onFeedsLoadedListener = onFeedsLoadedListener;
String[] urlList = new String[sourceItems.size()];
String[] sourceList = new String[sourceItems.size()];
String[] categories = new String[sourceItems.size()];
int[] categoryImgIds = new int[sourceItems.size()];
for (int i = 0; i < urlList.length; i++) {
urlList[i] = sourceItems.get(i).getSourceUrl();
sourceList[i] = sourceItems.get(i).getSourceName();
categories[i] = sourceItems.get(i).getSourceCategoryName();
categoryImgIds[i] = sourceItems.get(i).getSourceCategoryImgId();
}
Log.e("url", urlList[0]);
RssReader rssReader = new RssReader(mContext, urlList, sourceList, categories, categoryImgIds, this);
rssReader.readRssFeeds();
}
private FeedItem getFeedItem(String title, String description, String link, String imgUrl, String sourceName, String sourceUrlShort, String category, String pubDate, int categoryImgId) {
FeedItem feedItem = new FeedItem();
feedItem.setItemTitle(title);
feedItem.setItemDesc(description);
feedItem.setItemLink(link);
feedItem.setItemImgUrl(imgUrl);
feedItem.setItemSource(sourceName);
feedItem.setItemSourceUrl(sourceUrlShort);
feedItem.setItemCategory(category);
feedItem.setItemPubDate(pubDate);
feedItem.setItemCategoryImgId(categoryImgId);
return feedItem;
}
@Override | public void onSuccess(List<RssItem> rssItems) { | 5 |
InfinityRaider/NinjaGear | src/main/java/com/infinityraider/ninjagear/item/ItemRopeCoil.java | [
"public class EntityRopeCoil extends EntityThrowableBase {\n //For client side spawning\n private EntityRopeCoil(EntityType<? extends EntityRopeCoil> type, World world) {\n super(type, world);\n }\n\n public EntityRopeCoil(World world, PlayerEntity thrower) {\n super(EntityRegistry.getInst... | import com.infinityraider.ninjagear.entity.EntityRopeCoil;
import com.infinityraider.ninjagear.reference.Names;
import com.infinityraider.ninjagear.reference.Reference;
import com.infinityraider.infinitylib.item.ItemBase;
import com.infinityraider.ninjagear.api.v1.IHiddenItem;
import com.infinityraider.ninjagear.registry.ItemRegistry;
import net.minecraft.client.util.ITooltipFlag;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ActionResult;
import net.minecraft.util.ActionResultType;
import net.minecraft.util.Hand;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.TranslationTextComponent;
import net.minecraft.world.World;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import javax.annotation.Nullable;
import javax.annotation.ParametersAreNonnullByDefault;
import java.util.List; | package com.infinityraider.ninjagear.item;
public class ItemRopeCoil extends ItemBase implements IHiddenItem {
public ItemRopeCoil() { | super(Names.Items.ROPE_COIL, new Properties().group(ItemRegistry.CREATIVE_TAB)); | 1 |
ajitsing/Sherlock | sherlock/src/androidTest/java/com/singhajit/sherlock/crashes/CrashActivityTest.java | [
"public class Sherlock {\n private static final String TAG = Sherlock.class.getSimpleName();\n private static Sherlock instance;\n private final SherlockDatabaseHelper database;\n private final CrashReporter crashReporter;\n private AppInfoProvider appInfoProvider;\n\n private Sherlock(Context context) {\n ... | import android.content.Context;
import android.content.Intent;
import android.support.test.InstrumentationRegistry;
import android.support.test.rule.ActivityTestRule;
import com.singhajit.sherlock.R;
import com.singhajit.sherlock.core.Sherlock;
import com.singhajit.sherlock.core.database.CrashRecord;
import com.singhajit.sherlock.core.database.DatabaseResetRule;
import com.singhajit.sherlock.core.database.SherlockDatabaseHelper;
import com.singhajit.sherlock.core.investigation.AppInfo;
import com.singhajit.sherlock.core.investigation.AppInfoProvider;
import com.singhajit.sherlock.core.investigation.Crash;
import com.singhajit.sherlock.crashes.activity.CrashActivity;
import org.junit.Rule;
import org.junit.Test;
import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.action.ViewActions.scrollTo;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.matcher.ViewMatchers.hasDescendant;
import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed;
import static android.support.test.espresso.matcher.ViewMatchers.withText;
import static com.singhajit.sherlock.CustomEspressoMatchers.withRecyclerView;
import static org.hamcrest.Matchers.allOf; | package com.singhajit.sherlock.crashes;
public class CrashActivityTest {
@Rule
public DatabaseResetRule databaseResetRule = new DatabaseResetRule();
@Rule
public ActivityTestRule<CrashActivity> rule = new ActivityTestRule<>(CrashActivity.class, true, false);
@Test
public void shouldRenderCrashDetails() throws Exception {
Context targetContext = InstrumentationRegistry.getTargetContext();
Sherlock.init(targetContext);
Sherlock.setAppInfoProvider(new AppInfoProvider() {
@Override | public AppInfo getAppInfo() { | 4 |
matburt/mobileorg-android | MobileOrg/src/main/java/com/matburt/mobileorg/gui/outline/OutlineAdapter.java | [
"public class AgendaFragment extends Fragment {\n\n class AgendaItem {\n public OrgNodeTimeDate.TYPE type;\n public OrgNode node;\n public String text;\n long time;\n public AgendaItem(OrgNode node, OrgNodeTimeDate.TYPE type, long time){\n this.node = node;\n ... | import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.view.ActionMode;
import android.support.v7.widget.RecyclerView;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.matburt.mobileorg.AgendaFragment;
import com.matburt.mobileorg.gui.theme.DefaultTheme;
import com.matburt.mobileorg.orgdata.OrgContract;
import com.matburt.mobileorg.orgdata.OrgFile;
import com.matburt.mobileorg.orgdata.OrgNode;
import com.matburt.mobileorg.orgdata.OrgProviderUtils;
import com.matburt.mobileorg.OrgNodeDetailActivity;
import com.matburt.mobileorg.OrgNodeDetailFragment;
import com.matburt.mobileorg.OrgNodeListActivity;
import com.matburt.mobileorg.R;
import com.matburt.mobileorg.util.OrgNodeNotFoundException;
import java.util.ArrayList;
import java.util.List; | OutlineAdapter.this.clearSelections();
}
@Override
public boolean onCreateActionMode(ActionMode actionMode, Menu menu) {
MenuInflater inflater = activity.getMenuInflater();
inflater.inflate(R.menu.main_context_action_bar, menu);
return true;
}
@Override
public boolean onActionItemClicked(ActionMode actionMode, MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.item_delete:
String message;
int numSelectedItems = getSelectedItemCount();
if (numSelectedItems == 1)
message = activity.getResources().getString(R.string.prompt_delete_file);
else {
message = activity.getResources().getString(R.string.prompt_delete_files);
message = message.replace("#", String.valueOf(numSelectedItems));
}
new AlertDialog.Builder(activity)
.setMessage(message)
.setIcon(android.R.drawable.ic_dialog_alert)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
deleteSelectedFiles();
}
})
.setNegativeButton(android.R.string.no, null).show();
return true;
}
return false;
}
};
private DefaultTheme theme;
public OutlineAdapter(AppCompatActivity activity) {
super();
this.activity = activity;
this.resolver = activity.getContentResolver();
this.theme = DefaultTheme.getTheme(activity);
selectedItems = new SparseBooleanArray();
refresh();
}
public void refresh() {
clear();
for (OrgFile file : OrgProviderUtils.getFiles(resolver)){
add(file);
}
notifyDataSetChanged();
}
@Override public int getItemCount() {
return items.size() + numExtraItems;
}
@Override public OutlineItem onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.outline_item, parent, false);
return new OutlineItem(v);
}
@Override
public void onBindViewHolder(final OutlineItem holder, final int position) {
final int positionInItems = position - numExtraItems;
OrgFile file = null;
try{
file = items.get(positionInItems);
} catch(ArrayIndexOutOfBoundsException ignored){}
final boolean conflict = (file != null && file.getState() == OrgFile.State.kConflict);
String title;
if(position == 0) {
title = activity.getResources().getString(R.string.menu_todos);
} else if (position == 1){
title = activity.getResources().getString(R.string.menu_agenda);
} else {
title = items.get(positionInItems).name;
}
holder.titleView.setText(title);
TextView comment = (TextView)holder.mView.findViewById(R.id.comment);
if (conflict) {
comment.setText(R.string.conflict);
comment.setVisibility(View.VISIBLE);
} else {
comment.setVisibility(View.GONE);
}
holder.mView.setActivated(selectedItems.get(position, false));
final long itemId = getItemId(position);
holder.mView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Context context = v.getContext();
if (getSelectedItemCount() > 0) {
if(!isSelectableItem(position)) return;
toggleSelection(position);
} else {
if (mTwoPanes) {
Bundle arguments = new Bundle();
Intent intent;
// Special activity for conflicted file
if(conflict){
intent = new Intent(context, ConflictResolverActivity.class);
context.startActivity(intent);
return;
}
if(position == 0){ | arguments.putLong(OrgContract.NODE_ID, OrgContract.TODO_ID); | 2 |
JeffreyFalgout/ThrowingStream | throwing-stream/src/main/java/name/falgout/jeffrey/throwing/stream/adapter/CheckedIterator.java | [
"@FunctionalInterface\npublic interface ThrowingConsumer<T, X extends Throwable> {\n public void accept(T t) throws X;\n\n default public Consumer<T> fallbackTo(Consumer<? super T> fallback) {\n return fallbackTo(fallback, null);\n }\n\n default public Consumer<T> fallbackTo(Consumer<? super T> fallback,\n ... | import java.util.Iterator;
import name.falgout.jeffrey.throwing.ThrowingConsumer;
import name.falgout.jeffrey.throwing.ThrowingDoubleConsumer;
import name.falgout.jeffrey.throwing.ThrowingIntConsumer;
import name.falgout.jeffrey.throwing.ThrowingIterator;
import name.falgout.jeffrey.throwing.ThrowingLongConsumer;
import name.falgout.jeffrey.throwing.adapter.ExceptionMasker; | package name.falgout.jeffrey.throwing.stream.adapter;
class CheckedIterator<E, X extends Throwable, D extends Iterator<E>> extends CheckedAdapter<D, X>
implements ThrowingIterator<E, X> {
static class OfInt<X extends Throwable>
extends CheckedIterator<Integer, X, java.util.PrimitiveIterator.OfInt>
implements ThrowingIterator.OfInt<X> {
OfInt(java.util.PrimitiveIterator.OfInt delegate, ExceptionMasker<X> ExceptionMasker) {
super(delegate, ExceptionMasker);
}
@Override
public void forEachRemaining(ThrowingIntConsumer<? extends X> action) throws X {
unmaskException(() -> getDelegate().forEachRemaining(getExceptionMasker().mask(action)));
}
@Override
public int nextInt() throws X {
return unmaskException(getDelegate()::nextInt);
}
}
static class OfLong<X extends Throwable>
extends CheckedIterator<Long, X, java.util.PrimitiveIterator.OfLong>
implements ThrowingIterator.OfLong<X> {
OfLong(java.util.PrimitiveIterator.OfLong delegate, ExceptionMasker<X> ExceptionMasker) {
super(delegate, ExceptionMasker);
}
@Override | public void forEachRemaining(ThrowingLongConsumer<? extends X> action) throws X { | 4 |
piyell/NeteaseCloudMusic | app/src/main/java/com/zsorg/neteasecloudmusic/utils/AlertUtil.java | [
"public interface OnDeleteListener {\n public void onDelete(boolean isDeleteOnDisk);\n}",
"public interface OnItemCLickListener {\n void onItemClick(View view, int position);\n}",
"public interface OnTextSubmitListener {\n void onTextSubmit(String text);\n}",
"public class PlaylistAdapter extends Bas... | import android.content.Context;
import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import com.zsorg.neteasecloudmusic.callbacks.OnDeleteListener;
import com.zsorg.neteasecloudmusic.callbacks.OnItemCLickListener;
import com.zsorg.neteasecloudmusic.callbacks.OnTextSubmitListener;
import com.zsorg.neteasecloudmusic.adapters.PlaylistAdapter;
import com.zsorg.neteasecloudmusic.R;
import com.zsorg.neteasecloudmusic.models.ConfigModel;
import com.zsorg.neteasecloudmusic.models.PlaylistModel;
import com.zsorg.neteasecloudmusic.models.beans.MusicBean;
import java.util.List;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers; | package com.zsorg.neteasecloudmusic.utils;
/**
* Project:NeteaseCloudMusic
*
* @Author: piyel_000
* Created on 2017/2/3.
* E-mail:piyell@qq.com
*/
public class AlertUtil {
public static void showDeleteDialog(Context context, final OnDeleteListener listener) {
final boolean[] isDeleteOnDisk = new boolean[1];
new AlertDialog.Builder(context)
.setTitle(R.string.confirm_to_remove_music)
.setMultiChoiceItems(R.array.delete_on_disk_choice, new boolean[]{false}, new DialogInterface.OnMultiChoiceClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i, boolean b) {
isDeleteOnDisk[0] = b;
}
})
.setPositiveButton(R.string.delete, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
if (listener != null) {
listener.onDelete(isDeleteOnDisk[0]);
}
}
})
.setNegativeButton(R.string.cancel, null)
.show();
}
public static void showDeletePlaylistDialog(Context context, final OnDeleteListener listener) {
final boolean[] isDeleteOnDisk = new boolean[1];
new AlertDialog.Builder(context)
.setMessage(R.string.confirm_to_delete_playlist)
.setPositiveButton(R.string.delete, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
if (listener != null) {
listener.onDelete(isDeleteOnDisk[0]);
}
}
})
.setNegativeButton(R.string.cancel, null)
.show();
}
public static void showCollectionDialog(final Context context, final MusicBean bean) {
final PlaylistModel model = new PlaylistModel(context);
final AlertDialog dialog = new AlertDialog.Builder(context)
.setTitle(R.string.collect_to_playlist).create();
LayoutInflater inflater = LayoutInflater.from(context);
RecyclerView rvPlaylist = (RecyclerView) inflater.inflate(R.layout.dialog_collection_to_playlist, null);
rvPlaylist.setOverScrollMode(RecyclerView.OVER_SCROLL_NEVER);
rvPlaylist.setLayoutManager(new LinearLayoutManager(context));
final PlaylistAdapter adapter = new PlaylistAdapter(inflater,true);
View view = inflater.inflate(R.layout.header_add_playlist, null);
adapter.addHeaderView(view);
adapter.setOnItemClickListener(new OnItemCLickListener() {
@Override
public void onItemClick(View view, int position) {
switch (position) {
case 0: | showNewPlaylistDialog(context, new OnTextSubmitListener() { | 2 |
JoostvDoorn/GlutenVrijApp | app/src/main/java/com/joostvdoorn/glutenvrij/scanner/core/oned/UPCAReader.java | [
"public final class BarcodeFormat {\n\n // No, we can't use an enum here. J2ME doesn't support it.\n\n private static final Hashtable VALUES = new Hashtable();\n\n /** Aztec 2D barcode format. */\n public static final BarcodeFormat AZTEC = new BarcodeFormat(\"AZTEC\");\n\n /** CODABAR 1D format. */\n public s... | import com.joostvdoorn.glutenvrij.scanner.core.BarcodeFormat;
import com.joostvdoorn.glutenvrij.scanner.core.BinaryBitmap;
import com.joostvdoorn.glutenvrij.scanner.core.ChecksumException;
import com.joostvdoorn.glutenvrij.scanner.core.FormatException;
import com.joostvdoorn.glutenvrij.scanner.core.NotFoundException;
import com.joostvdoorn.glutenvrij.scanner.core.Result;
import com.joostvdoorn.glutenvrij.scanner.core.common.BitArray;
import java.util.Hashtable; | /*
* Copyright 2008 ZXing authors
*
* 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.joostvdoorn.glutenvrij.scanner.core.oned;
/**
* <p>Implements decoding of the UPC-A format.</p>
*
* @author dswitkin@google.com (Daniel Switkin)
* @author Sean Owen
*/
public final class UPCAReader extends UPCEANReader {
private final UPCEANReader ean13Reader = new EAN13Reader();
public Result decodeRow(int rowNumber, BitArray row, int[] startGuardRange, Hashtable hints) | throws NotFoundException, FormatException, ChecksumException { | 4 |
heroku/heroku.jar | heroku-api/src/main/java/com/heroku/api/request/addon/AddonList.java | [
"public class Addon implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n String name;\n String description;\n URL url;\n String state;\n String id;\n Plan plan;\n\n public Plan getPlan() {\n return plan;\n }\n\n public void setPlan(Plan plan) {\n ... | import com.heroku.api.Addon;
import com.heroku.api.Heroku;
import com.heroku.api.exception.RequestFailedException;
import com.heroku.api.http.Http;
import com.heroku.api.request.Request;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import static com.heroku.api.http.HttpUtil.noBody;
import static com.heroku.api.parser.Json.parse; | package com.heroku.api.request.addon;
/**
* TODO: Javadoc
*
* @author Naaman Newbold
*/
public class AddonList implements Request<List<Addon>> {
@Override
public Http.Method getHttpMethod() {
return Http.Method.GET;
}
@Override
public String getEndpoint() {
return Heroku.Resource.Addons.value;
}
@Override
public boolean hasBody() {
return false;
}
@Override
public String getBody() { | throw noBody(); | 5 |
Tonius/SimplyJetpacks | src/main/java/tonius/simplyjetpacks/handler/LivingTickHandler.java | [
"public static class ItemJetpack extends ItemPack<Jetpack> {\n \n public ItemJetpack(ModType modType, String registryName) {\n super(modType, registryName);\n }\n \n}",
"public class Jetpack extends PackBase {\n \n protected static final String TAG_HOVERMODE_ON = \"JetpackHoverMod... | import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import net.minecraft.entity.monster.EntityMob;
import net.minecraft.item.ItemStack;
import net.minecraft.util.DamageSource;
import net.minecraftforge.event.entity.living.LivingEvent.LivingUpdateEvent;
import tonius.simplyjetpacks.item.ItemPack.ItemJetpack;
import tonius.simplyjetpacks.item.meta.Jetpack;
import tonius.simplyjetpacks.item.meta.JetpackPotato;
import tonius.simplyjetpacks.network.PacketHandler;
import tonius.simplyjetpacks.network.message.MessageJetpackSync;
import tonius.simplyjetpacks.setup.ParticleType;
import cofh.lib.util.helpers.MathHelper;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import cpw.mods.fml.common.network.NetworkRegistry.TargetPoint; | package tonius.simplyjetpacks.handler;
public class LivingTickHandler {
private static final Map<Integer, ParticleType> lastJetpackState = new ConcurrentHashMap<Integer, ParticleType>();
@SubscribeEvent
public void onLivingTick(LivingUpdateEvent evt) {
if (!evt.entityLiving.worldObj.isRemote) {
ParticleType jetpackState = null;
ItemStack armor = evt.entityLiving.getEquipmentInSlot(3);
Jetpack jetpack = null; | if (armor != null && armor.getItem() instanceof ItemJetpack) { | 0 |
karthicks/gremlin-ogm | gremlin-objects/src/test/java/org/apache/tinkerpop/gremlin/object/reflect/PrimitivesTest.java | [
"public interface Graph {\n\n /**\n * Add an given {@link Vertex} to the graph.\n */\n <V extends Vertex> Graph addVertex(V vertex);\n\n /**\n * Remove the given {@link Vertex} from the graph.\n */\n <V extends Vertex> Graph removeVertex(V vertex);\n\n /**\n * Add an {@link Edge} from the current ve... | import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.apache.tinkerpop.gremlin.object.structure.Graph;
import org.junit.Before;
import org.junit.Test;
import java.time.Instant;
import java.util.Date;
import java.util.Set;
import static org.apache.tinkerpop.gremlin.object.vertices.Location.year;
import static org.apache.tinkerpop.gremlin.object.reflect.Primitives.isPrimitive;
import static org.apache.tinkerpop.gremlin.object.reflect.Primitives.isTimeType;
import static org.apache.tinkerpop.gremlin.object.reflect.Primitives.toTimeType; | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.tinkerpop.gremlin.object.reflect;
/**
* Assert that {@link Primitives} identifies the registered primitive types properly. It also tests
* that time properties can be converted between compatible types.
*
* @author Karthick Sankarachary (http://github.com/karthicks)
*/
public class PrimitivesTest extends ReflectTest {
private Instant now;
@Before
public void setUp() {
now = year(2017);
}
@Test
public void testIsPrimitiveType() {
assertTrue(isPrimitive(String.class)); | assertTrue(isPrimitive(Graph.Should.class)); | 0 |
bonigarcia/dualsub | src/test/java/io/github/bonigarcia/dualsub/test/TestSynchronization.java | [
"public class DualSrt {\n\n\tprivate static final Logger log = LoggerFactory.getLogger(DualSrt.class);\n\n\tprivate TreeMap<String, Entry[]> subtitles;\n\n\tprivate int signatureGap;\n\tprivate int signatureTime;\n\tprivate int gap;\n\tprivate int desync;\n\tprivate int extension;\n\tprivate boolean extend;\n\tpriv... | import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.github.bonigarcia.dualsub.srt.DualSrt;
import io.github.bonigarcia.dualsub.srt.Merger;
import io.github.bonigarcia.dualsub.srt.Srt;
import io.github.bonigarcia.dualsub.srt.SrtUtils;
import io.github.bonigarcia.dualsub.util.Charset;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.util.Properties;
import org.junit.Assert;
import org.junit.Before; | /*
* (C) Copyright 2014 Boni Garcia (http://bonigarcia.github.io/)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package io.github.bonigarcia.dualsub.test;
/**
* TestSynchronization.
*
* @author Boni Garcia (boni.gg@gmail.com)
* @since 1.0.0
*/
public class TestSynchronization {
private static final Logger log = LoggerFactory
.getLogger(TestSynchronization.class);
private Properties properties;
@Before
public void setup() throws IOException {
properties = new Properties();
InputStream inputStream = Thread.currentThread()
.getContextClassLoader()
.getResourceAsStream("dualsub.properties");
properties.load(inputStream);
}
@Test
public void testDesynchronization() throws ParseException, IOException {
// Initial configuration
SrtUtils.init("624", "Tahoma", 17, true, true, ".", 50, false, null,
null);
// Input subtitles | Srt srtLeft = new Srt("Exceptions (English).srt"); | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.