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
WhiteBlue/eleme-hackathon
src/main/java/cn/shiroblue/Catch.java
[ "public class ExceptionMapperFactory {\n\n private static ExceptionMapper exceptionMapper = null;\n\n private ExceptionMapperFactory() {\n }\n\n public static ExceptionMapper get() {\n if (exceptionMapper == null) {\n exceptionMapper = new ExceptionMapper();\n }\n return ...
import cn.shiroblue.core.ExceptionMapperFactory; import cn.shiroblue.http.Request; import cn.shiroblue.http.Response; import cn.shiroblue.modules.ExceptionHandler; import cn.shiroblue.modules.ExceptionHandlerImpl;
package cn.shiroblue; /** * Description: * <p> * ====================== * by WhiteBlue * on 15/11/6 */ public class Catch { private Catch() { } public static void exception(Class<? extends Exception> exceptionClass, final ExceptionHandler handler) { ExceptionHandlerImpl wrapper = new ExceptionHandlerImpl(exceptionClass) { @Override
public void handle(Exception exception, Request request, Response response) {
2
dominiks/uristmapsj
src/main/java/org/uristmaps/Uristmaps.java
[ "public class BuildFiles {\n\n /**\n * Return the path to the file-state file.\n * Contains a Map<String, FileInfo> object.\n * @return\n */\n public static File getFileStore() {\n return new File(conf.fetch(\"Paths\", \"build\"), \"files.kryo\");\n }\n\n /**\n * Contains a Wo...
import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.minlog.Log; import org.ini4j.Wini; import org.uristmaps.data.*; import org.uristmaps.tasks.*; import org.uristmaps.util.BuildFiles; import org.uristmaps.util.ExportFiles; import org.uristmaps.util.FileWatcher; import org.uristmaps.util.OutputFiles; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.util.*; import static org.uristmaps.util.Util.ANSI_RED; import static org.uristmaps.util.Util.ANSI_RESET;
package org.uristmaps; /** * Entry point for uristmaps application */ public class Uristmaps { public static final String VERSION = "0.3.3"; /** * The global configuration object. */ public static Wini conf; /** * The global kryo object. */ public static Kryo kryo; /** * The global file watcher object. */ public static FileWatcher files; /** * Entry point of the application. * * Runs all available tasks. * @param args */ public static void main(String[] args) { // Load configuration file Log.info("Uristmaps " + VERSION); loadConfig(args); initKryo(); initLogger(); initDirectories(); initFileInfo(); // Set logger to debug if flag is set in config if (conf.get("App", "debug", Boolean.class)) { Log.DEBUG(); Log.info("Enabled Debug Logging"); } // Fill the executor with all available tasks. TaskExecutor executor = new TaskExecutor(); // No file management for this task until subtasks are possible. executor.addTaskGroup(new TilesetsTaskGroup()); executor.addTask("BmpConvertTask", () -> BmpConverter.convert()); executor.addTask("SitesGeojson", new File[]{BuildFiles.getSitesFile(), BuildFiles.getWorldFile(), BuildFiles.getSitemapsIndex()}, OutputFiles.getSitesGeojson(), () -> WorldSites.geoJson()); executor.addTask("Sites",
new File[]{ExportFiles.getLegendsXML(),
1
Gdeeer/deerweather
app/src/main/java/com/deerweather/app/activity/ChooseAreaActivity.java
[ "public class City {\n private int id;\n private String cityName;\n private String cityCode;\n private int provinceId;\n public int getId() {\n return id;\n }\n public void setId(int id) {\n this.id = id;\n }\n public String getCityName() {\n return cityName;\n }\n...
import android.app.ProgressDialog; import android.content.Intent; import android.graphics.Color; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.text.TextUtils; import android.view.View; import android.view.WindowManager; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.Toast; import com.deerweather.app.R; import com.deerweather.app.model.City; import com.deerweather.app.model.County; import com.deerweather.app.model.DeerWeatherDB; import com.deerweather.app.model.Province; import com.deerweather.app.util.HttpCallBackListener; import com.deerweather.app.util.HttpUtil; import com.deerweather.app.util.JSONUtility; import com.deerweather.app.view.ColorView; import java.io.FileNotFoundException; import java.io.InputStream; import java.util.ArrayList; import java.util.List;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION); } mCvToolbar = (ColorView) findViewById(R.id.cv_toolbar_choose); setWallpaper(); mToolbar = (Toolbar) findViewById(R.id.toolbar_choose); mToolbar.setTitleTextColor(Color.WHITE); setSupportActionBar(mToolbar); listView = (ListView) findViewById(R.id.lv_choose); adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, dataList); listView.setAdapter(adapter); deerWeatherDB = DeerWeatherDB.getInstance(this); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if (currentLevel == LEVEL_PROVINCE) { selectedProvince = provinceList.get(position); queryCities(); } else if (currentLevel == LEVEL_CITY) { selectedCity = cityList.get(position); queryCounties(); } else if (currentLevel == LEVEL_COUNTY) { String countyCode = countyList.get(position).getCountyCode(); Intent intent = new Intent(); intent.putExtra("county_code_part", countyCode); setResult(RESULT_OK, intent); finish(); } } }); queryProvinces(); } public void setWallpaper() { String picturePath = getIntent().getStringExtra("picture"); int color = getIntent().getIntExtra("color", 0); if (picturePath != null && !picturePath.equals("")) { Uri pictureUri = Uri.parse(picturePath); InputStream inputStream = null; try { inputStream = getContentResolver().openInputStream(pictureUri); } catch (FileNotFoundException e) { e.printStackTrace(); } Drawable drawable = Drawable.createFromStream(inputStream, pictureUri.toString()); // mLlToolbar.setBackground(drawable); mCvToolbar.setBackground(drawable); } else { // mLlToolbar.setBackgroundColor(color); mCvToolbar.setBackgroundColor(color); } } private void queryProvinces() { provinceList = deerWeatherDB.loadProvinces(); if (provinceList.size() > 0) { dataList.clear(); for (Province province : provinceList) { dataList.add(province.getProvinceName()); } adapter.notifyDataSetChanged(); listView.setSelection(0); if (getSupportActionBar() != null) { getSupportActionBar().setTitle("中国"); } currentLevel = LEVEL_PROVINCE; } else { queryFromServerCity(null, "province"); } } private void queryCities() { cityList = deerWeatherDB.loadCities(selectedProvince.getId()); if (cityList.size() > 0) { dataList.clear(); for (City city : cityList) { dataList.add(city.getCityName()); } adapter.notifyDataSetChanged(); listView.setSelection(0); if (getSupportActionBar() != null) { getSupportActionBar().setTitle(selectedProvince.getProvinceName()); } currentLevel = LEVEL_CITY; } else { queryFromServerCity(selectedProvince.getProvinceCode(), "city"); } } private void queryCounties() { countyList = deerWeatherDB.loadCounties(selectedCity.getId()); if (countyList.size() > 0) { dataList.clear(); for (County county : countyList) { dataList.add(county.getCountyName()); } adapter.notifyDataSetChanged(); listView.setSelection(0); if (getSupportActionBar() != null) { getSupportActionBar().setTitle(selectedCity.getCityName()); } currentLevel = LEVEL_COUNTY; } else { queryFromServerCity(selectedCity.getCityCode(), "county"); } } private void queryFromServerCity(final String code, final String type) { String address; if (!TextUtils.isEmpty(code)) { address = "http://www.weather.com.cn/data/list3/city" + code + ".xml"; } else { address = "http://www.weather.com.cn/data/list3/city.xml"; } showProgressDialog();
HttpUtil.sendHttpRequest(address, new HttpCallBackListener() {
4
dropwizard/dropwizard-java8
dropwizard-java8-example/src/main/java/com/example/helloworld/HelloWorldApplication.java
[ "public class ExampleAuthenticator implements Authenticator<BasicCredentials, User> {\n @Override\n public Optional<User> authenticate(BasicCredentials credentials) throws AuthenticationException {\n if (\"secret\".equals(credentials.getPassword())) {\n return Optional.of(new User(credential...
import com.example.helloworld.auth.ExampleAuthenticator; import com.example.helloworld.auth.ExampleAuthorizer; import com.example.helloworld.cli.RenderCommand; import com.example.helloworld.core.Person; import com.example.helloworld.core.Template; import com.example.helloworld.core.User; import com.example.helloworld.db.PersonDAO; import com.example.helloworld.filter.DateRequiredFeature; import com.example.helloworld.health.TemplateHealthCheck; import com.example.helloworld.resources.FilteredResource; import com.example.helloworld.resources.HelloWorldResource; import com.example.helloworld.resources.PeopleResource; import com.example.helloworld.resources.PersonResource; import com.example.helloworld.resources.ProtectedResource; import com.example.helloworld.resources.ViewResource; import io.dropwizard.Application; import io.dropwizard.assets.AssetsBundle; import io.dropwizard.auth.AuthValueFactoryProvider; import io.dropwizard.configuration.EnvironmentVariableSubstitutor; import io.dropwizard.configuration.SubstitutingSourceProvider; import io.dropwizard.db.DataSourceFactory; import io.dropwizard.hibernate.HibernateBundle; import io.dropwizard.java8.Java8Bundle; import io.dropwizard.java8.auth.AuthDynamicFeature; import io.dropwizard.java8.auth.basic.BasicCredentialAuthFilter; import io.dropwizard.migrations.MigrationsBundle; import io.dropwizard.setup.Bootstrap; import io.dropwizard.setup.Environment; import io.dropwizard.views.ViewBundle; import org.glassfish.jersey.server.filter.RolesAllowedDynamicFeature; import java.util.Map;
package com.example.helloworld; public class HelloWorldApplication extends Application<HelloWorldConfiguration> { public static void main(String[] args) throws Exception { new HelloWorldApplication().run(args); } private final HibernateBundle<HelloWorldConfiguration> hibernateBundle = new HibernateBundle<HelloWorldConfiguration>(Person.class) { @Override public DataSourceFactory getDataSourceFactory(HelloWorldConfiguration configuration) { return configuration.getDataSourceFactory(); } }; @Override public String getName() { return "hello-world"; } @Override public void initialize(Bootstrap<HelloWorldConfiguration> bootstrap) { // Enable variable substitution with environment variables bootstrap.setConfigurationSourceProvider( new SubstitutingSourceProvider( bootstrap.getConfigurationSourceProvider(), new EnvironmentVariableSubstitutor(false) ) ); bootstrap.addCommand(new RenderCommand()); bootstrap.addBundle(new Java8Bundle()); bootstrap.addBundle(new AssetsBundle()); bootstrap.addBundle(new MigrationsBundle<HelloWorldConfiguration>() { @Override public DataSourceFactory getDataSourceFactory(HelloWorldConfiguration configuration) { return configuration.getDataSourceFactory(); } }); bootstrap.addBundle(hibernateBundle); bootstrap.addBundle(new ViewBundle<HelloWorldConfiguration>() { @Override public Map<String, Map<String, String>> getViewConfiguration(HelloWorldConfiguration configuration) { return configuration.getViewRendererConfiguration(); } }); } @Override public void run(HelloWorldConfiguration configuration, Environment environment) { final PersonDAO dao = new PersonDAO(hibernateBundle.getSessionFactory()); final Template template = configuration.buildTemplate(); environment.healthChecks().register("template", new TemplateHealthCheck(template)); environment.jersey().register(DateRequiredFeature.class); environment.jersey().register(new AuthDynamicFeature(new BasicCredentialAuthFilter.Builder<User>() .setAuthenticator(new ExampleAuthenticator()) .setAuthorizer(new ExampleAuthorizer()) .setRealm("SUPER SECRET STUFF") .buildAuthFilter())); environment.jersey().register(new AuthValueFactoryProvider.Binder<>(User.class)); environment.jersey().register(RolesAllowedDynamicFeature.class); environment.jersey().register(new HelloWorldResource(template)); environment.jersey().register(new ViewResource()); environment.jersey().register(new ProtectedResource()); environment.jersey().register(new PeopleResource(dao));
environment.jersey().register(new PersonResource(dao));
4
6ag/BaoKanAndroid
app/src/main/java/tv/baokan/baokanandroid/ui/activity/ModifySafeInfoActivity.java
[ "public class UserBean {\n\n private static final String TAG = \"UserBean\";\n\n // 用户id\n private String userid;\n\n // token\n private String token;\n\n // 用户名\n private String username;\n\n // 昵称\n private String nickname;\n\n // email\n private String email;\n\n // 用户组\n p...
import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.Handler; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.Editable; import android.text.TextUtils; import android.text.TextWatcher; import android.view.View; import android.view.inputmethod.InputMethodManager; import android.widget.Button; import android.widget.EditText; import com.kaopiz.kprogresshud.KProgressHUD; import org.json.JSONException; import org.json.JSONObject; import java.util.HashMap; import java.util.Timer; import java.util.TimerTask; import okhttp3.Call; import tv.baokan.baokanandroid.R; import tv.baokan.baokanandroid.model.UserBean; import tv.baokan.baokanandroid.utils.APIs; import tv.baokan.baokanandroid.utils.LogUtils; import tv.baokan.baokanandroid.utils.NetworkUtils; import tv.baokan.baokanandroid.utils.ProgressHUD; import tv.baokan.baokanandroid.widget.NavigationViewRed;
package tv.baokan.baokanandroid.ui.activity; public class ModifySafeInfoActivity extends BaseActivity implements TextWatcher { private static final String TAG = "ModifySafeInfoActivity"; private NavigationViewRed mNavigationViewRed; private EditText mOldPasswordEditText; // 老密码 private EditText mNewPasswordEditText; // 新密码 private EditText mConfirmPasswordEditText; // 确认新密码 private EditText mEmailEditText; // 邮箱 private Button mModifyButton; // 修改按钮 /** * 便捷启动当前activity * * @param activity 启动当前activity的activity */ public static void start(Activity activity) { Intent intent = new Intent(activity, ModifySafeInfoActivity.class); activity.startActivity(intent); activity.overridePendingTransition(R.anim.push_enter, R.anim.push_exit); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_modify_safe_info); prepareUI(); prepareData(); // 更新按钮状态 modifyButtonStateChange(); } /** * 准备UI */ private void prepareUI() { mNavigationViewRed = (NavigationViewRed) findViewById(R.id.nav_safe_modify_user_info); mOldPasswordEditText = (EditText) findViewById(R.id.et_safe_modify_user_info_password); mNewPasswordEditText = (EditText) findViewById(R.id.et_safe_modify_user_info_new_password); mConfirmPasswordEditText = (EditText) findViewById(R.id.et_safe_modify_user_info_confirm_password); mEmailEditText = (EditText) findViewById(R.id.et_safe_modify_user_info_email); mModifyButton = (Button) findViewById(R.id.btn_safe_modify_user_info_modify); mNavigationViewRed.setupNavigationView(true, false, "修改安全信息", new NavigationViewRed.OnClickListener() { @Override public void onBackClick(View v) { finish(); } }); mModifyButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { saveModifyInfo(); } }); mOldPasswordEditText.addTextChangedListener(this); mNewPasswordEditText.addTextChangedListener(this); mConfirmPasswordEditText.addTextChangedListener(this); mEmailEditText.addTextChangedListener(this); // 自动弹出键盘 Timer timer = new Timer(); timer.schedule(new TimerTask() { public void run() { InputMethodManager inputManager = (InputMethodManager) mOldPasswordEditText.getContext().getSystemService(Context.INPUT_METHOD_SERVICE); inputManager.showSoftInput(mOldPasswordEditText, 0); } }, 500); } /** * 准备数据 */ private void prepareData() {
mEmailEditText.setText(UserBean.shared().getEmail());
0
shibing624/similarity
src/main/java/org/xm/tendency/word/HownetWordTendency.java
[ "public class Concept implements IHownetMeta {\n // 概念名称\n protected String word;\n // 词性 part of speech\n protected String pos;\n // 定义\n protected String define;\n // 实词(true),虚词(false)\n protected boolean bSubstantive;\n // 主基本义原\n protected String mainSememe;\n // 其他基本义原\n pr...
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.xm.similarity.word.hownet.concept.Concept; import org.xm.similarity.word.hownet.concept.ConceptParser; import org.xm.similarity.word.hownet.concept.ConceptSimilarity; import org.xm.similarity.word.hownet.sememe.SememeParser; import org.xm.similarity.word.hownet.sememe.SememeSimilarity; import java.io.IOException; import java.util.Collection; import java.util.HashSet; import java.util.Set;
package org.xm.tendency.word; /** * 知网词语倾向性 * * @author xuming */ public class HownetWordTendency implements IWordTendency { private static final Logger logger = LoggerFactory.getLogger(HownetWordTendency.class);
private ConceptParser conceptParser;
1
tommai78101/PokemonWalking
game/src/main/java/script/Script.java
[ "public class Debug {\n\tstatic class NotYetImplemented {\n\t\tprivate int occurrences = 0;\n\t\tprivate final String location;\n\n\t\tpublic NotYetImplemented(String loc) {\n\t\t\tthis.location = loc;\n\t\t}\n\n\t\tpublic boolean grab(String loc) {\n\t\t\tif (this.location.equals(loc) && !this.hasReachedLimit()) {...
import java.awt.Graphics2D; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URISyntaxException; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.Map; import common.Debug; import dialogue.Dialogue; import entity.Player; import enums.ScriptTags; import level.Area; import level.WorldConstants; import screen.Scene; import utility.DialogueBuilder;
this.affirmativeMoves .add(Map.entry(e.getKey(), new MovementData(e.getValue()))); this.negativeMoves = new ArrayList<>(); for (Map.Entry<Integer, MovementData> e : s.negativeMoves) this.negativeMoves .add(Map.entry(e.getKey(), new MovementData(e.getValue()))); this.dialogues = new ArrayList<>(); for (Map.Entry<Integer, Dialogue> e : s.dialogues) this.dialogues .add(Map.entry(e.getKey(), new Dialogue(e.getValue()))); this.affirmativeDialogues = new ArrayList<>(); for (Map.Entry<Integer, Dialogue> e : s.affirmativeDialogues) this.affirmativeDialogues .add(Map.entry(e.getKey(), new Dialogue(e.getValue()))); this.negativeDialogues = new ArrayList<>(); for (Map.Entry<Integer, Dialogue> e : s.negativeDialogues) this.negativeDialogues .add(Map.entry(e.getKey(), new Dialogue(e.getValue()))); this.scriptIteration = s.scriptIteration; this.affirmativeIteration = s.affirmativeIteration; this.negativeIteration = s.negativeIteration; this.questionResponse = s.questionResponse; this.repeat = s.repeat; this.countdown = s.countdown; this.finished = s.finished; this.enabled = s.enabled; } // -------------------------------------------------------------------------------------- // Public methods. /** * Returns the current scripted movement action depending on what type of response the player has * given in the game. * * @return */ public MovementData getIteratedMoves() { if (this.questionResponse == null) { for (Map.Entry<Integer, MovementData> entry : this.moves) { if (entry.getKey() == this.scriptIteration) return entry.getValue(); } } else if (this.questionResponse == Boolean.TRUE) { for (Map.Entry<Integer, MovementData> entry : this.affirmativeMoves) { if (entry.getKey() == this.affirmativeIteration) return entry.getValue(); } } else if (this.questionResponse == Boolean.FALSE) { for (Map.Entry<Integer, MovementData> entry : this.negativeMoves) { if (entry.getKey() == this.negativeIteration) return entry.getValue(); } } return null; } /** * Returns the current scripted dialogue depending on what type of response the player has given in * the game. * * @return */ public Dialogue getIteratedDialogues() { if (this.questionResponse == null) { for (Map.Entry<Integer, Dialogue> entry : this.dialogues) { if (entry.getKey() == this.scriptIteration) { return entry.getValue(); } } } else if (this.questionResponse == Boolean.TRUE) { for (Map.Entry<Integer, Dialogue> entry : this.affirmativeDialogues) { if (entry.getKey() == this.affirmativeIteration) { return entry.getValue(); } } } else if (this.questionResponse == Boolean.FALSE) { for (Map.Entry<Integer, Dialogue> entry : this.negativeDialogues) { if (entry.getKey() == this.negativeIteration) { return entry.getValue(); } } } return null; } /** * Sets the script to execute a positive dialogue option route when the flag is set. */ public void setAffirmativeFlag() { this.questionResponse = Boolean.TRUE; } /** * Sets the script to execute a negative dialogue option route when the flag is set. */ public void setNegativeFlag() { this.questionResponse = Boolean.FALSE; } /** * Updates the script. * * @param area * @param entityX * @param entityY */ public void tick(Area area) { MovementData moves = this.getIteratedMoves(); Dialogue dialogue = this.getIteratedDialogues();
Player player = area.getPlayer();
2
PeterCxy/BlackLight
src/us/shandian/blacklight/ui/statuses/TimeLineFragment.java
[ "public class HomeTimeLineApiCache\n{\n\tprivate static HashMap<Long, SoftReference<Bitmap>> mThumnnailCache = new HashMap<Long, SoftReference<Bitmap>>();\n\t\n\tprotected DataBaseHelper mHelper;\n\tprotected FileCacheManager mManager;\n\t\n\tpublic MessageListModel mMessages;\n\t\n\tprotected int mCurrentPage = 0;...
import android.app.Fragment; import android.app.Service; import android.content.Intent; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.animation.TranslateAnimation; import android.widget.ListView; import android.widget.Toast; import android.os.Bundle; import android.os.Vibrator; import android.support.v4.widget.SwipeRefreshLayout; import java.util.ConcurrentModificationException; import us.shandian.blacklight.R; import us.shandian.blacklight.cache.statuses.HomeTimeLineApiCache; import us.shandian.blacklight.support.AsyncTask; import us.shandian.blacklight.support.Settings; import us.shandian.blacklight.support.Utility; import us.shandian.blacklight.support.adapter.WeiboAdapter; import us.shandian.blacklight.ui.common.SwipeUpAndDownRefreshLayout; import static us.shandian.blacklight.support.Utility.hasSmartBar;
/* * Copyright (C) 2014 Peter Cai * * This file is part of BlackLight * * BlackLight 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. * * BlackLight 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 BlackLight. If not, see <http://www.gnu.org/licenses/>. */ package us.shandian.blacklight.ui.statuses; public class TimeLineFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener, View.OnClickListener, View.OnTouchListener, View.OnLongClickListener { private ListView mList; private View mNew; private WeiboAdapter mAdapter; private HomeTimeLineApiCache mCache; // Pull To Refresh private SwipeUpAndDownRefreshLayout mSwipeRefresh; private boolean mRefreshing = false; private boolean mNewHidden = false; protected boolean mBindOrig = true; protected boolean mShowCommentStatus = true; private int mLastCount = 0; private float mLastY = -1.0f; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { initTitle(); View v = inflater.inflate(R.layout.home_timeline, null); mList = (ListView) v.findViewById(R.id.home_timeline); mCache = bindApiCache(); mCache.loadFromCache(); mAdapter = new WeiboAdapter(getActivity(), mList, mCache.mMessages, mBindOrig, mShowCommentStatus); mList.setAdapter(mAdapter); mList.setDrawingCacheEnabled(true); mList.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH); mList.setPersistentDrawingCache(ViewGroup.PERSISTENT_ANIMATION_CACHE | ViewGroup.PERSISTENT_SCROLLING_CACHE); // Swipe To Refresh bindSwipeToRefresh((ViewGroup) v); if (mCache.mMessages.getSize() == 0) { new Refresher().execute(new Boolean[]{true}); } // Floating "New" button bindNewButton(v); return v; } @Override public void onStop() { super.onStop(); try { mCache.cache(); } catch (ConcurrentModificationException e) { } } @Override public void onHiddenChanged(boolean hidden) { super.onHiddenChanged(hidden); if (!hidden) { initTitle(); resume(); } } @Override public void onResume() { super.onResume(); resume(); } public void resume() {
Settings settings = Settings.getInstance(getActivity());
2
goshippo/shippo-java-client
src/main/java/com/shippo/model/CarrierAccount.java
[ "public class APIConnectionException extends ShippoException {\n\n\tprivate static final long serialVersionUID = 1L;\n\n\tpublic APIConnectionException(String message) {\n\t\tsuper(message);\n\t}\n\n\tpublic APIConnectionException(String message, Throwable e) {\n\t\tsuper(message, e);\n\t}\n\n}", "public class AP...
import java.util.HashMap; import java.util.Map; import com.shippo.exception.APIConnectionException; import com.shippo.exception.APIException; import com.shippo.exception.AuthenticationException; import com.shippo.exception.InvalidRequestException; import com.shippo.net.APIResource;
package com.shippo.model; public class CarrierAccount extends APIResource { String objectId; String accountId; String carrier; Boolean test; Boolean active; Object parameters; public static CarrierAccount create(Map<String, Object> params)
throws AuthenticationException, InvalidRequestException,
2
Lyneira/MachinaCraft
MachinaDrill/src/me/lyneira/MachinaDrill/Detector.java
[ "public enum BlockRotation {\r\n ROTATE_0, ROTATE_90, ROTATE_180, ROTATE_270;\r\n\r\n private final static BlockFace[] yawFace = { BlockFace.SOUTH, BlockFace.EAST, BlockFace.NORTH, BlockFace.WEST };\r\n private final static BlockVector[] yawVector = { new BlockVector(yawFace[0]), new BlockVector(yawFace[1]...
import org.bukkit.Material; import org.bukkit.World; import org.bukkit.block.BlockFace; import org.bukkit.entity.Player; import me.lyneira.MachinaCore.block.BlockRotation; import me.lyneira.MachinaCore.block.BlockVector; import me.lyneira.MachinaCore.block.MachinaBlock; import me.lyneira.MachinaCore.machina.MachinaBlueprint; import me.lyneira.MachinaCore.machina.MachinaController; import me.lyneira.MachinaCore.machina.MachinaDetector; import me.lyneira.MachinaCore.machina.model.BlueprintModel; import me.lyneira.MachinaCore.machina.model.ConstructionModel;
package me.lyneira.MachinaDrill; class Detector implements MachinaDetector { static int activationDepthLimit = 0; static int materialCore = Material.GOLD_BLOCK.getId(); static int materialBase = Material.WOOD.getId(); static int materialHeadNormal = Material.IRON_BLOCK.getId(); static int materialHeadFast = Material.DIAMOND_BLOCK.getId(); static final int materialFurnace = Material.FURNACE.getId(); static final int materialFurnaceBurning = Material.BURNING_FURNACE.getId(); private static final int[] furnaceTypes = new int[] { materialFurnace, materialFurnaceBurning };
private final MachinaBlueprint blueprint;
3
bafomdad/realfilingcabinet
com/bafomdad/realfilingcabinet/items/capabilities/CapabilityFolder.java
[ "@Config(modid=RealFilingCabinet.MOD_ID)\npublic static class ConfigRFC {\n\t\t\n\t// RECIPES\n\t@Comment({\"Enable Crafting Upgrade recipe\"})\n\t@Tap\n\tpublic static boolean craftingUpgrade = true;\n\t@Comment({\"Enable Ender Upgrade recipe\"})\n\t@Tap\n\tpublic static boolean enderUpgrade = true;\n\t@Comment({\...
import com.bafomdad.realfilingcabinet.NewConfigRFC.ConfigRFC; import com.bafomdad.realfilingcabinet.RealFilingCabinet; import com.bafomdad.realfilingcabinet.helpers.StringLibs; import com.bafomdad.realfilingcabinet.helpers.TextHelper; import com.bafomdad.realfilingcabinet.init.RFCItems; import com.bafomdad.realfilingcabinet.items.ItemFolder; import com.bafomdad.realfilingcabinet.items.ItemFolder.FolderType; import com.bafomdad.realfilingcabinet.utils.NBTUtils; import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.client.util.ITooltipFlag; import net.minecraft.entity.*; import net.minecraft.entity.monster.EntityZombie; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.ResourceLocation; import net.minecraft.util.text.TextFormatting; import net.minecraft.world.World; import net.minecraftforge.common.util.INBTSerializable; import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.FluidRegistry; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fml.common.registry.EntityRegistry; import org.lwjgl.input.Keyboard; import java.util.List;
package com.bafomdad.realfilingcabinet.items.capabilities; // Funwayguy: Your new capability based class for dealing with folder stuff. Unique to each item rootStack so feel free to add/remove stuff. public class CapabilityFolder implements INBTSerializable<NBTTagCompound> { // The ItemStack instance you're working within (REFERENCE PURPOSES ONLY!) private final ItemStack rootStack; private String displayName = ""; private Object contents; private long count = 0; private int remSize = 0; public CapabilityFolder(ItemStack rootStack) { this.rootStack = rootStack; } public void addTooltips(World world, List<String> list, ITooltipFlag tooltipFlag) { if (rootStack.getItem() == RFCItems.dyedFolder) { ItemStack item = getItemStack(); list.add((Keyboard.isKeyDown(42)) || (Keyboard.isKeyDown(54)) ? count + " " + item.getDisplayName() : TextHelper.format(count) + " " + item.getDisplayName()); return; }
if(rootStack.getItemDamage() == ItemFolder.FolderType.FLUID.ordinal() && isFluidStack())
6
HumBuch/HumBuch
src/main/java/de/dhbw/humbuch/viewmodel/LoginViewModel.java
[ "public class LoginEvent {\n\tprivate final String message;\n\n\tpublic LoginEvent(String message) {\n\t\tthis.message = message;\n\t}\n\t\n\tpublic String getMessage() {\n\t\treturn message;\n\t}\n}", "public interface DAO<EntityType extends Entity> {\n\n\t/**\n\t * Should an event be fired?\n\t */\n\tpublic enu...
import java.security.NoSuchAlgorithmException; import java.security.spec.InvalidKeySpecException; import java.util.List; import org.hibernate.criterion.Restrictions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.eventbus.EventBus; import com.google.inject.Inject; import de.davherrmann.mvvm.ActionHandler; import de.davherrmann.mvvm.BasicState; import de.davherrmann.mvvm.State; import de.davherrmann.mvvm.annotations.HandlesAction; import de.davherrmann.mvvm.annotations.ProvidesState; import de.dhbw.humbuch.event.LoginEvent; import de.dhbw.humbuch.model.DAO; import de.dhbw.humbuch.model.entity.User; import de.dhbw.humbuch.util.PasswordHash; import de.dhbw.humbuch.view.MainUI;
package de.dhbw.humbuch.viewmodel; /** * @author David Vitt * @author Johannes Idelhauser * */ public class LoginViewModel { private final static Logger LOG = LoggerFactory.getLogger(MainUI.class); public interface IsLoggedIn extends State<Boolean> {} public interface DoLogout extends ActionHandler {} public interface DoLogin extends ActionHandler {} private DAO<User> daoUser; private EventBus eventBus; private Properties properties; @ProvidesState(IsLoggedIn.class) public final BasicState<Boolean> isLoggedIn = new BasicState<Boolean>(Boolean.class); /** * Constructor * * @param daoUser * @param properties * @param eventBus */ @Inject public LoginViewModel(DAO<User> daoUser, Properties properties, EventBus eventBus) { this.properties = properties; this.eventBus = eventBus; this.daoUser = daoUser; updateLoginStatus(); } private void updateLoginStatus() { isLoggedIn.set(properties.currentUser.get() != null); } /** * Validates {@code username} and {@code password}. Fires an event if something is wrong.<br> * Sets the logged in {@link User} in the corresponding {@link Properties} state * * @param username * @param password */ @HandlesAction(DoLogin.class) public void doLogin(String username, String password) { properties.currentUser.set(null); updateLoginStatus(); try { if (username.equals("") || password.equals("")) {
eventBus.post(new LoginEvent("Bitte geben Sie einen Nutzernamen und Passwort an."));
0
dotcool/coolreader
src/com/dotcool/reader/task/CopyDBTask.java
[ "public class LNReaderApplication extends FOCApplication {\n\tprivate static final String TAG = LNReaderApplication.class.toString();\n\tprivate static NovelsDao novelsDao = null;\n\tprivate static DownloadListActivity downloadListActivity = null;\n\tprivate static UpdateService service = null;\n\tprivate static LN...
import java.io.IOException; import android.content.Context; import android.os.AsyncTask; import android.util.Log; import com.dotcool.reader.LNReaderApplication; import com.dotcool.R; import com.dotcool.reader.callback.CallbackEventData; import com.dotcool.reader.callback.ICallbackEventData; import com.dotcool.reader.callback.ICallbackNotifier; import com.dotcool.reader.dao.NovelsDao;
package com.dotcool.reader.task; public class CopyDBTask extends AsyncTask<Void, ICallbackEventData, Void> implements ICallbackNotifier { private static final String TAG = CopyDBTask.class.toString(); private final ICallbackNotifier callback; private final String source; private final boolean makeBackup; public CopyDBTask(boolean makeBackup, ICallbackNotifier callback, String source) { this.makeBackup = makeBackup; this.source = source; this.callback = callback; } public void onCallback(ICallbackEventData message) { publishProgress(message); } @Override protected Void doInBackground(Void... params) { Context ctx = LNReaderApplication.getInstance().getApplicationContext(); try { copyDB(makeBackup); } catch (IOException e) { String message; if (makeBackup) { message = ctx.getResources().getString(R.string.copy_db_task_backup_error); } else { message = ctx.getResources().getString(R.string.copy_db_task_restore_error); }
publishProgress(new CallbackEventData(message));
1
Elopteryx/upload-parser
upload-parser-core/src/main/java/com/github/elopteryx/upload/internal/AbstractUploadParser.java
[ "@FunctionalInterface\npublic interface OnError {\n\n /**\n * The consumer function to implement.\n * @param context The upload context\n * @param throwable The error that occurred\n * @throws IOException If an error occurs with the IO\n * @throws ServletException If and error occurred with t...
import static java.nio.charset.StandardCharsets.ISO_8859_1; import static java.nio.file.StandardOpenOption.APPEND; import static java.nio.file.StandardOpenOption.CREATE; import static java.nio.file.StandardOpenOption.WRITE; import static java.util.Objects.requireNonNull; import com.github.elopteryx.upload.OnError; import com.github.elopteryx.upload.OnPartBegin; import com.github.elopteryx.upload.OnPartEnd; import com.github.elopteryx.upload.OnRequestComplete; import com.github.elopteryx.upload.PartOutput; import com.github.elopteryx.upload.errors.PartSizeException; import com.github.elopteryx.upload.errors.RequestSizeException; import com.github.elopteryx.upload.util.NullChannel; import com.github.elopteryx.upload.util.OutputStreamBackedChannel; import java.io.IOException; import java.io.OutputStream; import java.nio.ByteBuffer; import java.nio.channels.WritableByteChannel; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.util.EnumSet; import jakarta.servlet.http.HttpServletRequest;
/* * Copyright (C) 2016 Adam Forgacs * * 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.elopteryx.upload.internal; /** * Base class for the parser implementations. This holds the common methods, like the more specific * validation and the calling of the user-supplied functions. */ public abstract sealed class AbstractUploadParser implements MultipartParser.PartHandler permits AsyncUploadParser, BlockingUploadParser { /** * The default size allocated for the buffers. */ private static final int DEFAULT_USED_MEMORY = 4096; /** * The part begin callback, called at the beginning of each part parsing. */ private OnPartBegin partBeginCallback; /** * The part end callback, called at the end of each part parsing. */ private OnPartEnd partEndCallback; /** * The request callback, called after every part has been processed. */ OnRequestComplete requestCallback; /** * The error callback, called when an error occurred. */ OnError errorCallback; /** * The user object. */ private Object userObject; /** * The number of bytes to be allocated for the buffers. */ protected int maxBytesUsed = DEFAULT_USED_MEMORY; /** * The number of bytes that should be buffered before calling the part begin callback. */ protected int sizeThreshold; /** * The maximum size permitted for the parts. By default it is unlimited. */ private long maxPartSize = -1; /** * The maximum size permitted for the complete request. By default it is unlimited. */ protected long maxRequestSize = -1; /** * The valid mime type. */ protected static final String MULTIPART_FORM_DATA = "multipart/form-data"; /** * The buffer that stores the first bytes of the current part. */ protected ByteBuffer checkBuffer; /** * The channel to where the current part is written. */ private WritableByteChannel writableChannel; /** * The known size of the request. */ protected long requestSize; /** * The context instance. */ protected UploadContextImpl context; /** * The reference to the multipart parser. */ protected MultipartParser.ParseState parseState; /** * The buffer that stores the bytes which were read from the * servlet input stream or from a different source. */ protected ByteBuffer dataBuffer; /** * Sets up the necessary objects to start the parsing. Depending upon * the environment the concrete implementations can be very different. * @param request The servlet request * @throws RequestSizeException If the supplied size is invalid */ void init(final HttpServletRequest request) { // Fail fast mode if (maxRequestSize > -1) { final var requestSize = request.getContentLengthLong(); if (requestSize > maxRequestSize) { throw new RequestSizeException("The size of the request (" + requestSize + ") is greater than the allowed size (" + maxRequestSize + ")!", requestSize, maxRequestSize); } } checkBuffer = ByteBuffer.allocate(sizeThreshold); context = new UploadContextImpl(request, userObject); final var mimeType = request.getHeader(Headers.CONTENT_TYPE); if (mimeType != null && mimeType.startsWith(MULTIPART_FORM_DATA)) { final String boundary = Headers.extractBoundaryFromHeader(mimeType); if (boundary == null) { throw new IllegalArgumentException("Could not find boundary in multipart request with ContentType: " + mimeType + ", multipart data will not be available"); } final var encodingHeader = request.getCharacterEncoding(); final var charset = encodingHeader == null ? ISO_8859_1 : Charset.forName(encodingHeader); parseState = MultipartParser.beginParse(this, boundary.getBytes(charset), maxBytesUsed, charset); } } /** * Checks how many bytes have been read so far and stops the * parsing if a max size has been set and reached. * @param additional The amount to add, always non negative */ void checkPartSize(final int additional) { final long partSize = context.incrementAndGetPartBytesRead(additional); if (maxPartSize > -1 && partSize > maxPartSize) { throw new PartSizeException("The size of the part (" + partSize + ") is greater than the allowed size (" + maxPartSize + ")!", partSize, maxPartSize); } } /** * Checks how many bytes have been read so far and stops the * parsing if a max size has been set and reached. * @param additional The amount to add, always non negative */ void checkRequestSize(final int additional) { requestSize += additional; if (maxRequestSize > -1 && requestSize > maxRequestSize) { throw new RequestSizeException("The size of the request (" + requestSize + ") is greater than the allowed size (" + maxRequestSize + ")!", requestSize, maxRequestSize); } } @Override public void beginPart(final Headers headers) { final var disposition = headers.getHeader(Headers.CONTENT_DISPOSITION); if (disposition != null && disposition.startsWith("form-data")) { final var fieldName = Headers.extractQuotedValueFromHeader(disposition, "name"); final var fileName = Headers.extractQuotedValueFromHeader(disposition, "filename"); context.reset(new PartStreamImpl(fileName, fieldName, headers)); } } @Override public void data(final ByteBuffer buffer) throws IOException { checkPartSize(buffer.remaining()); copyBuffer(buffer); if (context.isBuffering() && context.getPartBytesRead() >= sizeThreshold) { validate(false); } if (!context.isBuffering()) { while (buffer.hasRemaining()) { writableChannel.write(buffer); } } } private void copyBuffer(final ByteBuffer buffer) { final var transferCount = Math.min(checkBuffer.remaining(), buffer.remaining()); if (transferCount > 0) { checkBuffer.put(buffer.array(), buffer.arrayOffset() + buffer.position(), transferCount); buffer.position(buffer.position() + transferCount); } } private void validate(final boolean partFinished) throws IOException { context.finishBuffering(); if (partFinished) { context.getCurrentPart().markAsFinished(); } PartOutput output = null; checkBuffer.flip(); if (partBeginCallback != null) { output = requireNonNull(partBeginCallback.onPartBegin(context, checkBuffer)); if (output.safeToCast(WritableByteChannel.class)) { writableChannel = output.unwrap(WritableByteChannel.class); } else if (output.safeToCast(OutputStream.class)) {
writableChannel = new OutputStreamBackedChannel(output.unwrap(OutputStream.class));
8
MHAVLOVICK/Sketchy
src/main/java/com/sketchy/image/ImageProcessingThread.java
[ "public class DrawingSize {\n\n\tprivate static final NumberFormat nf = NumberFormat.getInstance();\n\tstatic{\n\t\tnf.setGroupingUsed(false);\n\t\tnf.setMaximumFractionDigits(5);\n\t\tnf.setMaximumFractionDigits(0);\n\t\tnf.setMinimumIntegerDigits(1);\n\t\tnf.setMaximumIntegerDigits(5);\n\t}\n\t\n\tprivate double ...
import java.awt.Graphics2D; import java.awt.Image; import java.awt.RenderingHints; import java.awt.Toolkit; import java.awt.image.AreaAveragingScaleFilter; import java.awt.image.BufferedImage; import java.awt.image.FilteredImageSource; import java.awt.image.ImageProducer; import java.io.File; import javax.imageio.ImageIO; import marvin.image.MarvinImage; import marvin.image.MarvinImageMask; import marvin.plugin.MarvinImagePlugin; import marvin.util.MarvinPluginLoader; import org.apache.commons.io.FileUtils; import com.sketchy.drawing.DrawingSize; import com.sketchy.image.RenderedImageAttributes.CenterOption; import com.sketchy.image.RenderedImageAttributes.FlipOption; import com.sketchy.image.RenderedImageAttributes.RenderOption; import com.sketchy.image.RenderedImageAttributes.RotateOption; import com.sketchy.image.RenderedImageAttributes.ScaleOption; import com.sketchy.server.HttpServer; import com.sketchy.utils.image.SketchyImage;
/* Sketchy Copyright (C) 2015 Matthew Havlovick http://www.quickdrawbot.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 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Contact Info: Matt Havlovick QuickDraw 470 I St Washougal, WA 98671 matt@quickdrawbot.com http://www.quickdrawbot.com This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. */ package com.sketchy.image; public class ImageProcessingThread extends Thread{ public enum Status{ INIT, RENDERING, CANCELLED, ERROR, COMPLETED; } private RenderedImageAttributes renderedImageAttributes; private boolean cancel=false; private Status status = Status.INIT; private String statusMessage=""; private int progress=0; public ImageProcessingThread(RenderedImageAttributes renderedImageAttributes){ this.renderedImageAttributes = renderedImageAttributes; this.cancel=false; this.status=Status.INIT; this.statusMessage="Initializing Rendering"; } public void cancel(){ cancel=true; } public RenderedImageAttributes getRenderedImageAttributes() { return renderedImageAttributes; } public int getProgress() { return progress; } public void run(){ status=Status.RENDERING; try{ progress=5; DrawingSize drawingSize = DrawingSize.parse(renderedImageAttributes.getDrawingSize()); double dotsPerMM = 1/renderedImageAttributes.getPenWidth(); statusMessage = "Loading Image"; progress=10;
File sourceImage = HttpServer.getUploadFile(ImageAttributes.getImageFilename(renderedImageAttributes.getSourceImageName()));
6
OneNoteDev/Android-REST-API-Explorer
app/src/main/java/com/microsoft/o365_android_onenote_rest/snippet/PagesSnippet.java
[ "public class SnippetDetailFragment<T, Result>\n extends BaseFragment\n implements Callback<Result>,\n AuthenticationCallback<AuthenticationResult>, LiveAuthListener {\n\n public static final String ARG_ITEM_ID = \"item_id\";\n public static final String ARG_TEXT_INPUT = \"TextInput\";\n ...
import com.google.gson.JsonArray; import com.microsoft.o365_android_onenote_rest.R; import com.microsoft.o365_android_onenote_rest.SnippetDetailFragment; import com.microsoft.o365_android_onenote_rest.application.SnippetApp; import com.microsoft.onenoteapi.service.OneNotePartsMap; import com.microsoft.onenoteapi.service.PagesService; import com.microsoft.onenoteapi.service.PatchCommand; import com.microsoft.onenotevos.Envelope; import com.microsoft.onenotevos.Page; import com.microsoft.onenotevos.Section; import org.apache.commons.io.FileUtils; import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.IOUtils; import org.joda.time.DateTime; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.HashMap; import java.util.Map; import retrofit.RetrofitError; import retrofit.client.Response; import retrofit.mime.TypedFile; import retrofit.mime.TypedString; import timber.log.Timber; import static com.microsoft.o365_android_onenote_rest.R.array.create_page_under_named_section; import static com.microsoft.o365_android_onenote_rest.R.array.create_page_with_business_cards; import static com.microsoft.o365_android_onenote_rest.R.array.create_page_with_image; import static com.microsoft.o365_android_onenote_rest.R.array.create_page_with_note_tags; import static com.microsoft.o365_android_onenote_rest.R.array.create_page_with_pdf; import static com.microsoft.o365_android_onenote_rest.R.array.create_page_with_product_info; import static com.microsoft.o365_android_onenote_rest.R.array.create_page_with_recipe; import static com.microsoft.o365_android_onenote_rest.R.array.create_page_with_url_snapshot; import static com.microsoft.o365_android_onenote_rest.R.array.create_page_with_web_page_snapshot; import static com.microsoft.o365_android_onenote_rest.R.array.create_simple_page; import static com.microsoft.o365_android_onenote_rest.R.array.delete_page; import static com.microsoft.o365_android_onenote_rest.R.array.get_all_pages; import static com.microsoft.o365_android_onenote_rest.R.array.get_page_as_html; import static com.microsoft.o365_android_onenote_rest.R.array.get_pages_skip_and_top; import static com.microsoft.o365_android_onenote_rest.R.array.meta_specific_page; import static com.microsoft.o365_android_onenote_rest.R.array.page_append; import static com.microsoft.o365_android_onenote_rest.R.array.pages_selected_meta; import static com.microsoft.o365_android_onenote_rest.R.array.pages_specific_section; import static com.microsoft.o365_android_onenote_rest.R.array.search_all_pages; import static com.microsoft.o365_android_onenote_rest.R.array.specific_title;
/* * Copyright (c) Microsoft. All rights reserved. Licensed under the MIT license. See full license at the bottom of this file. */ package com.microsoft.o365_android_onenote_rest.snippet; public abstract class PagesSnippet<Result> extends AbstractSnippet<PagesService, Result> { public PagesSnippet(Integer descriptionArray) { super(SnippetCategory.pagesSnippetCategory, descriptionArray); } public PagesSnippet(Integer descriptionArray, Input input) { super(SnippetCategory.pagesSnippetCategory, descriptionArray, input); } static PagesSnippet[] getPagesSnippets() { return new PagesSnippet[]{ // Marker element new PagesSnippet(null) { @Override public void request( PagesService service , Callback callback) { // Not implemented } }, /* * POST a new OneNote page in the section picked by the user * HTTP POST https://www.onenote.com/api/beta/me/notes/sections/{id}/pages * @see http://dev.onenote.com/docs#/reference/post-pages */ new PagesSnippet<Page>(create_simple_page, Input.Spinner) { Map<String, Section> sectionMap = new HashMap<>(); String endpointVersion; @Override public void setUp(Services services, final retrofit.Callback<String[]> callback) { fillSectionSpinner(services, callback, sectionMap); } @Override public void request( PagesService service, Callback<Page> callback) { DateTime date = DateTime.now(); String simpleHtml = getSimplePageContentBody(SnippetApp .getApp() .getResources() .openRawResource(R.raw.simple_page), date.toString(), null); String contentType = "text/html; encoding=utf8"; TypedString typedString = new TypedString(simpleHtml) { @Override public String mimeType() { return "text/html"; } }; Section section = sectionMap.get(callback .getParams() .get(SnippetDetailFragment.ARG_SPINNER_SELECTION)); service.postPages( contentType, //Content-Type value getVersion(), //Version section.id, //Section Id, typedString, //HTML note body, callback); } }, /* * Creates a new page in a section referenced by title instead of Id * HTTP POST https://www.onenote.com/api/beta/me/notes/pages{?sectionName} * @see http://dev.onenote.com/docs#/reference/post-pages/v10menotespagessectionname */ new PagesSnippet<Envelope<Page>>(create_page_under_named_section, Input.Spinner) { Map<String, Section> sectionMap = new HashMap<>(); @Override public void setUp(Services services, final retrofit.Callback<String[]> callback) { fillSectionSpinner(services, callback, sectionMap); } @Override public void request(PagesService service, Callback<Envelope<Page>> callback) { DateTime date = DateTime.now(); String simpleHtml = getSimplePageContentBody(SnippetApp .getApp() .getResources() .openRawResource(R.raw.simple_page) , date.toString() , null); TypedString typedString = new TypedString(simpleHtml) { @Override public String mimeType() { return "text/html"; } }; Section section = sectionMap.get(callback .getParams() .get(SnippetDetailFragment.ARG_SPINNER_SELECTION)); service.postPagesInSection( "text/html; encoding=utf8", getVersion(), section.name, typedString, callback ); } }, /* * Creates a page with an embedded image * @see http://dev.onenote.com/docs#/reference/post-pages/v10menotespages */ new PagesSnippet<Envelope<Page>>(create_page_with_image, Input.Spinner) { Map<String, Section> sectionMap = new HashMap<>(); @Override public void setUp(Services services, final retrofit.Callback<String[]> callback) { fillSectionSpinner(services, callback, sectionMap); } @Override public void request(PagesService service, Callback<Envelope<Page>> callback) { DateTime date = DateTime.now(); String imagePartName = "image1"; String simpleHtml = getSimplePageContentBody(SnippetApp .getApp() .getResources() .openRawResource(R.raw.create_page_with_image) , date.toString() , imagePartName); TypedString presentationString = new TypedString(simpleHtml) { @Override public String mimeType() { return "text/html"; } };
OneNotePartsMap oneNotePartsMap = new OneNotePartsMap(presentationString);
2
kmonaghan/Broadsheet.ie-Android
src/ie/broadsheet/app/dialog/MakeCommentDialog.java
[ "public class BaseFragmentActivity extends SherlockFragmentActivity {\n private ProgressDialog mProgressDialog;\n\n private SpiceManager spiceManager = new SpiceManager(BroadsheetServices.class);\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceSt...
import ie.broadsheet.app.BaseFragmentActivity; import ie.broadsheet.app.BroadsheetApplication; import ie.broadsheet.app.R; import ie.broadsheet.app.model.json.Comment; import ie.broadsheet.app.requests.MakeCommentRequest; import ie.broadsheet.app.services.BroadsheetServices; import android.app.AlertDialog; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.SharedPreferences; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.WindowManager; import android.view.inputmethod.InputMethodManager; import android.widget.Button; import android.widget.EditText; import com.actionbarsherlock.app.SherlockDialogFragment; import com.octo.android.robospice.SpiceManager; import com.octo.android.robospice.persistence.exception.SpiceException; import com.octo.android.robospice.request.listener.RequestListener;
package ie.broadsheet.app.dialog; public class MakeCommentDialog extends SherlockDialogFragment implements OnClickListener { public interface CommentMadeListener { public void onCommentMade(Comment comment); } private CommentMadeListener mListener; private static final String TAG = "MakeCommentDialog"; private SpiceManager spiceManager = new SpiceManager(BroadsheetServices.class); private int postId; private int commentId = 0; private EditText email; private EditText commenterName; private EditText commenterUrl; private EditText commentBody; private Dialog dialog; public int getPostId() { return postId; } public void setPostId(int postId) { this.postId = postId; } public int getCommentId() { return commentId; } public void setCommentId(int commentId) { this.commentId = commentId; } public void setCommentMadeListener(CommentMadeListener mListener) { this.mListener = mListener; } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); // Get the layout inflater LayoutInflater inflater = getActivity().getLayoutInflater(); View view = inflater.inflate(R.layout.dialog_make_comment, null); commenterName = (EditText) view.findViewById(R.id.commenterName); email = (EditText) view.findViewById(R.id.commenterEmail); commenterUrl = (EditText) view.findViewById(R.id.commenterUrl); commentBody = (EditText) view.findViewById(R.id.commentBody); SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE); email.setText(sharedPref.getString("email", "")); commenterName.setText(sharedPref.getString("commenterName", "")); commenterUrl.setText(sharedPref.getString("commenterUrl", "")); // Inflate and set the layout for the dialog // Pass null as the parent view because its going in the dialog layout builder.setView(view) // Add action buttons .setPositiveButton(R.string.comment, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { } }).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { MakeCommentDialog.this.getDialog().cancel(); } }); dialog = builder.create(); commenterName.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (hasFocus) { dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE); } } }); return dialog; } @Override public void onStart() { spiceManager.start(getActivity()); super.onStart(); AlertDialog d = (AlertDialog) getDialog(); if (d != null) { Button positiveButton = (Button) d.getButton(Dialog.BUTTON_POSITIVE); positiveButton.setOnClickListener(this); } ((BroadsheetApplication) getActivity().getApplication()).getTracker().sendView("Post Comment"); } @Override public void onStop() { spiceManager.shouldStop(); super.onStop(); } @Override public void onClick(View v) { if (!validate()) { return; } SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedPref.edit(); editor.putString("email", email.getText().toString()); editor.putString("commenterName", commenterName.getText().toString()); editor.putString("commenterUrl", commenterUrl.getText().toString()); editor.commit();
MakeCommentRequest makeCommentRequest = new MakeCommentRequest();
3
mjdbc/mjdbc
src/test/java/com/github/mjdbc/test/DbValuesTest.java
[ "public class DbPreparedStatement<T> implements AutoCloseable {\n\n /**\n * Actual java.sql.PreparedStatement in use.\n */\n @NotNull\n public final PreparedStatement statement;\n\n /**\n * Mapper for the result. Used by methods like ${link {@link #query()} or {@link #queryList()}}\n */\...
import com.github.mjdbc.DbPreparedStatement; import com.github.mjdbc.Mappers; import com.github.mjdbc.type.DbInt; import com.github.mjdbc.type.DbLong; import com.github.mjdbc.type.DbString; import java.sql.Timestamp; import org.junit.Test;
package com.github.mjdbc.test; /** * Tests for DbValue (Int,Long..) support. */ public class DbValuesTest extends DbTest { @Test public void checkDbInt() { String login = db.execute(c -> new DbPreparedStatement<>(c, "SELECT login FROM users WHERE id = :id", Mappers.StringMapper) .set("id", () -> 1) .query()); assertEquals("u1", login); } @Test public void checkDbIntNull() { String login = db.execute(c -> new DbPreparedStatement<>(c, "SELECT login FROM users WHERE id = :id", Mappers.StringMapper)
.set("id", (DbInt) null)
2
titorenko/quick-csv-streamer
src/main/java/uk/elementarysoftware/quickcsv/parser/ByteSlice.java
[ "public static class ByteArrayChunk extends ReusableChunk {\n public static final ByteArrayChunk EMPTY = new ByteArrayChunk(new byte[0], 0, false, (b) -> {});\n \n private final byte[] data;\n private final int length;\n private final boolean isLast;\n\n /**\n * @param data - underlying co...
import java.nio.charset.Charset; import uk.elementarysoftware.quickcsv.api.ByteArraySource.ByteArrayChunk; import uk.elementarysoftware.quickcsv.api.CSVParserBuilder.CSVFileMetadata; import uk.elementarysoftware.quickcsv.functional.Pair; import uk.elementarysoftware.quickcsv.functional.PrimitiveFunctions.FunBiCharToBoolean; import uk.elementarysoftware.quickcsv.functional.PrimitiveFunctions.FunBiCharToT; import uk.elementarysoftware.quickcsv.functional.PrimitiveFunctions.FunCharToBoolean; import uk.elementarysoftware.quickcsv.functional.PrimitiveFunctions.FunCharToT;
@Override public boolean nextLine() { for(; hasMoreData() && buffer[currentIndex]!=CR && buffer[currentIndex]!=LF; currentIndex++); return frontTrim(); } public String currentLine() { int startIdx = currentIndex; for(; startIdx > start && buffer[startIdx]!=CR && buffer[startIdx]!=LF; startIdx--); int endIdx = currentIndex; for(; endIdx < end && buffer[endIdx]!=CR && buffer[endIdx]!=LF; endIdx++); return new String(buffer, startIdx, endIdx - startIdx); } public Pair<ByteSlice, ByteSlice> splitOnLastLineEnd() { int i = end-1; for (;i >=currentIndex && buffer[i] != LF; i--); SingleByteSlice prefix = new SingleByteSlice(src, buffer, currentIndex, i+1, charset); SingleByteSlice suffix = new SingleByteSlice(src, buffer, i+1, end, charset); return Pair.of(prefix, suffix); } public boolean skipUntil(final char c) { boolean isFound = false; while(currentIndex < end) { if (buffer[currentIndex]==c) { currentIndex++; isFound = true; break; } currentIndex++; } return isFound; } public boolean skipUntil(char c, char q) { boolean inQuote = currentIndex < buffer.length && buffer[currentIndex] == q; if (!inQuote) return skipUntil(c); currentIndex++; boolean isFound = false; while(currentIndex < end) { if (buffer[currentIndex]==c && buffer[currentIndex-1] == q) { currentIndex++; isFound = true; break; } currentIndex++; } return isFound; } public ByteArrayField nextField(final char c) { int startIndex = currentIndex; int endIndex = currentIndex; while(currentIndex < end) { byte cur = buffer[currentIndex]; if (cur == c || cur == CR || cur == LF) { endIndex = currentIndex; if (cur == c) currentIndex++; break; } else { currentIndex++; } } if (currentIndex == startIndex) return null; if (currentIndex == end) endIndex = end; fieldTemplateObject.modifyBounds(startIndex, endIndex); return fieldTemplateObject; } @Override public ByteArrayField nextField(char c, char q) { boolean inQuote = currentIndex < buffer.length && buffer[currentIndex] == q; if (!inQuote) return nextField(c); currentIndex++; int startIndex = currentIndex; int endIndex = currentIndex; while(currentIndex < end) { byte cur = buffer[currentIndex]; if ((cur == c || cur == CR || cur == LF) && buffer[currentIndex-1] == q) {//there is an issue when we have escaped quote and then separator, but we ignore it for now endIndex = currentIndex - 1; if (cur == c) currentIndex++; //let frontTrim consume linebreaks later break; } else { currentIndex++; } } if (currentIndex == startIndex) return null; if (currentIndex == end) { if (buffer[end-1] == q) endIndex = end - 1; else endIndex = end; } fieldTemplateObject.modifyBounds(startIndex, endIndex, q); return fieldTemplateObject; } @Override public String toString() { return new String(buffer, start, size()); } @Override public void incrementUse() { src.incrementUseCount(); } @Override public void decremenentUse() { src.decrementUseCount(); } } final class CompositeByteSlice implements ByteSlice { private final SingleByteSlice prefix; private final SingleByteSlice suffix; private final ByteArrayField prefixFieldTemplateObject; private final ByteArrayField suffixFieldTemplateObject; private FunCharToT<ByteArrayField> nextFieldFun;
private FunBiCharToT<ByteArrayField> nextFieldFunQuoted;
4
awvalenti/bauhinia
coronata/coronata-demos/src/main/java/com/github/awvalenti/bauhinia/coronata/demo5vibration/Vibration.java
[ "public class CoronataBuilder {\n\n\tprivate final CoronataConfig config = new CoronataConfig();\n\n\tprivate CoronataBuilder() {\n\t}\n\n\tpublic static CoronataBuilder beginConfig() {\n\t\treturn new CoronataBuilder();\n\t}\n\n\tpublic CoronataBuilder wiiRemotesExpected(int count) {\n\t\tconfig.setNumberOfWiiRemo...
import com.github.awvalenti.bauhinia.coronata.CoronataBuilder; import com.github.awvalenti.bauhinia.coronata.CoronataException; import com.github.awvalenti.bauhinia.coronata.CoronataWiiRemote; import com.github.awvalenti.bauhinia.coronata.CoronataWiiRemoteButton; import com.github.awvalenti.bauhinia.coronata.observers.CoronataButtonObserver; import com.github.awvalenti.bauhinia.coronata.observers.CoronataConnectionObserver; import com.github.awvalenti.bauhinia.coronata.observers.CoronataErrorObserver;
package com.github.awvalenti.bauhinia.coronata.demo5vibration; public class Vibration implements CoronataConnectionObserver, CoronataButtonObserver, CoronataErrorObserver {
private CoronataWiiRemote wiiRemote;
2
fzakaria/WaterFlow
src/main/java/com/github/fzakaria/waterflow/poller/DecisionPoller.java
[ "public abstract class Workflow<InputType,OutputType> {\n\n protected final Logger log = LoggerFactory.getLogger(getClass());\n\n public abstract Name name();\n\n public abstract Version version();\n /**\n * Workflow name and version glued together to make a key.\n */\n @Value.Derived\n pu...
import com.amazonaws.services.simpleworkflow.flow.common.WorkflowExecutionUtils; import com.amazonaws.services.simpleworkflow.model.Decision; import com.amazonaws.services.simpleworkflow.model.DecisionTask; import com.amazonaws.services.simpleworkflow.model.FailWorkflowExecutionDecisionAttributes; import com.amazonaws.services.simpleworkflow.model.HistoryEvent; import com.amazonaws.services.simpleworkflow.model.PollForDecisionTaskRequest; import com.amazonaws.services.simpleworkflow.model.RegisterWorkflowTypeRequest; import com.amazonaws.services.simpleworkflow.model.RespondDecisionTaskCompletedRequest; import com.amazonaws.services.simpleworkflow.model.TaskList; import com.amazonaws.services.simpleworkflow.model.TypeAlreadyExistsException; import com.github.fzakaria.waterflow.Workflow; import com.github.fzakaria.waterflow.converter.DataConverter; import com.github.fzakaria.waterflow.event.Event; import com.github.fzakaria.waterflow.immutable.DecisionContext; import com.github.fzakaria.waterflow.immutable.Key; import com.github.fzakaria.waterflow.immutable.Name; import com.github.fzakaria.waterflow.immutable.Version; import com.github.fzakaria.waterflow.swf.DecisionTaskIterator; import com.github.fzakaria.waterflow.swf.RegisterWorkflowTypeRequestBuilder; import com.google.common.base.Joiner; import com.google.common.base.Throwables; import com.google.common.collect.Lists; import org.immutables.value.Value; import java.util.List; import java.util.Optional; import java.util.concurrent.CompletionStage; import java.util.stream.Collectors; import static com.amazonaws.services.simpleworkflow.model.EventType.WorkflowExecutionCancelRequested; import static com.github.fzakaria.waterflow.TaskType.WORKFLOW_EXECUTION; import static com.github.fzakaria.waterflow.Workflow.createCompleteWorkflowExecutionDecision; import static com.github.fzakaria.waterflow.Workflow.createFailWorkflowExecutionDecision; import static com.github.fzakaria.waterflow.event.EventState.ERROR; import static java.lang.String.format;
package com.github.fzakaria.waterflow.poller; /** * Poll for {@link DecisionTask} event on a single domain and task list and ask a registered {@link Workflow} for next decisions. * <p/> * Implements {@link Runnable} so that multiple instances of this class can be scheduled to handle higher levels of activity tasks. * * @see BasePoller */ @Value.Immutable public abstract class DecisionPoller extends BasePoller<DecisionTask> { public abstract List<Workflow<?,?>> workflows(); public abstract DataConverter dataConverter(); /** * Register workflows added to this poller on Amazon SWF with this instance's domain and task list. * {@link TypeAlreadyExistsException} are ignored making this method idempotent. * */ @Override public void register() { for (Workflow workflow : workflows()) { try { RegisterWorkflowTypeRequest request = RegisterWorkflowTypeRequestBuilder.builder().domain(domain()) .workflow(workflow).build(); swf().registerWorkflowType(request); log.info(format("Register workflow succeeded %s", workflow)); } catch (TypeAlreadyExistsException e) { log.info(format("Register workflow already exists %s", workflow)); } catch (Throwable t) { String format = format("Register workflow failed %s", workflow); log.error(format); throw new IllegalStateException(format, t); } } } @Override protected DecisionTask poll() { // Events are request in newest-first reverse order; PollForDecisionTaskRequest request = createPollForDecisionTaskRequest(); //If no decision task is available in the specified task list before the timeout of 60 seconds expires, //an empty result is returned. An empty result, in this context, means that a DecisionTask is returned, //but that the value of taskToken is an empty string. //{@see http://docs.aws.amazon.com/amazonswf/latest/apireference/API_PollForDecisionTask.html} DecisionTask decisionTask = swf().pollForDecisionTask(request); if (decisionTask == null || decisionTask.getTaskToken() == null) { return null; } return decisionTask; } @Override protected void consume(DecisionTask decisionTask) { // Events are request in newest-first reverse order; PollForDecisionTaskRequest request = createPollForDecisionTaskRequest(); DecisionTaskIterator decisionTaskIterator = new DecisionTaskIterator(swf(), request, decisionTask); final List<HistoryEvent> historyEvents = Lists.newArrayList(decisionTaskIterator); final List<Event> events = Event.fromHistoryEvents(historyEvents); if (events.isEmpty()) { log.debug("No decisions found for a workflow"); return; } final Workflow<?,?> workflow = lookupWorkflow(decisionTask); // Finished loading history for this workflow, now ask it to make the next set of decisions. final String workflowId = decisionTask.getWorkflowExecution().getWorkflowId(); final String runId = decisionTask.getWorkflowExecution().getRunId(); //Order here is important since decisionContext creates a new array final DecisionContext decisionContext = DecisionContext.create().addAllEvents(events); final List<Decision> decisions = decisionContext.decisions(); List<Event> workflowErrors = events.stream().filter(e -> e.task() == WORKFLOW_EXECUTION) .filter(e -> e.state() == ERROR).collect(Collectors.toList()); if (workflowErrors.isEmpty()) { try { //No need to replay if cancel event exists. Just cancel immediately Optional<Event> cancelEvent = events.stream().filter(e -> e.type() == WorkflowExecutionCancelRequested).findFirst(); cancelEvent.ifPresent(event -> workflow.onCancelRequested(event, decisions)); CompletionStage<?> future = workflow.decide(decisionContext); future.thenApply( r -> { log.debug("Workflow {} completed. Added final decision to complete workflow.", workflow.key()); return dataConverter().toData(r); }).exceptionally(t -> { Throwable rootCause = Throwables.getRootCause(t); log.debug("Workflow {} failed. Added final decision to complete workflow.", workflow.key(), rootCause); return dataConverter().toData(rootCause); }).thenAccept(r -> decisions.add(createCompleteWorkflowExecutionDecision(r))); if (log.isDebugEnabled()) { log.debug(WorkflowExecutionUtils.prettyPrintDecisions(decisions)); } } catch (Throwable t) { String runInfo = format("%s %s", workflowId, runId); String details = dataConverter().toData(t); log.error(runInfo, t);
decisions.add(createFailWorkflowExecutionDecision(runInfo, t.getMessage(), details));
5
multi-os-engine/moe-plugin-gradle
src/main/java/org/moe/gradle/tasks/AbstractBaseTask.java
[ "public abstract class RuleClosure extends Closure<Task> {\n\n protected RuleClosure(Object owner) {\n super(Require.nonNull(owner));\n }\n\n public abstract Task doCall(String taskName);\n}", "public abstract class ValueClosure<V> extends Closure<V> {\n\n protected ValueClosure(@NotNull Object...
import org.gradle.api.*; import org.gradle.api.logging.Logger; import org.gradle.api.logging.Logging; import org.gradle.api.tasks.Input; import org.gradle.api.tasks.Internal; import org.gradle.api.tasks.OutputFile; import org.gradle.api.tasks.TaskAction; import org.gradle.process.ExecResult; import org.gradle.process.ExecSpec; import org.gradle.process.JavaExecSpec; import org.moe.common.utils.FileUtilsKt; import org.moe.gradle.*; import org.moe.gradle.anns.IgnoreUnused; import org.moe.gradle.anns.NotNull; import org.moe.gradle.anns.Nullable; import org.moe.gradle.groovy.closures.RuleClosure; import org.moe.gradle.groovy.closures.ValueClosure; import org.moe.gradle.remote.Server; import org.moe.gradle.utils.FileUtils; import org.moe.gradle.utils.Require; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Date; import java.util.function.Function; import java.util.function.Supplier;
/* Copyright (C) 2016 Migeran 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.moe.gradle.tasks; public abstract class AbstractBaseTask extends DefaultTask { protected static final String CONVENTION_LOG_FILE = "logFile"; private static final String CONVENTION_REMOTE_BUILD_HELPER = "remoteBuildHelper"; private static final String MOE_RAW_BINDING_OUTPUT_OPTION = "raw-binding-output"; private Object logFile; private final Logger logger = Logging.getLogger(getClass()); @OutputFile @NotNull public File getLogFile() { return getProject().file(getOrConvention(logFile, CONVENTION_LOG_FILE)); } @IgnoreUnused public void setLogFile(Object logFile) { this.logFile = logFile; } private Boolean remoteExecutionStatusSet; @Internal public boolean getRemoteExecutionStatusSet() { return Require.nonNull(remoteExecutionStatusSet); } @Input @NotNull @IgnoreUnused public Long getRemoteBuildHelper() { Require.nonNull(remoteExecutionStatusSet, "Remote execution status was not set on task '" + getName() + "'"); return getOrConvention(null, CONVENTION_REMOTE_BUILD_HELPER); } protected void setSupportsRemoteBuild(boolean value) { Require.nullObject(remoteExecutionStatusSet, "Remote execution status was already set on task '" + getName() + "'"); remoteExecutionStatusSet = value; addConvention(CONVENTION_REMOTE_BUILD_HELPER, () -> { if (remoteExecutionStatusSet) { if (getMoePlugin().getRemoteServer() != null) { return new Date().getTime(); } else { return 0L; } } else { return 0L; } }); } @TaskAction @IgnoreUnused private void runInternal() { // Reset logs FileUtils.write(getLogFile(), ""); run(); setDidWork(true); } abstract protected void run(); @Internal protected @NotNull MoeExtension getMoeExtension() { return (MoeExtension) getExtension(); } @Internal public @NotNull AbstractMoeExtension getExtension() { return AbstractMoeExtension.getInstance(getProject()); } @NotNull @Internal protected MoePlugin getMoePlugin() { return Require.nonNull((MoePlugin) getMoeExtension().plugin); } @Internal protected @NotNull MoeSDK getMoeSDK() { return getMoeExtension().plugin.getSDK(); } public void addConvention(String name, Supplier<@Nullable Object> supplier) { Require.nonNull(name); Require.nonNull(supplier);
getConvention().add(name, new ValueClosure<Object>(this) {
1
kstateome/lti-attendance
src/main/java/edu/ksu/canvas/attendance/controller/RosterController.java
[ "@Entity\n@Table(name = \"attendance_section\")\npublic class AttendanceSection implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n @Id\n @GeneratedValue(strategy = GenerationType.AUTO)\n @Column(name = \"section_id\")\n private Long sectionId; //attendance project's lo...
import edu.ksu.canvas.attendance.entity.AttendanceSection; import edu.ksu.canvas.attendance.form.RosterForm; import edu.ksu.canvas.attendance.form.RosterFormValidator; import edu.ksu.canvas.attendance.model.SectionModelFactory; import edu.ksu.canvas.attendance.services.AttendanceCourseService; import edu.ksu.canvas.attendance.services.AttendanceSectionService; import edu.ksu.canvas.attendance.services.AttendanceService; import edu.ksu.canvas.attendance.util.DropDownOrganizer; import edu.ksu.lti.launch.exception.NoLtiSessionException; import org.apache.commons.validator.routines.LongValidator; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.LogManager; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.propertyeditors.CustomDateEditor; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import org.springframework.validation.BindingResult; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletResponse; import javax.validation.Valid; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List;
package edu.ksu.canvas.attendance.controller; @Controller @Scope("session") @SessionAttributes("rosterForm") @RequestMapping("/roster") public class RosterController extends AttendanceBaseController { private static final Logger LOG = LogManager.getLogger(RosterController.class); @Autowired private SectionModelFactory sectionModelFactory; @Autowired private AttendanceService attendanceService; @Autowired private AttendanceCourseService courseService; @Autowired private AttendanceSectionService sectionService; @Autowired private RosterFormValidator validator; @InitBinder protected void initBinder(WebDataBinder binder) { SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy"); binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false)); } @RequestMapping() public ModelAndView roster(@RequestParam(required = false) Date date) throws NoLtiSessionException { return roster(date, null); } @RequestMapping("/{sectionId}") public ModelAndView roster(@RequestParam(required = false) Date date, @PathVariable String sectionId) throws NoLtiSessionException { ensureCanvasApiTokenPresent(); Long validatedSectionId = LongValidator.getInstance().validate(sectionId);
AttendanceSection selectedSection = getSelectedSection(validatedSectionId);
0
onesocialweb/osw-lib-gwt
src/org/onesocialweb/gwt/service/imp/GwtActivities.java
[ "public class GwtActivityDomReader extends ActivityDomReader {\n\n\t@Override\n\tprotected AclDomReader getAclDomReader() {\n\t\treturn new GwtAclDomReader();\n\t}\n\n\t@Override\n\tprotected ActivityFactory getActivityFactory() {\n\t\treturn new DefaultActivityFactory();\n\t}\n\n\t@Override\n\tprotected AtomDomRea...
import java.util.ArrayList; import java.util.List; import org.onesocialweb.gwt.model.GwtActivityDomReader; import org.onesocialweb.gwt.service.RequestCallback; import org.onesocialweb.gwt.service.Stream; import org.onesocialweb.gwt.service.StreamEvent; import org.onesocialweb.gwt.service.StreamEvent.Type; import org.onesocialweb.gwt.util.ObservableHelper; import org.onesocialweb.gwt.util.Observer; import org.onesocialweb.gwt.xml.ElementAdapter; import org.onesocialweb.model.activity.ActivityEntry; import org.onesocialweb.xml.dom.ActivityDomReader; import org.w3c.dom.Element; import com.calclab.emite.core.client.packet.IPacket; import com.calclab.emite.core.client.packet.gwt.GWTPacket; import com.calclab.emite.core.client.xmpp.session.Session; import com.calclab.emite.core.client.xmpp.stanzas.IQ; import com.calclab.emite.core.client.xmpp.stanzas.XmppURI; import com.calclab.suco.client.Suco; import com.calclab.suco.client.events.Listener;
/* * Copyright 2010 Vodafone Group Services Ltd. * * 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.onesocialweb.gwt.service.imp; public class GwtActivities implements Stream<ActivityEntry> { private final ObservableHelper<StreamEvent<ActivityEntry>> helper = new ObservableHelper<StreamEvent<ActivityEntry>>(); private final Session session = Suco.get(Session.class); private final String jid; private final List<ActivityEntry> entries = new ArrayList<ActivityEntry>(); private boolean isReady = false; public GwtActivities(String jid) { this.jid = jid; } @Override public List<ActivityEntry> getItems() { return entries; } @Override public void refresh(final RequestCallback<List<ActivityEntry>> callback) { IQ iq = new IQ(IQ.Type.get); IPacket pubsubElement = iq.addChild("pubsub", "http://jabber.org/protocol/pubsub"); IPacket itemsElement = pubsubElement.addChild("items", "http://jabber.org/protocol/pubsub"); itemsElement.setAttribute("node", "urn:xmpp:microblog:0"); iq.setTo(XmppURI.jid(jid)); session.sendIQ("osw", iq, new Listener<IPacket>() { public void onEvent(IPacket packet) { // Check if not an error if (IQ.isSuccess(packet)) { // IQ Succes means we can clear the existing entries entries.clear(); // Parse the packet and check if a proper query result IPacket pubsubResult = packet.getFirstChild("pubsub"); IPacket itemsResult = pubsubResult.getFirstChild("items"); if (itemsResult != null && itemsResult.getChildrenCount() > 0) { // Parse the packet and store the notifications for (IPacket item : itemsResult.getChildren()) { if (item instanceof GWTPacket) { GWTPacket i_packet = (GWTPacket) item .getFirstChild("entry"); if (i_packet == null) continue; Element element = new ElementAdapter(i_packet .getElement()); ActivityDomReader reader = new GwtActivityDomReader(); ActivityEntry activity = reader .readEntry(element); entries.add(activity); } } } // Set the ready flag to true isReady = true; // Fire the event to the observer helper .fireEvent(new ActivityEvent(Type.refreshed, entries)); // Execute the callback if (callback != null) { callback.onSuccess(entries); return; } // Done return; } // If we are here, there was an error if (callback != null) { callback.onFailure(); } } }); } @Override public void registerEventHandler(
Observer<StreamEvent<ActivityEntry>> handler) {
6
JavaBaas/JavaBaas_SDK_Android
source/src/main/java/com/javabaas/cache/JBCacheManager.java
[ "public abstract class IObjectManager {\n\n static String appKey = \"\";\n static String appId = \"\";\n static String host = \"\";\n static final int LOGIN_WITH_USERNAME_TYPE = 0;\n static final int LOGIN_WITH_SNS_TYPE = 1;\n static final int LOGIN_WITH_PHONE_TYPE = 2;\n\n private String table...
import com.alibaba.fastjson.JSON; import java.io.File; import java.util.List; import com.javabaas.IObjectManager; import com.javabaas.JBCloud; import com.javabaas.callback.FindCallback; import com.javabaas.JBObject; import com.javabaas.exception.JBException; import com.javabaas.util.Utils;
package com.javabaas.cache; public class JBCacheManager { private static JBCacheManager instance = null; private static File keyValueCacheDir() { File dir = new File(JBPersistenceUtils.getCacheDir(), "JBKeyValueCache"); dir.mkdirs(); return dir; } private static File getCacheFile(String fileName) { return new File(keyValueCacheDir(), fileName); } private JBCacheManager() { } public static synchronized JBCacheManager sharedInstance() { if(instance == null) { instance = new JBCacheManager(); } return instance; } public String fileCacheKey(String key, String ts) { return !Utils.isBlankString(ts)?Utils.MD5(key + ts):Utils.MD5(key); } public boolean hasCache(String key) { return this.hasCache(key, (String)null); } public boolean hasCache(String key, String ts) { File file = this.getCacheFile(key, ts); return file.exists(); } public boolean hasValidCache(String key, String ts, long maxAgeInMilliseconds) { File file = this.getCacheFile(key, ts); return file.exists() && System.currentTimeMillis() - file.lastModified() < maxAgeInMilliseconds; } private File getCacheFile(String key, String ts) { return getCacheFile(this.fileCacheKey(key, ts)); }
public <T> void get(String key, long maxAgeInMilliseconds, String className, Class<T> clazz, FindCallback<T> getCallback) {
2
6ag/BaoKanAndroid
app/src/main/java/tv/baokan/baokanandroid/ui/fragment/NewsFragment.java
[ "public class TabFragmentPagerAdapter extends FragmentPagerAdapter {\n\n private List<ColumnBean> mSelectedList = new ArrayList<>();\n private List<BaseFragment> mListFragments = new ArrayList<>();\n\n public TabFragmentPagerAdapter(FragmentManager fm, List<? extends BaseFragment> listFragments, List<Colum...
import android.content.Intent; import android.support.design.widget.TabLayout; import android.support.v4.view.ViewPager; import android.view.View; import android.widget.ImageButton; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; import tv.baokan.baokanandroid.R; import tv.baokan.baokanandroid.adapter.TabFragmentPagerAdapter; import tv.baokan.baokanandroid.app.BaoKanApp; import tv.baokan.baokanandroid.model.ColumnBean; import tv.baokan.baokanandroid.ui.activity.ColumnActivity; import tv.baokan.baokanandroid.utils.LogUtils; import tv.baokan.baokanandroid.utils.StreamUtils; import static android.app.Activity.RESULT_OK;
package tv.baokan.baokanandroid.ui.fragment; public class NewsFragment extends BaseFragment { private static final String TAG = "NewsFragment"; public static final int REQUEST_CODE_COLUMN = 0; private TabLayout mNewsTabLayout; private ViewPager mNewsViewPager; private ImageButton mNewsClassAdd; private List<ColumnBean> selectedList = new ArrayList<>(); private List<ColumnBean> optionalList = new ArrayList<>(); List<NewsListFragment> newsListFragments = new ArrayList<>(); private TabFragmentPagerAdapter mFragmentPageAdapter; @Override protected View prepareUI() { View view = View.inflate(mContext, R.layout.fragment_news, null); mNewsTabLayout = (TabLayout) view.findViewById(R.id.tl_news_tabLayout); mNewsViewPager = (ViewPager) view.findViewById(R.id.vp_news_viewPager); mNewsClassAdd = (ImageButton) view.findViewById(R.id.ib_news_class_add); // 点击加号进入栏目编辑activity mNewsClassAdd.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // 弹出栏目管理activity ColumnActivity.start(getActivity(), selectedList, optionalList); } }); return view; } @Override protected void loadData() { // 判断手机缓存里有没有栏目数据,有则加载,无咋加载默认json数据
if (StreamUtils.fileIsExists(BaoKanApp.getContext().getFileStreamPath("column.json").getAbsolutePath())) {
5
magnetsystems/message-samples-android
SmartShopper/app/src/main/java/com/magnet/smartshopper/activities/ProductListActivity.java
[ "public class ProductAdapter extends ArrayAdapter<Product> {\n // View lookup cache\n private static class ViewHolder {\n public ImageView ivItemImage;\n public TextView tvItemTitle;\n public TextView tvItemPrice;\n }\n\n public ProductAdapter(Context context, ArrayList<Product> aBo...
import android.content.Intent; import android.content.res.Resources; import android.os.AsyncTask; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import com.magnet.mmx.client.common.Log; import com.magnet.smartshopper.R; import com.magnet.smartshopper.adapters.ProductAdapter; import com.magnet.smartshopper.services.MagnetMessageService; import com.magnet.smartshopper.walmart.SearchItemService; import com.magnet.smartshopper.walmart.SearchItemServiceClient; import com.magnet.smartshopper.walmart.model.Items; import com.magnet.smartshopper.walmart.model.Product; import com.magnet.smartshopper.walmart.model.SearchResponseObject; import com.magnet.smartshopper.wunderground.WeatherService; import com.magnet.smartshopper.wunderground.model.Weather; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Properties; import retrofit.RestAdapter;
package com.magnet.smartshopper.activities; public class ProductListActivity extends AppCompatActivity { private static final String API_KEY = "API_KEY"; private static String RESPONSE_FORMAT = "RESPONSE_FORMAT"; private static final String BASE_URL = "BASE_URL"; private final String TAG = "ProductListActivity"; public static final String PRODUCT_DETAIL_KEY = "product"; private ListView lvProducts; private ProductAdapter productAdapter; private ProgressBar progress; private RestAdapter restAdapter; private Properties credentials; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); initWalmartApiCredentials(); setContentView(R.layout.activity_product_list); Log.setLoggable(null, Log.VERBOSE); Toast.makeText(ProductListActivity.this, "Trying to get the weather", Toast.LENGTH_LONG).show(); MagnetMessageService.registerAndLoginUser(this); lvProducts = (ListView) findViewById(R.id.lvProducts); ArrayList<Product> products = new ArrayList<Product>(); // initialize the adapter productAdapter = new ProductAdapter(this, products); // attach the adapter to the ListView lvProducts.setAdapter(productAdapter); progress = (ProgressBar) findViewById(R.id.progress); setupProductSelectedListener(); //Get Current Weather for fixed location SF new AsyncTask<Void,String,Weather>() { @Override protected Weather doInBackground(Void ...avoid) { try {
Weather weather = WeatherService.getCurrentTemperature();
7
dirk/hummingbird2
src/main/java/org/hummingbirdlang/nodes/frames/CreateBindingsNode.java
[ "@NodeInfo(language = \"HB\")\npublic abstract class HBNode extends Node {\n // Execute with a generic unspecialized return value.\n public abstract Object executeGeneric(VirtualFrame frame);\n\n // Execute without a return value.\n public void executeVoid(VirtualFrame frame) {\n executeGeneric(frame);\n }\...
import com.oracle.truffle.api.dsl.Cached; import com.oracle.truffle.api.dsl.NodeField; import com.oracle.truffle.api.dsl.Specialization; import com.oracle.truffle.api.frame.MaterializedFrame; import com.oracle.truffle.api.frame.VirtualFrame; import java.util.ArrayList; import java.util.List; import org.hummingbirdlang.nodes.HBNode; import org.hummingbirdlang.runtime.bindings.Binding; import org.hummingbirdlang.runtime.bindings.Bindings; import org.hummingbirdlang.runtime.bindings.MaterializedBinding; import org.hummingbirdlang.types.FunctionType; import org.hummingbirdlang.types.scope.Resolution; import org.hummingbirdlang.types.scope.Scope;
package org.hummingbirdlang.nodes.frames; // Assembles the `Bindings` for a function. @NodeField(name = "type", type = FunctionType.class) public abstract class CreateBindingsNode extends HBNode { protected abstract FunctionType getType();
public abstract Bindings executeCreateBindings(VirtualFrame frame);
2
davidmoten/rxjava2-jdbc
rxjava2-jdbc/src/main/java/org/davidmoten/rx/jdbc/GetterTx.java
[ "public class Tuple2<T1, T2> {\n\n private final T1 value1;\n private final T2 value2;\n\n /**\n * Constructor.\n * \n * @param value1\n * first element\n * @param value2\n * second element\n */\n public Tuple2(T1 value1, T2 value2) {\n this.value...
import java.sql.ResultSet; import java.util.Optional; import javax.annotation.Nonnull; import org.davidmoten.rx.jdbc.tuple.Tuple2; import org.davidmoten.rx.jdbc.tuple.Tuple3; import org.davidmoten.rx.jdbc.tuple.Tuple4; import org.davidmoten.rx.jdbc.tuple.Tuple5; import org.davidmoten.rx.jdbc.tuple.Tuple6; import org.davidmoten.rx.jdbc.tuple.Tuple7; import org.davidmoten.rx.jdbc.tuple.TupleN; import org.davidmoten.rx.jdbc.tuple.Tuples; import com.github.davidmoten.guavamini.Preconditions; import io.reactivex.Flowable; import io.reactivex.Single;
package org.davidmoten.rx.jdbc; public interface GetterTx { /** * Transforms the results using the given function. * * @param mapper * transforms ResultSet row to an object of type T * @param <T> * the type being mapped to * @return the results of the query as an Observable */ <T> Flowable<Tx<T>> get(@Nonnull ResultSetMapper<? extends T> mapper); default <T> Flowable<Tx<T>> getAs(@Nonnull Class<T> cls) { Preconditions.checkNotNull(cls, "cls cannot be null"); return get(rs -> Util.mapObject(rs, cls, 1)); } default <T> Flowable<Tx<Optional<T>>> getAsOptional(@Nonnull Class<T> cls) { Preconditions.checkNotNull(cls, "cls cannot be null"); return get(rs -> Optional.ofNullable(Util.mapObject(rs, cls, 1))); } /** * <p> * Transforms each row of the {@link ResultSet} into an instance of * <code>T</code> using <i>automapping</i> of the ResultSet columns into * corresponding constructor parameters that are assignable. Beyond normal * assignable criteria (for example Integer 123 is assignable to a Double) other * conversions exist to facilitate the automapping: * </p> * <p> * They are: * <ul> * <li>java.sql.Blob --&gt; byte[]</li> * <li>java.sql.Blob --&gt; java.io.InputStream</li> * <li>java.sql.Clob --&gt; String</li> * <li>java.sql.Clob --&gt; java.io.Reader</li> * <li>java.sql.Date --&gt; java.util.Date</li> * <li>java.sql.Date --&gt; Long</li> * <li>java.sql.Timestamp --&gt; java.util.Date</li> * <li>java.sql.Timestamp --&gt; Long</li> * <li>java.sql.Time --&gt; java.util.Date</li> * <li>java.sql.Time --&gt; Long</li> * <li>java.math.BigInteger --&gt; * Short,Integer,Long,Float,Double,BigDecimal</li> * <li>java.math.BigDecimal --&gt; * Short,Integer,Long,Float,Double,BigInteger</li> * </ul> * * @param cls * class to automap each row of the ResultSet to * @param <T> * generic type of returned stream emissions * @return Flowable of T * */ default <T> Flowable<Tx<T>> autoMap(@Nonnull Class<T> cls) { Preconditions.checkNotNull(cls, "cls cannot be null"); return get(Util.autoMap(cls)); } /** * Automaps all the columns of the {@link ResultSet} into the target class * <code>cls</code>. See {@link #autoMap(Class) autoMap()}. * * @param cls * class of the TupleN elements * @param <T> * generic type of returned stream emissions * @return stream of transaction items */ default <T> Flowable<Tx<TupleN<T>>> getTupleN(@Nonnull Class<T> cls) { Preconditions.checkNotNull(cls, "cls cannot be null"); return get(Tuples.tupleN(cls)); } /** * Automaps all the columns of the {@link ResultSet} into {@link Object} . See * {@link #autoMap(Class) autoMap()}. * * @return stream of transaction items */ default Flowable<Tx<TupleN<Object>>> getTupleN() { return get(Tuples.tupleN(Object.class)); } /** * Automaps the columns of the {@link ResultSet} into the specified classes. See * {@link #autoMap(Class) autoMap()}. * * @param cls1 * first class * @param cls2 * second class * @param <T1> * type of first class * @param <T2> * type of second class * @return stream of transaction items */ default <T1, T2> Flowable<Tx<Tuple2<T1, T2>>> getAs(@Nonnull Class<T1> cls1, @Nonnull Class<T2> cls2) { return get(Tuples.tuple(cls1, cls2)); } /** * Automaps the columns of the {@link ResultSet} into the specified classes. See * {@link #autoMap(Class) autoMap()}. * * @param cls1 * first class * @param cls2 * second class * @param cls3 * third class * @param <T1> * type of first class * @param <T2> * type of second class * @param <T3> * type of third class * @return stream of tuples */ default <T1, T2, T3> Flowable<Tx<Tuple3<T1, T2, T3>>> getAs(@Nonnull Class<T1> cls1, @Nonnull Class<T2> cls2, @Nonnull Class<T3> cls3) { return get(Tuples.tuple(cls1, cls2, cls3)); } /** * Automaps the columns of the {@link ResultSet} into the specified classes. See * {@link #autoMap(Class) autoMap()}. * * @param cls1 * first class * @param cls2 * second class * @param cls3 * third class * @param cls4 * fourth class * @param <T1> * type of first class * @param <T2> * type of second class * @param <T3> * type of third class * @param <T4> * type of fourth class * @return stream of tuples */ default <T1, T2, T3, T4> Flowable<Tx<Tuple4<T1, T2, T3, T4>>> getAs(@Nonnull Class<T1> cls1, @Nonnull Class<T2> cls2, @Nonnull Class<T3> cls3, @Nonnull Class<T4> cls4) { return get(Tuples.tuple(cls1, cls2, cls3, cls4)); } /** * Automaps the columns of the {@link ResultSet} into the specified classes. See * {@link #autoMap(Class) autoMap()}. * * @param cls1 * first class * @param cls2 * second class * @param cls3 * third class * @param cls4 * fourth class * @param cls5 * fifth class * @param <T1> * type of first class * @param <T2> * type of second class * @param <T3> * type of third class * @param <T4> * type of fourth class * @param <T5> * type of fifth class * @return stream of transaction items */
default <T1, T2, T3, T4, T5> Flowable<Tx<Tuple5<T1, T2, T3, T4, T5>>> getAs(
3
cm-heclouds/JAVA-HTTP-SDK
javaSDK/src/main/java/cmcc/iot/onenet/javasdk/api/cmds/QueryCmdsStatus.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.util.HashMap; import java.util.Map; import org.apache.http.HttpResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; 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.cmds.CmdsResponse; import cmcc.iot.onenet.javasdk.utils.Config;
package cmcc.iot.onenet.javasdk.api.cmds; public class QueryCmdsStatus extends AbstractAPI { private final Logger logger = LoggerFactory.getLogger(this.getClass()); private HttpGetMethod HttpMethod; private String cmdUuid; /** * @param cmdUuid:命令id,String * @param key:masterkey或者设备apikey */ public QueryCmdsStatus(String cmdUuid,String key) { this.cmdUuid = cmdUuid; this.key=key; this.method= Method.GET; this.HttpMethod=new HttpGetMethod(method); Map<String, Object> headmap = new HashMap<String, Object>(); headmap.put("api-key", key); HttpMethod.setHeader(headmap); this.url = Config.getString("test.url") + "/cmds/" + cmdUuid; HttpMethod.setcompleteUrl(url,null); } public BasicResponse<CmdsResponse> executeApi() { BasicResponse response=null; try { HttpResponse httpResponse=HttpMethod.execute(); response = mapper.readValue(httpResponse.getEntity().getContent(), BasicResponse.class); response.setJson(mapper.writeValueAsString(response)); Object newData = mapper.readValue(mapper.writeValueAsString(response.getDataInternal()), CmdsResponse.class); response.setData(newData); return response; } catch (Exception e) { logger.error("json error {}", e.getMessage());
throw new OnenetApiException(e.getMessage());
1
quhfus/DoSeR-Disambiguation
doser-dis-disambiguationserver/src/main/java/doser/server/actions/disambiguation/DisambiguationService.java
[ "public final class DisambiguationMainService {\n\n\tpublic final static int MAXCLAUSECOUNT = 4096;\n\n\tprivate static final int TIMERPERIOD = 10000;\n\n\tprivate static DisambiguationMainService instance = null;\n\n//\tprivate Model hdtdbpediaCats;\n//\tprivate Model hdtdbpediaCats_ger;\n//\tprivate Model hdtdbpe...
import java.util.LinkedList; import java.util.List; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import doser.entitydisambiguation.backend.DisambiguationMainService; import doser.entitydisambiguation.backend.AbstractDisambiguationTask; import doser.entitydisambiguation.backend.DisambiguationTaskCollective; import doser.entitydisambiguation.backend.DisambiguationTaskSingle; import doser.entitydisambiguation.dpo.DisambiguationRequest; import doser.entitydisambiguation.dpo.DisambiguationResponse; import doser.entitydisambiguation.dpo.EntityDisambiguationDPO; import doser.entitydisambiguation.dpo.Response; import doser.entitydisambiguation.properties.Properties;
package doser.server.actions.disambiguation; @Controller @RequestMapping("/disambiguation") public class DisambiguationService { public DisambiguationService() { super(); } /** * Testing * * @param request * @return */ @RequestMapping(value = "/disambiguateWithoutCategories-single", method = RequestMethod.POST, headers = "Accept=application/json") public @ResponseBody DisambiguationResponse annotateSingle(@RequestBody final DisambiguationRequest request) { DisambiguationResponse annotationResponse = disambiguateSingle(request); return annotationResponse; } @RequestMapping(value = "/disambiguationWithoutCategories-collective", method = RequestMethod.POST, headers = "Accept=application/json") public @ResponseBody DisambiguationResponse annotateCollectiveWithoutCategories( @RequestBody final DisambiguationRequest request) { final DisambiguationResponse response = new DisambiguationResponse(); final DisambiguationMainService mainService = DisambiguationMainService.getInstance(); final List<EntityDisambiguationDPO> listToDis = request.getSurfaceFormsToDisambiguate(); if (mainService != null) { final List<AbstractDisambiguationTask> tasks = new LinkedList<AbstractDisambiguationTask>(); DisambiguationTaskCollective collectiveTask = new DisambiguationTaskCollective(listToDis, request.getMainTopic()); collectiveTask.setKbIdentifier("default", "EntityCentric"); collectiveTask.setReturnNr(1000); tasks.add(collectiveTask); mainService.disambiguate(tasks); List<Response> responses = collectiveTask.getResponse(); response.setTasks(responses); response.setDocumentUri(request.getDocumentUri()); } return response; } @RequestMapping(value = "/disambiguationWithoutCategoriesBiomed-collective", method = RequestMethod.POST, headers = "Accept=application/json") public @ResponseBody DisambiguationResponse annotateCollectiveWithoutCategoriesBiomed( @RequestBody final DisambiguationRequest request) { final DisambiguationResponse response = new DisambiguationResponse(); final DisambiguationMainService mainService = DisambiguationMainService.getInstance(); final List<EntityDisambiguationDPO> listToDis = request.getSurfaceFormsToDisambiguate(); if (mainService != null) { final List<AbstractDisambiguationTask> tasks = new LinkedList<AbstractDisambiguationTask>(); DisambiguationTaskCollective collectiveTask = new DisambiguationTaskCollective(listToDis, request.getMainTopic()); collectiveTask.setKbIdentifier("biomed", "EntityCentric"); collectiveTask.setReturnNr(1000); tasks.add(collectiveTask); mainService.disambiguate(tasks); List<Response> responses = collectiveTask.getResponse(); response.setTasks(responses); response.setDocumentUri(request.getDocumentUri()); } return response; } private DisambiguationResponse disambiguateSingle(DisambiguationRequest request) { final DisambiguationResponse response = new DisambiguationResponse(); final List<EntityDisambiguationDPO> listToDis = request.getSurfaceFormsToDisambiguate(); List<Response> responseList = new LinkedList<Response>(); response.setDocumentUri(request.getDocumentUri()); final List<AbstractDisambiguationTask> tasks = new LinkedList<AbstractDisambiguationTask>(); final DisambiguationMainService mainService = DisambiguationMainService.getInstance(); if (mainService != null) { int docsToReturn = 0; if (request.getDocsToReturn() == null) { docsToReturn = Properties.getInstance().getDisambiguationResultSize(); } else { docsToReturn = request.getDocsToReturn(); } for (int i = 0; i < listToDis.size(); i++) { EntityDisambiguationDPO dpo = listToDis.get(i);
DisambiguationTaskSingle task = new DisambiguationTaskSingle(dpo);
3
indvd00m/java-ascii-render
ascii-render/src/test/java/com/indvd00m/ascii/render/tests/plot/TestPlot.java
[ "public class Region implements IRegion {\n\n\tprotected int x;\n\tprotected int y;\n\tprotected int width;\n\tprotected int height;\n\n\tpublic Region(int x, int y, int width, int height) {\n\t\tsuper();\n\t\tif (width < 0) {\n\t\t\tthrow new IllegalArgumentException();\n\t\t}\n\t\tif (height < 0) {\n\t\t\tthrow n...
import com.indvd00m.ascii.render.Region; import com.indvd00m.ascii.render.Render; import com.indvd00m.ascii.render.api.ICanvas; import com.indvd00m.ascii.render.api.IContextBuilder; import com.indvd00m.ascii.render.api.IRender; import com.indvd00m.ascii.render.elements.plot.Plot; import com.indvd00m.ascii.render.elements.plot.api.IPlotPoint; import com.indvd00m.ascii.render.elements.plot.misc.PlotPoint; import org.junit.Before; import org.junit.Test; import java.util.ArrayList; import java.util.List; import java.util.Locale; import static org.junit.Assert.assertEquals;
package com.indvd00m.ascii.render.tests.plot; /** * @author indvd00m (gotoindvdum[at]gmail[dot]com) * @since 1.0.0 */ public class TestPlot { @Before public void setUpLocale() throws Exception { Locale.setDefault(Locale.ENGLISH); } @Test public void test01() { List<IPlotPoint> points = new ArrayList<IPlotPoint>(); for (int degree = 0; degree <= 360; degree++) { double val = Math.sin(Math.toRadians(degree)); IPlotPoint plotPoint = new PlotPoint(degree, val); points.add(plotPoint); } IRender render = new Render();
IContextBuilder builder = render.newBuilder();
3
flapdoodle-oss/de.flapdoodle.embed.process
src/main/java/de/flapdoodle/embed/process/store/UrlConnectionDownloader.java
[ "@Value.Immutable\npublic interface DownloadConfig {\n\t\n\tDistributionDownloadPath getDownloadPath();\n\t\n\tProgressListener getProgressListener();\n\n\tDirectory getArtifactStorePath();\n\t\n\tTempNaming getFileNaming();\n\n\tString getDownloadPrefix();\n\n\tString getUserAgent();\n\n\tOptional<String> getAutho...
import java.net.URL; import java.net.URLConnection; import java.util.Optional; import de.flapdoodle.embed.process.config.store.DownloadConfig; import de.flapdoodle.embed.process.config.store.ProxyFactory; import de.flapdoodle.embed.process.config.store.TimeoutConfig; import de.flapdoodle.embed.process.distribution.Distribution; import de.flapdoodle.embed.process.io.directories.PropertyOrPlatformTempDir; import de.flapdoodle.embed.process.io.file.Files; import de.flapdoodle.embed.process.io.progress.ProgressListener; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.Proxy;
/** * Copyright (C) 2011 * Michael Mosmann <michael@mosmann.de> * Martin Jöhren <m.joehren@googlemail.com> * * with contributions from * konstantin-ba@github, Archimedes Trajano (trajano@github), Kevin D. Keck (kdkeck@github), Ben McCann (benmccann@github) * * 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 de.flapdoodle.embed.process.store; /** * Class for downloading runtime */ public class UrlConnectionDownloader implements Downloader { private static final int DEFAULT_CONTENT_LENGTH = 20 * 1024 * 1024; private static final int BUFFER_LENGTH = 1024 * 8 * 8; private static final int READ_COUNT_MULTIPLIER = 100; @Override public String getDownloadUrl(DownloadConfig runtime, Distribution distribution) { return runtime.getDownloadPath().getPath(distribution) + runtime.getPackageResolver().packageFor(distribution).archivePath(); } @Override public File download(DownloadConfig downloadConfig, Distribution distribution) throws IOException { String progressLabel = "Download " + distribution; ProgressListener progress = downloadConfig.getProgressListener(); progress.start(progressLabel); File ret = Files.createTempFile(PropertyOrPlatformTempDir.defaultInstance(), downloadConfig.getFileNaming() .nameFor(downloadConfig.getDownloadPrefix(), "." + downloadConfig.getPackageResolver().packageFor(distribution).archiveType())); if (ret.canWrite()) { BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(ret)); InputStreamAndLength downloadStreamAndLength = downloadInputStream(downloadConfig, distribution); long length = downloadStreamAndLength.contentLength(); InputStream downloadStream = downloadStreamAndLength.downloadStream(); progress.info(progressLabel, "DownloadSize: " + length); if (length == -1) length = DEFAULT_CONTENT_LENGTH; long downloadStartedAt = System.currentTimeMillis(); try { BufferedInputStream bis = new BufferedInputStream(downloadStream); byte[] buf = new byte[BUFFER_LENGTH]; int read = 0; long readCount = 0; while ((read = bis.read(buf)) != -1) { bos.write(buf, 0, read); readCount = readCount + read; if (readCount > length) length = readCount; progress.progress(progressLabel, (int) (readCount * READ_COUNT_MULTIPLIER / length)); } progress.info(progressLabel, "downloaded with " + downloadSpeed(downloadStartedAt,length)); } finally { downloadStream.close(); bos.flush(); bos.close(); } } else { throw new IOException("Can not write " + ret); } progress.done(progressLabel); return ret; } private InputStreamAndLength downloadInputStream(DownloadConfig downloadConfig, Distribution distribution) throws IOException { URL url = new URL(getDownloadUrl(downloadConfig, distribution)); Optional<Proxy> proxy = downloadConfig.proxyFactory().map(ProxyFactory::createProxy); try { URLConnection openConnection; if (proxy.isPresent()) { openConnection = url.openConnection(proxy.get()); } else { openConnection = url.openConnection(); } openConnection.setRequestProperty("User-Agent",downloadConfig.getUserAgent()); if (downloadConfig.getAuthorization().isPresent()) { openConnection.setRequestProperty("Authorization", downloadConfig.getAuthorization().get()); }
TimeoutConfig timeoutConfig = downloadConfig.getTimeoutConfig();
2
osglworks/java-tool
src/test/java/org/osgl/util/MimeTypeTest.java
[ "public abstract class TestBase extends osgl.ut.TestBase {\n\n protected static void run(Class<? extends TestBase> cls) {\n new JUnitCore().run(cls);\n }\n \n protected static void println(String tmpl, Object... args) {\n System.out.println(String.format(tmpl, args));\n }\n\n protect...
import org.junit.Test; import org.osgl.TestBase; import org.osgl.util.MimeType.Trait; import static org.osgl.util.MimeType.Trait.*; import static org.osgl.util.MimeType.findByContentType; import static org.osgl.util.MimeType.findByFileExtension;
package org.osgl.util; /*- * #%L * Java Tool * %% * Copyright (C) 2014 - 2018 OSGL (Open Source General Library) * %% * 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. * #L% */ public class MimeTypeTest extends TestBase { @Test public void test() {
MimeType mimeType = findByFileExtension("pdf");
4
alda-lang/alda-client-java
src/alda/repl/commands/ReplDownUp.java
[ "public class AldaScore {\n @SerializedName(\"chord-mode\")\n public Boolean chordMode;\n @SerializedName(\"current-instruments\")\n public Set<String> currentInstruments;\n\n public Map<String, Set<String>> nicknames;\n\n /**\n * Returns the current instruments if possible\n * @return null if not possibl...
import alda.AldaResponse.AldaScore; import alda.AldaServer; import alda.error.AlreadyUpException; import alda.error.InvalidOptionsException; import alda.error.NoResponseException; import alda.error.SystemException; import alda.repl.AldaRepl; import java.util.function.Consumer; import jline.console.ConsoleReader;
package alda.repl.commands; public class ReplDownUp implements ReplCommand { @Override public void act(String args, StringBuffer history, AldaServer server, ConsoleReader reader, Consumer<AldaScore> newInstrument)
throws NoResponseException {
4
PerficientDigital/AEM-DataLayer
weretail-reference/src/main/java/com/perficient/aem/weretail/datalayer/ProductGridItem.java
[ "public class Component extends CategorizableDataObject {\n\n\tpublic static final String DATA_KEY_COMPONENT_INFO = \"componentInfo\";\n\n\tpublic Component() {\n\t\tput(DATA_KEY_COMPONENT_INFO, new ComponentInfo());\n\t}\n\n\tpublic ComponentInfo getComponentInfo() {\n\t\treturn get(DATA_KEY_COMPONENT_INFO, Compon...
import org.apache.sling.api.resource.Resource; import org.apache.sling.models.annotations.Model; import com.adobe.cq.commerce.api.Product; import com.day.cq.wcm.api.Page; import com.perficient.aem.datalayer.api.Component; import com.perficient.aem.datalayer.api.ComponentDataElement; import com.perficient.aem.datalayer.api.DataLayer; import com.perficient.aem.datalayer.api.ProductInfo; import com.perficient.aem.datalayer.core.DataLayerUtil;
package com.perficient.aem.weretail.datalayer; @Model(adaptables = Resource.class, resourceType = { "weretail/components/content/productgrid/item" }, adapters = ComponentDataElement.class) public class ProductGridItem implements ComponentDataElement { private Resource resource; private Resource productDataResource; private Product productData; public ProductGridItem(Resource resource) { this.resource = resource; this.productDataResource = resource.getResourceResolver() .getResource(resource.getValueMap().get("cq:productMaster", String.class)); productData = productDataResource.adaptTo(Product.class); } @Override public void updateDataLayer(DataLayer dataLayer) { com.perficient.aem.datalayer.api.Product product = new com.perficient.aem.datalayer.api.Product(); ProductInfo productInfo = product.getProductInfo(); productInfo.setDescription(productData.getDescription()); productInfo.setProductID(productData.getPath()); productInfo.setProductImage(dataLayer.getConfig().getUrlPrefix() + productData.getImageUrl()); productInfo.setProductName(productData.getTitle()); productInfo.setProductThumbnail(dataLayer.getConfig().getUrlPrefix() + productData.getThumbnailUrl()); Page page = dataLayer.getAEMPage(); productInfo.setProductURL(DataLayerUtil.getSiteUrl(page, dataLayer.getConfig())); productInfo.setSku(productData.getSKU()); product.setProductInfo(productInfo); product.addAttribute("displayType", "productgrid/item"); dataLayer.addProduct(product);
Component component = new Component();
0
google/mug
mug/src/test/java/com/google/mu/util/stream/CasesTest.java
[ "static <T> Collector<T, ?, TinyContainer<T>> toTinyContainer() {\n return Collector.of(TinyContainer::new, TinyContainer::add, TinyContainer::addAll);\n}", "public static <T> Collector<T, ?, T> onlyElement() {\n return collectingAndThen(toTinyContainer(), TinyContainer::onlyOne);\n}", "public static <T, R> C...
import static com.google.mu.util.stream.Cases.TinyContainer.toTinyContainer; import static com.google.mu.util.stream.Cases.onlyElement; import static com.google.mu.util.stream.Cases.onlyElements; import static com.google.mu.util.stream.Cases.cases; import static com.google.mu.util.stream.Cases.when; import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth8.assertThat; import static java.util.function.Function.identity; import static org.junit.jupiter.api.Assertions.assertThrows; import com.google.common.testing.NullPointerTester; import com.google.mu.util.stream.Cases.TinyContainer; import java.util.stream.Stream; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4;
package com.google.mu.util.stream; @RunWith(JUnit4.class) public final class CasesTest { @Test public void when_zeroElement() { assertThat(Stream.of(1).collect(when(() -> "zero"))).isEmpty(); assertThat(Stream.empty().collect(when(() -> "zero"))).hasValue("zero"); } @Test public void when_oneElement() { assertThat(Stream.of(1).collect(when(i -> i + 1))).hasValue(2); assertThat(Stream.of(1, 2).collect(when(i -> i + 1))).isEmpty(); assertThat(Stream.of(1).collect(when(x -> x == 1, i -> i + 1))).hasValue(2); assertThat(Stream.of(1).collect(when(x -> x == 2, i -> i + 1))).isEmpty(); } @Test public void when_twoElements() { assertThat(Stream.of(2, 3).collect(when((a, b) -> a * b))).hasValue(6); assertThat(Stream.of(2, 3, 4).collect(when((a, b) -> a * b))).isEmpty(); assertThat(Stream.of(2, 3).collect(when((x, y) -> x < y, (a, b) -> a * b))).hasValue(6); assertThat(Stream.of(2, 3).collect(when((x, y) -> x > y, (a, b) -> a * b))).isEmpty(); } @Test public void only_oneElement() { String result = Stream.of("foo").collect(onlyElement()); assertThat(result).isEqualTo("foo"); IllegalArgumentException thrown = assertThrows( IllegalArgumentException.class, () -> Stream.of(1, 2, 3).collect(onlyElement())); assertThat(thrown).hasMessageThat().contains("size: 3"); } @Test public void only_twoElements() { int result = Stream.of(2, 3).collect(onlyElements((a, b) -> a * b)); assertThat(result).isEqualTo(6); IllegalArgumentException thrown = assertThrows( IllegalArgumentException.class, () -> Stream.of(1).collect(onlyElements((a, b) -> a * b))); assertThat(thrown).hasMessageThat().contains("size: 1"); } @Test public void cases_firstCaseMatch() { String result = Stream.of("foo", "bar").collect(cases(when((a, b) -> a + b), when(a -> a))); assertThat(result).isEqualTo("foobar"); } @Test public void cases_secondCaseMatch() { String result = Stream.of("foo").collect(cases(when((a, b) -> a + b), when(a -> a))); assertThat(result).isEqualTo("foo"); } @Test public void cases_noMatchingCase() { IllegalArgumentException thrown = assertThrows( IllegalArgumentException.class, () -> Stream.of(1, 2, 3).collect(cases(when((a, b) -> a + b), when(a -> a)))); assertThat(thrown).hasMessageThat().contains("size: 3"); } @Test public void toTinyContainer_empty() {
assertThat(Stream.empty().collect(toTinyContainer()).size()).isEqualTo(0);
0
jackyhung/consumer-dispatcher
src/main/java/com/thenetcircle/comsumerdispatcher/thread/ConsumerJobExecutorPool.java
[ "public class CountChangedWatcher extends BaseJobPoolLevelWatcher implements ICountChangedWatcher {\n\tprivate static Log _logger = LogFactory.getLog(CountChangedWatcher.class);\n\t\n\tprotected int numToSet = 0;\n\tprotected String newSubNode = null;\n\t\n\t@Override\n\tpublic void register(ConsumerJobExecutorPool...
import java.lang.Thread.State; import java.lang.management.ManagementFactory; import java.net.URL; import java.util.HashSet; import java.util.Hashtable; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.locks.ReentrantLock; import javax.management.MBeanServer; import javax.management.ObjectName; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.log4j.Level; import org.apache.log4j.Logger; import com.thenetcircle.comsumerdispatcher.distribution.watcher.CountChangedWatcher; import com.thenetcircle.comsumerdispatcher.distribution.watcher.IJobPoolLevelWatcher; import com.thenetcircle.comsumerdispatcher.distribution.watcher.NewUrlWatcher; import com.thenetcircle.comsumerdispatcher.distribution.watcher.QueuePurgeWatcher; import com.thenetcircle.comsumerdispatcher.job.JobExecutor; import com.thenetcircle.comsumerdispatcher.job.exception.JobFailedException; import com.thenetcircle.comsumerdispatcher.job.exception.JobStopException;
package com.thenetcircle.comsumerdispatcher.thread; public class ConsumerJobExecutorPool implements ConsumerJobExecutorPoolMBean { private static Log _logger = LogFactory.getLog(ConsumerJobExecutorPool.class); private final ObjectName mbeanName; private final NamedThreadFactory threadFactory; private final JobExecutor job; private final HashSet<Worker> workers = new HashSet<Worker>(); protected final AtomicInteger completeTaskCount = new AtomicInteger(0); private final AtomicInteger activeExecutorCount = new AtomicInteger(0); private final AtomicBoolean logErrorJobToFile = new AtomicBoolean(false); private IJobPoolLevelWatcher purgeWatcher, countChangedWatcher, urlChangedWatcher; public ConsumerJobExecutorPool(JobExecutor job) { String jmxType = job.getQueue() + "_" + job.getFetcherQConf().getHost() + "_" + job.getFetcherQConf().getVhost(); this.job = job; threadFactory = new NamedThreadFactory(jmxType); MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); try { URL url = new URL(job.getUrl()); String domain = url.getHost(); Hashtable<String, String> kv = new Hashtable<String, String>(); kv.put("queue", job.getQueue()); kv.put("q_host", job.getFetcherQConf().getHost()); kv.put("q_vhost", job.getFetcherQConf().getVhost()); mbeanName = new ObjectName(domain, kv); mbs.registerMBean(this, new ObjectName(domain, kv)); //watchers
purgeWatcher = new QueuePurgeWatcher();
3
onyxbits/TradeTrax
src/main/java/de/onyxbits/tradetrax/pages/edit/VariantEditor.java
[ "@Entity\n@Table(name = \"stock\")\npublic class Stock implements Serializable {\n\n\t/**\n\t * \n\t */\n\tprivate static final long serialVersionUID = 1L;\n\n\t/**\n\t * Row index\n\t */\n\t@Id\n\t@GeneratedValue(strategy = GenerationType.IDENTITY)\n\tprivate long id;\n\n\t/**\n\t * Optional storage location ident...
import java.util.List; import org.apache.tapestry5.alerts.AlertManager; import org.apache.tapestry5.alerts.Duration; import org.apache.tapestry5.alerts.Severity; import org.apache.tapestry5.annotations.Component; import org.apache.tapestry5.annotations.Import; import org.apache.tapestry5.annotations.InjectPage; import org.apache.tapestry5.annotations.Property; import org.apache.tapestry5.beaneditor.Validate; import org.apache.tapestry5.corelib.components.EventLink; import org.apache.tapestry5.corelib.components.Form; import org.apache.tapestry5.corelib.components.TextField; import org.apache.tapestry5.hibernate.annotations.CommitAfter; import org.apache.tapestry5.ioc.Messages; import org.apache.tapestry5.ioc.annotations.Inject; import org.apache.tapestry5.services.javascript.JavaScriptSupport; import org.hibernate.Session; import org.hibernate.criterion.Projections; import org.hibernate.criterion.Restrictions; import de.onyxbits.tradetrax.entities.Stock; import de.onyxbits.tradetrax.entities.Variant; import de.onyxbits.tradetrax.pages.Index; import de.onyxbits.tradetrax.pages.tools.LabelManager; import de.onyxbits.tradetrax.services.EventLogger;
package de.onyxbits.tradetrax.pages.edit; @Import(library = "context:js/mousetrap.min.js") public class VariantEditor { @Property private long variantId; @Property @Validate("required") private String name; @Property private String status; @Component(id = "nameField") private TextField nameField; @Component(id = "editForm") private Form form; @Inject private Session session; @Inject
private EventLogger eventLogger;
4
loganj/foursquared
main/src/com/joelapenna/foursquared/VenueActivity.java
[ "public class Tip implements FoursquareType, Parcelable {\n\n private String mCreated;\n private String mDistance;\n private String mId;\n private String mText;\n private User mUser;\n private Venue mVenue;\n\n public Tip() {\n }\n\n private Tip(Parcel in) {\n mCreated = ParcelUtil...
import com.joelapenna.foursquare.types.Tip; import com.joelapenna.foursquare.types.Venue; import com.joelapenna.foursquare.util.VenueUtils; import com.joelapenna.foursquared.location.LocationUtils; import com.joelapenna.foursquared.preferences.Preferences; import com.joelapenna.foursquared.util.MenuUtils; import com.joelapenna.foursquared.util.NotificationsUtil; import com.joelapenna.foursquared.util.TabsUtil; import com.joelapenna.foursquared.util.UserUtils; import com.joelapenna.foursquared.widget.VenueView; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.TabActivity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.net.Uri; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.preference.PreferenceManager; import android.text.TextUtils; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.View.OnClickListener; import android.widget.EditText; import android.widget.Spinner; import android.widget.TabHost; import android.widget.Toast; import java.util.HashSet; import java.util.Observable;
Intent intent; tag = (String) this.getText(R.string.venue_checkins_tab); intent = new Intent(this, VenueCheckinsActivity.class); TabsUtil.addNativeLookingTab(this, tabHost, "t1", tag, R.drawable.friends_tab, intent); tag = (String) this.getText(R.string.map_label); intent = new Intent(this, VenueMapActivity.class); TabsUtil.addNativeLookingTab(this, tabHost, "t2", tag, R.drawable.map_tab, intent); tag = (String) this.getText(R.string.venue_info_tab); intent = new Intent(this, VenueTipsActivity.class); TabsUtil.addNativeLookingTab(this, tabHost, "t3", tag, R.drawable.tips_tab, intent); } private void onVenueSet() { Venue venue = mStateHolder.venue; if (DEBUG) Log.d(TAG, "onVenueSet:" + venue.getName()); setTitle(venue.getName() + " - Foursquare"); mVenueView.setVenue(venue); mVenueView.setCheckinButtonEnabled(mStateHolder.venueId != null); } private void setVenue(Venue venue) { mStateHolder.venue = venue; mStateHolder.venueId = venue.getId(); venueObservable.notifyObservers(venue); onVenueSet(); } private void startCheckin() { Intent intent = new Intent(this, CheckinOrShoutGatherInfoActivity.class); intent.putExtra(CheckinOrShoutGatherInfoActivity.INTENT_EXTRA_IS_CHECKIN, true); intent.putExtra(CheckinOrShoutGatherInfoActivity.INTENT_EXTRA_VENUE_ID, mStateHolder.venue.getId()); intent.putExtra(CheckinOrShoutGatherInfoActivity.INTENT_EXTRA_VENUE_NAME, mStateHolder.venue.getName()); startActivityForResult(intent, RESULT_CODE_ACTIVITY_CHECKIN_EXECUTE); } private void startCheckinQuick() { SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this); boolean tellFriends = settings.getBoolean(Preferences.PREFERENCE_SHARE_CHECKIN, true); boolean tellTwitter = settings.getBoolean(Preferences.PREFERENCE_TWITTER_CHECKIN, false); boolean tellFacebook = settings.getBoolean(Preferences.PREFERENCE_FACEBOOK_CHECKIN, false); Intent intent = new Intent(VenueActivity.this, CheckinExecuteActivity.class); intent.putExtra(CheckinExecuteActivity.INTENT_EXTRA_VENUE_ID, mStateHolder.venue.getId()); intent.putExtra(CheckinExecuteActivity.INTENT_EXTRA_SHOUT, ""); intent.putExtra(CheckinExecuteActivity.INTENT_EXTRA_TELL_FRIENDS, tellFriends); intent.putExtra(CheckinExecuteActivity.INTENT_EXTRA_TELL_TWITTER, tellTwitter); intent.putExtra(CheckinExecuteActivity.INTENT_EXTRA_TELL_FACEBOOK, tellFacebook); startActivityForResult(intent, RESULT_CODE_ACTIVITY_CHECKIN_EXECUTE); } private void showWebViewForSpecial() { Intent intent = new Intent(this, SpecialWebViewActivity.class); intent.putExtra(SpecialWebViewActivity.EXTRA_CREDENTIALS_USERNAME, PreferenceManager.getDefaultSharedPreferences(this).getString(Preferences.PREFERENCE_LOGIN, "")); intent.putExtra(SpecialWebViewActivity.EXTRA_CREDENTIALS_PASSWORD, PreferenceManager.getDefaultSharedPreferences(this).getString(Preferences.PREFERENCE_PASSWORD, "")); intent.putExtra(SpecialWebViewActivity.EXTRA_SPECIAL_ID, mStateHolder.venue.getSpecials().get(0).getId()); startActivity(intent); } class VenueObservable extends Observable { @Override public void notifyObservers(Object data) { setChanged(); super.notifyObservers(data); } public Venue getVenue() { return mStateHolder.venue; } } private class VenueTask extends AsyncTask<String, Void, Venue> { private static final String PROGRESS_BAR_TASK_ID = TAG + "VenueTask"; private Exception mReason; @Override protected void onPreExecute() { startProgressBar(PROGRESS_BAR_TASK_ID); } @Override protected Venue doInBackground(String... params) { try { return ((Foursquared) getApplication()).getFoursquare().venue( params[0], LocationUtils.createFoursquareLocation(((Foursquared) getApplication()) .getLastKnownLocation())); } catch (Exception e) { mReason = e; } return null; } @Override protected void onPostExecute(Venue venue) { try { if (VenueUtils.isValid(venue)) { setVenue(venue); } else { NotificationsUtil.ToastReasonForFailure(VenueActivity.this, mReason); finish(); } } finally { stopProgressBar(PROGRESS_BAR_TASK_ID); } } @Override protected void onCancelled() { stopProgressBar(PROGRESS_BAR_TASK_ID); } }
private class TipAddTask extends AsyncTask<String, Void, Tip> {
0
jenshadlich/s3srv
src/main/java/de/jeha/s3srv/resources/S3OperationsFacade.java
[ "public class RequestContext {\n\n private final boolean pathStyle;\n private final String bucket;\n private final String key;\n\n private RequestContext(boolean pathStyle, String bucket, String key) {\n this.pathStyle = pathStyle;\n this.bucket = bucket;\n this.key = key;\n }\n\...
import com.codahale.metrics.annotation.Timed; import de.jeha.s3srv.common.s3.RequestContext; import de.jeha.s3srv.operations.buckets.*; import de.jeha.s3srv.operations.objects.CreateObject; import de.jeha.s3srv.operations.objects.DeleteObject; import de.jeha.s3srv.operations.objects.ExistsObject; import de.jeha.s3srv.operations.objects.GetObject; import de.jeha.s3srv.operations.service.ListBuckets; import de.jeha.s3srv.storage.StorageBackend; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.*; import javax.ws.rs.core.Context; import javax.ws.rs.core.Response;
package de.jeha.s3srv.resources; /** * @author jenshadlich@googlemail.com */ @Path("/") public class S3OperationsFacade { private static final Logger LOG = LoggerFactory.getLogger(S3OperationsFacade.class); private final StorageBackend storageBackend; public S3OperationsFacade(StorageBackend storageBackend) { this.storageBackend = storageBackend; } @HEAD @Path("{subResources:.*}") @Timed public Response head(@Context HttpServletRequest request) { LOG.info("head"); final RequestContext context = RequestContext.build(request); LOG.info("{}", context); if (context.getBucket() != null && context.getKey() != null) { return new ExistsObject(storageBackend).doesObjectExist(request, context.getBucket(), context.getKey()); } if (context.getBucket() != null) { return new ExistsBucket(storageBackend).doesBucketExist(request, context.getBucket()); } throw new UnsupportedOperationException("Not yet implemented!"); // TODO } @GET @Path("{subResources:.*}") @Timed public Response get(@Context HttpServletRequest request) { LOG.info("get"); final RequestContext context = RequestContext.build(request); LOG.info("{}", context); if (context.getBucket() != null && context.getKey() != null) { return new GetObject(storageBackend).getObject(request, context.getBucket(), context.getKey()); } if (context.getBucket() != null && "acl".equals(request.getQueryString())) { return new GetBucketACL(storageBackend).getBucketACL(request, context.getBucket()); } if (context.getBucket() != null) { return new ListObjects(storageBackend).listObjects(request, context.getBucket()); }
return new ListBuckets(storageBackend).listBuckets(request);
5
fuinorg/ddd-4-java
src/test/java/org/fuin/ddd4j/ddd/DomainEventExpectedEntityIdPathValidatorTest.java
[ "public class ACreatedEvent extends AbstractDomainEvent<AId> {\n\n private static final long serialVersionUID = 1L;\n\n private static final EventType EVENT_TYPE = new EventType(\"ACreatedEvent\");\n\n private AId id;\n\n public ACreatedEvent(final AId id) {\n super(new EntityIdPath(id));\n ...
import static org.assertj.core.api.Assertions.assertThat; import java.lang.annotation.Annotation; import jakarta.validation.Payload; import org.fuin.ddd4j.test.ACreatedEvent; import org.fuin.ddd4j.test.AId; import org.fuin.ddd4j.test.BId; import org.fuin.ddd4j.test.CAddedEvent; import org.fuin.ddd4j.test.CEvent; import org.fuin.ddd4j.test.CId; import org.junit.Test;
/** * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ * * 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 3 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, see http://www.gnu.org/licenses/. */ package org.fuin.ddd4j.ddd; //CHECKSTYLE:OFF Test code public class DomainEventExpectedEntityIdPathValidatorTest { @Test public void testIsValidNull() { // PREPARE final DomainEventExpectedEntityIdPath anno = createAnnotation(AId.class); final DomainEventExpectedEntityIdPathValidator testee = new DomainEventExpectedEntityIdPathValidator(); testee.initialize(anno); // TEST & VERIFY assertThat(testee.isValid(null, null)).isTrue(); } @Test public void testIsValidOneLevel() { // PREPARE final AId aid = new AId(1L); final BId bid = new BId(2L); final CId cid = new CId(3L); final DomainEventExpectedEntityIdPath anno = createAnnotation(AId.class); final DomainEventExpectedEntityIdPathValidator testee = new DomainEventExpectedEntityIdPathValidator(); testee.initialize(anno); // TEST & VERIFY assertThat(testee.isValid(new ACreatedEvent(aid), null)).isTrue(); assertThat(testee.isValid(new CAddedEvent(aid, bid, cid), null)).isFalse();
assertThat(testee.isValid(new CEvent(aid, bid, cid), null)).isFalse();
4
bencvt/LibShapeDraw
projects/main/src/test/java/libshapedraw/SetupTestEnvironment.java
[ "public class LSDController {\n private static LSDController instance;\n private final Logger log;\n private final LinkedHashSet<LibShapeDraw> apiInstances;\n private int topApiInstanceId;\n private MinecraftAccess minecraftAccess;\n private LSDUpdateCheck updateCheck;\n private boolean initial...
import java.io.File; import java.lang.reflect.Field; import libshapedraw.internal.LSDController; import libshapedraw.internal.LSDGlobalSettings; import libshapedraw.internal.LSDInternalException; import libshapedraw.internal.LSDInternalReflectionException; import libshapedraw.internal.LSDModDirectory; import libshapedraw.internal.LSDUtil; import org.junit.BeforeClass; import org.lwjgl.LWJGLException; import org.lwjgl.opengl.Display; import org.lwjgl.opengl.DisplayMode;
package libshapedraw; /** * To ensure that JUnit testing does not touch the production Minecraft * installation, every test case should extend SetupTestEnvironment.TestCase. * <p> * Involves some ClassLoader and Reflection hackery. * <p> * If you're running one of these test case classes individually in Eclipse or * another IDE, you'll probably need to add the following to the VM arguments: * -Djava.library.path=../../lib/natives */ public class SetupTestEnvironment { private static File testMinecraftDirectory = null; private static final String MODDIRECTORY_CLASS_NAME = "libshapedraw.internal.LSDModDirectory"; private static final String MODDIRECTORY_FIELD_NAME = "DIRECTORY"; public static class TestCase { protected static final MockMinecraftAccess mockMinecraftAccess = new MockMinecraftAccess(); @BeforeClass public static void setupTestEnvironment() throws LWJGLException { if (setup()) { LSDController.getInstance().initialize(mockMinecraftAccess); try { Display.setDisplayMode(new DisplayMode(0, 0)); Display.create(); } catch (UnsatisfiedLinkError e) { throw new LSDInternalException("LWJGL link error, " + "probably caused by missing VM argument:\n" + "-Djava.library.path=../../lib/natives", e); } } } /** * An alternative to @Test(expected=SomeException.class) for test cases * with multiple lines that should be throwing exceptions. */ public static void assertThrows(Class<? extends Throwable> expected, Runnable method) { try { method.run(); } catch (Throwable thrown) { if (expected.isInstance(thrown)) { return; } throw new RuntimeException("expected " + String.valueOf(expected) + " not thrown", thrown); } throw new RuntimeException("expected " + String.valueOf(expected) + " not thrown"); } public static void assertThrowsIAE(Runnable method) { assertThrows(IllegalArgumentException.class, method); } public static File getTempDirectory() { return testMinecraftDirectory; } } private static boolean setup() { println("setup test environment"); if (testMinecraftDirectory == null) { testMinecraftDirectory = LSDUtil.createTempDirectory("LibShapeDrawJUnitTemp"); monkeyPatch(); return true; } // else we've already monkey patched, as we're running an entire test suite return false; } private static void monkeyPatch() { if (LSDUtil.isClassLoaded(MODDIRECTORY_CLASS_NAME)) { throw new LSDInternalException("internal error, " + MODDIRECTORY_CLASS_NAME + " already loaded"); } // Force ModDirectory class load and monkey patch ModDirectory.DIRECTORY. File origDir = LSDModDirectory.DIRECTORY; Field field; try { field = LSDModDirectory.class.getDeclaredField(MODDIRECTORY_FIELD_NAME); } catch (Exception e) { throw new LSDInternalReflectionException("unable to get field named " + MODDIRECTORY_FIELD_NAME, e); } LSDUtil.setFinalField(field, null, testMinecraftDirectory); println("monkey patched directory field from:\n " + origDir + "\nto:\n " + testMinecraftDirectory); if (!LSDModDirectory.class.getName().equals(MODDIRECTORY_CLASS_NAME) || !LSDUtil.isClassLoaded(MODDIRECTORY_CLASS_NAME) || !LSDModDirectory.DIRECTORY.equals(testMinecraftDirectory)) { throw new LSDInternalException("internal error, sanity check failed"); } disableUpdateCheck(); } private static void disableUpdateCheck() {
if (!LSDGlobalSettings.isUpdateCheckEnabled()) {
1
leandreck/spring-typescript-services
annotations/src/main/java/org/leandreck/endpoints/processor/TypeScriptEndpointProcessor.java
[ "public class MultipleConfigurationsFoundException extends Exception {\n\n private final transient Set<Element> elementsWithConfiguration;\n\n /**\n * @param elementsWithConfiguration all {@link Element}s annotated with {@link org.leandreck.endpoints.annotations.TypeScriptTemplatesConfiguration}\n */\...
import freemarker.template.TemplateException; import org.leandreck.endpoints.annotations.TypeScriptEndpoint; import org.leandreck.endpoints.annotations.TypeScriptIgnore; import org.leandreck.endpoints.annotations.TypeScriptTemplatesConfiguration; import org.leandreck.endpoints.annotations.TypeScriptType; import org.leandreck.endpoints.processor.config.MultipleConfigurationsFoundException; import org.leandreck.endpoints.processor.config.TemplateConfiguration; import org.leandreck.endpoints.processor.model.EndpointNode; import org.leandreck.endpoints.processor.model.EndpointNodeFactory; import org.leandreck.endpoints.processor.model.typefactories.MissingConfigurationTemplateException; import org.leandreck.endpoints.processor.model.TypeNode; import org.leandreck.endpoints.processor.printer.Engine; import org.leandreck.endpoints.processor.printer.TypesPackage; import javax.annotation.processing.AbstractProcessor; import javax.annotation.processing.Filer; import javax.annotation.processing.Messager; import javax.annotation.processing.ProcessingEnvironment; import javax.annotation.processing.RoundEnvironment; import javax.annotation.processing.SupportedSourceVersion; import javax.lang.model.SourceVersion; import javax.lang.model.element.Element; import javax.lang.model.element.ElementKind; import javax.lang.model.element.TypeElement; import javax.lang.model.util.Types; import javax.tools.StandardLocation; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.io.Writer; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Objects; import java.util.Set; import static java.util.stream.Collectors.toList; import static javax.tools.Diagnostic.Kind.ERROR;
/** * Copyright © 2016 Mathias Kowalzik (Mathias.Kowalzik@leandreck.org) * * 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.leandreck.endpoints.processor; /** * Annotation Processor for TypeScript-Annotations. */ @SupportedSourceVersion(SourceVersion.RELEASE_8) public class TypeScriptEndpointProcessor extends AbstractProcessor { private Filer filer; private Messager messager; @Override public synchronized void init(ProcessingEnvironment processingEnv) { super.init(processingEnv); filer = processingEnv.getFiler(); messager = processingEnv.getMessager(); } @Override public Set<String> getSupportedAnnotationTypes() { final Set<String> annotations = new LinkedHashSet<>(); annotations.add(TypeScriptEndpoint.class.getCanonicalName()); annotations.add(TypeScriptIgnore.class.getCanonicalName()); annotations.add(TypeScriptType.class.getCanonicalName()); return annotations; } @Override public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { final Set<? extends Element> annotated = roundEnv.getElementsAnnotatedWith(TypeScriptEndpoint.class); final List<TypeElement> endpoints = annotated.stream() .filter(element -> !ElementKind.METHOD.equals(element.getKind())) .map(element -> (TypeElement) element) .collect(toList()); if (!endpoints.isEmpty()) { try { final TemplateConfiguration templateConfiguration = TemplateConfiguration.buildFromEnvironment(roundEnv); processEndpoints(templateConfiguration, endpoints); } catch (MultipleConfigurationsFoundException mcfe) { printMessage("Multiple configurations found for the template locations."); printConfigurationErrors(mcfe); } catch (MissingConfigurationTemplateException mcte) { printMessage(mcte.getElement(), mcte.getMessage()); } catch (Exception unknown) { final StringWriter writer = new StringWriter(); unknown.printStackTrace(new PrintWriter(writer)); printMessage("Unkown Error occured, please file a Bug https://github.com/leandreck/spring-typescript-services/issues \n%s", writer.toString()); } } return true; } private void processEndpoints(TemplateConfiguration templateConfiguration, final List<TypeElement> endpointElements) { final Types typeUtils = processingEnv.getTypeUtils();
final Engine engine = new Engine(templateConfiguration);
5
hhua/product-hunt-android
app/src/main/java/com/hhua/android/producthunt/fragments/FollowingFragment.java
[ "public class ProductHuntApplication extends com.activeandroid.app.Application {\n private static Context context;\n\n @Override\n public void onCreate() {\n super.onCreate();\n ProductHuntApplication.context = this;\n Parse.initialize(this, ApiConfig.PARSE_API_APPLICATION_ID, ApiConfi...
import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ListView; import com.hhua.android.producthunt.ProductHuntApplication; import com.hhua.android.producthunt.ProductHuntClient; import com.hhua.android.producthunt.R; import com.hhua.android.producthunt.activities.UserActivity; import com.hhua.android.producthunt.adapters.EndlessScrollListener; import com.hhua.android.producthunt.adapters.FollowersArrayAdapter; import com.hhua.android.producthunt.models.Follower; import com.hhua.android.producthunt.models.User; import com.loopj.android.http.JsonHttpResponseHandler; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; import cz.msebera.android.httpclient.Header;
package com.hhua.android.producthunt.fragments; public class FollowingFragment extends Fragment { private final String LOG_D = "FollowingFragment"; private ProductHuntClient client; private ListView lvUsers; private List<Follower> followers; private FollowersArrayAdapter followersArrayAdapter; private int userId; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_users, container, false); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); client = ProductHuntApplication.getRestClient(); lvUsers = (ListView) view.findViewById(R.id.lvUsers); lvUsers.setOnScrollListener(new EndlessScrollListener() { @Override public boolean onLoadMore(int page, int totalItemsCount) { customLoadMoreDataFromApi(page); return true; } }); lvUsers.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { User user = followers.get(position).getUser();
Intent intent = new Intent(getContext(), UserActivity.class);
2
kesenhoo/Camera2
src/com/android/camera/VideoModule.java
[ "public interface CameraPictureCallback {\n public void onPictureTaken(byte[] data, CameraProxy camera);\n}", "public interface CameraProxy {\n\n /**\n * Returns the underlying {@link android.hardware.Camera} object used\n * by this proxy. This method should only be used when handing the\n * cam...
import android.annotation.TargetApi; import android.app.Activity; import android.content.ActivityNotFoundException; import android.content.BroadcastReceiver; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences.Editor; import android.content.res.Configuration; import android.graphics.Bitmap; import android.graphics.SurfaceTexture; import android.hardware.Camera.CameraInfo; import android.hardware.Camera.Parameters; import android.hardware.Camera.Size; import android.location.Location; import android.media.CamcorderProfile; import android.media.CameraProfile; import android.media.MediaRecorder; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.os.ParcelFileDescriptor; import android.os.SystemClock; import android.provider.MediaStore; import android.provider.MediaStore.MediaColumns; import android.provider.MediaStore.Video; import android.util.Log; import android.view.KeyEvent; import android.view.OrientationEventListener; import android.view.View; import android.view.WindowManager; import android.widget.Toast; import com.android.camera.CameraManager.CameraPictureCallback; import com.android.camera.CameraManager.CameraProxy; import com.android.camera.app.OrientationManager; import com.android.camera.exif.ExifInterface; import com.android.camera.ui.RotateTextToast; import com.android.camera.util.AccessibilityUtils; import com.android.camera.util.ApiHelper; import com.android.camera.util.CameraUtil; import com.android.camera.util.UsageStatistics; import com.android.camera2.R; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Iterator; import java.util.List;
} private void saveVideo() { if (mVideoFileDescriptor == null) { long duration = SystemClock.uptimeMillis() - mRecordingStartTime; if (duration > 0) { if (mCaptureTimeLapse) { duration = getTimeLapseVideoLength(duration); } } else { Log.w(TAG, "Video duration <= 0 : " + duration); } mActivity.getMediaSaveService().addVideo(mCurrentVideoFilename, duration, mCurrentVideoValues, mOnVideoSavedListener, mContentResolver); } mCurrentVideoValues = null; } private void deleteVideoFile(String fileName) { Log.v(TAG, "Deleting video " + fileName); File f = new File(fileName); if (!f.delete()) { Log.v(TAG, "Could not delete " + fileName); } } private PreferenceGroup filterPreferenceScreenByIntent( PreferenceGroup screen) { Intent intent = mActivity.getIntent(); if (intent.hasExtra(MediaStore.EXTRA_VIDEO_QUALITY)) { CameraSettings.removePreferenceFromScreen(screen, CameraSettings.KEY_VIDEO_QUALITY); } if (intent.hasExtra(MediaStore.EXTRA_DURATION_LIMIT)) { CameraSettings.removePreferenceFromScreen(screen, CameraSettings.KEY_VIDEO_QUALITY); } return screen; } // from MediaRecorder.OnErrorListener @Override public void onError(MediaRecorder mr, int what, int extra) { Log.e(TAG, "MediaRecorder error. what=" + what + ". extra=" + extra); if (what == MediaRecorder.MEDIA_RECORDER_ERROR_UNKNOWN) { // We may have run out of space on the sdcard. stopVideoRecording(); mActivity.updateStorageSpaceAndHint(); } } // from MediaRecorder.OnInfoListener @Override public void onInfo(MediaRecorder mr, int what, int extra) { if (what == MediaRecorder.MEDIA_RECORDER_INFO_MAX_DURATION_REACHED) { if (mMediaRecorderRecording) onStopVideoRecording(); } else if (what == MediaRecorder.MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED) { if (mMediaRecorderRecording) onStopVideoRecording(); // Show the toast. Toast.makeText(mActivity, R.string.video_reach_size_limit, Toast.LENGTH_LONG).show(); } } /* * Make sure we're not recording music playing in the background, ask the * MediaPlaybackService to pause playback. */ private void pauseAudioPlayback() { // Shamelessly copied from MediaPlaybackService.java, which // should be public, but isn't. Intent i = new Intent("com.android.music.musicservicecommand"); i.putExtra("command", "pause"); mActivity.sendBroadcast(i); } // For testing. public boolean isRecording() { return mMediaRecorderRecording; } private void startVideoRecording() { Log.v(TAG, "startVideoRecording"); mUI.cancelAnimations(); mUI.setSwipingEnabled(false); mActivity.updateStorageSpaceAndHint(); if (mActivity.getStorageSpaceBytes() <= Storage.LOW_STORAGE_THRESHOLD_BYTES) { Log.v(TAG, "Storage issue, ignore the start request"); return; } //?? //if (!mCameraDevice.waitDone()) return; mCurrentVideoUri = null; initializeRecorder(); if (mMediaRecorder == null) { Log.e(TAG, "Fail to initialize media recorder"); return; } pauseAudioPlayback(); try { mMediaRecorder.start(); // Recording is now started } catch (RuntimeException e) { Log.e(TAG, "Could not start media recorder. ", e); releaseMediaRecorder(); // If start fails, frameworks will not lock the camera for us. mCameraDevice.lock(); return; } // Make sure the video recording has started before announcing // this in accessibility.
AccessibilityUtils.makeAnnouncement(mUI.getShutterButton(),
3
fauu/HelixEngine
core/src/com/github/fauu/helix/manager/AreaManager.java
[ "public enum AreaType {\n\n INDOOR,\n OUTDOOR\n\n}", "public enum PassageAction {\n\n ENTRY, EXIT;\n\n}", "public enum TilePermission {\n\n OBSTACLE(\"Obstacle\", -1),\n PASSAGE(\"Area Passage\", -1),\n RAMP(\"Ramp\", -1),\n LEVEL0(\"Level 0\", 0),\n LEVEL1(\"Level 1\", 1),\n LEVEL2(\"Level 2\", 2),\n ...
import com.artemis.ComponentMapper; import com.artemis.Entity; import com.artemis.Manager; import com.artemis.annotations.Wire; import com.artemis.managers.TagManager; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.assets.AssetManager; import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.graphics.g3d.Material; import com.badlogic.gdx.graphics.g3d.Model; import com.badlogic.gdx.graphics.g3d.attributes.FloatAttribute; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.Json; import com.badlogic.gdx.utils.JsonWriter; import com.github.fauu.helix.AreaType; import com.github.fauu.helix.PassageAction; import com.github.fauu.helix.TilePermission; import com.github.fauu.helix.component.*; import com.github.fauu.helix.datum.Tile; import com.github.fauu.helix.datum.TileAreaPassage; import com.github.fauu.helix.displayable.AreaDisplayable; import com.github.fauu.helix.json.wrapper.AreaWrapper; import com.github.fauu.helix.json.wrapper.TileWrapper; import com.github.fauu.helix.util.IntVector2; import java.io.FileWriter; import java.io.IOException;
/* * Copyright (C) 2014-2016 Helix Engine Developers * (http://github.com/fauu/HelixEngine) * * This software is licensed under the GNU General Public License * (version 3 or later). See the COPYING file in this distribution. * * You should have received a copy of the GNU Library General Public License * along with this software. If not, see <http://www.gnu.org/licenses/>. * * Authored by: Piotr Grabowski <fau999@gmail.com> */ package com.github.fauu.helix.manager; public class AreaManager extends Manager { @Wire private ComponentMapper<AreaTypeComponent> areaTypeMapper; @Wire private ComponentMapper<DimensionsComponent> dimensionsMapper; @Wire private ComponentMapper<DisplayableComponent> displayableMapper; @Wire private ComponentMapper<NameComponent> nameMapper; @Wire private ComponentMapper<TilesComponent> tilesMapper; @Wire private AssetManager assetManager; private Entity area; // FIXME: Add area type public void create(String name, int width, int length) { Json json = new Json(); IntVector2 dimensions = new IntVector2(width, length); FileHandle file = Gdx.files.internal("area/" + name + ".json"); try { json.setWriter(new JsonWriter(new FileWriter(file.file()))); } catch (IOException e) { e.printStackTrace(); } json.writeObjectStart(); json.writeValue("width", dimensions.x); json.writeValue("length", dimensions.y); json.writeArrayStart("tiles"); for (int y = 0; y < dimensions.y; y++) { for (int x = 0; x < dimensions.x; x++) { json.writeObjectStart(); json.writeValue("permissions", TilePermission.LEVEL0.toString()); json.writeObjectEnd(); } } json.writeArrayEnd(); json.writeObjectEnd(); try { json.getWriter().close(); } catch (IOException e) { e.printStackTrace(); } } public void load(String name) { loadFromFile(Gdx.files.internal("area/" + name + ".json"), name); } public void loadFromFile(FileHandle file, String name) { Json json = new Json(); json.setIgnoreUnknownFields(true);
AreaWrapper areaWrapper = json.fromJson(AreaWrapper.class, file);
6
sritchie/kryo
src/com/esotericsoftware/kryo/serializers/JavaSerializer.java
[ "public class Kryo {\r\n\tstatic public final byte NAME = -1;\r\n\tstatic public final byte NULL = 0;\r\n\tstatic public final byte NOT_NULL = 1;\r\n\r\n\tprivate Class<? extends Serializer> defaultSerializer = FieldSerializer.class;\r\n\tprivate final ArrayList<DefaultSerializerEntry> defaultSerializers = new Arra...
import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.KryoException; import com.esotericsoftware.kryo.KryoSerializable; import com.esotericsoftware.kryo.Serializer; import com.esotericsoftware.kryo.io.Input; import com.esotericsoftware.kryo.io.Output;
package com.esotericsoftware.kryo.serializers; /** Serializes objects using Java's built in serialization mechanism. Note that this is very inefficient and should be avoided if * possible. * @see Serializer * @see FieldSerializer * @see KryoSerializable * @author Nathan Sweet <misc@n4te.com> */ public class JavaSerializer extends Serializer { private ObjectOutputStream objectStream; private Output lastOutput; public void write (Kryo kryo, Output output, Object object) { try { if (output != lastOutput) { objectStream = new ObjectOutputStream(output); lastOutput = output; } else objectStream.reset(); objectStream.writeObject(object); objectStream.flush(); } catch (Exception ex) { throw new KryoException("Error during Java serialization.", ex); } }
public Object create (Kryo kryo, Input input, Class type) {
3
paoding-code/jade-plugin-sql
src/main/java/net/paoding/rose/jade/plugin/sql/PlumSQLInterpreter.java
[ "public interface IDialect {\n\n\t/**\n\t * 将指定的操作转换为目标数据库的查询语句\n\t * @param operation 操作映射对象\n\t * @param runtime Statement运行时\n\t * \n\t * @return 查询语句\n\t * \n\t * @see IOperationMapper\n\t * @see StatementRuntime\n\t */\n\tpublic <T extends IOperationMapper> String translate(T operation, StatementRuntime runtim...
import java.util.Arrays; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanFactoryUtils; import org.springframework.beans.factory.InitializingBean; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.core.annotation.Order; import org.springframework.dao.InvalidDataAccessApiUsageException; import net.paoding.rose.jade.annotation.SQL; import net.paoding.rose.jade.plugin.sql.annotations.Table; import net.paoding.rose.jade.plugin.sql.dialect.IDialect; import net.paoding.rose.jade.plugin.sql.dialect.MySQLDialect; import net.paoding.rose.jade.plugin.sql.mapper.EntityMapperManager; import net.paoding.rose.jade.plugin.sql.mapper.IOperationMapper; import net.paoding.rose.jade.plugin.sql.mapper.OperationMapperManager; import net.paoding.rose.jade.plugin.sql.util.BasicSQLFormatter; import net.paoding.rose.jade.plugin.sql.util.PlumUtils; import net.paoding.rose.jade.statement.DAOMetaData; import net.paoding.rose.jade.statement.Interpreter; import net.paoding.rose.jade.statement.StatementMetaData; import net.paoding.rose.jade.statement.StatementRuntime;
/** * */ package net.paoding.rose.jade.plugin.sql; /** * Plum插件用于生成SQL的拦截器。 * * @author Alan.Geng[gengzhi718@gmail.com] */ @Order(-1) public class PlumSQLInterpreter implements Interpreter, InitializingBean, ApplicationContextAware { private static final Log logger = LogFactory.getLog(PlumSQLInterpreter.class); private ApplicationContext applicationContext; private OperationMapperManager operationMapperManager; private IDialect dialect; public void setDialect(IDialect dialect) { this.dialect = dialect; } public void setOperationMapperManager(OperationMapperManager operationMapperManager) { this.operationMapperManager = operationMapperManager; } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } @Override public void afterPropertiesSet() throws Exception { if (operationMapperManager == null) { operationMapperManager = new OperationMapperManager(); operationMapperManager.setEntityMapperManager(new EntityMapperManager()); } if (dialect == null) { // 将来可能扩展点:不同的DAO可以有不同的Dialect哦,而且是自动知道,不需要外部设置。 dialect = new MySQLDialect(); } // if (logger.isInfoEnabled()) { String[] beanNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(// applicationContext, GenericDAO.class); logger.info("[jade-plugin-sql] found " + beanNames.length + " GenericDAOs: " + Arrays.toString(beanNames)); } } /** * 对 {@link GenericDAO} 及其子DAO接口中没有注解&reg;SQL或仅仅&reg;SQL("")的方法进行解析,根据实际参数情况自动动态生成SQL语句 */ @Override public void interpret(StatementRuntime runtime) { final String interpreterAttribute = "jade-plugin-sql.interpreter"; Interpreter interpreter = runtime.getMetaData().getAttribute(interpreterAttribute); if (interpreter == null) { StatementMetaData smd = runtime.getMetaData(); synchronized (smd) { interpreter = smd.getAttribute(interpreterAttribute); if (interpreter == null) { interpreter = PassThroughInterpreter; if (GenericDAO.class.isAssignableFrom(smd.getDAOMetaData().getDAOClass())) { interpreter = VariableResolverInterpreter; SQL sqlAnnotation = smd.getMethod().getAnnotation(SQL.class); if (sqlAnnotation == null // 没有注解@SQL
|| PlumUtils.isBlank(sqlAnnotation.value()) // 虽注解但没有写SQL
6
AmadeusITGroup/sonar-stash
src/main/java/org/sonar/plugins/stash/issue/collector/StashCollector.java
[ "public enum IssueType {\r\n CONTEXT,\r\n REMOVED,\r\n ADDED,\r\n}\r", "public class StashComment {\r\n\r\n private final long id;\r\n private final String message;\r\n private final StashUser author;\r\n private final long version;\r\n private long line;\r\n private String path;\r\n private List<StashT...
import com.github.cliftonlabs.json_simple.JsonArray; import com.github.cliftonlabs.json_simple.JsonObject; import java.math.BigDecimal; import org.sonar.plugins.stash.PullRequestRef; import org.sonar.plugins.stash.StashPlugin.IssueType; import org.sonar.plugins.stash.exceptions.StashReportExtractionException; import org.sonar.plugins.stash.issue.StashComment; import org.sonar.plugins.stash.issue.StashCommentReport; import org.sonar.plugins.stash.issue.StashDiff; import org.sonar.plugins.stash.issue.StashDiffReport; import org.sonar.plugins.stash.issue.StashPullRequest; import org.sonar.plugins.stash.issue.StashTask; import org.sonar.plugins.stash.issue.StashUser;
package org.sonar.plugins.stash.issue.collector; public final class StashCollector { private static final String AUTHOR = "author"; private static final String VERSION = "version"; private StashCollector() { // Hiding implicit public constructor with an explicit private one (squid:S1118) } public static StashCommentReport extractComments(JsonObject jsonComments) { StashCommentReport result = new StashCommentReport(); JsonArray jsonValues = (JsonArray)jsonComments.get("values"); if (jsonValues != null) { for (Object obj : jsonValues.toArray()) { JsonObject jsonComment = (JsonObject)obj; StashComment comment = extractComment(jsonComment); result.add(comment); } } return result; } public static StashComment extractComment(JsonObject jsonComment, String path, Long line) { long id = getLong(jsonComment, "id"); String message = (String)jsonComment.get("text"); long version = getLong(jsonComment, VERSION); JsonObject jsonAuthor = (JsonObject)jsonComment.get(AUTHOR); StashUser stashUser = extractUser(jsonAuthor); return new StashComment(id, message, path, line, stashUser, version); } public static StashComment extractComment(JsonObject jsonComment) { JsonObject jsonAnchor = (JsonObject)jsonComment.get("anchor"); if (jsonAnchor == null) { throw new StashReportExtractionException("JSON Comment does not contain any \"anchor\" tag" + " to describe comment \"line\" and \"path\""); } String path = (String)jsonAnchor.get("path"); // can be null if comment is attached to the global file Long line = getLong(jsonAnchor, "line"); return extractComment(jsonComment, path, line); } public static StashPullRequest extractPullRequest(PullRequestRef pr, JsonObject jsonPullRequest) { StashPullRequest result = new StashPullRequest(pr); long version = getLong(jsonPullRequest, VERSION); result.setVersion(version); JsonArray jsonReviewers = (JsonArray)jsonPullRequest.get("reviewers"); if (jsonReviewers != null) { for (Object objReviewer : jsonReviewers.toArray()) { JsonObject jsonReviewer = (JsonObject)objReviewer; JsonObject jsonUser = (JsonObject)jsonReviewer.get("user"); if (jsonUser != null) { StashUser reviewer = extractUser(jsonUser); result.addReviewer(reviewer); } } } return result; } public static StashUser extractUser(JsonObject jsonUser) { long id = getLong(jsonUser, "id"); String name = (String)jsonUser.get("name"); String slug = (String)jsonUser.get("slug"); String email = (String)jsonUser.get("email"); return new StashUser(id, name, slug, email); }
public static StashDiffReport extractDiffs(JsonObject jsonObject) {
4
KostyaSha/github-integration-plugin
github-pullrequest-plugin/src/test/java/org/jenkinsci/plugins/github/pullrequest/events/impl/GitHubPRCommentEventTest.java
[ "public class GitHubPRCause extends GitHubCause<GitHubPRCause> {\n private static final Logger LOGGER = LoggerFactory.getLogger(GitHubPRCause.class);\n\n private String headSha;\n private int number;\n private boolean mergeable;\n private String targetBranch;\n private String sourceBranch;\n pr...
import hudson.model.TaskListener; import org.jenkinsci.plugins.github.pullrequest.GitHubPRCause; import org.jenkinsci.plugins.github.pullrequest.GitHubPRLabel; import org.jenkinsci.plugins.github.pullrequest.GitHubPRPullRequest; import org.jenkinsci.plugins.github.pullrequest.GitHubPRTrigger; import org.junit.Test; import org.junit.runner.RunWith; import org.kohsuke.github.GHCommitPointer; import org.kohsuke.github.GHIssue; import org.kohsuke.github.GHIssueComment; import org.kohsuke.github.GHIssueState; import org.kohsuke.github.GHLabel; import org.kohsuke.github.GHPullRequest; import org.kohsuke.github.GHRepository; import org.kohsuke.github.GHUser; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import java.io.IOException; import java.io.PrintStream; import java.util.ArrayList; import java.util.Date; import java.util.Set; import static com.github.kostyasha.github.integration.generic.GitHubPRDecisionContext.newGitHubPRDecisionContext; import static java.util.Collections.emptyList; import static java.util.Collections.emptySet; import static org.hamcrest.core.Is.is; import static org.hamcrest.core.IsNot.not; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.mockito.Matchers.anyInt; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when;
package org.jenkinsci.plugins.github.pullrequest.events.impl; /** * @author Kanstantsin Shautsou */ @RunWith(MockitoJUnitRunner.class) public class GitHubPRCommentEventTest { @Mock private GHPullRequest remotePr; @Mock private GitHubPRPullRequest localPR; @Mock private GitHubPRLabel labels; @Mock private GHRepository repository; @Mock private GHIssue issue; @Mock private GHLabel mergeLabel; @Mock private GHLabel reviewedLabel; @Mock private GHLabel testLabel; @Mock private TaskListener listener; @Mock private PrintStream logger; @Mock private GitHubPRTrigger trigger; @Mock private GHUser author; @Mock private GHUser author2; @Mock private GHIssueComment comment; @Mock private GHIssueComment comment2; @Test public void testNullLocalComment() throws IOException { when(listener.getLogger()).thenReturn(logger); when(issue.getCreatedAt()).thenReturn(new Date()); when(comment.getBody()).thenReturn("body"); final ArrayList<GHIssueComment> ghIssueComments = new ArrayList<>(); ghIssueComments.add(comment); when(remotePr.getComments()).thenReturn(ghIssueComments);
GitHubPRCause cause = new GitHubPRCommentEvent("Comment")
0
jentrata/jentrata
ebms-msh-jdbc-store/src/test/java/org/jentrata/ebms/messaging/internal/JDBCMessageStoreTest.java
[ "public class EbmsConstants {\n\n public static final String JENTRATA_VERSION = \"JentrataVersion\";\n\n //Jentrata Message Header keys\n public static final String SOAP_VERSION = \"JentrataSOAPVersion\";\n public static final String EBMS_VERSION = \"JentrataEBMSVersion\";\n public static final Strin...
import org.apache.camel.Exchange; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.impl.DefaultExchange; import org.apache.camel.test.junit4.CamelTestSupport; import org.apache.commons.io.IOUtils; import org.h2.jdbcx.JdbcConnectionPool; import org.jentrata.ebms.EbmsConstants; import org.jentrata.ebms.MessageStatusType; import org.jentrata.ebms.MessageType; import org.jentrata.ebms.messaging.Message; import org.jentrata.ebms.messaging.MessageStore; import org.jentrata.ebms.messaging.UUIDGenerator; import org.jentrata.ebms.messaging.internal.sql.RepositoryManagerFactory; import org.junit.Test; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.List; import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.notNullValue;
package org.jentrata.ebms.messaging.internal; /** * unit test for org.jentrata.ebms.messaging.internal.JDBCMessageStore * * @author aaronwalker */ public class JDBCMessageStoreTest extends CamelTestSupport { private JdbcConnectionPool dataSource; private JDBCMessageStore messageStore; @Test public void testShouldCreateMessageStoreTablesByDefault() throws Exception { try(Connection conn = dataSource.getConnection()) { try (Statement st = conn.createStatement()) { assertTableGotCreated(st,"repository"); assertTableGotCreated(st,"message"); } } } @Test public void testShouldStoreMimeMessage() throws Exception { File body = fileFromClasspath("simple-as4-receipt.xml"); String contentType = "Multipart/Related; boundary=\"----=_Part_7_10584188.1123489648993\"; type=\"application/soap+xml\"; start=\"<soapPart@jentrata.org>\""; String messageId = "testMimeMessage1"; assertStoredMessage(messageId, contentType, body, MessageType.USER_MESSAGE); } @Test public void testShouldStoreSoapMessage() throws Exception { String contentType = "application/soap+xml"; File body = fileFromClasspath("simple-as4-receipt.xml"); String messageId = "testSoapMessage1"; assertStoredMessage(messageId, contentType, body, MessageType.SIGNAL_MESSAGE_WITH_USER_MESSAGE); } @Test public void testUpdateStoreMimeMessage() throws Exception { File body = fileFromClasspath("simple-as4-receipt.xml"); String contentType = "Multipart/Related; boundary=\"----=_Part_7_10584188.1123489648993\"; type=\"application/soap+xml\"; start=\"<soapPart@jentrata.org>\""; String messageId = "testMimeMessage1"; assertStoredMessage(messageId, contentType, body, MessageType.USER_MESSAGE); messageStore.updateMessage(messageId, EbmsConstants.MESSAGE_DIRECTION_INBOUND, MessageStatusType.RECEIVED,"Message Received"); try(Connection conn = dataSource.getConnection()) { try (PreparedStatement st = conn.prepareStatement("select * from message where message_id = ?")) { st.setString(1,messageId); ResultSet resultSet = st.executeQuery(); assertThat(resultSet.next(),is(true)); assertThat(resultSet.getString("status"),equalTo("RECEIVED")); assertThat(resultSet.getString("status_description"),equalTo("Message Received")); } } } @Test public void testFindByMessageId() throws Exception { String contentType = "application/soap+xml"; File body = fileFromClasspath("simple-as4-receipt.xml"); String messageId = "testSoapMessage1"; assertStoredMessage(messageId, contentType, body, MessageType.SIGNAL_MESSAGE_WITH_USER_MESSAGE); messageStore.updateMessage(messageId, EbmsConstants.MESSAGE_DIRECTION_INBOUND, MessageStatusType.RECEIVED,"Message Received");
Message message = messageStore.findByMessageId("testSoapMessage1",EbmsConstants.MESSAGE_DIRECTION_INBOUND);
3
uvagfx/hipi
core/src/test/java/org/hipi/test/JpegCodecTestCase.java
[ "public class FloatImage extends RasterImage {\n\n public FloatImage() {\n super((PixelArray)(new PixelArrayFloat()));\n }\n\n public FloatImage(int width, int height, int bands) throws IllegalArgumentException {\n super((PixelArray)(new PixelArrayFloat()));\n HipiImageHeader header = new HipiImageHeade...
import static org.junit.Assert.*; import static org.junit.Assume.*; import org.hipi.image.HipiImage; import org.hipi.image.RasterImage; import org.hipi.image.ByteImage; import org.hipi.image.FloatImage; import org.hipi.image.PixelArrayByte; import org.hipi.image.PixelArrayFloat; import org.hipi.image.PixelArray; import org.hipi.image.HipiImageFactory; import org.hipi.image.HipiImageHeader; import org.hipi.image.io.ImageDecoder; import org.hipi.image.io.ImageEncoder; import org.hipi.image.io.JpegCodec; import org.hipi.image.io.PpmCodec; import org.hipi.util.ByteUtils; import org.apache.commons.io.FilenameUtils; import org.apache.commons.lang.ArrayUtils; import org.junit.BeforeClass; import org.junit.Test; import org.junit.Ignore; import java.awt.image.BufferedImage; import java.awt.image.DataBuffer; import java.awt.image.Raster; import java.awt.image.ColorConvertOp; import java.awt.color.ColorSpace; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.lang.System; import java.util.Scanner; import java.util.Iterator; import javax.imageio.ImageIO; import javax.imageio.ImageReadParam; import javax.imageio.ImageReader; import javax.imageio.stream.ImageInputStream;
package org.hipi.test; public class JpegCodecTestCase { @BeforeClass public static void setup() throws IOException { TestUtils.setupTmpDirectory(); } private void printExifData(HipiImage image) { // display EXIF data for (String key : image.getAllExifData().keySet()) { String value = image.getExifData(key); System.out.println(key + " : " + value); } } @Test public void testTwelveMonkeysPlugIn() { boolean foundTwelveMonkeys = false; Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName("JPEG"); while (readers.hasNext()) { ImageReader imageReader = readers.next(); // System.out.println("ImageReader: " + imageReader); if (imageReader.toString().startsWith("com.twelvemonkeys.imageio.plugins.jpeg")) { foundTwelveMonkeys = true; } } assertTrue("FATAL ERROR: failed to locate TwelveMonkeys ImageIO plugins", foundTwelveMonkeys); } /** * Test method for {@link hipi.image.io.JpegCodec#decodeHeader(java.io.InputStream)}. * * @throws IOException */ @Test public void testDecodeHeader() throws IOException { ImageDecoder decoder = JpegCodec.getInstance(); String[] fileName = {"canon-ixus", "fujifilm-dx10", "fujifilm-finepix40i", "fujifilm-mx1700", "kodak-dc210", "kodak-dc240", "nikon-e950", "olympus-c960", "ricoh-rdc5300", "sanyo-vpcg250", "sanyo-vpcsx550", "sony-cybershot", "sony-d700", "fujifilm-x100s"}; String[] model = {"Canon DIGITAL IXUS", "DX-10", "FinePix40i", "MX-1700ZOOM", "DC210 Zoom (V05.00)", "KODAK DC240 ZOOM DIGITAL CAMERA", "E950", "C960Z,D460Z", "RDC-5300", "SR6", "SX113", "CYBERSHOT", "DSC-D700", "X100S"}; int[] width = {640, 1024, 600, 640, 640, 640, 800, 640, 896, 640, 640, 640, 672, 3456}; int[] height = {480, 768, 450, 480, 480, 480, 600, 480, 600, 480, 480, 480, 512, 2304}; for (int i = 0; i < fileName.length; i++) { String fname = "../testdata/jpeg-exif-test/" + fileName[i] + ".jpg"; FileInputStream fis = new FileInputStream(fname); HipiImageHeader header = decoder.decodeHeader(fis, true); assertNotNull("failed to decode header: " + fname, header); assertEquals("exif model not correct: " + fname, model[i].trim(), header.getExifData("Model").trim()); assertEquals("width not correct: " + fname, width[i], header.getWidth()); assertEquals("height not correct: " + fname, height[i], header.getHeight()); } } @Test public void testSRGBConversions() throws IOException { ImageDecoder jpegDecoder = JpegCodec.getInstance(); ImageEncoder ppmEncoder = PpmCodec.getInstance(); File[] cmykFiles = new File("../testdata/jpeg-cmyk").listFiles(); File[] rgbFiles = new File("../testdata/jpeg-rgb").listFiles(); File[] files = (File[])ArrayUtils.addAll(cmykFiles,rgbFiles); for (File file : files) { String ext = FilenameUtils.getExtension(file.getName()); if (file.isFile() && ext.equalsIgnoreCase("jpg")) { String jpgPath = file.getPath(); String ppmPath = FilenameUtils.removeExtension(file.getPath()) + "_hipi.ppm"; System.out.println("Testing linear RGB color conversion for: " + jpgPath); // Using FloatImage forces conversion from non-linear sRGB to linear RGB by default FloatImage jpegImage = (FloatImage)jpegDecoder.decodeHeaderAndImage( new FileInputStream(jpgPath), HipiImageFactory.getFloatImageFactory(), true); assertNotNull(jpegImage); BufferedImage javaImage = ImageIO.read(new FileInputStream(jpgPath)); assertNotNull(javaImage); ColorSpace ics = ColorSpace.getInstance(ColorSpace.CS_LINEAR_RGB); ColorConvertOp cco = new ColorConvertOp(ics, null); BufferedImage rgbImage = cco.filter(javaImage, null); assertNotNull(rgbImage); Raster raster = rgbImage.getData(); DataBuffer dataBuffer = raster.getDataBuffer(); int w = raster.getWidth(); int h = raster.getHeight(); assertEquals(w,jpegImage.getWidth()); assertEquals(h,jpegImage.getHeight()); assertEquals(3,raster.getNumBands()); ppmEncoder.encodeImage(jpegImage, new FileOutputStream(ppmPath)); System.out.println("wrote: " + ppmPath); String truthPath = FilenameUtils.removeExtension(file.getPath()) + "_photoshop.ppm"; Runtime rt = Runtime.getRuntime(); String cmd = "compare -metric PSNR " + ppmPath + " " + truthPath + " " + TestUtils.getTmpPath("psnr.png"); System.out.println(cmd); Process pr = rt.exec(cmd); Scanner scanner = new Scanner(new InputStreamReader(pr.getErrorStream())); float psnr = scanner.hasNextFloat() ? scanner.nextFloat() : 0; System.out.println("PSNR with respect to Photoshop ground truth: " + psnr); assertTrue("PSNR is too low : " + psnr, psnr > 30); } } } @Test public void testDecodeImage() throws IOException { ImageDecoder jpegDecoder = JpegCodec.getInstance(); ImageDecoder ppmDecoder = PpmCodec.getInstance(); File[] cmykFiles = new File("../testdata/jpeg-cmyk").listFiles(); // File[] rgbFiles = new File("./testimages/jpeg-rgb").listFiles(); File[] rgbFiles = null; File[] files = (File[])ArrayUtils.addAll(cmykFiles,rgbFiles); for (int iter=0; iter<=1; iter++) { for (File file : files) { String ext = FilenameUtils.getExtension(file.getName()); if (file.isFile() && ext.equalsIgnoreCase("jpg")) { String jpgPath = file.getPath(); String ppmPath = FilenameUtils.removeExtension(file.getPath()) + "_photoshop.ppm"; System.out.println("Testing JPEG decoder (" + (iter == 0 ? "ByteImage" : "FloatImage") + ") for: " + jpgPath); FileInputStream fis = new FileInputStream(ppmPath); RasterImage ppmImage = (RasterImage)ppmDecoder.decodeHeaderAndImage(fis, (iter == 0 ? HipiImageFactory.getByteImageFactory() : HipiImageFactory.getFloatImageFactory()), false); assumeNotNull(ppmImage); fis = new FileInputStream(jpgPath); RasterImage jpegImage = (RasterImage)jpegDecoder.decodeHeaderAndImage(fis, (iter == 0 ? HipiImageFactory.getByteImageFactory() : HipiImageFactory.getFloatImageFactory()), true); assumeNotNull(jpegImage); float maxDiff = (iter == 0 ? 45.0f : 45.0f/255.0f); if (!ppmImage.equalsWithTolerance((RasterImage)jpegImage, maxDiff)) { // allow 3 8-bit values difference to account for color space conversion System.out.println(ppmImage); System.out.println(jpegImage); // Get pointers to pixel arrays
PixelArray ppmPA = ppmImage.getPixelArray();
2
MazeSolver/MazeSolver
src/es/ull/mazesolver/agent/DStarAgent.java
[ "public interface BlackboardCommunication {\n /**\n * Obtiene la pizarra asociada al agente.\n *\n * @return Pizarra que contiene actualmente el agente.\n */\n public Object getBlackboard ();\n\n /**\n * Cambia la pizarra que tiene el agente.\n *\n * @param blackboard\n * Nueva pizarra p...
import es.ull.mazesolver.agent.util.BlackboardCommunication; import es.ull.mazesolver.gui.configuration.AgentConfigurationPanel; import es.ull.mazesolver.gui.configuration.HeuristicAgentConfigurationPanel; import es.ull.mazesolver.gui.environment.Environment; import es.ull.mazesolver.maze.Maze; import es.ull.mazesolver.maze.MazeCell; import es.ull.mazesolver.maze.algorithm.EmptyMaze; import es.ull.mazesolver.util.BlackboardManager; import es.ull.mazesolver.util.Direction; import java.awt.Color; import java.awt.Point; import java.util.ArrayList; import java.util.PriorityQueue;
/* * This file is part of MazeSolver. * * 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/>. * * Copyright (c) 2014 MazeSolver * Sergio M. Afonso Fumero <theSkatrak@gmail.com> * Kevin I. Robayna Hernández <kevinirobaynahdez@gmail.com> */ /** * @file DStarAgent.java * @date 10/12/2014 */ package es.ull.mazesolver.agent; /** * Agente que implementa el algoritmo D* para calcular la ruta más corta hasta * la salida teniendo tan sólo conocimiento local del entorno. * * @see <a * href="http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.15.3683"> * Optimal and Efficient Path Planning for Unknown and Dynamic Environments * </a> */ public class DStarAgent extends HeuristicAgent implements BlackboardCommunication { private static final long serialVersionUID = 1342168437798267323L; private static String BLACKBOARD_CHANNEL = "D* Agents Channel"; /** * Representa el estado del algoritmo, que es lo que es compartido entre * agentes D* como pizarra. */ /** * */ private static class AlgorithmState { /** * No se trata del laberinto en el que el agente se mueve, sino la * representación de lo que el agente conoce sobre el laberinto. Todas * aquellas zonas que el agente no ha visitado supone que no contienen * paredes. */ public Maze maze; /** * Posición de la celda del laberinto más cercana a su salida. */ public Point exit; /** * Representa la matriz de posiciones del laberinto con el estado del agente * asociado a cada celda. */ public ArrayList <ArrayList <State>> state_maze; /** * Lista "open" de estados del algoritmo. */ public PriorityQueue <State> open; /** * Valor de "k_old" del algoritmo. */ public double k_old; } private transient AlgorithmState m_st; /** * Crea un nuevo agente D* en el entorno indicado. * * @param env * Entorno en el que se va a colocar al agente. */ public DStarAgent (Environment env) { super(env); } /* * (non-Javadoc) * * @see agent.Agent#getAlgorithmName() */ @Override public String getAlgorithmName () { return "D*"; } /* * (non-Javadoc) * * @see es.ull.mazesolver.agent.Agent#getAlgorithmColor() */ @Override public Color getAlgorithmColor () { return Color.BLUE; } /* * (non-Javadoc) * * @see agent.Agent#setEnvironment(gui.environment.Environment) */ @Override public void setEnvironment (Environment env) { super.setEnvironment(env); resetMemory(); BlackboardManager mgr = env.getBlackboardManager(); try { setBlackboard(mgr.getBlackboard(BLACKBOARD_CHANNEL)); } catch (Exception e) { Maze real_maze = env.getMaze(); m_st = new AlgorithmState(); m_st.maze = new Maze(new EmptyMaze(real_maze.getHeight(), real_maze.getWidth())); // Creamos la matriz de estados, donde cada celda representa un nodo en el // grafo que manipula el algoritmo. Esto será lo que se comparta entre // todos los agentes. m_st.state_maze = new ArrayList <ArrayList <State>>(m_st.maze.getHeight()); for (int i = 0; i < m_st.maze.getHeight(); i++) { m_st.state_maze.add(new ArrayList <State>(m_st.maze.getWidth())); for (int j = 0; j < m_st.maze.getWidth(); j++) m_st.state_maze.get(i).add(new State(new Point(j, i))); } // La salida la colocaremos dentro del laberinto para que el agente pueda // utilizarla como un estado más, luego en el método getNextMovement() se // encarga de moverse al exterior si está en el punto al lado de la salida m_st.exit = real_maze.getExit(); if (m_st.exit.x < 0) m_st.exit.x++; else if (m_st.exit.x == m_st.maze.getWidth()) m_st.exit.x--; else if (m_st.exit.y < 0) m_st.exit.y++; else /* m_st.exit.y == m_st.maze.getHeight() */ m_st.exit.y--; BLACKBOARD_CHANNEL = mgr.addBlackboard(m_st, BLACKBOARD_CHANNEL); } } /* * (non-Javadoc) * * @see agent.Agent#getNextMovement() */ @Override public Direction getNextMovement () { // Si estamos al lado de la salida evitamos cálculos y salimos directamente for (int i = 1; i < Direction.MAX_DIRECTIONS; i++) { Direction dir = Direction.fromIndex(i);
if (m_env.look(m_pos, dir) == MazeCell.Vision.OFFLIMITS)
5
justyoyo/Contrast
pdf417/src/main/java/com/justyoyo/contrast/pdf417/PDF417HighLevelEncoder.java
[ "public enum BarcodeFormat {\n\n /** Aztec 2D barcode format. */\n AZTEC,\n\n /** CODABAR 1D format. */\n CODABAR,\n\n /** Code 39 1D format. */\n CODE_39,\n\n /** Code 93 1D format. */\n CODE_93,\n\n /** Code 128 1D format. */\n CODE_128,\n\n /** Data Matrix 2D barcode format. */\n DATA_MATRIX,\n\n /*...
import android.graphics.Bitmap; import com.justyoyo.contrast.BarcodeFormat; import com.justyoyo.contrast.EncodeHintType; import com.justyoyo.contrast.WriterException; import com.justyoyo.contrast.common.BitMatrix; import com.justyoyo.contrast.common.CharacterSetECI; import com.justyoyo.contrast.common.Compaction; import java.math.BigInteger; import java.nio.charset.Charset; import java.nio.charset.CharsetEncoder; import java.util.Arrays; import java.util.EnumMap; import java.util.Map; import static android.graphics.Color.BLACK; import static android.graphics.Color.WHITE;
package com.justyoyo.contrast.pdf417; /** * Created by tiberiugolaes on 08/11/2016. */ public final class PDF417HighLevelEncoder { private int dimension = Integer.MIN_VALUE; private String displayContents = null; private String contents = null; private Map<EncodeHintType, Object> hints = null; private boolean encoded = false; public PDF417HighLevelEncoder(String data, int dimension, Map<EncodeHintType, Object> hints) { this.dimension = dimension; this.encoded = encodeContents(data); this.hints = hints; } private boolean encodeContents(String data) { contents = data; displayContents = data; return contents != null && contents.length() > 0; } public String getContents() { return contents; } /** * code for Text compaction */ private static final int TEXT_COMPACTION = 0; /** * code for Byte compaction */ private static final int BYTE_COMPACTION = 1; /** * code for Numeric compaction */ private static final int NUMERIC_COMPACTION = 2; /** * Text compaction submode Alpha */ private static final int SUBMODE_ALPHA = 0; /** * Text compaction submode Lower */ private static final int SUBMODE_LOWER = 1; /** * Text compaction submode Mixed */ private static final int SUBMODE_MIXED = 2; /** * Text compaction submode Punctuation */ private static final int SUBMODE_PUNCTUATION = 3; /** * mode latch to Text Compaction mode */ private static final int LATCH_TO_TEXT = 900; /** * mode latch to Byte Compaction mode (number of characters NOT a multiple of 6) */ private static final int LATCH_TO_BYTE_PADDED = 901; /** * mode latch to Numeric Compaction mode */ private static final int LATCH_TO_NUMERIC = 902; /** * mode shift to Byte Compaction mode */ private static final int SHIFT_TO_BYTE = 913; /** * mode latch to Byte Compaction mode (number of characters a multiple of 6) */ private static final int LATCH_TO_BYTE = 924; /** * identifier for a user defined Extended Channel Interpretation (ECI) */ private static final int ECI_USER_DEFINED = 925; /** * identifier for a general purpose ECO format */ private static final int ECI_GENERAL_PURPOSE = 926; /** * identifier for an ECI of a character set of code page */ private static final int ECI_CHARSET = 927; /** * Raw code table for text compaction Mixed sub-mode */ private static final byte[] TEXT_MIXED_RAW = { 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 38, 13, 9, 44, 58, 35, 45, 46, 36, 47, 43, 37, 42, 61, 94, 0, 32, 0, 0, 0}; /** * Raw code table for text compaction: Punctuation sub-mode */ private static final byte[] TEXT_PUNCTUATION_RAW = { 59, 60, 62, 64, 91, 92, 93, 95, 96, 126, 33, 13, 9, 44, 58, 10, 45, 46, 36, 47, 34, 124, 42, 40, 41, 63, 123, 125, 39, 0}; private static final byte[] MIXED = new byte[128]; private static final byte[] PUNCTUATION = new byte[128]; private static final Charset DEFAULT_ENCODING = Charset.forName("ISO-8859-1"); public PDF417HighLevelEncoder() { } static { //Construct inverse lookups Arrays.fill(MIXED, (byte) -1); for (int i = 0; i < TEXT_MIXED_RAW.length; i++) { byte b = TEXT_MIXED_RAW[i]; if (b > 0) { MIXED[b] = (byte) i; } } Arrays.fill(PUNCTUATION, (byte) -1); for (int i = 0; i < TEXT_PUNCTUATION_RAW.length; i++) { byte b = TEXT_PUNCTUATION_RAW[i]; if (b > 0) { PUNCTUATION[b] = (byte) i; } } } /** * Performs high-level encoding of a PDF417 message using the algorithm described in annex P * of ISO/IEC 15438:2001(E). If byte compaction has been selected, then only byte compaction * is used. * * @param msg the message * @param compaction compaction mode to use * @param encoding character encoding used to encode in default or byte compaction * or {@code null} for default / not applicable * @return the encoded message (the char values range from 0 to 928) */
public static String encodeHighLevel(String msg, Compaction compaction, Charset encoding) throws WriterException {
2
KostyaSha/github-integration-plugin
github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/events/impl/GitHubPRLabelAddedEvent.java
[ "public class GitHubPRDecisionContext extends GitHubDecisionContext<GitHubPREvent, GitHubPRCause> {\n private final GHPullRequest remotePR;\n private final GitHubPRPullRequest localPR;\n private final GitHubPRUserRestriction prUserRestriction;\n private final GitHubPRRepository localRepo;\n\n protect...
import com.github.kostyasha.github.integration.generic.GitHubPRDecisionContext; import hudson.Extension; import hudson.model.TaskListener; import org.jenkinsci.Symbol; import org.jenkinsci.plugins.github.pullrequest.GitHubPRCause; import org.jenkinsci.plugins.github.pullrequest.GitHubPRLabel; import org.jenkinsci.plugins.github.pullrequest.GitHubPRPullRequest; import org.jenkinsci.plugins.github.pullrequest.events.GitHubPREvent; import org.jenkinsci.plugins.github.pullrequest.events.GitHubPREventDescriptor; import org.kohsuke.github.GHIssueState; import org.kohsuke.github.GHLabel; import org.kohsuke.github.GHPullRequest; import org.kohsuke.stapler.DataBoundConstructor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import edu.umd.cs.findbugs.annotations.NonNull; import java.io.IOException; import java.io.PrintStream; import java.util.Collection; import java.util.HashSet; import java.util.Set; import static java.util.Objects.isNull;
package org.jenkinsci.plugins.github.pullrequest.events.impl; /** * When label is added to pull request. Set of labels is considered added only when * at least one label of set was newly added (was not saved in local PR previously) * AND every label of set exists on remote PR now. * * @author Kanstantsin Shautsou */ public class GitHubPRLabelAddedEvent extends GitHubPREvent { private static final String DISPLAY_NAME = "Labels added"; private static final Logger LOG = LoggerFactory.getLogger(GitHubPRLabelAddedEvent.class); private final GitHubPRLabel label; @DataBoundConstructor public GitHubPRLabelAddedEvent(GitHubPRLabel label) { this.label = label; } public GitHubPRLabel getLabel() { return label; } @Override
public GitHubPRCause check(@NonNull GitHubPRDecisionContext prDecisionContext) throws IOException {
0
SecUSo/privacy-friendly-weather
app/src/main/java/org/secuso/privacyfriendlyweather/weather_api/open_weather_map/OwmHttpRequestAddCity.java
[ "@SuppressWarnings({RoomWarnings.PRIMARY_KEY_FROM_EMBEDDED_IS_DROPPED,\n RoomWarnings.MISSING_INDEX_ON_FOREIGN_KEY_CHILD, RoomWarnings.INDEX_FROM_EMBEDDED_ENTITY_IS_DROPPED})\n\n/**\n * This class is the database model for the cities to watch. 'Cities to watch' means the locations\n * for which a user would ...
import android.content.Context; import org.secuso.privacyfriendlyweather.database.data.CityToWatch; import org.secuso.privacyfriendlyweather.http.HttpRequestType; import org.secuso.privacyfriendlyweather.http.IHttpRequest; import org.secuso.privacyfriendlyweather.http.VolleyHttpRequest; import org.secuso.privacyfriendlyweather.weather_api.IHttpRequestForCityList; import java.util.List;
package org.secuso.privacyfriendlyweather.weather_api.open_weather_map; /** * This class provides the functionality for making and processing HTTP requests to the * OpenWeatherMap to retrieve the latest weather data for a given city and then process the * response. */ public class OwmHttpRequestAddCity extends OwmHttpRequest implements IHttpRequestForCityList { private Context context; /** * @param context The application context. */ public OwmHttpRequestAddCity(Context context) { this.context = context; } /** * @see IHttpRequestForCityList#perform(List) */ @Override public void perform(List<CityToWatch> cities) {
IHttpRequest httpRequest = new VolleyHttpRequest(context);
2
Multiplayer-italia/AuthMe-Reloaded
src/main/java/uk/org/whoami/authme/commands/RegisterCommand.java
[ "public class Utils {\r\n //private Settings settings = Settings.getInstance();\r\n private Player player;\r\n private String currentGroup;\r\n private static Utils singleton;\r\n private String unLoggedGroup = Settings.getUnloggedinGroup;\r\n /* \r\n public Utils(Player player) {\r\n t...
import uk.org.whoami.authme.cache.limbo.LimboPlayer; import uk.org.whoami.authme.datasource.DataSource; import uk.org.whoami.authme.security.PasswordSecurity; import uk.org.whoami.authme.settings.Messages; import uk.org.whoami.authme.settings.Settings; import java.security.NoSuchAlgorithmException; import java.util.Date; import org.bukkit.GameMode; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import uk.org.whoami.authme.ConsoleLogger; import uk.org.whoami.authme.Utils; import uk.org.whoami.authme.cache.auth.PlayerAuth; import uk.org.whoami.authme.cache.auth.PlayerCache; import uk.org.whoami.authme.cache.limbo.LimboCache;
/* * Copyright 2011 Sebastian Köhler <sebkoehler@whoami.org.uk>. * * 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 uk.org.whoami.authme.commands; public class RegisterCommand implements CommandExecutor { private Messages m = Messages.getInstance(); //private Settings settings = Settings.getInstance(); private DataSource database; public boolean isFirstTimeJoin; public RegisterCommand(DataSource database) { this.database = database; this.isFirstTimeJoin = false; } @Override public boolean onCommand(CommandSender sender, Command cmnd, String label, String[] args) { if (!(sender instanceof Player)) { return true; } if (!sender.hasPermission("authme." + label.toLowerCase())) { sender.sendMessage(m._("no_perm")); return true; } Player player = (Player) sender; String name = player.getName().toLowerCase(); String ip = player.getAddress().getAddress().getHostAddress(); if (PlayerCache.getInstance().isAuthenticated(name)) { player.sendMessage(m._("logged_in")); return true; } if (!Settings.isRegistrationEnabled) { player.sendMessage(m._("reg_disabled")); return true; } if (args.length == 0 || (Settings.getEnablePasswordVerifier && args.length < 2) ) { player.sendMessage(m._("usage_reg")); return true; } //System.out.println("pass legth "+args[0].length()); //System.out.println("pass length permit"+Settings.passwordMaxLength); if(args[0].length() < Settings.getPasswordMinLen || args[0].length() > Settings.passwordMaxLength) { player.sendMessage(m._("pass_len")); return true; } if (database.isAuthAvailable(player.getName().toLowerCase())) { player.sendMessage(m._("user_regged")); return true; } // // Check if player exeded the max number of registration // if(Settings.getmaxRegPerIp > 0 ){ String ipAddress = player.getAddress().getAddress().getHostAddress(); if(!sender.hasPermission("authme.allow2accounts") && database.getIps(ipAddress) >= Settings.getmaxRegPerIp) { //System.out.println("number of reg "+database.getIps(ipAddress)); player.sendMessage(m._("max_reg")); return true; } } try { String hash; if(Settings.getEnablePasswordVerifier) { if (args[0].equals(args[1])) { hash = PasswordSecurity.getHash(Settings.getPasswordHash, args[0]); } else { player.sendMessage(m._("password_error")); return true; } } else hash = PasswordSecurity.getHash(Settings.getPasswordHash, args[0]); PlayerAuth auth = new PlayerAuth(name, hash, ip, new Date().getTime()); if (!database.saveAuth(auth)) { player.sendMessage(m._("error")); return true; } PlayerCache.getInstance().addPlayer(auth); LimboPlayer limbo = LimboCache.getInstance().getLimboPlayer(name); if (limbo != null) { // player.getInventory().setContents(limbo.getInventory()); // player.getInventory().setArmorContents(limbo.getArmour()); player.setGameMode(GameMode.getByValue(limbo.getGameMode())); if (Settings.isTeleportToSpawnEnabled) { player.teleport(limbo.getLoc()); } sender.getServer().getScheduler().cancelTask(limbo.getTimeoutTaskId()); LimboCache.getInstance().deleteLimboPlayer(name); } if(!Settings.getRegisteredGroup.isEmpty()){
Utils.getInstance().setGroup(player, Utils.groupType.REGISTERED);
0
onepf/OPFPush
opfpush/src/main/java/org/onepf/opfpush/backoff/RetryManager.java
[ "public final class ConnectivityChangeReceiver extends BroadcastReceiver {\n\n @Override\n public void onReceive(@NonNull final Context context, @NonNull final Intent intent) {\n OPFLog.logMethod(context, OPFUtils.toString(intent));\n\n final Set<Pair<String, String>> retryProvidersActions = Ret...
import android.app.AlarmManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.Pair; import org.onepf.opfpush.ConnectivityChangeReceiver; import org.onepf.opfpush.RetryBroadcastReceiver; import org.onepf.opfpush.model.Operation; import org.onepf.opfutils.OPFChecks; import org.onepf.opfutils.OPFLog; import org.onepf.opfutils.exception.InitException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashSet; import java.util.Locale; import java.util.Set; import static android.content.Context.ALARM_SERVICE; import static android.net.ConnectivityManager.CONNECTIVITY_ACTION; import static org.onepf.opfpush.OPFConstants.ACTION_RETRY_REGISTER; import static org.onepf.opfpush.OPFConstants.ACTION_RETRY_UNREGISTER; import static org.onepf.opfpush.OPFConstants.EXTRA_PROVIDER_NAME; import static org.onepf.opfpush.model.Operation.REGISTER; import static org.onepf.opfpush.model.Operation.UNREGISTER;
/* * 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.opfpush.backoff; /** * @author Roman Savin * @since 06.02.2015 */ public final class RetryManager implements BackoffManager { private static volatile RetryManager instance; @NonNull private final Context appContext; @NonNull private final BackoffManager backoffManager; @NonNull private final AlarmManager alarmManager; private final Set<Pair<String, String>> retryProvidersActions; @Nullable private ConnectivityChangeReceiver connectivityChangeReceiver; private RetryManager(@NonNull final Context context, @NonNull final BackoffManager backoffManager) { this.appContext = context.getApplicationContext(); this.backoffManager = backoffManager; this.alarmManager = (AlarmManager) context.getSystemService(ALARM_SERVICE); this.retryProvidersActions = new HashSet<>(); } @NonNull @SuppressWarnings("PMD.NonThreadSafeSingleton") public static RetryManager init(@NonNull final Context context, @NonNull final BackoffManager backoffManager) { OPFChecks.checkThread(true); checkInit(false); return instance = new RetryManager(context, backoffManager); } @NonNull public static RetryManager getInstance() { OPFChecks.checkThread(true); checkInit(true); return instance; } private static void checkInit(final boolean initExpected) { final boolean isInit = instance != null; if (initExpected != isInit) { throw new InitException(isInit); } } @Override public boolean hasTries(@NonNull final String providerName, @NonNull final Operation operation) { return backoffManager.hasTries(providerName, operation); } @Override public long getTryDelay(@NonNull final String providerName, @NonNull final Operation operation) { return backoffManager.getTryDelay(providerName, operation); } @Override public void reset(@NonNull final String providerName, @NonNull final Operation operation) { backoffManager.reset(providerName, operation); } public void postRetryRegister(@NonNull final String providerName) { OPFLog.logMethod(providerName); postRetry(providerName, REGISTER, ACTION_RETRY_REGISTER); } public void postRetryUnregister(@NonNull final String providerName) { OPFLog.logMethod(providerName); postRetry(providerName, UNREGISTER, ACTION_RETRY_UNREGISTER); } public void cancelRetryAllOperations(@NonNull final String providerName) { cancelRetryRegister(providerName); cancelRetryUnregister(providerName); } public void cancelRetryRegister(@NonNull final String providerName) { OPFLog.logMethod(providerName); cancelRetry(providerName, REGISTER, ACTION_RETRY_REGISTER); } public void cancelRetryUnregister(@NonNull final String providerName) { OPFLog.logMethod(providerName); cancelRetry(providerName, UNREGISTER, ACTION_RETRY_UNREGISTER); } @NonNull public Set<Pair<String, String>> getRetryProvidersActions() { OPFLog.logMethod(); return retryProvidersActions; } private void postRetry(@NonNull final String providerName, @NonNull final Operation operation, @NonNull final String action) { final long when = System.currentTimeMillis() + getTryDelay(providerName, operation); OPFLog.d("Post retry %s provider '%s' at %s", operation, providerName, SimpleDateFormat.getDateTimeInstance( DateFormat.DEFAULT, DateFormat.DEFAULT, Locale.US ).format(new Date(when)) ); retryProvidersActions.add(new Pair<>(providerName, action)); registerConnectivityChangeReceiver();
final Intent intent = new Intent(appContext, RetryBroadcastReceiver.class);
1
AbrarSyed/SecretRoomsMod-forge
src/main/java/com/wynprice/secretroomsmod/base/interfaces/ISecretBlock.java
[ "@Config(modid = SecretRooms5.MODID, category = \"\")\n@EventBusSubscriber(modid=SecretRooms5.MODID)\npublic final class SecretConfig {\n\n public static final General GENERAL = new General();\n public static final EnergizedPaste ENERGIZED_PASTE = new EnergizedPaste();\n public static final SRMBlockFunctio...
import java.util.ArrayList; import java.util.List; import java.util.Random; import com.wynprice.secretroomsmod.SecretConfig; import com.wynprice.secretroomsmod.handler.ParticleHandler; import com.wynprice.secretroomsmod.render.FakeBlockAccess; import com.wynprice.secretroomsmod.render.RenderStateUnlistedProperty; import com.wynprice.secretroomsmod.render.fakemodels.FakeBlockModel; import com.wynprice.secretroomsmod.render.fakemodels.SecretBlockModel; import com.wynprice.secretroomsmod.render.fakemodels.TrueSightModel; import com.wynprice.secretroomsmod.tileentity.TileEntityInfomationHolder; import net.minecraft.block.Block; import net.minecraft.block.ITileEntityProvider; import net.minecraft.block.SoundType; import net.minecraft.block.state.BlockFaceShape; import net.minecraft.block.state.IBlockState; import net.minecraft.client.particle.ParticleManager; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLiving.SpawnPlacementType; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Blocks; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.BlockRenderLayer; import net.minecraft.util.EnumBlockRenderType; import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumParticleTypes; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.RayTraceResult; import net.minecraft.util.math.Vec3d; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import net.minecraft.world.WorldServer; import net.minecraftforge.common.property.IExtendedBlockState; import net.minecraftforge.common.property.IUnlistedProperty; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly;
package com.wynprice.secretroomsmod.base.interfaces; /** * The interface used by all SRM blocks. Most methods here are called directly from the block, as to store all the same code in the same place. * Extends {@link ITileEntityProvider} as all SRM blocks have TileEntities. * <br>Not needed but means, * <br>{@code public class SRMBlock implements ISecretBlock, ITileEntityProvider} * <br>becomes: * <br>{@code public class SRMBlock implements ISecretBlock} * @author Wyn Price * */ public interface ISecretBlock extends ITileEntityProvider { /** * The unlisted property used to store the RenderState */ IUnlistedProperty<IBlockState> RENDER_PROPERTY = new RenderStateUnlistedProperty(); /** * Used to get the renderState from the World and the position * @param world the world the blocks in * @param pos the position of the block * @return the rendered state of the block, or null if there is none */ default public IBlockState getState(IBlockAccess world, BlockPos pos) { return world.getTileEntity(pos) instanceof ISecretTileEntity ? ISecretTileEntity.getMirrorState(world, pos) : Blocks.STONE.getDefaultState(); } /** * Gets the world from the TileEntity at the position * @param access The world * @param pos the position of the tilentity * @return The world, or null if it cant be found */ default public World getWorld(IBlockAccess access, BlockPos pos) { return access.getTileEntity(pos) != null ? access.getTileEntity(pos).getWorld() : null; } /** * Used to force the block render state to the {@link ISecretTileEntity}, if it exists. * @param world the world the SRM blocks in * @param tePos the position of the block * @param state the state of which to force the block to */ default public void forceBlockState(World world, BlockPos tePos, IBlockState state) { if(world.getTileEntity(tePos) instanceof ISecretTileEntity) ((ISecretTileEntity)world.getTileEntity(tePos)).setMirrorStateForcable(state); } @Override default TileEntity createNewTileEntity(World worldIn, int meta) { return new TileEntityInfomationHolder(); } /** * Used so individual blocks can change the BlockModel for rendering. Used for things like Glass and Doors to make them different * @param model the original model, will be returned if the Block dosn't need different visuals * @return the model that will be rendered */ @SideOnly(Side.CLIENT) default FakeBlockModel phaseModel(FakeBlockModel model) { return model; } /** * Used to get the class from {@link #phaseModel(FakeBlockModel)} * @return the class that {@link #phaseModel(FakeBlockModel)} uses, with the default being {@link FakeBlockModel} */ @SideOnly(Side.CLIENT) default Class<? extends FakeBlockModel> getModelClass() { return phaseModel(new FakeBlockModel(Blocks.STONE.getDefaultState())).getClass(); } @SideOnly(Side.CLIENT) default boolean isRenderTransparent() { return getModelClass() != FakeBlockModel.class; } /** * Used so individual blocks can change the BlockModel for rendering, when the Helmet of True Sight is on. * @param model the original model, will be returned if the Block dosn't need different visuals * @return the model that will be rendered */ @SideOnly(Side.CLIENT) default TrueSightModel phaseTrueModel(TrueSightModel model) { return model; } /** * Used as an override to SRM blocks. Used to run {@code Block#canCreatureSpawn(IBlockState, IBlockAccess, BlockPos, SpawnPlacementType)} on Mirrored states * @param state The current state * @param world The current world * @param pos Block position in world * @param type The Mob Category Type * @return True to allow a mob of the specified category to spawn, false to prevent it. */ default boolean canCreatureSpawn(IBlockState state, IBlockAccess world, BlockPos pos, SpawnPlacementType type) { return getState(world, pos).getBlock().canCreatureSpawn(getState(world, pos), new FakeBlockAccess(world), pos, type); } /** * Used as an override to SRM blocks. Used to run {@link Block#canHarvestBlock(IBlockAccess, BlockPos, EntityPlayer)} on mirrored states * @param world The world * @param player The player damaging the block * @param pos The block's current position * @return True to spawn the drops */ default boolean canHarvestBlock(IBlockAccess world, BlockPos pos, EntityPlayer player) { return getState(world, pos).getBlock().canHarvestBlock(new FakeBlockAccess(world), pos, player); } /** * Used as an override to SRM blocks. Used to attempt to get the Mirrored State bounding box * @param state The input state. not needed what so ever. <b> Exists because {@link Block#getBoundingBox(IBlockState, IBlockAccess, BlockPos)} has the {@link IBlockState} as a field. </b> * @param source the world * @param pos the position * @return the bounding box of the Mirrored State, or {@link Block#FULL_BLOCK_AABB} if does there is no tileEntity at the position. */ default AxisAlignedBB getBoundingBox(IBlockState state, IBlockAccess source, BlockPos pos) { if(source.getTileEntity(pos) instanceof ISecretTileEntity && ((ISecretTileEntity)source.getTileEntity(pos)).getMirrorStateSafely() != null) return ((ISecretTileEntity)source.getTileEntity(pos)).getMirrorStateSafely().getBoundingBox(new FakeBlockAccess(source), pos); return Block.FULL_BLOCK_AABB; } /** * Used as an override to SRM blocks. Used to run {@link Block#canBeConnectedTo(IBlockAccess, BlockPos, EnumFacing)} on the MirrorState * @param world The current world * @param pos The position of the block * @param facing The side the connecting block is on * @return True to allow another block to connect to this block */ default boolean canBeConnectedTo(IBlockAccess world, BlockPos pos, EnumFacing facing) { return getState(world, pos).getBlock().canBeConnectedTo(new FakeBlockAccess(world), pos, facing); } /** * Used as an override to SRM blocks. Used to run {@link Block#getBlockFaceShape(IBlockAccess, IBlockState, BlockPos, EnumFacing)} on Mirror State. * @param worldIn The current world * @param state The {@link IBlockState} of the current position * @param pos The position of the block * @param face The side thats being checked * @return an approximation of the form of the given face. */ default BlockFaceShape getBlockFaceShape(IBlockAccess worldIn, IBlockState state, BlockPos pos, EnumFacing face) { return getState(worldIn, pos).getBlockFaceShape(new FakeBlockAccess(worldIn), pos, face); } /** * Used as an override to SRM blocks. Used to run {@link Block#getBlockHardness(IBlockState, World, BlockPos)} on the Mirrored state * @param worldIn The current world * @param blockState The {@link IBlockState} of the current position * @param pos The position of the block * @return the hardness of the block */ default float getBlockHardness(IBlockState blockState, World worldIn, BlockPos pos) { return ISecretTileEntity.getMirrorState(worldIn, pos).getBlockHardness(worldIn, pos); } /** * Used as an override for SRM blocks. Used to run {@link #canConnectRedstone(IBlockState, IBlockAccess, BlockPos, EnumFacing)} on the mirrored state * @param state The current state * @param world The current world * @param pos Block position in world * @param side The side that is trying to make the connection, CAN BE NULL * @return True to make the connection */ default public boolean canConnectRedstone(IBlockState state, IBlockAccess world, BlockPos pos, EnumFacing side) { return getState(world, pos).getBlock().canConnectRedstone(getState(world, pos), new FakeBlockAccess(world), pos, side); } /** * Used as an override for SRM blocks. Used to run {@link Block#getSlipperiness(IBlockState, IBlockAccess, BlockPos, Entity)} on the mirrored state * @param state state of the block * @param world the world * @param pos the position in the world * @param entity the entity in question * @return the factor by which the entity's motion should be multiplied */ default public float getSlipperiness(IBlockState state, IBlockAccess world, BlockPos pos, Entity entity) { return getState(world, pos).getBlock().getSlipperiness(getState(world, pos), new FakeBlockAccess(world), pos, entity); } /** * Used as an override for SRM block. Used to run {@link Block#canPlaceTorchOnTop(IBlockState, IBlockAccess, BlockPos)} on the mirrored state * @param state The current state * @param world The current world * @param pos Block position in world * @return True to allow the torch to be placed */ default public boolean canPlaceTorchOnTop(IBlockState state, IBlockAccess world, BlockPos pos) { return getState(world, pos).getBlock().canPlaceTorchOnTop(getState(world, pos), new FakeBlockAccess(world), pos); } /** * Used as an override for SRM blocks. Used to run {@link Block#collisionRayTrace(IBlockState, World, BlockPos, Vec3d, Vec3d)} on the mirrored state * @param blockState The current state * @param worldIn the current world * @param pos the current position * @param start the start of the raytrace * @param end the end of the raytrace * @return the raytrace to use */ default public RayTraceResult collisionRayTrace(IBlockState blockState, World worldIn, BlockPos pos, Vec3d start, Vec3d end) { return getState(worldIn, pos).collisionRayTrace(worldIn, pos, start, end); } /** * A list of all ISecretTileEntities. Used to get Material and things like that */ public static final ArrayList<TileEntity> ALL_SECRET_TILE_ENTITIES = new ArrayList<>(); /** * Used as an override to SRM blocks. Used to run {@link Block#isSideSolid(IBlockState, IBlockAccess, BlockPos, EnumFacing)} on the mirrored state * @param base_state The base state, getActualState should be called first * @param world The current world * @param pos Block position in world * @param side The side to check * @return True if the mirrored state is solid on the specified side. */ default boolean isSideSolid(IBlockState base_state, IBlockAccess world, BlockPos pos, EnumFacing side) { return getState(world, pos).isSideSolid(new FakeBlockAccess(world), pos, side); } /** * Used as an override for SRM blocks. Used to run {@link Block#addCollisionBoxToList(IBlockState, World, BlockPos, AxisAlignedBB, List, Entity, boolean)} on the mirrored state * @param state The current BlockState * @param worldIn The current World * @param pos The current BlockPos * @param entityBox The colliding Entities bounding box * @param collidingBoxes The list of bounding boxes * @param entityIn The Entity Colliding with the block * @param isActualState Is the {@code state} the actual state */ default void addCollisionBoxToList(IBlockState state, World worldIn, BlockPos pos, AxisAlignedBB entityBox, List<AxisAlignedBB> collidingBoxes, Entity entityIn, boolean isActualState) { if(worldIn.getTileEntity(pos) instanceof ISecretTileEntity && ISecretTileEntity.getMirrorState(worldIn, pos) != null) ISecretTileEntity.getMirrorState(worldIn, pos).addCollisionBoxToList(worldIn, pos, entityBox, collidingBoxes, entityIn, isActualState); else Blocks.STONE.addCollisionBoxToList(state, worldIn, pos, entityBox, collidingBoxes, entityIn, isActualState); } /** * Used as an override for SRM blocks. Used to run {@link Block#getSoundType(IBlockState, World, BlockPos, Entity)} on the mirrored state * @param state The state * @param world The world * @param pos The position. Note that the world may not necessarily have {@code state} here! * @param entity The entity that is breaking/stepping on/placing/hitting/falling on this block, or null if no entity is in this context * @return A SoundType to use */ default SoundType getSoundType(IBlockState state, World world, BlockPos pos, Entity entity) { return world.getTileEntity(pos) instanceof ISecretTileEntity && ISecretTileEntity.getMirrorState(world, pos) != null ? ISecretTileEntity.getMirrorState(world, pos).getBlock().getSoundType() : SoundType.STONE; } /** * Used to override the opacity of a block. Used to call {@link Block#getLightOpacity(IBlockState)} on the mirrored state * @param state the state * @param world the world * @param pos the position * @return the opacity */ default int getLightOpacity(IBlockState state, IBlockAccess world, BlockPos pos) {
return SecretConfig.BLOCK_FUNCTIONALITY.copyLight ? ISecretTileEntity.getMirrorState(world, pos).getLightOpacity(new FakeBlockAccess(world), pos) : 255; //Dont use getState as the tileEntity may be null
0
DDoS/JICI
src/main/java/ca/sapon/jici/evaluator/member/ArrayLengthVariable.java
[ "public class LiteralReferenceType extends SingleReferenceType implements LiteralType, TypeArgument {\n public static final LiteralReferenceType THE_STRING = LiteralReferenceType.of(String.class);\n public static final LiteralReferenceType THE_OBJECT = LiteralReferenceType.of(Object.class);\n public static...
import java.lang.reflect.Array; import ca.sapon.jici.evaluator.type.LiteralReferenceType; import ca.sapon.jici.evaluator.type.PrimitiveType; import ca.sapon.jici.evaluator.type.Type; import ca.sapon.jici.evaluator.value.IntValue; import ca.sapon.jici.evaluator.value.Value;
/* * 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.evaluator.member; /** * */ public class ArrayLengthVariable implements ClassVariable { private final LiteralReferenceType declaror; private ArrayLengthVariable(LiteralReferenceType declaror) { this.declaror = declaror; } @Override public LiteralReferenceType getDeclaringType() { return declaror; } @Override public String getName() { return "length"; } @Override public Type getType() { return PrimitiveType.THE_INT; } @Override public Type getTargetType() { return PrimitiveType.THE_INT; } @Override public boolean isStatic() { return false; } @Override
public Value getValue(Value target) {
4
sih4sing5hong5/han3_ji7_tsoo1_kian3
src/main/java/idsrend/services/IDSrendServlet.java
[ "public abstract class ExpSequenceLookup\n{\n\t/**\n\t * 查詢其展開式,若無,回傳null。\n\t * \n\t * @param 統一碼控制碼\n\t * 欲查的控制碼\n\t * @return 這字的展開式\n\t */\n\tpublic abstract String 查詢展開式(int 統一碼控制碼);\n\n\t/**\n\t * 查詢字串第一个字的展開式,若無,回傳null。\n\t * \n\t * @param 待查文字\n\t * 欲查的字\n\t * @return 第一个字的展開式\n\t */\n...
import java.awt.Font; import java.awt.Stroke; import java.awt.font.FontRenderContext; import java.awt.geom.AffineTransform; import java.io.IOException; import java.net.URLDecoder; import java.net.URLEncoder; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.ServletContext; import cc.ccomponent_adjuster.ExpSequenceLookup; import cc.ccomponent_adjuster.ExpSequenceLookup_byDB; import cc.char_indexingtool.ChineseCharacterTypeSetter; import cc.char_indexingtool.FontRefSettingTool; import cc.layouttools.MergePieceAdjuster; import cc.char_indexingtool.FontCorrespondTable; import cc.char_indexingtool.CommonFontNoSearch; import cc.char_indexingtool.CommonFontNoSearchbyDB; import cc.stroke.FunctinoalBasicBolder; import cc.stroketool.MkeSeparateMovableType_Bolder; import cc.tool.database.PgsqlConnection; import idsrend.CharComponentStructureAdjuster.IDSnormalizer; import java.lang.System;
package idsrend.services; /** * 佮愛規的服務佮提供的字體攏總整合起來。 * * @author Ihc */ public class IDSrendServlet extends HttpServlet { /** 序列化編號 */ private static final long serialVersionUID = 1224634082415129183L; /** 組宋體用的工具 */ protected IDSrendService 宋體組字工具; /** 組宋體粗體用的工具 */ protected IDSrendService 粗宋組字工具; /** 組楷體用的工具 */ protected IDSrendService 楷體組字工具; /** 組楷體粗體用的工具 */ protected IDSrendService 粗楷組字工具; /** 產生圖形傳予組字介面畫。毋過無X11、圖形介面就袂使用 */ // GraphicsConfiguration 系統圖畫設定; /** 佮資料庫的連線 */
protected PgsqlConnection 連線;
8
YTEQ/fixb
fixb-quickfix/src/test/java/org/fixb/quickfix/QuickFixFieldExtractorTest.java
[ "public class FixException extends RuntimeException {\n private static final long serialVersionUID = 1;\n\n /**\n * @param tag the field tag that has not been found\n * @param fixMessage the FIX message that does not contain the tag\n * @return an instance of FixException for a field-not-found cas...
import static org.fixb.quickfix.test.data.TestModels.Component; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import org.fixb.FixException; import org.fixb.meta.FixBlockMeta; import org.fixb.meta.FixMetaScanner; import org.joda.time.DateTimeZone; import org.joda.time.Instant; import org.joda.time.LocalDate; import org.junit.Test; import quickfix.Message; import java.math.BigDecimal; import java.util.*; import static java.util.Arrays.asList; import static org.fixb.quickfix.QuickFixMessageBuilder.fixMessage;
/* * Copyright 2013 YTEQ Ltd. * * 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.fixb.quickfix; public class QuickFixFieldExtractorTest { private final QuickFixFieldExtractor extractor = new QuickFixFieldExtractor(); @Test public void testGetStringFieldValue() { // Given Message message = fixMessage().setField(10, "TEST VALUE").build(); // When / Then assertEquals("TEST VALUE", extractor.getFieldValue(message, String.class, 10, false)); } @Test public void testGetIntFieldValue() { // Given Message message = fixMessage().setField(10, 123).build(); // When / Then assertEquals(123, extractor.getFieldValue(message, Integer.class, 10, false).intValue()); assertEquals(123, extractor.getFieldValue(message, int.class, 10, false).intValue()); } @Test public void testGetCharFieldValue() { // Given Message message = fixMessage().setField(10, 'X').build(); // When / Then assertEquals('X', extractor.getFieldValue(message, Character.class, 10, false).charValue()); assertEquals('X', extractor.getFieldValue(message, char.class, 10, false).charValue()); } @Test public void testGetDoubleFieldValue() { // Given Message message = fixMessage().setField(10, 123.456).setField(20, 100.00).build(); // When / Then assertEquals(123.456, extractor.getFieldValue(message, Double.class, 10, false), 0); assertEquals(100.00, extractor.getFieldValue(message, double.class, 20, false), 0); } @Test public void testGetBigDecimalFieldValue() { // Given Message message = fixMessage().setField(10, new BigDecimal(123.00)).build(); // When / Then assertEquals(new BigDecimal(123.00), extractor.getFieldValue(message, BigDecimal.class, 10, false)); } @Test public void testGetLocalDateFieldValue() { TimeZone.setDefault(TimeZone.getTimeZone("Australia/Sydney")); DateTimeZone.setDefault(DateTimeZone.forTimeZone(TimeZone.getDefault())); // Given LocalDate date = LocalDate.parse("2012-10-10"); Message message = fixMessage().setField(10, date).build(); // When / Then assertEquals(date, extractor.getFieldValue(message, LocalDate.class, 10, false)); } @Test public void testGetBooleanFieldValue() { // Given boolean value = true; Message message = fixMessage().setField(10, "Y").build(); // When / Then assertEquals(value, extractor.getFieldValue(message, boolean.class, 10, false)); } @Test(expected = FixException.class) public void testGetFieldValueWithIncorrectType() { // Given Message message = fixMessage().setField(10, "TEXT").build(); // When / Then assertEquals("TEXT", extractor.getFieldValue(message, int.class, 10, false)); } @Test(expected = FixException.class) public void testGetFieldValueWithIncorrectTag() { // Given Message message = fixMessage().setField(10, "TEXT").build(); // When / Then assertNull(extractor.getFieldValue(message, String.class, 12, true)); assertEquals("TEXT", extractor.getFieldValue(message, String.class, 12, false)); } @Test(expected = IllegalArgumentException.class) public void testGetFieldValueWithUnsupportedType() { // Given Message message = fixMessage().build(); // When / Then assertEquals("777", extractor.getFieldValue(message, StringBuilder.class, 10, false)); } @Test public void testGetGroupsWithSimpleElements() { // Given Message message = fixMessage().setGroups(10, 11, asList("A", "B", "C"), true) .setGroups(20, 21, asList("D", "E", "F"), false) .setGroups(30, 31, asList(1, 2, 3, 3), false).build(); // When / Then assertEquals(asList("A", "B", "C"), extractor.getGroups(message, List.class, 10, String.class, 11, false)); assertEquals(asList("D", "E", "F"), extractor.getGroups(message, List.class, 20, String.class, 21, false)); assertEquals(asSet(1, 2, 3), extractor.getGroups(message, Set.class, 30, Integer.class, 31, false)); assertEquals(asList(), extractor.getGroups(message, Collection.class, 333, Double.class, 444, true)); } @Test public void testGetGroupsWithComplexElements() { // Given
final FixBlockMeta<Component> componentMeta = FixMetaScanner.scanClass(Component.class);
4
xushaomin/apple-deploy
src/main/java/com/appleframework/deploy/plus/ssh/SshDeployPlus.java
[ "public class ProjectWithBLOBs extends Project implements Serializable {\r\n \r\n\tprivate String hosts;\r\n\r\n private String preDeploy;\r\n\r\n private String postDeploy;\r\n\r\n private String afterDeploy;\r\n\r\n private static final long serialVersionUID = 1L;\r\n\r\n public String getHosts(...
import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import com.appleframework.config.core.util.StringUtils; import com.appleframework.deploy.entity.ProjectWithBLOBs; import com.appleframework.deploy.entity.Task; import com.appleframework.deploy.model.DeployType; import com.appleframework.deploy.plus.DeployPlus; import com.appleframework.deploy.utils.Constants; import com.appleframework.deploy.websocket.WebSocketServer; import com.jcraft.jsch.ChannelExec; import com.jcraft.jsch.JSch; import com.jcraft.jsch.Session;
package com.appleframework.deploy.plus.ssh; public class SshDeployPlus implements DeployPlus { private static String APPEND = "----------"; public void doDeploy(Task task, ProjectWithBLOBs project) { Constants.BOOT_STATUS_MAP.put(task.getId(), false); String hostStr = task.getHosts(); String hosts[] = com.appleframework.deploy.utils.StringUtils.replaceBlank(hostStr).split(","); for (String host : hosts) { StringBuffer commandBuffer = new StringBuffer(); commandBuffer.append("mkdir -p " + project.getReleaseTo() + "\n"); // pre deploy if(!StringUtils.isEmpty(project.getPreDeploy())) { commandBuffer.append(project.getPreDeploy() + "\n"); } // post deploy if (project.getType() == DeployType.NEXUS.getIndex()) { commandBuffer.append(project.getPostDeploy() + " "); commandBuffer.append(project.getReleaseTo() + " "); commandBuffer.append(project.getNexusUrl() + " "); commandBuffer.append(project.getNexusGroup() + " "); commandBuffer.append(project.getNexusArtifact() + " "); commandBuffer.append(project.getVersion() + " "); } else { if(!StringUtils.isEmpty(project.getPostDeploy())) { commandBuffer.append(project.getPostDeploy() + "\n"); } } // after deploy if(!StringUtils.isEmpty(project.getAfterDeploy())) { commandBuffer.append(project.getAfterDeploy() + "\n"); } Session session = null; ChannelExec openChannel = null; try { JSch jsch = new JSch(); jsch.addIdentity("/root/.ssh/id_dsa"); session = jsch.getSession(project.getReleaseUser(), host, 22); java.util.Properties config = new java.util.Properties(); //设置第一次登陆的时候提示,可选值:(ask | yes | no) config.put("StrictHostKeyChecking", "no"); session.setConfig(config); //session.setPassword("123456"); session.connect(); openChannel = (ChannelExec) session.openChannel("exec"); openChannel.setCommand(commandBuffer.toString()); int exitStatus = openChannel.getExitStatus(); if(exitStatus != -1) {
WebSocketServer.sendMessage(task.getId(), host + APPEND + "认证失败:" + exitStatus);
5
Catalysts/cat-boot
cat-boot-report-pdf/src/main/java/cc/catalysts/boot/report/pdf/impl/PdfReportGenerator.java
[ "public class PdfPageLayout {\n\n private float width;\n private float height;\n private float marginLeft;\n private float marginRight;\n private float marginTop;\n private float marginBottom;\n private float lineDistance;\n private float header;\n private float footer;\n private Posit...
import cc.catalysts.boot.report.pdf.config.PdfPageLayout; import cc.catalysts.boot.report.pdf.config.PdfStyleSheet; import cc.catalysts.boot.report.pdf.elements.ReportCompositeElement; import cc.catalysts.boot.report.pdf.elements.ReportElement; import cc.catalysts.boot.report.pdf.elements.ReportElementStatic; import cc.catalysts.boot.report.pdf.elements.ReportImage; import cc.catalysts.boot.report.pdf.elements.ReportTable; import cc.catalysts.boot.report.pdf.exception.PdfReportGeneratorException; import cc.catalysts.boot.report.pdf.utils.PdfFontContext; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.PDPage; import org.apache.pdfbox.pdmodel.PDPageContentStream; import org.apache.pdfbox.pdmodel.PDPageTree; import org.springframework.core.io.Resource; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Queue;
package cc.catalysts.boot.report.pdf.impl; /** * @author Paul Klingelhuber */ class PdfReportGenerator { public PdfReportGenerator() { } public void printToStream(PdfPageLayout pageConfig, Resource templateResource, PdfReportStructure report, OutputStream stream, PDDocument document) throws IOException { final DocumentWithResources documentWithResources = generate(pageConfig, templateResource, report, document); documentWithResources.saveAndClose(stream); } public DocumentWithResources generate(PdfPageLayout pageConfig, Resource templateResource, PdfReportStructure report) throws IOException { return generate(pageConfig, templateResource, report, new PDDocument()); } public DocumentWithResources generate(PdfStyleSheet styleSheet, PdfPageLayout pageConfig, Resource templateResource, PdfReportStructure report) throws IOException { return generateInternal(pageConfig, templateResource, report, new PDDocument()); } /** * @param pageConfig page config * @param report the report to print * @return object that contains the printed PdfBox document and resources that need to be closed after finally writing the document * @throws java.io.IOException * fallback fonts from PdfStyleSheet. */ public DocumentWithResources generate(PdfPageLayout pageConfig, Resource templateResource, PdfReportStructure report, PDDocument document) throws IOException { try (PdfFontContext context = PdfFontContext.currentOrCreate()) { return generateInternal(pageConfig, templateResource, report, document); } } private DocumentWithResources generateInternal(PdfPageLayout pageConfig, Resource templateResource, PdfReportStructure report, PDDocument document) throws IOException { final DocumentWithResources documentWithResources = new DocumentWithResources(document); PrintData printData = new PrintData(templateResource, pageConfig); PrintCursor cursor = new PrintCursor(); breakPage(documentWithResources, cursor, printData); float maxWidth = pageConfig.getUsableWidth(); int reportElementIndex = 0, nrOfReportElements = report.getElements().size(); ReportElement currentReportElement = report.getElements().isEmpty() ? null : report.getElements().get(reportElementIndex); ReportElement nextReportElement = null; boolean performedBreakPageForCurrentReportElement = false; // for each element max. one break page allowed while (currentReportElement != null) { boolean forceBreak = false; float height = currentReportElement.getHeight(maxWidth); if (cursor.yPos - height < pageConfig.getLastY(cursor.currentPageNumber)) { //out of bounds if (currentReportElement.isSplitable() && (cursor.yPos - currentReportElement.getFirstSegmentHeight(maxWidth)) >= pageConfig.getLastY(cursor.currentPageNumber)) { if (currentReportElement instanceof ReportTable) { //it's a Table out of bounds, so we also do a height split ReportElement[] twoElements = currentReportElement.split(maxWidth, cursor.yPos - pageConfig.getLastY(cursor.currentPageNumber)); if (twoElements.length != 2) { throw new IllegalStateException("The split method should always two parts."); } currentReportElement = twoElements[0]; nextReportElement = twoElements[1]; if (((ReportTable) currentReportElement).getExtraSplitting()) { forceBreak = true; }
} else if (currentReportElement instanceof ReportCompositeElement) {
2
vangj/jbayes
src/test/java/com/github/vangj/jbayes/inf/exact/graph/pptc/blocks/PropagationTest.java
[ "public class Dag extends Graph {\n\n protected Map<String, List<Node>> parents;\n protected Map<String, List<Node>> children;\n\n public Dag() {\n parents = new HashMap<>();\n children = new HashMap<>();\n }\n\n /**\n * Initializes the potential for each node.\n *\n * @return Dag.\n */\n public...
import static org.junit.Assert.assertEquals; import com.github.vangj.jbayes.inf.exact.graph.Dag; import com.github.vangj.jbayes.inf.exact.graph.Ug; import com.github.vangj.jbayes.inf.exact.graph.lpd.PotentialEntry; import com.github.vangj.jbayes.inf.exact.graph.pptc.Clique; import com.github.vangj.jbayes.inf.exact.graph.pptc.HuangExample; import com.github.vangj.jbayes.inf.exact.graph.pptc.JoinTree; import java.util.List; import org.junit.Test;
package com.github.vangj.jbayes.inf.exact.graph.pptc.blocks; public class PropagationTest extends HuangExample { @Test public void testPropagation() { Dag dag = getDag(); Ug m = Moralize.moralize(dag);
List<Clique> cliques = Triangulate.triangulate(m);
3
ZhaoYukai/ManhuaHouse
src/com/zykmanhua/app/activity/MyRecordCollect.java
[ "public class ManhuaCollectAdapter extends BaseAdapter {\n\t\n\tprivate Context mContext = null;\n\tprivate LayoutInflater mLayoutInflater = null;\n\tprivate ImageLoader mImageLoader = null;\n\tprivate DisplayImageOptions mOptions = null;\n\tprivate GroupCollect mGroupCollect = null;\n\tprivate Map<String, Manhua> ...
import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Map.Entry; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.zykmanhua.app.R; import com.zykmanhua.app.adapter.ManhuaCollectAdapter; import com.zykmanhua.app.bean.GroupCollect; import com.zykmanhua.app.bean.Manhua; import com.zykmanhua.app.util.Config; import com.zykmanhua.app.util.UpdateCollectListener; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.Button; import android.widget.ListView;
package com.zykmanhua.app.activity; public class MyRecordCollect extends Fragment implements OnClickListener , UpdateCollectListener { private Context mContext = null; private ListView mListView = null;
private GroupCollect mGroupCollect = null;
1
InfinityRaider/NinjaGear
src/main/java/com/infinityraider/ninjagear/item/ItemSai.java
[ "@Mod(Reference.MOD_ID)\npublic class NinjaGear extends InfinityMod<IProxy, Config> {\n public static NinjaGear instance;\n\n public NinjaGear() {\n super();\n }\n\n @Override\n public String getModId() {\n return Reference.MOD_ID;\n }\n\n @Override\n protected void onModConstr...
import com.google.common.collect.ImmutableMultimap; import com.infinityraider.infinitylib.item.ItemBase; import com.infinityraider.ninjagear.NinjaGear; import com.infinityraider.ninjagear.api.v1.IHiddenItem; import com.infinityraider.ninjagear.handler.NinjaAuraHandler; import com.infinityraider.ninjagear.reference.Reference; import com.infinityraider.ninjagear.registry.ItemRegistry; import com.infinityraider.ninjagear.registry.EffectRegistry; import com.google.common.collect.Multimap; import mcp.MethodsReturnNonnullByDefault; import net.minecraft.block.BlockState; import net.minecraft.block.Blocks; import net.minecraft.block.material.Material; import net.minecraft.client.util.ITooltipFlag; import net.minecraft.entity.Entity; import net.minecraft.entity.LivingEntity; import net.minecraft.entity.ai.attributes.Attribute; import net.minecraft.entity.ai.attributes.AttributeModifier; import net.minecraft.entity.ai.attributes.Attributes; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.inventory.EquipmentSlotType; import net.minecraft.item.ItemStack; import net.minecraft.item.UseAction; import net.minecraft.item.crafting.Ingredient; import net.minecraft.tags.BlockTags; import net.minecraft.util.math.BlockPos; 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; @MethodsReturnNonnullByDefault public class ItemSai extends ItemBase implements IHiddenItem { private final Multimap<Attribute, AttributeModifier> attributeModifiers; private final Multimap<Attribute, AttributeModifier> attributeModifiersCrit; private final Multimap<Attribute, AttributeModifier> attributeModifiersIneffective; public ItemSai() { super("sai", new Properties() .maxDamage(1000) .group(ItemRegistry.CREATIVE_TAB)); ImmutableMultimap.Builder<Attribute, AttributeModifier> builder = ImmutableMultimap.builder(); this.attributeModifiers = builder .put(Attributes.ATTACK_DAMAGE, new AttributeModifier(ATTACK_DAMAGE_MODIFIER, "Sai Attack Damage Modifier", 3.0 + NinjaGear.instance.getConfig().getSaiDamage(), AttributeModifier.Operation.ADDITION)) .put(Attributes.ATTACK_SPEED, new AttributeModifier(ATTACK_SPEED_MODIFIER, "Sai Attack Speed Modifier", 1, AttributeModifier.Operation.ADDITION)) .build(); builder = ImmutableMultimap.builder(); this.attributeModifiersCrit = builder .put(Attributes.ATTACK_DAMAGE, new AttributeModifier(ATTACK_DAMAGE_MODIFIER, "Sai Attack Damage Modifier", 3.0 + NinjaGear.instance.getConfig().getCitMultiplier()*NinjaGear.instance.getConfig().getSaiDamage(), AttributeModifier.Operation.ADDITION)) .put(Attributes.ATTACK_SPEED, new AttributeModifier(ATTACK_SPEED_MODIFIER, "Sai Attack Speed Modifier", 1, AttributeModifier.Operation.ADDITION)) .build(); builder = ImmutableMultimap.builder(); this.attributeModifiersIneffective = builder .put(Attributes.ATTACK_DAMAGE, new AttributeModifier(ATTACK_DAMAGE_MODIFIER, "Sai Attack Damage Modifier", 3.0, AttributeModifier.Operation.ADDITION)) .put(Attributes.ATTACK_SPEED, new AttributeModifier(ATTACK_SPEED_MODIFIER, "Sai Attack Speed Modifier", -2, AttributeModifier.Operation.ADDITION)) .build(); } public UseAction getUseAction(ItemStack stack) { return UseAction.BLOCK; } @Override public float getDestroySpeed(ItemStack stack, BlockState state) { if (state.matchesBlock(Blocks.COBWEB)) { return 15.0F; } else { Material material = state.getMaterial(); return material != Material.PLANTS && material != Material.TALL_PLANTS && material != Material.CORAL && !state.isIn(BlockTags.LEAVES) && material != Material.GOURD ? 1.0F : 1.5F; } } @Override public boolean hitEntity(ItemStack stack, LivingEntity target, LivingEntity attacker) { if(attacker instanceof PlayerEntity) { NinjaAuraHandler.getInstance().revealEntity((PlayerEntity) attacker, NinjaGear.instance.getConfig().getHidingCooldown(), true); } stack.damageItem(1, attacker, (entity) -> { entity.sendBreakAnimation(EquipmentSlotType.MAINHAND); }); ItemStack offhand = attacker.getItemStackFromSlot(EquipmentSlotType.OFFHAND); if(offhand != null && offhand.getItem() instanceof ItemSai) { offhand.damageItem(1, attacker, (entity) -> { entity.sendBreakAnimation(EquipmentSlotType.MAINHAND); }); } return true; } @Override public boolean onBlockDestroyed(ItemStack stack, World world, BlockState state, BlockPos pos, LivingEntity entity) { if ((double)state.getBlockHardness(world, pos) != 0.0D) { stack.damageItem(1, entity, (e) -> { e.sendBreakAnimation(EquipmentSlotType.MAINHAND); }); ItemStack offhand = entity.getItemStackFromSlot(EquipmentSlotType.OFFHAND); if(offhand != null && offhand.getItem() instanceof ItemSai) { offhand.damageItem(1, entity, (e) -> { e.sendBreakAnimation(EquipmentSlotType.MAINHAND); }); } } return true; } @Override public boolean canHarvestBlock(BlockState blockIn) { return blockIn.getBlock() == Blocks.COBWEB; } @Override public int getItemEnchantability() { return 15; } @Override public boolean getIsRepairable(ItemStack toRepair, ItemStack repair) { return getRepairItem().test(repair); } @Override public boolean onLeftClickEntity(ItemStack stack, PlayerEntity player, Entity entity) { ItemStack offHand = player.getItemStackFromSlot(EquipmentSlotType.OFFHAND); if(offHand != null && offHand.getItem() == this) {
if(player.isPotionActive(EffectRegistry.getInstance().effectNinjaHidden)) {
5
ToroCraft/Minecoprocessors
src/main/java/net/torocraft/minecoprocessors/processor/Processor.java
[ "@Mod(modid = Minecoprocessors.MODID, version = Minecoprocessors.VERSION, name = Minecoprocessors.MODNAME)\npublic class Minecoprocessors {\n\n public static final String MODID = \"minecoprocessors\";\n public static final String VERSION = \"1.12.2-5\";\n public static final String MODNAME = \"Minecoprocessors\"...
import java.util.ArrayList; import java.util.List; import net.minecraft.nbt.NBTBase; import net.minecraft.nbt.NBTTagByteArray; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.torocraft.minecoprocessors.Minecoprocessors; import net.torocraft.minecoprocessors.gui.GuiMinecoprocessor; import net.torocraft.minecoprocessors.util.ByteUtil; import net.torocraft.minecoprocessors.util.InstructionUtil; import net.torocraft.minecoprocessors.util.Label; import net.torocraft.minecoprocessors.util.ParseException;
@Override public void load(List<String> file) { try { flush(); if (file != null) { program = InstructionUtil.parseFile(file, labels); } else { program = new ArrayList<>(); labels = new ArrayList<>(); } } catch (ParseException e) { error = e.getMessage(); faultCode = FaultCode.FAULT_UNKNOWN_OPCODE; fault = true; } } long packFlags() { long flags = 0; flags = ByteUtil.setShort(flags, ip, 3); flags = ByteUtil.setByte(flags, sp, 5); // byte 4 not currently used flags = ByteUtil.setBit(flags, fault, 0); flags = ByteUtil.setBit(flags, zero, 1); flags = ByteUtil.setBit(flags, overflow, 2); flags = ByteUtil.setBit(flags, carry, 3); flags = ByteUtil.setBit(flags, wait, 4); return flags; } void unPackFlags(long flags) { ip = ByteUtil.getShort(flags, 3); sp = ByteUtil.getByte(flags, 5); // byte 4 not currently used fault = ByteUtil.getBit(flags, 0); zero = ByteUtil.getBit(flags, 1); overflow = ByteUtil.getBit(flags, 2); carry = ByteUtil.getBit(flags, 3); wait = ByteUtil.getBit(flags, 4); } private static byte[] addRegistersIfMissing(byte[] registersIn) { if (registersIn.length >= Register.values().length) { return registersIn; } byte[] registersNew = new byte[Register.values().length]; System.arraycopy(registersIn, 0, registersNew, 0, registersIn.length); return registersNew; } @Override public void readFromNBT(NBTTagCompound c) { stack = c.getByteArray(NBT_STACK); registers = addRegistersIfMissing(c.getByteArray(NBT_REGISTERS)); faultCode = c.getByte(NBT_FAULTCODE); unPackFlags(c.getLong(NBT_FLAGS)); error = c.getString(NBT_ERROR); if (error != null && error.isEmpty()) { error = null; } program = new ArrayList<>(); NBTTagList programTag = (NBTTagList) c.getTag(NBT_PROGRAM); if (programTag != null) { for (NBTBase tag : programTag) { program.add(((NBTTagByteArray) tag).getByteArray()); } } labels = new ArrayList<>(); NBTTagList labelTag = (NBTTagList) c.getTag(NBT_LABELS); if (labelTag != null) { for (NBTBase tag : labelTag) { labels.add(Label.fromNbt((NBTTagCompound) tag)); } } } @Override public NBTTagCompound writeToNBT() { NBTTagCompound c = new NBTTagCompound(); c.setByteArray(NBT_STACK, stack); c.setByteArray(NBT_REGISTERS, registers); c.setByte(NBT_FAULTCODE, faultCode); c.setLong(NBT_FLAGS, packFlags()); if (error != null) { c.setString(NBT_ERROR, error); } NBTTagList programTag = new NBTTagList(); for (byte[] b : program) { programTag.appendTag(new NBTTagByteArray(b)); } c.setTag(NBT_PROGRAM, programTag); NBTTagList labelTag = new NBTTagList(); for (Label label : labels) { labelTag.appendTag(label.toNbt()); } c.setTag(NBT_LABELS, labelTag); return c; } /** * returns true if GUI should be updated after this tick */ @Override public boolean tick() { if (fault || (wait && !step)) { return false; } step = false; try { process(); // TODO handle parse exception (actually make a new exception type to use in a running processor) } catch (Exception e) {
Minecoprocessors.proxy.handleUnexpectedException(e);
0
gustav9797/PowerfulPerms
PowerfulPerms/src/main/java/com/github/gustav9797/PowerfulPerms/PowerfulPermissionPlayer.java
[ "public abstract class PermissionManagerBase {\n\n protected HashMap<UUID, PermissionPlayer> players = new HashMap<>();\n protected ReentrantLock playersLock = new ReentrantLock();\n\n protected ConcurrentHashMap<UUID, CachedPlayer> cachedPlayers = new ConcurrentHashMap<>();\n\n protected HashMap<Intege...
import com.github.gustav9797.PowerfulPerms.common.PermissionManagerBase; import com.github.gustav9797.PowerfulPerms.common.PermissionPlayerBase; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import com.github.gustav9797.PowerfulPermsAPI.CachedGroup; import com.github.gustav9797.PowerfulPermsAPI.Permission; import com.github.gustav9797.PowerfulPermsAPI.PowerfulPermsPlugin;
package com.github.gustav9797.PowerfulPerms; public class PowerfulPermissionPlayer extends PermissionPlayerBase { private Player player;
public PowerfulPermissionPlayer(Player p, LinkedHashMap<String, List<CachedGroup>> serverGroups, List<Permission> permissions, String prefix, String suffix, PowerfulPermsPlugin plugin,
3
treasure-lau/CSipSimple
app/src/main/java/com/csipsimple/ui/incall/InCallCard.java
[ "public abstract class UtilityWrapper {\n\n private static UtilityWrapper instance;\n\n public static UtilityWrapper getInstance() {\n if (instance == null) {\n if (Build.VERSION.SDK_INT >= 16) {\n instance = new Utility16();\n } else if (Build.VERSION.SDK_INT >= 14...
import android.content.Context; import android.content.Intent; import android.os.Handler; import android.os.Message; import android.text.TextUtils; import android.util.AttributeSet; import android.util.FloatMath; import android.view.LayoutInflater; import android.view.SurfaceView; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.Chronometer; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import com.actionbarsherlock.internal.utils.UtilityWrapper; import com.actionbarsherlock.internal.view.menu.ActionMenuPresenter; import com.actionbarsherlock.internal.view.menu.ActionMenuView; import com.actionbarsherlock.internal.view.menu.MenuBuilder; import com.actionbarsherlock.internal.view.menu.MenuBuilder.Callback; import com.actionbarsherlock.view.MenuInflater; import com.actionbarsherlock.view.MenuItem; import com.csipsimple.R; import com.csipsimple.api.SipCallSession; import com.csipsimple.api.SipCallSession.MediaState; import com.csipsimple.api.SipConfigManager; import com.csipsimple.api.SipManager; import com.csipsimple.api.SipProfile; import com.csipsimple.api.SipUri; import com.csipsimple.api.SipUri.ParsedSipContactInfos; import com.csipsimple.models.CallerInfo; import com.csipsimple.service.SipService; import com.csipsimple.utils.ContactsAsyncHelper; import com.csipsimple.utils.CustomDistribution; import com.csipsimple.utils.ExtraPlugins; import com.csipsimple.utils.ExtraPlugins.DynActivityPlugin; import com.csipsimple.utils.Log; import com.csipsimple.utils.PreferencesProviderWrapper; import org.webrtc.videoengine.ViERenderer; import java.util.ArrayList; import java.util.List; import java.util.Map;
/** * Copyright (C) 2010-2012 Regis Montoya (aka r3gis - www.r3gis.fr) * This file is part of CSipSimple. * * CSipSimple 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. * If you own a pjsip commercial license you can also redistribute it * and/or modify it under the terms of the GNU Lesser General Public License * as an android library. * * CSipSimple 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 CSipSimple. If not, see <http://www.gnu.org/licenses/>. */ package com.csipsimple.ui.incall; public class InCallCard extends FrameLayout implements OnClickListener, Callback { private static final String THIS_FILE = "InCallCard"; private SipCallSession callInfo; private String cachedRemoteUri = ""; private int cachedInvState = SipCallSession.InvState.INVALID;
private int cachedMediaState = MediaState.ERROR;
4
gustav9797/PowerfulPerms
PowerfulPerms/src/main/java/com/github/gustav9797/PowerfulPerms/command/UserRemoveGroupCommand.java
[ "public interface ICommand {\n public boolean hasPermission(String name, String permission); \n}", "public interface Group {\n\n public int getId();\n\n public String getName();\n\n public List<Group> getParents();\n\n public String getPrefix(String server);\n\n public String getSuffix(String...
import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.UUID; import java.util.concurrent.ExecutionException; import com.github.gustav9797.PowerfulPerms.common.ICommand; import com.github.gustav9797.PowerfulPermsAPI.Group; import com.github.gustav9797.PowerfulPermsAPI.PermissionManager; import com.github.gustav9797.PowerfulPermsAPI.PowerfulPermsPlugin; import com.github.gustav9797.PowerfulPermsAPI.Response;
package com.github.gustav9797.PowerfulPerms.command; public class UserRemoveGroupCommand extends SubCommand { public UserRemoveGroupCommand(PowerfulPermsPlugin plugin, PermissionManager permissionManager) { super(plugin, permissionManager); usage.add("/pp user <user> removegroup <group> (server) (expires)"); } @Override public CommandResult execute(final ICommand invoker, final String sender, final String[] args) throws InterruptedException, ExecutionException { if (hasBasicPerms(invoker, sender, "powerfulperms.user.removegroup") || (args != null && args.length >= 3 && hasPermission(invoker, sender, "powerfulperms.user.removegroup." + args[2]))) { if (args != null && args.length >= 2 && args[1].equalsIgnoreCase("removegroup")) { if (args.length < 3) { sendSender(invoker, sender, getUsage()); return CommandResult.success; } final String playerName = args[0]; String groupName = args[2]; final boolean negated = groupName.startsWith("-"); if (negated) groupName = groupName.substring(1); final Group group = permissionManager.getGroup(groupName); if (group == null) { sendSender(invoker, sender, "Group does not exist."); return CommandResult.success; } final int groupId = group.getId(); UUID uuid = permissionManager.getConvertUUIDBase(playerName); if (uuid == null) { sendSender(invoker, sender, "Could not find player UUID."); } else { String server = ""; Date expires = null; if (args.length >= 4) server = args[3]; if (args.length >= 5 && !args[4].equalsIgnoreCase("NONE")) { if (args[4].equalsIgnoreCase("ANY")) expires = Utils.getAnyDate(); else expires = Utils.getDate(args[4]); if (expires == null) { sendSender(invoker, sender, "Invalid expiration format."); return CommandResult.success; } }
Response response = permissionManager.removePlayerGroupBase(uuid, groupId, server, negated, expires);
4
loklak/loklak_server
src/org/loklak/DumpProcessConversation.java
[ "public class JSONObject {\n /**\n * JSONObject.NULL is equivalent to the value that JavaScript calls null,\n * whilst Java's null is equivalent to the value that JavaScript calls\n * undefined.\n */\n private static final class Null {\n\n /**\n * There is only intended to be a ...
import java.util.concurrent.atomic.AtomicLong; import org.json.JSONObject; import org.loklak.data.DAO; import org.loklak.harvester.TwitterScraper.TwitterTweet; import org.loklak.tools.storage.JsonFactory; import org.loklak.tools.storage.JsonReader; import org.loklak.tools.storage.JsonStreamReader; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.SortedMap; import java.util.TreeMap; import java.util.concurrent.ConcurrentHashMap;
/** * DumpProcessConversation * Copyright 18.04.2018 by Michael Peter Christen, @0rb1t3r * * 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 program in the file lgpl21.txt * If not, see <http://www.gnu.org/licenses/>. */ package org.loklak; public class DumpProcessConversation extends Thread { private boolean shallRun = true, isBusy = false; private int count = Integer.MAX_VALUE; public DumpProcessConversation(int count) { this.count = count; } /** * ask the thread to shut down */ public void shutdown() { this.shallRun = false; this.interrupt(); DAO.log("catched ProcessConversation termination signal"); } public boolean isBusy() { return this.isBusy; } @Override public void run() { Set<File> processedFiles = new HashSet<>(); // work loop loop: while (this.shallRun) try { this.isBusy = false; // scan dump input directory to import files Collection<File> dumps = DAO.message_dump.getOwnDumps(this.count); File dump = null; select: for (File d: dumps) { if (processedFiles.contains(d)) continue select; dump = d; break; } if (dump == null) { Thread.currentThread(); Thread.sleep(10000); continue loop; } this.isBusy = true; // take only one file and process this file final JsonReader dumpReader = DAO.message_dump.getDumpReader(dump); final AtomicLong tweetcount = new AtomicLong(0); DAO.log("started scan of dump file " + dump.getAbsolutePath()); // aggregation object Map<String, Map<Long, TwitterTweet>> usertweets = new ConcurrentHashMap<>(); // we start concurrent indexing threads to process the json objects Thread[] indexerThreads = new Thread[dumpReader.getConcurrency()]; for (int i = 0; i < dumpReader.getConcurrency(); i++) { indexerThreads[i] = new Thread() { public void run() {
JsonFactory tweet;
3
coverity/pie
pie-sm/src/main/java/com/coverity/security/pie/policy/securitymanager/fact/PermissionActionFactMetaData.java
[ "public class EqualityStringMatcher implements StringMatcher {\n \n private static final EqualityStringMatcher instance = new EqualityStringMatcher();\n \n private EqualityStringMatcher() {\n }\n \n public static EqualityStringMatcher getInstance() {\n return instance;\n }\n\n @Ove...
import com.coverity.security.pie.core.EqualityStringMatcher; import com.coverity.security.pie.core.FactMetaData; import com.coverity.security.pie.core.NullStringCollapser; import com.coverity.security.pie.core.PolicyConfig; import com.coverity.security.pie.core.StringCollapser; import com.coverity.security.pie.core.UnsupportedFactMetaData;
package com.coverity.security.pie.policy.securitymanager.fact; public class PermissionActionFactMetaData implements FactMetaData { private static final PermissionActionFactMetaData instance = new PermissionActionFactMetaData(); private PermissionActionFactMetaData() { } public static PermissionActionFactMetaData getInstance() { return instance; } @Override public StringCollapser getCollapser(PolicyConfig policyConfig) { return NullStringCollapser.getInstance(); } @Override public boolean matches(String matcher, String matchee) {
return EqualityStringMatcher.getInstance().matches(matcher, matchee);
0
axxepta/project-argon
src/main/java/de/axxepta/oxygen/actions/SearchInFilesAction.java
[ "public class TreeListener extends MouseAdapter implements TreeSelectionListener, TreeWillExpandListener,\n KeyListener, ObserverInterface<MsgTopic> {\n\n private static final Logger logger = LogManager.getLogger(TreeListener.class);\n private static final PluginWorkspace workspace = PluginWorkspacePro...
import de.axxepta.oxygen.tree.TreeListener; import de.axxepta.oxygen.tree.TreeUtils; import de.axxepta.oxygen.utils.ConnectionWrapper; import de.axxepta.oxygen.utils.DialogTools; import de.axxepta.oxygen.utils.Lang; import ro.sync.ecss.extensions.api.component.AuthorComponentFactory; import ro.sync.exml.workspace.api.PluginWorkspace; import ro.sync.exml.workspace.api.PluginWorkspaceProvider; import javax.swing.*; import javax.swing.border.TitledBorder; import javax.swing.tree.TreePath; import java.awt.*; import java.awt.event.ActionEvent; import java.io.IOException; import java.util.ArrayList; import java.util.List;
package de.axxepta.oxygen.actions; /** * @author Markus on 03.11.2016. */ public class SearchInFilesAction extends AbstractAction { private static final PluginWorkspace workspace = PluginWorkspaceProvider.getPluginWorkspace(); private final JTree tree; private String path = ""; private JDialog searchDialog; private JTextField searchTermTextField; private JCheckBox elementCheckBox; private JCheckBox textCheckBox; private JCheckBox attributeCheckBox; private JCheckBox attrValueCheckBox; private JCheckBox wholeCheckBox; private JCheckBox caseCheckBox; private JFrame parentFrame; public SearchInFilesAction(String name, Icon icon, JTree tree) { super(name, icon); this.tree = tree; } @Override public void actionPerformed(ActionEvent e) { TreePath treePath = ((TreeListener) tree.getTreeSelectionListeners()[0]).getPath(); path = TreeUtils.resourceFromTreePath(treePath); parentFrame = (JFrame) ((new AuthorComponentFactory()).getWorkspaceUtilities().getParentFrame());
searchDialog = DialogTools.getOxygenDialog(parentFrame, Lang.get(Lang.Keys.cm_search));
3
assist-group/assist-mcommerce-sdk-android
sdk/src/main/java/ru/assisttech/sdk/processor/AssistResultProcessor.java
[ "public class AssistResult {\n\n /**\n * Status of payment result\n **/\n private OrderState state;\n /**\n * Result code\n **/\n private String approvalCode;\n /**\n * Number of payment in Assist\n **/\n private String billNumber;\n /**\n * Additional information\n ...
import android.content.Context; import android.util.Log; import android.util.Xml; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import java.io.ByteArrayInputStream; import java.io.IOException; import java.util.ArrayList; import ru.assisttech.sdk.AssistResult; import ru.assisttech.sdk.network.AssistNetworkEngine; import ru.assisttech.sdk.network.HttpResponse; import ru.assisttech.sdk.storage.AssistTransaction; import ru.assisttech.sdk.xml.XmlHelper;
@Override public void asyncProcessing(HttpResponse response) { try { XmlPullParser parser = Xml.newPullParser(); parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true); parser.setInput(new ByteArrayInputStream(response.getData().getBytes()), null); int eventType = parser.getEventType(); while (eventType != XmlPullParser.END_DOCUMENT) { if (eventType == XmlPullParser.START_TAG) { switch (parser.getName()) { case OrderResult.TAG: orderResult = new OrderResult(parser); break; case "Fault": fault = new Fault(parser); break; } } eventType = parser.next(); } } catch (Exception e) { e.printStackTrace(); errorMessage = e.getMessage(); isError = true; } } @Override public void syncPostProcessing() { long tID = getTransaction().getId(); if (isError) { if (hasListener()) { getListener().onError(tID, errorMessage); } } else { AssistResult result = new AssistResult(); if (orderResult != null && orderResult.getOrder() != null) { result.setOrderState(orderResult.getOrder().orderstate); result.setBillNumber(orderResult.getOrder().billnumber); result.setOrderNumber(orderResult.getOrder().ordernumber); result.setSignature(orderResult.getOrder().signature); result.setCheckValue(orderResult.getOrder().checkvalue); result.setComment(orderResult.getOrder().ordercomment); result.setAmount(orderResult.getOrder().orderamount); result.setCurrency(orderResult.getOrder().ordercurrency); result.setFirstName(orderResult.getOrder().firstname); result.setLastName(orderResult.getOrder().lastname); result.setMiddleName(orderResult.getOrder().middlename); result.setEmail(orderResult.getOrder().email); if (orderResult.getOrder().getLastOperation() != null) { result.setExtra(orderResult.getOrder().getLastOperation().usermessage); result.setCardholder(orderResult.getOrder().getLastOperation().cardholder); result.setMeanNumber(orderResult.getOrder().getLastOperation().meannumber); result.setMeantypeName(orderResult.getOrder().getLastOperation().meantypename); result.setCardExpirationDate(orderResult.getOrder().getLastOperation().cardexpirationdate); } } else if (fault != null) { result.setExtra(fault.faultcode + " (" + fault.faultstring + ")"); } if (hasListener()) { getListener().onFinished(tID, result); } } finish(); } } /** * Represents XML tag "orderresult" in SOAP response from orderresult.cfm */ private class OrderResult { static final String TAG = "orderresult"; ArrayList<Order> orders = new ArrayList<>(); OrderResult(XmlPullParser parser) throws XmlPullParserException, IOException { while (!endOfTag(parser, OrderResult.TAG)) { parser.next(); if (isTag(parser, Order.TAG)) { orders.add(new Order(parser)); } } } Order getOrder() { if (orders.isEmpty()) { return null; } else { return orders.get(orders.size() - 1); } } } /** * Represents XML tag "order" in SOAP response from orderresult.cfm */ private class Order { static final String TAG = "order"; String ordernumber; String billnumber; String orderstate; String email; String checkvalue; String signature; String orderamount; String ordercurrency; String ordercomment; String firstname; String lastname; String middlename; ArrayList<Operation> operations = new ArrayList<>(); Order(XmlPullParser parser) throws XmlPullParserException, IOException { while (!endOfTag(parser, Order.TAG)) { if (parser.next() == XmlPullParser.START_TAG) { switch (parser.getName()) { case "ordernumber":
ordernumber = XmlHelper.readValue(parser, "ordernumber");
4
R2RML-api/R2RML-api
r2rml-api-rdf4j-binding/src/test/java/rdf4jTest/NTriplesSyntax1_Test.java
[ "public class RDF4JR2RMLMappingManager extends R2RMLMappingManagerImpl {\n\n private static RDF4JR2RMLMappingManager INSTANCE = new RDF4JR2RMLMappingManager(new RDF4J());\n\n private RDF4JR2RMLMappingManager(RDF4J rdf) {\n super(rdf);\n }\n\n public Collection<TriplesMap> importMappings(Model mod...
import org.eclipse.rdf4j.rio.helpers.StatementCollector; import eu.optique.r2rml.api.model.GraphMap; import eu.optique.r2rml.api.model.Join; import eu.optique.r2rml.api.model.PredicateObjectMap; import eu.optique.r2rml.api.model.RefObjectMap; import eu.optique.r2rml.api.model.SubjectMap; import eu.optique.r2rml.api.model.TriplesMap; import java.io.InputStream; import java.util.Collection; import java.util.Iterator; import eu.optique.r2rml.api.binding.rdf4j.RDF4JR2RMLMappingManager; import org.junit.Assert; import org.junit.Test; import org.eclipse.rdf4j.model.Model; import org.eclipse.rdf4j.model.impl.LinkedHashModel; import org.eclipse.rdf4j.rio.RDFFormat; import org.eclipse.rdf4j.rio.RDFParser; import org.eclipse.rdf4j.rio.Rio;
/******************************************************************************* * Copyright 2013, the Optique Consortium * 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. * * This first version of the R2RML API was developed jointly at the University of Oslo, * the University of Bolzano, La Sapienza University of Rome, and fluid Operations AG, * as part of the Optique project, www.optique-project.eu ******************************************************************************/ package rdf4jTest; /** * JUnit Test Cases * * @author Riccardo Mancini */ public class NTriplesSyntax1_Test{ @Test public void test() throws Exception{ InputStream fis = getClass().getResourceAsStream("../mappingFiles/test28.ttl"); RDF4JR2RMLMappingManager mm = RDF4JR2RMLMappingManager.getInstance(); // Read the file into a model. RDFParser rdfParser = Rio.createParser(RDFFormat.NTRIPLES); Model m = new LinkedHashModel(); rdfParser.setRDFHandler(new StatementCollector(m)); rdfParser.parse(fis, "testMapping"); Collection<TriplesMap> coll = mm.importMappings(m); Assert.assertTrue(coll.size()==2); Iterator<TriplesMap> it=coll.iterator(); while(it.hasNext()){ TriplesMap current=it.next(); Iterator<PredicateObjectMap> pomit=current.getPredicateObjectMaps().iterator(); int cont=0; while(pomit.hasNext()){ pomit.next(); cont++; } if(cont==1){ //we are analyzing the TriplesMap2 SubjectMap s=current.getSubjectMap();
Iterator<GraphMap> gmit=s.getGraphMaps().iterator();
1
tvbarthel/SimpleWeatherForecast
SimpleWeatherForecast/src/main/java/fr/tvbarthel/apps/simpleweatherforcast/services/DailyForecastUpdateService.java
[ "@TargetApi(Build.VERSION_CODES.HONEYCOMB)\npublic class WeatherWidgetReceiver extends AppWidgetProvider {\n\n //An intent Action used to notify a data change: text color, temperature value\n // temperature unit etc.\n public static final String APPWIDGET_DATA_CHANGED =\n \"fr.tvbarthel.apps.sim...
import android.app.Service; import android.content.Context; import android.content.Intent; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.os.Handler; import android.os.HandlerThread; import android.os.IBinder; import android.os.Looper; import java.io.IOException; import java.net.MalformedURLException; import java.net.SocketTimeoutException; import java.util.Locale; import fr.tvbarthel.apps.simpleweatherforcast.R; import fr.tvbarthel.apps.simpleweatherforcast.receivers.WeatherWidgetReceiver; import fr.tvbarthel.apps.simpleweatherforcast.utils.ConnectivityUtils; import fr.tvbarthel.apps.simpleweatherforcast.utils.LocationUtils; import fr.tvbarthel.apps.simpleweatherforcast.utils.SharedPreferenceUtils; import fr.tvbarthel.apps.simpleweatherforcast.utils.URLUtils;
package fr.tvbarthel.apps.simpleweatherforcast.services; /** * A Simple {@link android.app.Service} used to update the daily forecast. */ public class DailyForecastUpdateService extends Service implements LocationListener { // update action public static final String ACTION_UPDATE = "DailyForecastUpdateService.Actions.Update"; // update error action public static final String ACTION_UPDATE_ERROR = "DailyForecastUpdateService.Actions.UpdateError"; // update error extra public static final String EXTRA_UPDATE_ERROR = "DailyForecastUpdateService.Extra.UpdateError"; private LocationManager mLocationManager; private Looper mServiceLooper; private Handler mServiceHandler; private Boolean mIsUpdatingTemperature; public static void startForUpdate(Context context) { final Intent intent = new Intent(context, DailyForecastUpdateService.class); intent.setAction(ACTION_UPDATE); context.startService(intent); } @Override public void onCreate() { super.onCreate(); mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE); HandlerThread thread = new HandlerThread("DailyForecastUpdateService", android.os.Process.THREAD_PRIORITY_BACKGROUND); thread.start(); mServiceLooper = thread.getLooper(); mServiceHandler = new Handler(mServiceLooper); mIsUpdatingTemperature = false; } @Override public void onDestroy() { mServiceLooper.quit(); super.onDestroy(); } @Override public IBinder onBind(Intent intent) { // We don't support binding. return null; } @Override public int onStartCommand(Intent intent, int flags, int startId) { if (intent != null && ACTION_UPDATE.equals(intent.getAction()) && !mIsUpdatingTemperature) { if (ConnectivityUtils.isConnected(getApplicationContext())) { mIsUpdatingTemperature = true; // First get a new location getNewLocation(); } else { broadcastErrorAndStop(R.string.toast_no_connection_available); } } return START_STICKY; } private void updateForecast(final Location newLocation) { mServiceHandler.post(new Runnable() { @Override public void run() { try { final String JSON = getForecastAsJSON(newLocation);
SharedPreferenceUtils.storeWeather(DailyForecastUpdateService.this, JSON);
3
sumeetchhetri/gatf
alldep-jar/src/main/java/com/gatf/selenium/SeleniumTest.java
[ "public class AcceptanceTestContext {\r\n\r\n\tprivate Logger logger = Logger.getLogger(AcceptanceTestContext.class.getSimpleName());\r\n\t\r\n\tpublic final static String\r\n\t PROP_SOAP_ACTION_11 = \"SOAPAction\",\r\n\t PROP_SOAP_ACTION_12 = \"action=\",\r\n\t PROP_CONTENT_TYPE = \"Content-Type\",\r\n\t ...
import java.awt.AWTException; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.Serializable; import java.lang.reflect.Method; import java.net.URL; import java.nio.charset.Charset; import java.security.Security; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.UUID; import java.util.concurrent.TimeUnit; import java.util.function.Function; import java.util.logging.Level; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.imageio.ImageIO; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.RandomStringUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.exception.ExceptionUtils; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.Keys; import org.openqa.selenium.OutputType; import org.openqa.selenium.Point; import org.openqa.selenium.Rectangle; import org.openqa.selenium.SearchContext; import org.openqa.selenium.TakesScreenshot; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebDriver.TargetLocator; import org.openqa.selenium.WebDriverException; import org.openqa.selenium.WebElement; import org.openqa.selenium.interactions.Actions; import org.openqa.selenium.logging.LogEntry; import org.openqa.selenium.logging.LogType; import org.openqa.selenium.logging.LoggingPreferences; import org.openqa.selenium.remote.Augmenter; import org.openqa.selenium.remote.RemoteWebElement; import org.openqa.selenium.support.ui.ExpectedCondition; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.Select; import org.openqa.selenium.support.ui.WebDriverWait; import com.gatf.executor.core.AcceptanceTestContext; import com.gatf.executor.core.GatfExecutorConfig; import com.gatf.executor.core.WorkflowContextHandler; import com.gatf.executor.report.RuntimeReportUtil; import com.gatf.selenium.Command.GatfSelCodeParseError; import com.gatf.selenium.SeleniumTestSession.SeleniumResult; import com.google.common.io.Resources; import io.appium.java_client.AppiumDriver; import io.appium.java_client.MobileDriver; import io.appium.java_client.MultiTouchAction; import io.appium.java_client.TouchAction; import io.appium.java_client.android.AndroidDriver; import io.appium.java_client.ios.IOSDriver; import io.selendroid.client.SelendroidDriver; import ru.yandex.qatools.ashot.AShot; import ru.yandex.qatools.ashot.Screenshot; import ru.yandex.qatools.ashot.shooting.ShootingStrategies;
/* Copyright 2013-2019, Sumeet Chhetri 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.gatf.selenium; public abstract class SeleniumTest { @SuppressWarnings("serial") protected final static Map<String, Level> LOG_LEVEL_BY_NAME_MAP = new HashMap<String, Level>(){{ put(Level.ALL.getName().toLowerCase(), Level.ALL); put(Level.CONFIG.getName().toLowerCase(), Level.CONFIG); put(Level.FINE.getName().toLowerCase(), Level.FINE); put(Level.FINER.getName().toLowerCase(), Level.FINER); put(Level.FINEST.getName().toLowerCase(), Level.FINEST); put(Level.INFO.getName().toLowerCase(), Level.INFO); put(Level.OFF.getName().toLowerCase(), Level.OFF); put(Level.SEVERE.getName().toLowerCase(), Level.SEVERE); put(Level.WARNING.getName().toLowerCase(), Level.WARNING); }}; @SuppressWarnings("serial") protected final static HashSet<String> LOG_TYPES_SET = new HashSet<String>() {{ add(LogType.BROWSER); add(LogType.CLIENT); add(LogType.DRIVER); add(LogType.PERFORMANCE); add(LogType.PROFILER); add(LogType.SERVER); }}; private static final String TOP_LEVEL_PROV_NAME = UUID.randomUUID().toString(); private transient AcceptanceTestContext ___cxt___ = null; List<SeleniumTestSession> sessions = new ArrayList<SeleniumTestSession>(); protected String name; protected transient int sessionNum = -1; protected int index; protected void nextSession() { if(sessions.size()>sessionNum+1) { sessionNum++; } } protected void setSession(String sns, int sn, boolean startFlag) { if(sn>=0 && sessions.size()>sn) { sessionNum = sn; } else if(sns!=null) { sn = 0; for (SeleniumTestSession s : sessions) { if(s.sessionName.equalsIgnoreCase(sns)) { sessionNum = sn; } sn++; } } else if(sn==-1 && sns==null) { sessionNum = 0; } if(startFlag) { startTest(); } } @SuppressWarnings("serial") protected Set<String> addTest(String sessionName, String browserName) { final SeleniumTestSession s = new SeleniumTestSession(); s.sessionName = sessionName; s.browserName = browserName; sessions.add(s); if(!s.__result__.containsKey(browserName)) { SeleniumResult r = new SeleniumResult(); r.browserName = browserName; s.__result__.put(browserName, r); } else { //throw new RuntimeException("Duplicate browser defined"); } return new HashSet<String>(){{add(s.sessionName); add((sessions.size()-1)+"");}}; } protected void startTest() { if(getSession().__teststarttime__==0) { getSession().__teststarttime__ = System.nanoTime(); } } public void pushResult(SeleniumTestResult result) { if(getSession().__subtestname__==null) { result.executionTime = System.nanoTime() - getSession().__teststarttime__; getSession().__result__.get(getSession().browserName).result = result; } else { getSession().__result__.get(getSession().browserName).__cresult__.put(getSession().__subtestname__, result);
RuntimeReportUtil.addEntry(index, result.status);
3
jedwards1211/Jhrome
src/main/java/org/sexydock/tabs/demos/NotepadDemo.java
[ "public class DefaultFloatingTabHandler implements IFloatingTabHandler\r\n{\r\n\tprivate Window\tdragImageWindow\t= null;\r\n\tprivate Image\tdragImage\t\t= null;\r\n\t\r\n\tprivate int\t\txOffs;\r\n\tprivate int\t\tyOffs;\r\n\t\r\n\tpublic void initialize( Tab draggedTab , Point grabPoint )\r\n\t{\r\n\t\tJTabbedPa...
import java.awt.BorderLayout; import java.awt.Component; import java.awt.Dimension; import java.awt.Window; import java.awt.event.ActionEvent; import java.awt.event.ContainerAdapter; import java.awt.event.ContainerEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import javax.swing.AbstractAction; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTabbedPane; import javax.swing.JTextArea; import javax.swing.SwingUtilities; import javax.swing.UIManager; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.filechooser.FileNameExtensionFilter; import org.sexydock.tabs.DefaultFloatingTabHandler; import org.sexydock.tabs.DefaultTabDropFailureHandler; import org.sexydock.tabs.DefaultWindowsClosedHandler; import org.sexydock.tabs.ITabFactory; import org.sexydock.tabs.ITabbedPaneDndPolicy; import org.sexydock.tabs.ITabbedPaneWindow; import org.sexydock.tabs.ITabbedPaneWindowFactory; import org.sexydock.tabs.Tab; import org.sexydock.tabs.jhrome.JhromeTabbedPaneUI;
package org.sexydock.tabs.demos; @SuppressWarnings( "serial" ) public class NotepadDemo extends JFrame implements ISexyTabsDemo , ITabbedPaneWindow , ITabbedPaneWindowFactory , ITabFactory { public static void main( String[ ] args ) { SwingUtilities.invokeLater( new Runnable( ) { @Override public void run( ) { new NotepadDemo( ).start( ); } } ); } public NotepadDemo( ) { initGUI( ); } private void initGUI( ) { setTitle( "Notepad" ); tabbedPane = new JTabbedPane( );
tabbedPane.setUI( new JhromeTabbedPaneUI( ) );
8
darko1002001/android-rest-client
rest-client-demo/src/main/java/com/dg/examples/restclientdemo/communication/requests/BlogsGoogleRequest.java
[ "public class RestConstants {\n\n public static final String TAG = RestConstants.class.getSimpleName();\n\n public static final String BASE_URL = \"https://ajax.googleapis.com\";\n public static final String LOG_SERVICE_URL = \"http://log-requests.herokuapp.com/\";\n public static final String HTTP_BIN_URL = \"...
import android.util.Log; import com.dg.examples.restclientdemo.communication.RestConstants; import com.dg.examples.restclientdemo.communication.parsers.BlogsGoogleParser; import com.dg.examples.restclientdemo.domain.ResponseModel; import com.dg.libs.rest.client.RequestMethod; import com.dg.libs.rest.requests.RestClientRequest; import com.squareup.okhttp.OkHttpClient;
package com.dg.examples.restclientdemo.communication.requests; public class BlogsGoogleRequest extends RestClientRequest<ResponseModel> { public static final String TAG = BlogsGoogleRequest.class.getSimpleName(); public BlogsGoogleRequest(String query) { super(); setRequestMethod(RequestMethod.GET); setUrl(RestConstants.GOOGLE_BLOGS);
setParser(new BlogsGoogleParser());
1
albertogiunta/justintrain-client-android
app/src/main/java/com/jaus/albertogiunta/justintrain_oraritreni/aboutAndSettings/ItemBuilder.java
[ "public enum ENUM_CATEGORIES {\n\n FR(\"Frecciarossa\"), FB(\"Frecciabianca\"), FA(\"Frecciargento\"), IC(\"Intercity\"), REG(\"Regionale\"), RV(\"Regionale Veloce\"), BUS(\"Bus\");\n\n private final String alias;\n\n ENUM_CATEGORIES(String alias) {\n this.alias = alias;\n }\n\n public String ...
import com.google.android.flexbox.FlexboxLayout; import android.content.Context; import android.support.v7.widget.SwitchCompat; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.CheckBox; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import com.jaus.albertogiunta.justintrain_oraritreni.R; import com.jaus.albertogiunta.justintrain_oraritreni.utils.constants.ENUM_CATEGORIES; import com.jaus.albertogiunta.justintrain_oraritreni.utils.helpers.AnalyticsHelper; import com.jaus.albertogiunta.justintrain_oraritreni.utils.sharedPreferences.SettingsPreferences; import static butterknife.ButterKnife.apply; import static com.jaus.albertogiunta.justintrain_oraritreni.utils.components.ViewsUtils.GONE; import static com.jaus.albertogiunta.justintrain_oraritreni.utils.components.ViewsUtils.VISIBLE; import static com.jaus.albertogiunta.justintrain_oraritreni.utils.constants.CONST_ANALYTICS.SCREEN_SETTINGS;
package com.jaus.albertogiunta.justintrain_oraritreni.aboutAndSettings; public class ItemBuilder { private final LayoutInflater inflater; private final LinearLayout parent; private View view; public ItemBuilder(Context context, LinearLayout parent) { this.inflater = LayoutInflater.from(context); this.parent = parent; } public ItemBuilder addItemGroupHeader(String header) { view = inflater.inflate(R.layout.item_element_header, parent, false); RelativeLayout rl = (RelativeLayout) view.findViewById(R.id.rl_container); TextView tv = (TextView) rl.findViewById(R.id.tv_header); tv.setText(header); return this; } public ItemBuilder addItemWithTitle(String title) { view = inflater.inflate(R.layout.item_element_title, parent, false); TextView tv = (TextView) view.findViewById(R.id.tv_title); tv.setText(title); return this; } public ItemBuilder addItemWithIconTitle(int icon, String title) { view = inflater.inflate(R.layout.item_element_icon_title, parent, false); ImageView iv = (ImageView) view.findViewById(R.id.iv_icon); iv.setImageResource(icon); TextView tv = (TextView) view.findViewById(R.id.tv_title); tv.setText(title); return this; } public ItemBuilder addItemWithTitleSubtitle(String title, String subtitle) { view = inflater.inflate(R.layout.item_element_title_subtitle, parent, false); TextView tv = (TextView) view.findViewById(R.id.tv_title); tv.setText(title); TextView tv2 = (TextView) view.findViewById(R.id.tv_subtitle); tv2.setText(subtitle); return this; } public ItemBuilder addItemWithIconTitleSubtitle(int icon, String title, String subtitle) { view = inflater.inflate(R.layout.item_element_icon_title_subtitle, parent, false); ImageView iv = (ImageView) view.findViewById(R.id.iv_icon); iv.setImageResource(icon); TextView tv = (TextView) view.findViewById(R.id.tv_title); tv.setText(title); TextView tv2 = (TextView) view.findViewById(R.id.tv_subtitle); tv2.setText(subtitle); return this; } public ItemBuilder addItemPrefWithToggle(Context context, String title, String subtitle, boolean isChecked, boolean useSwitch, boolean isProFeature, boolean userIsPro, String preferenceCONST, String settingsEnabledAction, String settingsDisabledAction) { view = inflater.inflate(R.layout.item_element_title_subtitle_checkbox, parent, false); TextView tv = (TextView) view.findViewById(R.id.tv_title); tv.setText(title); TextView tv2 = (TextView) view.findViewById(R.id.tv_subtitle); tv2.setText(subtitle); CheckBox checkboxButton = (CheckBox) view.findViewById(R.id.cb_pref); SwitchCompat switchButton = (SwitchCompat) view.findViewById(R.id.sw_pref); checkboxButton.setChecked(isChecked); switchButton.setChecked(isChecked); if (useSwitch) { apply(checkboxButton, GONE); apply(switchButton, VISIBLE); } else { apply(checkboxButton, VISIBLE); apply(switchButton, GONE); } View.OnClickListener listener = view1 -> { if (SettingsPreferences.isGenericSettingEnabled(context, preferenceCONST, true)) { SettingsPreferences.disableGenericSetting(context, preferenceCONST);
AnalyticsHelper.getInstance(context).logScreenEvent(SCREEN_SETTINGS, settingsDisabledAction);
1
BoD/bikey
wear/src/main/java/org/jraf/android/bikey/wearable/app/display/DisplayActivity.java
[ "public class CommConstants {\n /*\n * Ride.\n */\n\n public static final String PATH_RIDE = \"/ride\";\n\n /**\n * Indicates whether a ride is currently ongoing ({@code boolean}).\n */\n public static final String PATH_RIDE_ONGOING = PATH_RIDE + \"/ongoing\";\n\n /**\n * Measurem...
import android.databinding.DataBindingUtil; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.view.MotionEvent; import android.view.View; import android.view.WindowManager; import com.google.android.gms.wearable.DataApi; import com.google.android.gms.wearable.DataEvent; import com.google.android.gms.wearable.DataEventBuffer; import com.google.android.gms.wearable.DataItem; import com.google.android.gms.wearable.DataMap; import com.google.android.gms.wearable.DataMapItem; import org.jraf.android.bikey.R; import org.jraf.android.bikey.common.wear.CommConstants; import org.jraf.android.bikey.common.wear.WearCommHelper; import org.jraf.android.bikey.common.widget.fragmentcycler.FragmentCycler; import org.jraf.android.bikey.databinding.DisplayBinding; import org.jraf.android.bikey.wearable.app.display.fragment.currenttime.CurrentTimeDisplayFragment; import org.jraf.android.bikey.wearable.app.display.fragment.elapsedtime.ElapsedTimeDisplayFragment; import org.jraf.android.bikey.wearable.app.display.fragment.speed.SpeedDisplayFragment; import org.jraf.android.bikey.wearable.app.display.fragment.totaldistance.TotalDistanceDisplayFragment; import org.jraf.android.util.log.Log;
/* * This source is part of the * _____ ___ ____ * __ / / _ \/ _ | / __/___ _______ _ * / // / , _/ __ |/ _/_/ _ \/ __/ _ `/ * \___/_/|_/_/ |_/_/ (_)___/_/ \_, / * /___/ * repository. * * Copyright (C) 2014 Benoit 'BoD' Lubek (BoD@JRAF.org) * * 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.jraf.android.bikey.wearable.app.display; public class DisplayActivity extends FragmentActivity { private DisplayBinding mBinding; private FragmentCycler mFragmentCycler; private SpeedDisplayFragment mSpeedDisplayFragment; private ElapsedTimeDisplayFragment mElapsedTimeDisplayFragment; private TotalDistanceDisplayFragment mTotalDistanceDisplayFragment; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); mBinding = DataBindingUtil.setContentView(this, R.layout.display); mBinding.vieFragmentCycle.setOnTouchListener(this::fragmentCycleOnTouch); setupFragments(); retrieveRideValues(); } private void retrieveRideValues() { // Retrieve the latest values now, to show the elapsed time new AsyncTask<Void, Void, Bundle>() { @Override protected Bundle doInBackground(Void... params) {
return WearCommHelper.get().retrieveRideValues();
1
awslabs/amazon-sqs-java-messaging-lib
src/main/java/com/amazon/sqs/javamessaging/SQSMessageProducer.java
[ "public class SQSBytesMessage extends SQSMessage implements BytesMessage {\n private static final Log LOG = LogFactory.getLog(SQSBytesMessage.class);\n\n private byte[] bytes;\n\n private ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();\n\n private DataInputStream dataIn;\n \n private...
import java.util.Enumeration; import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import javax.jms.Destination; import javax.jms.IllegalStateException; import javax.jms.InvalidDestinationException; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.MessageFormatException; import javax.jms.MessageProducer; import javax.jms.Queue; import javax.jms.QueueSender; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.amazon.sqs.javamessaging.message.SQSBytesMessage; import com.amazon.sqs.javamessaging.message.SQSMessage; import com.amazon.sqs.javamessaging.message.SQSMessage.JMSMessagePropertyValue; import com.amazon.sqs.javamessaging.message.SQSObjectMessage; import com.amazon.sqs.javamessaging.message.SQSTextMessage; import com.amazonaws.services.sqs.model.MessageAttributeValue; import com.amazonaws.services.sqs.model.SendMessageRequest; import com.amazonaws.services.sqs.model.SendMessageResult; import com.amazonaws.util.Base64;
/* * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazon.sqs.javamessaging; /** * A client uses a MessageProducer object to send messages to a queue * destination. A MessageProducer object is created by passing a Destination * object to a message-producer creation method supplied by a session. * <P> * A client also has the option of creating a message producer without supplying * a queue destination. In this case, a destination must be provided with every send * operation. * <P> */ public class SQSMessageProducer implements MessageProducer, QueueSender { private static final Log LOG = LogFactory.getLog(SQSMessageProducer.class); private long MAXIMUM_DELIVERY_DELAY_MILLISECONDS = TimeUnit.MILLISECONDS.convert(15, TimeUnit.MINUTES); private int deliveryDelaySeconds = 0; /** This field is not actually used. */ private long timeToLive; /** This field is not actually used. */ private int defaultPriority; /** This field is not actually used. */ private int deliveryMode; /** This field is not actually used. */ private boolean disableMessageTimestamp; /** This field is not actually used. */ private boolean disableMessageID; /** * State of MessageProducer. * True if MessageProducer is closed. */ final AtomicBoolean closed = new AtomicBoolean(false); private final AmazonSQSMessagingClientWrapper amazonSQSClient; private final SQSQueueDestination sqsDestination; private final SQSSession parentSQSSession; SQSMessageProducer(AmazonSQSMessagingClientWrapper amazonSQSClient, SQSSession parentSQSSession, SQSQueueDestination destination) throws JMSException { this.sqsDestination = destination; this.amazonSQSClient = amazonSQSClient; this.parentSQSSession = parentSQSSession; } void sendInternal(SQSQueueDestination queue, Message rawMessage) throws JMSException { checkClosed(); String sqsMessageBody = null; String messageType = null;
if (!(rawMessage instanceof SQSMessage)) {
1
Catbag/redux-android-sample
app/src/main/java/br/com/catbag/gifreduxsample/reducers/AppStateReducer.java
[ "public final class AppStateActionCreator extends BaseActionCreator {\n\n public static final String APP_STATE_LOAD = \"APP_STATE_LOAD\";\n public static final String APP_STATE_LOADED = \"APP_STATE_LOADED\";\n\n private static AppStateActionCreator sInstance;\n\n private AppStateActionCreator() {\n ...
import com.umaplay.fluxxan.annotation.BindAction; import com.umaplay.fluxxan.impl.BaseAnnotatedReducer; import java.util.LinkedHashMap; import java.util.Map; import br.com.catbag.gifreduxsample.actions.AppStateActionCreator; import br.com.catbag.gifreduxsample.actions.GifActionCreator; import br.com.catbag.gifreduxsample.actions.GifListActionCreator; import br.com.catbag.gifreduxsample.actions.PayloadParams; import br.com.catbag.gifreduxsample.models.AppState; import br.com.catbag.gifreduxsample.models.Gif; import br.com.catbag.gifreduxsample.models.ImmutableAppState;
package br.com.catbag.gifreduxsample.reducers; /** Copyright 26/10/2016 Felipe Piñeiro (fpbitencourt@gmail.com), Nilton Vasques (nilton.vasques@gmail.com) and Raul Abreu (raulccabreu@gmail.com) Be free to ask for help, email us! 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. **/ public class AppStateReducer extends BaseAnnotatedReducer<AppState> { @BindAction(AppStateActionCreator.APP_STATE_LOADED) public AppState stateLoaded(AppState oldState, AppState newState) { return createImmutableAppBuilder(newState) .build(); } @BindAction(GifListActionCreator.GIF_LIST_UPDATED) public AppState listUpdated(AppState state, Map<String, Object> params) {
Map<String, Gif> gifs = (Map<String, Gif>) params.get(PayloadParams.PARAM_GIFS);
3
AwaisKing/Linked-Words
app/src/main/java/awais/sephiroth/numberpicker/HorizontalNumberPicker.java
[ "public final class Utils {\n static {\n AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);\n }\n\n private static final Intent SEARCH_QUERY_INTENT = new Intent(Intent.ACTION_WEB_SEARCH);\n\n public static final int[] CUSTOM_TAB_COLORS = new int[]{0xFF4888F2, 0xFF333333, 0xFF3B496B};\n ...
import android.annotation.SuppressLint; import android.content.Context; import android.content.res.Resources; import android.graphics.Color; import android.graphics.drawable.Drawable; import android.graphics.drawable.GradientDrawable; import android.graphics.drawable.StateListDrawable; import android.os.Build; import android.text.Editable; import android.text.TextWatcher; import android.util.AttributeSet; import android.util.TypedValue; import android.view.Gravity; import android.view.MotionEvent; import android.view.View; import android.view.ViewConfiguration; import android.view.ViewGroup; import android.view.ViewParent; import android.view.inputmethod.EditorInfo; import android.widget.EditText; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatDelegate; import androidx.appcompat.view.ContextThemeWrapper; import androidx.appcompat.widget.AppCompatImageButton; import androidx.appcompat.widget.LinearLayoutCompat; import androidx.core.content.ContextCompat; import androidx.core.content.res.ResourcesCompat; import androidx.core.widget.NestedScrollView; import androidx.recyclerview.widget.RecyclerView; import awais.backworddictionary.R; import awais.backworddictionary.helpers.Utils; import awais.backworddictionary.interfaces.NumberPickerProgressListener; import awais.sephiroth.uigestures.UIGestureRecognizer.State; import awais.sephiroth.uigestures.UIGestureRecognizerDelegate; import awais.sephiroth.uigestures.UILongPressGestureRecognizer; import awais.sephiroth.uigestures.UITapGestureRecognizer; import awais.sephiroth.xtooltip.Tooltip; import awais.sephiroth.xtooltip.TooltipFunctions;
package awais.sephiroth.numberpicker; /** * Thanks to sephiroth74 for his NumberPicker library written in Kotlin * https://github.com/sephiroth74/NumberSlidingPicker */ public final class HorizontalNumberPicker extends LinearLayoutCompat implements TextWatcher { static { AppCompatDelegate.setCompatVectorFromResourcesEnabled(true); } private static final int DEFAULT_MAX_VALUE = 1000; private static final int DEFAULT_MIN_VALUE = 1; private static final long LONG_TAP_TIMEOUT = 300L; private static final int[][] API_20_BELOW_STATE_DRAWABLES = { new int[]{-android.R.attr.state_focused}, new int[]{android.R.attr.state_focused}, new int[]{-android.R.attr.state_enabled}, }; private static final int[] FOCUSED_STATE_ARRAY = {android.R.attr.state_focused}; private static final int[] UNFOCUSED_STATE_ARRAY = {-android.R.attr.state_focused}; // todo was 0, -focused private final ExponentialTracker tracker; private final UIGestureRecognizerDelegate delegate = new UIGestureRecognizerDelegate(); private final AppCompatImageButton btnLeft, btnRight; private final EditText editText; private int minValue = DEFAULT_MIN_VALUE, maxValue = DEFAULT_MAX_VALUE, value = 1; private boolean requestedDisallowIntercept = false;
private NumberPickerProgressListener progressListener;
1
philliphsu/ClockPlus
app/src/main/java/com/philliphsu/clock2/alarms/ui/ExpandedAlarmViewHolder.java
[ "@AutoValue\npublic abstract class Alarm extends ObjectWithId implements Parcelable {\n private static final int MAX_MINUTES_CAN_SNOOZE = 30;\n\n // =================== MUTABLE =======================\n private long snoozingUntilMillis;\n private boolean enabled;\n private final boolean[] recurringDa...
import android.content.Context; import android.content.res.ColorStateList; import android.graphics.drawable.Drawable; import android.media.RingtoneManager; import android.net.Uri; import android.os.Vibrator; import android.support.annotation.IdRes; import android.support.v4.graphics.drawable.DrawableCompat; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ToggleButton; import com.philliphsu.clock2.R; import com.philliphsu.clock2.alarms.Alarm; import com.philliphsu.clock2.alarms.misc.AlarmController; import com.philliphsu.clock2.alarms.misc.DaysOfWeek; import com.philliphsu.clock2.dialogs.RingtonePickerDialog; import com.philliphsu.clock2.dialogs.RingtonePickerDialogController; import com.philliphsu.clock2.list.OnListItemInteractionListener; import com.philliphsu.clock2.timepickers.Utils; import com.philliphsu.clock2.util.FragmentTagUtils; import butterknife.Bind; import butterknife.OnClick;
/* * Copyright 2017 Phillip Hsu * * This file is part of ClockPlus. * * ClockPlus 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. * * ClockPlus 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 ClockPlus. If not, see <http://www.gnu.org/licenses/>. */ package com.philliphsu.clock2.alarms.ui; /** * Created by Phillip Hsu on 7/31/2016. */ public class ExpandedAlarmViewHolder extends BaseAlarmViewHolder { private static final String TAG = "ExpandedAlarmViewHolder"; @Bind(R.id.ok) Button mOk; @Bind(R.id.delete) Button mDelete; @Bind(R.id.ringtone) Button mRingtone; @Bind(R.id.vibrate) TempCheckableImageButton mVibrate; @Bind({R.id.day0, R.id.day1, R.id.day2, R.id.day3, R.id.day4, R.id.day5, R.id.day6}) ToggleButton[] mDays; private final ColorStateList mDayToggleColors; private final ColorStateList mVibrateColors; private final RingtonePickerDialogController mRingtonePickerController; public ExpandedAlarmViewHolder(ViewGroup parent, final OnListItemInteractionListener<Alarm> listener, AlarmController controller) { super(parent, R.layout.item_expanded_alarm, listener, controller); // Manually bind listeners, or else you'd need to write a getter for the // OnListItemInteractionListener in the BaseViewHolder for use in method binding. mDelete.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { listener.onListItemDeleted(getAlarm()); } }); mOk.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // Since changes are persisted as soon as they are made, there's really // nothing we have to persist here. Let the listener know we should // collapse this VH. // While this works, it also makes an update to the DB and thus reschedules // the alarm, so the snackbar will show up as well. We want to avoid that.. // listener.onListItemUpdate(getAlarm(), getAdapterPosition()); // TODO: This only works because we know what the implementation looks like.. // This is bad because we just made the proper function of this dependent // on the implementation. listener.onListItemClick(getAlarm(), getAdapterPosition()); } }); // https://code.google.com/p/android/issues/detail?id=177282 // https://stackoverflow.com/questions/15673449/is-it-confirmed-that-i-cannot-use-themed-color-attribute-in-color-state-list-res // Programmatically create the ColorStateList for our day toggles using themed color // attributes, "since prior to M you can't create a themed ColorStateList from XML but you // can from code." (quote from google) // The first array level is analogous to an XML node defining an item with a state list. // The second level lists all the states considered by the item from the first level. // An empty list of states represents the default stateless item. int[][] states = { /*item 1*/{/*states*/android.R.attr.state_checked}, /*item 2*/{/*states*/} }; // TODO: Phase out Utils.getColorFromThemeAttr because it doesn't work for text colors. // WHereas getTextColorFromThemeAttr works for both regular colors and text colors. int[] dayToggleColors = { /*item 1*/Utils.getTextColorFromThemeAttr(getContext(), R.attr.colorAccent), /*item 2*/Utils.getTextColorFromThemeAttr(getContext(), android.R.attr.textColorHint) }; int[] vibrateColors = { /*item 1*/Utils.getTextColorFromThemeAttr(getContext(), R.attr.colorAccent), /*item 2*/Utils.getTextColorFromThemeAttr(getContext(), R.attr.themedIconTint) }; mDayToggleColors = new ColorStateList(states, dayToggleColors); mVibrateColors = new ColorStateList(states, vibrateColors); mRingtonePickerController = new RingtonePickerDialogController(mFragmentManager, new RingtonePickerDialog.OnRingtoneSelectedListener() { @Override public void onRingtoneSelected(Uri ringtoneUri) { Log.d(TAG, "Selected ringtone: " + ringtoneUri.toString()); final Alarm oldAlarm = getAlarm(); Alarm newAlarm = oldAlarm.toBuilder() .ringtone(ringtoneUri.toString()) .build(); oldAlarm.copyMutableFieldsTo(newAlarm); persistUpdatedAlarm(newAlarm, false); } } ); } @Override public void onBind(Alarm alarm) { super.onBind(alarm); mRingtonePickerController.tryRestoreCallback(makeTag(R.id.ringtone)); bindDays(alarm); bindRingtone(); bindVibrate(alarm.vibrates()); } @Override protected void bindLabel(boolean visible, String label) { super.bindLabel(true, label); } @OnClick(R.id.ok) void save() { // TODO } // @OnClick(R.id.delete) // void delete() { // // TODO // } @OnClick(R.id.ringtone) void showRingtonePickerDialog() { // Intent intent = new Intent(RingtoneManager.ACTION_RINGTONE_PICKER); // intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TYPE, RingtoneManager.TYPE_ALARM) // .putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_SILENT, false) // // The ringtone to show as selected when the dialog is opened // .putExtra(RingtoneManager.EXTRA_RINGTONE_EXISTING_URI, getSelectedRingtoneUri()) // // Whether to show "Default" item in the list // .putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_DEFAULT, false); // // The ringtone that plays when default option is selected // //.putExtra(RingtoneManager.EXTRA_RINGTONE_DEFAULT_URI, DEFAULT_TONE); // // TODO: This is VERY BAD. Use a Controller/Presenter instead. // // The result will be delivered to MainActivity, and then delegated to AlarmsFragment. // ((Activity) getContext()).startActivityForResult(intent, AlarmsFragment.REQUEST_PICK_RINGTONE); mRingtonePickerController.show(getSelectedRingtoneUri(), makeTag(R.id.ringtone)); } @OnClick(R.id.vibrate) void onVibrateToggled() { final boolean checked = mVibrate.isChecked(); if (checked) { Vibrator vibrator = (Vibrator) getContext().getSystemService(Context.VIBRATOR_SERVICE); vibrator.vibrate(300); } final Alarm oldAlarm = getAlarm(); Alarm newAlarm = oldAlarm.toBuilder() .vibrates(checked) .build(); oldAlarm.copyMutableFieldsTo(newAlarm); persistUpdatedAlarm(newAlarm, false); } @OnClick({ R.id.day0, R.id.day1, R.id.day2, R.id.day3, R.id.day4, R.id.day5, R.id.day6 }) void onDayToggled(ToggleButton view) { final Alarm oldAlarm = getAlarm(); Alarm newAlarm = oldAlarm.toBuilder().build(); oldAlarm.copyMutableFieldsTo(newAlarm); // --------------------------------------------------------------------------------- // TOneverDO: precede copyMutableFieldsTo() int position = ((ViewGroup) view.getParent()).indexOfChild(view);
int weekDayAtPosition = DaysOfWeek.getInstance(getContext()).weekDayAt(position);
2
vdmeer/svg2vector
src/main/java/de/vandermeer/svg2vector/applications/fh/Svg2Vector_FH.java
[ "public abstract class AppBase <L extends SV_DocumentLoader, P extends AppProperties<L>> implements ExecS_Application {\r\n\r\n\t/** CLI parser. */\r\n\tfinal private ExecS_CliParser cli;\r\n\r\n\t/** The properties of the application. */\r\n\tfinal private P props;\r\n\r\n\t/**\r\n\t * Creates a new base applicati...
import de.vandermeer.svg2vector.applications.fh.converters.Fh_Svg2Svg; import java.awt.Color; import java.io.File; import java.util.Iterator; import java.util.Map.Entry; import java.util.Set; import org.freehep.graphicsbase.util.UserProperties; import de.vandermeer.svg2vector.applications.base.AppBase; import de.vandermeer.svg2vector.applications.base.AppProperties; import de.vandermeer.svg2vector.applications.base.SvgTargets; import de.vandermeer.svg2vector.applications.fh.converters.BatikLoader; import de.vandermeer.svg2vector.applications.fh.converters.FhConverter; import de.vandermeer.svg2vector.applications.fh.converters.Fh_Svg2Emf; import de.vandermeer.svg2vector.applications.fh.converters.Fh_Svg2Pdf;
/* Copyright 2017 Sven van der Meer <vdmeer.sven@mykolab.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 de.vandermeer.svg2vector.applications.fh; /** * The Svg2Vector application using the FreeHep library. * It an SVG graphic to a vector format. * Currently supported are EMF, PDF and SVG. * The tool does support SVG and SVGZ input formats from file or URI. * It also can deal with SVG layers. * All options can be set via command line. * * @author Sven van der Meer &lt;vdmeer.sven@mykolab.com&gt; * @version v2.0.0 build 170413 (13-Apr-17) for Java 1.8 * @since v1.1.0 */ public class Svg2Vector_FH extends AppBase<BatikLoader, AppProperties<BatikLoader>> { /** Application name. */ public final static String APP_NAME = "s2v-fh"; /** Application display name. */ public final static String APP_DISPLAY_NAME = "Svg2Vector FreeHep"; /** Application version, should be same as the version in the class JavaDoc. */ public final static String APP_VERSION = "v2.0.0 build 170413 (13-Apr-17) for Java 1.8"; /** Application option for not-transparent mode. */ AO_NotTransparent optionNotTransparent = new AO_NotTransparent(false, 'n', "switch off transparency"); /** Application option for clip mode. */ AO_Clip optionClip = new AO_Clip(false, 'c', "activate clip property"); /** Application option for background-color mode. */ AO_BackgroundColor optionBackgroundColor = new AO_BackgroundColor(false, 'r', "sets the background color"); /** Application option for no-background mode. */ AO_NoBackground optionNoBackground = new AO_NoBackground(false, 'b', "switch off background property"); /** * Returns a new application. */ public Svg2Vector_FH(){ super(new AppProperties<BatikLoader>(new SvgTargets[]{SvgTargets.pdf, SvgTargets.emf, SvgTargets.svg}, new BatikLoader())); this.addOption(this.optionNotTransparent); this.addOption(this.optionClip); this.addOption(this.optionBackgroundColor); this.addOption(this.optionNoBackground); } @Override public int executeApplication(String[] args) { // parse command line, exit with help screen if error int ret = super.executeApplication(args); if(ret!=0){ return ret; } SvgTargets target = this.getProps().getTarget(); FhConverter converter = TARGET_2_CONVERTER(target); if(converter==null){ this.printErrorMessage("no converter found for target <" + target.name() + ">"); return -20; } converter.setPropertyTransparent(!this.optionNotTransparent.inCli()); converter.setPropertyClip(this.optionClip.inCli()); converter.setPropertyBackground(!this.optionNoBackground.inCli()); converter.setPropertyTextAsShapes(this.getProps().doesTextAsShape()); if(this.optionBackgroundColor.inCli()){ Color color = Color.getColor(this.optionBackgroundColor.getValue()); converter.setPropertyBackgroundColor(color); } UserProperties up = converter.getProperties(); Set<Object> keys = up.keySet(); Iterator<Object>it = keys.iterator(); while(it.hasNext()){ String key = it.next().toString(); String val = up.getProperty(key); key=key.substring(key.lastIndexOf('.')+1, key.length()); this.printDetailMessage("using SVG property " + key + "=" + val); } String err; BatikLoader loader = this.getProps().getLoader(); if(this.getProps().doesLayers()){ for(Entry<String, Integer> entry : loader.getLayers().entrySet()){ loader.switchOffAllLayers(); loader.switchOnLayer(entry.getKey()); this.printProgressMessage("processing layer " + entry.getKey()); this.printDetailMessage("writing to file " + this.getProps().getFnOut(entry) + "." + target.name()); if(this.getProps().canWriteFiles()){ err = converter.convertDocument(loader, new File(this.getProps().getFnOut(entry) + "." + target.name())); if(err!=null){ this.printErrorMessage(err); return -99;//TODO } } } } else{ this.printProgressMessage("converting input"); this.printDetailMessage("writing to file " + this.getProps().getFoutFile()); if(this.getProps().canWriteFiles()){ err = converter.convertDocument(loader, this.getProps().getFoutFile()); if(err!=null){ this.printErrorMessage(err); return -99;//TODO } } } this.printProgressMessage("finished successfully"); return 0; } @Override public String getAppName() { return APP_NAME; } @Override public String getAppDisplayName(){ return APP_DISPLAY_NAME; } @Override public String getAppDescription() { return "Converts SVG graphics into other vector formats using FreeHep libraries, with options for handling layers"; } @Override public String getAppVersion() { return APP_VERSION; } /** * Returns a converter for a given target * @param target the target, can be null * @return null if target was null or no converter found, a new converter object for the target otherwise */ public static FhConverter TARGET_2_CONVERTER(SvgTargets target){ if(target==null){ return null; } switch(target){ case eps: case png: case ps: case wmf: break; case pdf: return new Fh_Svg2Pdf(); case svg: return new Fh_Svg2Svg(); case emf:
return new Fh_Svg2Emf();
5
roadhouse-dev/RxDbflow
examplerx1/src/main/java/au/com/roadhouse/rxdbflow/examplerx1/MainActivity.java
[ "@Table(database = au.com.roadhouse.rxdbflow.example.model.ExampleDatabase.class, name = InheritanceTestModel.NAME, insertConflict = ConflictAction.REPLACE)\npublic class InheritanceTestModel extends RxBaseModel<InheritanceTestModel> {\n\n public static final String NAME = \"test-inheritance\";\n\n @PrimaryKe...
import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import com.raizlabs.android.dbflow.sql.language.Method; import com.raizlabs.android.dbflow.sql.language.SQLite; import com.raizlabs.android.dbflow.structure.database.DatabaseWrapper; import java.util.List; import au.com.roadhouse.rxdbflow.exampleRx1.model.InheritanceTestModel; import au.com.roadhouse.rxdbflow.exampleRx1.model.TestModel; import au.com.roadhouse.rxdbflow.rx1.DBFlowSchedulers; import au.com.roadhouse.rxdbflow.rx1.sql.language.RxSQLite; import au.com.roadhouse.rxdbflow.rx1.sql.transaction.RxGenericTransactionBlock; import au.com.roadhouse.rxdbflow.rx1.sql.transaction.RxModelOperationTransaction; import au.com.roadhouse.rxdbflow.rx1.structure.RxModelAdapter; import rx.Subscription; import rx.android.schedulers.AndroidSchedulers; import rx.functions.Action1; import rx.schedulers.Schedulers; import rx.subscriptions.CompositeSubscription;
package au.com.roadhouse.rxdbflow.exampleRx1; public class MainActivity extends AppCompatActivity { private CompositeSubscription mDataSubscribers; private Subscription mDatabaseInitSubscription; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mDataSubscribers = new CompositeSubscription();
mDatabaseInitSubscription = RxSQLite.select(Method.count())
3
Lambda-3/DiscourseSimplification
src/main/java/org/lambda3/text/simplification/discourse/runner/discourse_tree/extraction/rules/ListNP/ListNPExtractor.java
[ "public class Extraction {\n private String extractionRule;\n private boolean referring;\n private String cuePhrase; // optional\n private Relation relation;\n private boolean contextRight; // only for subordinate relations\n private List<Leaf> constituents;\n\n public Extraction(String extract...
import org.lambda3.text.simplification.discourse.utils.parseTree.ParseTreeExtractionUtils; import org.lambda3.text.simplification.discourse.utils.words.WordsUtils; import java.util.ArrayList; import java.util.List; import java.util.Optional; import edu.stanford.nlp.ling.Word; import edu.stanford.nlp.trees.tregex.TregexMatcher; import edu.stanford.nlp.trees.tregex.TregexPattern; import org.lambda3.text.simplification.discourse.runner.discourse_tree.extraction.Extraction; import org.lambda3.text.simplification.discourse.runner.discourse_tree.extraction.ExtractionRule; import org.lambda3.text.simplification.discourse.runner.discourse_tree.extraction.utils.ListNPSplitter; import org.lambda3.text.simplification.discourse.runner.discourse_tree.model.Leaf; import org.lambda3.text.simplification.discourse.utils.parseTree.ParseTreeException;
/* * ==========================License-Start============================= * DiscourseSimplification : ListNPExtractor * * Copyright © 2017 Lambda³ * * GNU General Public License 3 * 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/. * ==========================License-End============================== */ package org.lambda3.text.simplification.discourse.runner.discourse_tree.extraction.rules.ListNP; /** * */ public abstract class ListNPExtractor extends ExtractionRule { private final String pattern; public ListNPExtractor(String pattern) { this.pattern = pattern; } @Override public Optional<Extraction> extract(Leaf leaf) throws ParseTreeException { TregexPattern p = TregexPattern.compile(pattern); TregexMatcher matcher = p.matcher(leaf.getParseTree()); while (matcher.findAt(leaf.getParseTree())) { Optional<ListNPSplitter.Result> r = ListNPSplitter.splitList(leaf.getParseTree(), matcher.getNode("np")); if (r.isPresent()) { // constituents List<Word> precedingWords = ParseTreeExtractionUtils.getPrecedingWords(leaf.getParseTree(), matcher.getNode("np"), false); List<Word> followingWords = ParseTreeExtractionUtils.getFollowingWords(leaf.getParseTree(), matcher.getNode("np"), false); List<Leaf> constituents = new ArrayList<>(); if (r.get().getIntroductionWords().isPresent()) { List<Word> words = new ArrayList<Word>(); words.addAll(precedingWords); words.addAll(r.get().getIntroductionWords().get()); words.addAll(followingWords);
Leaf constituent = new Leaf(getClass().getSimpleName(), WordsUtils.wordsToProperSentenceString(words));
6
YiuChoi/MicroReader
app/src/main/java/name/caiyao/microreader/ui/adapter/VideoAdapter.java
[ "public class UtilRequest {\n\n private UtilRequest() {}\n\n private static UtilApi utilApi = null;\n private static final Object monitor = new Object();\n\n public static UtilApi getUtilApi() {\n synchronized (monitor) {\n if (utilApi == null) {\n utilApi = new Retrofit...
import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.graphics.Color; import android.net.Uri; import android.support.v7.widget.CardView; import android.support.v7.widget.PopupMenu; import android.support.v7.widget.RecyclerView; import android.text.TextUtils; import android.util.Log; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import java.io.IOException; import java.util.ArrayList; import butterknife.BindView; import butterknife.ButterKnife; import name.caiyao.microreader.R; import name.caiyao.microreader.api.util.UtilRequest; import name.caiyao.microreader.bean.weiboVideo.WeiboVideoBlog; import name.caiyao.microreader.config.Config; import name.caiyao.microreader.ui.activity.VideoActivity; import name.caiyao.microreader.ui.activity.VideoWebViewActivity; import name.caiyao.microreader.utils.DBUtils; import name.caiyao.microreader.utils.ImageLoader; import name.caiyao.microreader.utils.SharePreferenceUtil; import okhttp3.ResponseBody; import rx.Observer; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers;
package name.caiyao.microreader.ui.adapter; /** * Created by 蔡小木 on 2016/4/29 0029. */ public class VideoAdapter extends RecyclerView.Adapter<VideoAdapter.VideoViewHolder> { private ArrayList<WeiboVideoBlog> gankVideoItems; private Context mContext; public VideoAdapter(Context context, ArrayList<WeiboVideoBlog> gankVideoItems) { this.gankVideoItems = gankVideoItems; this.mContext = context; } @Override public VideoViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { return new VideoViewHolder(LayoutInflater.from(mContext).inflate(R.layout.video_item, parent, false)); } @Override public void onBindViewHolder(final VideoViewHolder holder, int position) { final WeiboVideoBlog weiboVideoBlog = gankVideoItems.get(position); final String title = weiboVideoBlog.getBlog().getText().replaceAll("&[a-zA-Z]{1,10};", "").replaceAll( "<[^>]*>", ""); if (DBUtils.getDB(mContext).isRead(Config.VIDEO, weiboVideoBlog.getBlog().getPageInfo().getVideoUrl(), 1)) holder.tvTitle.setTextColor(Color.GRAY); else holder.tvTitle.setTextColor(Color.BLACK); ImageLoader.loadImage(mContext, weiboVideoBlog.getBlog().getPageInfo().getVideoPic(), holder.mIvVideo); holder.tvTitle.setText(title); holder.tvTime.setText(weiboVideoBlog.getBlog().getCreateTime()); holder.btnVideo.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { PopupMenu popupMenu = new PopupMenu(mContext, holder.btnVideo); popupMenu.getMenuInflater().inflate(R.menu.pop_menu, popupMenu.getMenu()); popupMenu.getMenu().removeItem(R.id.pop_fav); final boolean isRead = DBUtils.getDB(mContext).isRead(Config.VIDEO, weiboVideoBlog.getBlog().getPageInfo().getVideoUrl(), 1); if (!isRead) popupMenu.getMenu().findItem(R.id.pop_unread).setTitle(R.string.common_set_read); else popupMenu.getMenu().findItem(R.id.pop_unread).setTitle(R.string.common_set_unread); popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { switch (item.getItemId()) { case R.id.pop_unread: if (isRead) { DBUtils.getDB(mContext).insertHasRead(Config.VIDEO, weiboVideoBlog.getBlog().getPageInfo().getVideoUrl(), 0); holder.tvTitle.setTextColor(Color.BLACK); } else { DBUtils.getDB(mContext).insertHasRead(Config.VIDEO, weiboVideoBlog.getBlog().getPageInfo().getVideoUrl(), 1); holder.tvTitle.setTextColor(Color.GRAY); } break; case R.id.pop_share: Intent shareIntent = new Intent(); shareIntent.setAction(Intent.ACTION_SEND); shareIntent.putExtra(Intent.EXTRA_TEXT, title + " " + weiboVideoBlog.getBlog().getPageInfo().getVideoUrl() + mContext.getString(R.string.share_tail)); shareIntent.setType("text/plain"); //设置分享列表的标题,并且每次都显示分享列表 mContext.startActivity(Intent.createChooser(shareIntent, mContext.getString(R.string.share))); break; } return true; } }); popupMenu.show(); } }); holder.cvVideo.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { DBUtils.getDB(mContext).insertHasRead(Config.VIDEO, weiboVideoBlog.getBlog().getPageInfo().getVideoUrl(), 1); holder.tvTitle.setTextColor(Color.GRAY); VideoAdapter.this.getPlayUrl(weiboVideoBlog, title); } }); } private void getPlayUrl(final WeiboVideoBlog weiboVideoBlog, final String title) { final ProgressDialog progressDialog = new ProgressDialog(mContext); progressDialog.setMessage(mContext.getString(R.string.fragment_video_get_url)); progressDialog.show(); UtilRequest.getUtilApi().getVideoUrl(weiboVideoBlog.getBlog().getPageInfo().getVideoUrl()) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Observer<ResponseBody>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { if (progressDialog.isShowing()) { e.printStackTrace(); progressDialog.dismiss(); Toast.makeText(mContext, "视频解析失败!", Toast.LENGTH_SHORT).show(); mContext.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(weiboVideoBlog.getBlog().getPageInfo().getVideoUrl()))); } } @Override public void onNext(ResponseBody responseBody) { //防止停止后继续执行 if (progressDialog.isShowing()) { progressDialog.dismiss(); try { String shareUrl = weiboVideoBlog.getBlog().getPageInfo().getVideoUrl(); String url = responseBody.string(); if (TextUtils.isEmpty(shareUrl)) { Toast.makeText(mContext, "播放地址为空", Toast.LENGTH_SHORT).show(); return; } Log.i("TAG", shareUrl); Log.i("TAG", url); if (url.contains("http")) {
mContext.startActivity(new Intent(mContext, VideoActivity.class)
3
mathisdt/trackworktime
app/src/main/java/org/zephyrsoft/trackworktime/report/CsvGenerator.java
[ "public class DAO {\n\n\t// TODO use prepared statements as described here: http://stackoverflow.com/questions/7255574\n\n\tprivate volatile SQLiteDatabase db;\n\tprivate final MySQLiteHelper dbHelper;\n\tprivate final Context context;\n\tprivate final WorkTimeTrackerBackupManager backupManager;\n\tprivate final Ba...
import androidx.arch.core.util.Function; import org.pmw.tinylog.Logger; import org.supercsv.cellprocessor.CellProcessorAdaptor; import org.supercsv.cellprocessor.Optional; import org.supercsv.cellprocessor.constraint.NotNull; import org.supercsv.cellprocessor.ift.CellProcessor; import org.supercsv.io.CsvBeanWriter; import org.supercsv.io.ICsvBeanWriter; import org.supercsv.prefs.CsvPreference; import org.supercsv.util.CsvContext; import org.threeten.bp.LocalDate; import org.threeten.bp.OffsetDateTime; import org.threeten.bp.ZonedDateTime; import org.threeten.bp.format.DateTimeFormatter; import org.zephyrsoft.trackworktime.database.DAO; import org.zephyrsoft.trackworktime.model.Event; import org.zephyrsoft.trackworktime.model.Target; import org.zephyrsoft.trackworktime.model.TargetWrapper; import org.zephyrsoft.trackworktime.model.Task; import org.zephyrsoft.trackworktime.model.TimeSum; import org.zephyrsoft.trackworktime.model.TypeEnum; import org.zephyrsoft.trackworktime.util.DateTimeUtil; import java.io.IOException; import java.io.StringWriter; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Map.Entry;
/* * This file is part of TrackWorkTime (TWT). * * TWT is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License 3.0 as published by * the Free Software Foundation. * * TWT 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 3.0 for more details. * * You should have received a copy of the GNU General Public License 3.0 * along with TWT. If not, see <http://www.gnu.org/licenses/>. */ package org.zephyrsoft.trackworktime.report; /** * Creates CSV reports from events. */ public class CsvGenerator { private final DAO dao; public CsvGenerator(DAO dao) { this.dao = dao; } /** time, type, task, text */ private final CellProcessor[] eventProcessors = new CellProcessor[] { new CellProcessorAdaptor() { @Override public Object execute(Object arg0, CsvContext arg1) { if (arg0 == null) { throw new IllegalStateException("event time may not be null"); } else { return ((OffsetDateTime) arg0).format(DateTimeFormatter.ISO_OFFSET_DATE_TIME); } } }, new CellProcessorAdaptor() { @Override public Object execute(Object arg0, CsvContext arg1) { if (arg0 == null) { throw new IllegalStateException("event type may not be null"); } else { return TypeEnum.byValue((Integer) arg0).getReadableName(); } } }, new CellProcessorAdaptor() { @Override public Object execute(Object arg0, CsvContext arg1) { if (arg0 == null) { return null; } else { Task task = dao.getTask((Integer) arg0); return task == null ? "" : task.getName(); } } }, new Optional() }; /** date, type, value, comment */ private final CellProcessor[] targetProcessors = new CellProcessor[] { new CellProcessorAdaptor() { @Override public Object execute(Object arg0, CsvContext arg1) { if (arg0 == null) { throw new IllegalStateException("target date may not be null"); } else { return ((LocalDate) arg0).format(DateTimeFormatter.ISO_LOCAL_DATE); } } }, new CellProcessorAdaptor() { @Override public Object execute(Object arg0, CsvContext arg1) { if (arg0 == null) { throw new IllegalStateException("target type may not be null"); } else { return arg0; } } }, new CellProcessorAdaptor() { @Override public Object execute(Object arg0, CsvContext arg1) { if (arg0 == null || (arg0 instanceof Integer && ((Integer) arg0).intValue() == 0)) { return null; } else { return DateTimeUtil.formatDuration((Integer) arg0); } } }, new Optional() }; /** task, spent */ private final CellProcessor[] sumsProcessors = new CellProcessor[] { new NotNull(), new CellProcessorAdaptor() { @Override public Object execute(Object arg0, CsvContext arg1) { if (arg0 == null) { throw new IllegalStateException("time sum may not be null"); } else { return arg0.toString(); } } } }; /** (month|week), task, spent */ private final CellProcessor[] sumsPerRangeProcessors = new CellProcessor[] { new NotNull(), new NotNull(), new CellProcessorAdaptor() { @Override public Object execute(Object arg0, CsvContext arg1) { if (arg0 == null) { throw new IllegalStateException("time sum may not be null"); } else { return arg0.toString(); } } } }; /** * Warning: could modify the provided event list! */ public String createTargetCsv(List<Target> targets) { ICsvBeanWriter beanWriter = null; StringWriter resultWriter = new StringWriter(); try { beanWriter = new CsvBeanWriter(resultWriter, CsvPreference.EXCEL_NORTH_EUROPE_PREFERENCE); // the header elements are used to map the bean values to each column (names must match!) final String[] header = new String[] { "date", "type", "value", "comment" }; beanWriter.writeHeader(header); for (Target target : targets) { beanWriter.write(new TargetWrapper(target), header, targetProcessors); } } catch (IOException e) { Logger.error(e, "error while writing"); } finally { if (beanWriter != null) { try { beanWriter.close(); } catch (IOException e) { // do nothing } } } return resultWriter.toString(); } /** * Warning: could modify the provided event list! */
public String createEventCsv(List<Event> events) {
1
albfernandez/javadbf
src/test/java/com/linuxense/javadbf/bug94_error_f5/Bug94ErrorF5Test.java
[ "public class DBFException extends RuntimeException {\n\n\tprivate static final long serialVersionUID = 1906727217048909819L;\n\n\n\t/**\n\t * Constructs an DBFException with the specified detail message.\n\t * @param message The detail message (which is saved for later retrieval by the Throwable.getMessage() metho...
import java.io.DataInputStream; import java.io.File; import java.io.IOException; import java.nio.file.Files; import org.junit.Assert; import org.junit.Test; import com.linuxense.javadbf.DBFException; import com.linuxense.javadbf.DBFUtils; import com.linuxense.javadbf.DBFWriter; import com.linuxense.javadbf.ReadDBFAssert; import com.linuxense.javadbf.testutils.FileUtils;
package com.linuxense.javadbf.bug94_error_f5; public class Bug94ErrorF5Test { private File testFile = new File("src/test/resources/fixtures/dbase_f5.dbf"); public Bug94ErrorF5Test() { super(); } @Test public void testSimpleRead() throws DBFException, IOException { ReadDBFAssert.testReadDBFFile(testFile, 60, 975, true); } @Test public void testWrite() throws Exception { File tmpFile = Files.createTempFile("tmp", ".dbf").toFile();
FileUtils.copyFile(testFile, tmpFile);
4
XhinLiang/Studio
app/src/main/java/com/wecan/xhin/studio/activity/RegisterActivity.java
[ "public abstract class BaseActivity extends RxAppCompatActivity {\n\n protected void setHasHomeButton() {\n if (getSupportActionBar() != null) {\n getSupportActionBar().setDisplayHomeAsUpEnabled(true);\n getSupportActionBar().setHomeButtonEnabled(true);\n }\n }\n\n\n pub...
import android.app.ProgressDialog; import android.databinding.DataBindingUtil; import android.os.Bundle; import com.jakewharton.rxbinding.view.ViewClickEvent; import com.wecan.xhin.baselib.activity.BaseActivity; import com.wecan.xhin.baselib.rx.RxNetworking; import com.wecan.xhin.studio.App; import com.wecan.xhin.studio.R; import com.wecan.xhin.studio.api.Api; import com.wecan.xhin.studio.bean.down.BaseData; import com.wecan.xhin.studio.bean.up.RegisterBody; import com.wecan.xhin.studio.databinding.ActivityRegisterBinding; import rx.Observable; import rx.android.schedulers.AndroidSchedulers; import rx.functions.Action1; import rx.functions.Func0; import rx.schedulers.Schedulers;
package com.wecan.xhin.studio.activity; /** * Created by xhinliang on 15-11-23. * xhinliang@gmail.com */ public class RegisterActivity extends BaseActivity { private ActivityRegisterBinding binding; private Api api; private Observable<BaseData> observableRegister; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); binding = DataBindingUtil.setContentView(this, R.layout.activity_register); setSupportActionBar(binding.toolbar); if (getSupportActionBar() != null) { getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setHomeButtonEnabled(true); } api = App.from(this).createApi(Api.class); ProgressDialog pd = new ProgressDialog(this); Observable.Transformer<BaseData, BaseData> networkingIndicator = RxNetworking.bindConnecting(pd); observableRegister = Observable //defer操作符是直到有订阅者订阅时,才通过Observable的工厂方法创建Observable并执行 //defer操作符能够保证Observable的状态是最新的 .defer(new Func0<Observable<BaseData>>() { @Override public Observable<BaseData> call() {
return api.register(new RegisterBody(binding.acpPosition.getSelectedItemPosition()
5
dmfs/xmlobjects
src/org/dmfs/xmlobjects/builder/TransientObjectBuilder.java
[ "public final class ElementDescriptor<T>\n{\n\tpublic final static XmlContext DEFAULT_CONTEXT = new XmlContext()\n\t{\n\t};\n\n\t/**\n\t * The {@link QualifiedName} of this element.\n\t */\n\tpublic final QualifiedName qualifiedName;\n\n\t/**\n\t * An {@link IObjectBuilder} for elements of this type.\n\t */\n\tpubl...
import java.io.IOException; import org.dmfs.xmlobjects.ElementDescriptor; import org.dmfs.xmlobjects.QualifiedName; import org.dmfs.xmlobjects.XmlContext; import org.dmfs.xmlobjects.pull.ParserContext; import org.dmfs.xmlobjects.pull.XmlObjectPullParserException; import org.dmfs.xmlobjects.serializer.SerializerContext; import org.dmfs.xmlobjects.serializer.SerializerException; import org.dmfs.xmlobjects.serializer.XmlObjectSerializer.IXmlChildWriter;
/* * Copyright (C) 2014 Marten Gajda <marten@dmfs.org> * * 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.dmfs.xmlobjects.builder; /** * A builder that just returns one of its child elements. It always returns the last child with the given {@link ElementDescriptor} or {@link IObjectBuilder}. * It's handy in cases like this, when the parent element can have only one child element of a specific type: * * <pre> * &lt;location>&lt;href>http://example.com&lt;/href>&lt;/location> * </pre> * * <p> * <strong>Note:</strong> Serialization requires that either an {@link ElementDescriptor} is provided or the child element is a {@link QualifiedName}s. * </p> * * <p> * Please be aware that the child object is not serialized if the object is <code>null</code>. * </p> * * @author Marten Gajda <marten@dmfs.org> */ public class TransientObjectBuilder<T> extends AbstractObjectBuilder<T> { /** * The descriptor of the child element to pass through. */ private final ElementDescriptor<T> mChildDescriptor; private final IObjectBuilder<T> mChildBuilder; public TransientObjectBuilder(ElementDescriptor<T> childDescriptor) { mChildDescriptor = childDescriptor; mChildBuilder = null; } public TransientObjectBuilder(IObjectBuilder<T> childBuilder) { mChildDescriptor = null; mChildBuilder = childBuilder; } @SuppressWarnings("unchecked") @Override
public <V> T update(ElementDescriptor<T> descriptor, T object, ElementDescriptor<V> childDescriptor, V child, ParserContext context)
3
hiBrianLee/AndroidMvvm
sample/src/main/java/com/hibrianlee/sample/mvvm/fragment/AndroidVersionsFragment.java
[ "public abstract class ViewModelFragment extends Fragment {\n\n private static final String EXTRA_VIEW_MODEL_STATE = \"viewModelState\";\n\n private ViewModel viewModel;\n\n protected void inject(AppComponent appComponent) {\n appComponent.inject(this);\n }\n\n @Nullable\n protected abstrac...
import butterknife.ButterKnife; import butterknife.OnClick; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.hibrianlee.mvvmapp.fragment.ViewModelFragment; import com.hibrianlee.mvvmapp.inject.ActivityComponent; import com.hibrianlee.mvvmapp.viewmodel.ViewModel; import com.hibrianlee.sample.mvvm.R; import com.hibrianlee.sample.mvvm.adapter.AndroidVersionsAdapter; import com.hibrianlee.sample.mvvm.databinding.FragmentAndroidVersionsBinding; import com.hibrianlee.sample.mvvm.viewmodel.AndroidVersionsViewModel;
/* * Copyright (C) 2015 Brian Lee (@hiBrianLee) * * 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.hibrianlee.sample.mvvm.fragment; public class AndroidVersionsFragment extends BaseFragment { private AndroidVersionsViewModel androidVersionsViewModel; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View root = inflater.inflate(R.layout.fragment_android_versions, container, false); ButterKnife.bind(this, root); return root; } @Nullable @Override protected ViewModel createAndBindViewModel(View root,
@NonNull ActivityComponent activityComponent,
1
mmonkey/Destinations
src/main/java/com/github/mmonkey/destinations/commands/BringCommand.java
[ "public class PlayerTeleportBringEvent extends AbstractPlayerTeleportEvent implements PlayerTeleportEvent.Bring {\n\n /**\n * PlayerTeleportBringEvent constructor\n *\n * @param player Player\n * @param location Location\n * @param rotation Vector3d\n */\n public PlayerTeleportBringE...
import com.github.mmonkey.destinations.events.PlayerTeleportBringEvent; import com.github.mmonkey.destinations.events.PlayerTeleportPreEvent; import com.github.mmonkey.destinations.teleportation.TeleportationService; import com.github.mmonkey.destinations.utilities.FormatUtil; import com.github.mmonkey.destinations.utilities.MessagesUtil; import org.spongepowered.api.Sponge; import org.spongepowered.api.command.CommandException; import org.spongepowered.api.command.CommandResult; import org.spongepowered.api.command.CommandSource; import org.spongepowered.api.command.args.CommandContext; import org.spongepowered.api.command.args.GenericArguments; import org.spongepowered.api.command.spec.CommandExecutor; import org.spongepowered.api.command.spec.CommandSpec; import org.spongepowered.api.entity.living.player.Player; import org.spongepowered.api.service.pagination.PaginationService; import org.spongepowered.api.text.Text; import org.spongepowered.api.text.action.TextActions; import org.spongepowered.api.text.format.TextStyles; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList;
package com.github.mmonkey.destinations.commands; public class BringCommand implements CommandExecutor { public static final String[] ALIASES = {"bring", "tpaccept", "tpyes"}; /** * Get the Command Specifications for this command * * @return CommandSpec */ public static CommandSpec getCommandSpec() { return CommandSpec.builder() .permission("destinations.tpa") .description(Text.of("/bring [player] or /tpaccept [player] or /tpyes [player]")) .extendedDescription(Text.of("Teleports a player that has issued a call request to your current location.")) .executor(new BringCommand()) .arguments(GenericArguments.optional(GenericArguments.firstParsing(GenericArguments.player(Text.of("player"))))) .build(); } @Override public CommandResult execute(CommandSource src, CommandContext args) throws CommandException { if (!(src instanceof Player)) { return CommandResult.empty(); } Player target = (Player) src; Player caller = args.getOne("player").isPresent() ? (Player) args.getOne("player").get() : null; if (caller == null) { int numCallers = TeleportationService.instance.getNumCallers(target); switch (numCallers) { case 0: target.sendMessage(MessagesUtil.error(target, "bring.empty")); return CommandResult.success(); case 1: Player calling = TeleportationService.instance.getFirstCaller(target); return executeBring(calling, target); default: return listCallers(target, args); } } if (TeleportationService.instance.isCalling(caller, target)) { return executeBring(caller, target); } target.sendMessage(MessagesUtil.error(target, "bring.not_found", caller.getName())); return CommandResult.success(); } private CommandResult listCallers(Player target, CommandContext args) { List<String> callList = TeleportationService.instance.getCalling(target); List<Text> list = new CopyOnWriteArrayList<>(); callList.forEach(caller -> list.add(getBringAction(caller))); PaginationService paginationService = Sponge.getServiceManager().provide(PaginationService.class).get(); paginationService.builder().title(MessagesUtil.get(target, "bring.title")).contents(list).padding(Text.of("-")).sendTo(target); return CommandResult.success(); } private CommandResult executeBring(Player caller, Player target) { TeleportationService.instance.removeCall(caller, target); Sponge.getGame().getEventManager().post(new PlayerTeleportPreEvent(caller, caller.getLocation(), caller.getRotation())); Sponge.getGame().getEventManager().post(new PlayerTeleportBringEvent(caller, target.getLocation(), target.getRotation())); caller.sendMessage(MessagesUtil.success(caller, "bring.teleport", target.getName())); return CommandResult.success(); } static Text getBringAction(String name) { return Text.builder("/bring " + name) .onClick(TextActions.runCommand("/bring " + name))
.onHover(TextActions.showText(Text.of(FormatUtil.DIALOG, "/bring ", FormatUtil.OBJECT, name)))
3
KaloyanBogoslovov/Virtual-Trading
src/data/updating/DataUpdating.java
[ "public class Database {\n\n private static final String DBURL = \"jdbc:h2:~/test\";\n private static final String DBUSER = \"Kaloyan_Bogoslovov\";\n private static final String DBPASS = \"qwerty\";\n private static Connection connection;\n\n public static void connectingToDB() throws ClassNotFoundException, S...
import static java.util.concurrent.TimeUnit.SECONDS; import java.math.BigDecimal; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import database.Database; import logfile.LogFile; import yahoo.UpdateData; import yahoo.UpdateDataFromYahoo; import yahoo.YahooFinance;
package data.updating; public class DataUpdating { private BigDecimal zero = new BigDecimal(0); private int i = 0; private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); private BigDecimal liveProfit = new BigDecimal(0); public void dataUpdate() { final Runnable beeper = new Runnable() { public void run() { if (userLogedIn()) { try { Database.connectingToDB(); String[] companies = getCompanies(); System.out.println("companies"); if (companies.length != 0) {
LogFile.saveDataToLogFile(
1
feedzai/fos-core
fos-server/src/main/java/com/feedzai/fos/server/FosServer.java
[ "public class FosConfig {\n /**\n * The config fqn for factory name.\n */\n public static final String FACTORY_NAME = \"fos.factoryName\";\n /**\n * The config fqn for registry port.\n */\n public static final String REGISTRY_PORT = \"fos.registryPort\";\n /**\n * The config fqn f...
import java.rmi.RemoteException; import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; import java.rmi.server.UnicastRemoteObject; import com.feedzai.fos.api.config.FosConfig; import com.feedzai.fos.server.remote.api.IRemoteManager; import com.feedzai.fos.server.remote.api.RemoteScorer; import com.feedzai.fos.server.remote.impl.RemoteManager; import com.feedzai.fos.server.remote.impl.RemoteManagerFactory; import org.apache.commons.configuration.ConfigurationException; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
/* * $# * FOS Server *   * Copyright (C) 2013 Feedzai SA *   * This software is licensed under the Apache License, Version 2.0 (the "Apache License") or the GNU * Lesser General Public License version 3 (the "GPL License"). You may choose either license to govern * your use of this software only upon the condition that you accept all of the terms of either the Apache * License or the LGPL License. * * You may obtain a copy of the Apache License and the LGPL License at: * * http://www.apache.org/licenses/LICENSE-2.0.txt * http://www.gnu.org/licenses/lgpl-3.0.txt * * Unless required by applicable law or agreed to in writing, software distributed under the Apache License * or the LGPL License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the Apache License and the LGPL License for the specific language governing * permissions and limitations under the Apache License and the LGPL License. * #$ */ package com.feedzai.fos.server; /** * Server that registers the classification implementation in the RMI registry. * * @author Marco Jorge (marco.jorge@feedzai.com) */ public class FosServer { private final static Logger logger = LoggerFactory.getLogger(FosServer.class); private FosConfig parameters; private final RemoteManager remoteManager; private Registry registry; /** * Creates a new server with the given parameters. * <p/> Creates a new @{RemoteManager} from the configuration file defined in the parameters. * * @param parameters a list of parameters * @throws ConfigurationException when the configuration file specified in the parameters cannot be open/read. */ public FosServer(FosConfig parameters) throws ConfigurationException { this.parameters = parameters; this.remoteManager = new RemoteManagerFactory().createManager(parameters); } /** * Binds the Manager and Scorer to the RMI Registry. * <p/> Also registers a shutdown hook for closing and removing the items from the registry. * * @throws RemoteException when binding was not possible. */ public void bind() throws RemoteException { registry = LocateRegistry.getRegistry(parameters.getRegistryPort());
registry.rebind(IRemoteManager.class.getSimpleName(), UnicastRemoteObject.exportObject(remoteManager, parameters.getRegistryPort()));
1
free46000/MultiItem
demo/src/main/java/com/freelib/multiitem/demo/MultiItemActivity.java
[ "public class BaseItemAdapter extends RecyclerView.Adapter<BaseViewHolder> {\n private List<Object> dataItems = new ArrayList<>();\n private List<Object> headItems = new ArrayList<>();\n private List<Object> footItems = new ArrayList<>();\n private ItemTypeManager itemTypeManager;\n private LoadMoreM...
import android.content.Context; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import com.freelib.multiitem.adapter.BaseItemAdapter; import com.freelib.multiitem.demo.bean.ImageBean; import com.freelib.multiitem.demo.bean.ImageTextBean; import com.freelib.multiitem.demo.bean.TextBean; import com.freelib.multiitem.demo.viewholder.ImageAndTextManager; import com.freelib.multiitem.demo.viewholder.ImageViewManager; import com.freelib.multiitem.demo.viewholder.TextViewManager; import org.androidannotations.annotations.AfterViews; import org.androidannotations.annotations.EActivity; import org.androidannotations.annotations.ViewById; import java.util.ArrayList; import java.util.List;
package com.freelib.multiitem.demo; @EActivity(R.layout.layout_recycler) public class MultiItemActivity extends AppCompatActivity { @ViewById(R.id.recyclerView) protected RecyclerView recyclerView; public static void startActivity(Context context) { MultiItemActivity_.intent(context).start(); } @AfterViews protected void initViews() { setTitle(R.string.multi_item_title); recyclerView.setLayoutManager(new LinearLayoutManager(this)); //初始化adapter
BaseItemAdapter adapter = new BaseItemAdapter();
0