blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
5
132
path
stringlengths
2
382
src_encoding
stringclasses
34 values
length_bytes
int64
9
3.8M
score
float64
1.5
4.94
int_score
int64
2
5
detected_licenses
listlengths
0
142
license_type
stringclasses
2 values
text
stringlengths
9
3.8M
download_success
bool
1 class
0719d14ddf6174028789a4803b9898ae4d1824be
Java
dixit-coder/september15
/Arrays/src/com/divesh/core/MaximumDifferenceBetweenTwoElements.java
UTF-8
781
3.75
4
[]
no_license
package com.divesh.core; public class MaximumDifferenceBetweenTwoElements { /** * Given an array arr[] of integers, find out the difference between any two * elements such that larger element appears after the smaller number in * arr[] */ int maxDiff(int arr[]) { int max = arr[0], min = arr[0], diff = Integer.MIN_VALUE; for (int i = 1; i < arr.length; i++) { if (arr[i] > max) { max = arr[i]; diff = max - min; } if (arr[i] < min) min = arr[i]; } return diff; } public static void main(String args[]) { int arr[] = { 7, 6, 5, 4, 3, 2 };//{ 2, 3, 10, 6, 4, 8, 1 };// {1, 2, 6, 80, 100}; MaximumDifferenceBetweenTwoElements twoElements = new MaximumDifferenceBetweenTwoElements(); System.out.println(twoElements.maxDiff(arr)); } }
true
25a716b818731d4779c26c7ebb72d8e49637f7f3
Java
miltomasz/BakingApp
/app/src/main/java/com/plumya/bakingapp/ui/list/RecipeStepsActivity.java
UTF-8
6,086
1.976563
2
[]
no_license
package com.plumya.bakingapp.ui.list; import android.appwidget.AppWidgetManager; import android.arch.lifecycle.Observer; import android.arch.lifecycle.ViewModelProviders; import android.content.ComponentName; import android.content.Intent; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.annotation.Nullable; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import com.plumya.bakingapp.R; import com.plumya.bakingapp.data.model.Recipe; import com.plumya.bakingapp.data.model.Step; import com.plumya.bakingapp.data.widget.IngredientsWidgetProvider; import com.plumya.bakingapp.di.Injector; import com.plumya.bakingapp.ui.fragments.RecipeStepDetailViewFragment; import com.plumya.bakingapp.ui.fragments.RecipeStepsFragment; import com.plumya.bakingapp.ui.view.RecipeStepDetailViewActivity; import java.util.ArrayList; import java.util.List; /** * Created by miltomasz on 18/04/18. */ public class RecipeStepsActivity extends AppCompatActivity implements RecipeStepsFragment.OnItemClickListener { public static final String RECIPE_ID = "recipeId"; public static final int FIRST_ITEM = 0; public static final int STEP_NOT_FOUND = -1; private static final String LOG_TAG = RecipeStepsActivity.class.getSimpleName(); private boolean twoPane; private class RecipeObserver implements Observer<Recipe> { private final Bundle savedInstanceState; public RecipeObserver(Bundle savedInstanceState) { this.savedInstanceState = savedInstanceState; } @Override public void onChanged(@Nullable Recipe recipe) { if (savedInstanceState == null) { getSupportFragmentManager() .beginTransaction() .add(R.id.recipe_instructions_fragment, createRecipeStepDetailViewFragment(getFirstStepId(recipe.steps), recipe.steps)) .commit(); } } } @Override protected void onCreate(@Nullable final Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_recipe_steps); final long recipeId = getIntent().getLongExtra(RECIPE_ID, -1L); if (savedInstanceState == null) { Bundle arguments = new Bundle(); arguments.putLong(RECIPE_ID, recipeId); RecipeStepsFragment recipeStepsFragment = new RecipeStepsFragment(); recipeStepsFragment.setArguments(arguments); getSupportFragmentManager() .beginTransaction() .add(R.id.recipe_steps_fragment, recipeStepsFragment) .commit(); } boolean isTablet = getResources().getBoolean(R.bool.tablet); if (isTablet) { // This LinearLayout will only initially exist in the two-pane tablet case twoPane = true; RecipeStepsViewModelFactory factory = Injector.provideRecipeStepsViewModelFactory(this.getApplicationContext()); RecipeStepsActivityViewModel viewModel = ViewModelProviders .of(this, factory).get(RecipeStepsActivityViewModel.class); viewModel.selectRecipeId(recipeId); viewModel.getRecipe().observe(this, new RecipeObserver(savedInstanceState)); } else { // No more actions needed twoPane = false; } } @Override public void onItemSelected(long stepId, List<Step> steps) { if (twoPane) { getSupportFragmentManager() .beginTransaction() .replace(R.id.recipe_instructions_fragment, createRecipeStepDetailViewFragment(stepId, steps)) .commit(); } else { Intent intent = new Intent(this, RecipeStepDetailViewActivity.class); intent.putExtra(RecipeStepDetailViewActivity.STEP_ID, stepId); intent.putExtra(RecipeStepDetailViewActivity.STEPS, (ArrayList<Step>) steps); startActivity(intent); } } @Override public void onAddToWidgetClick(String recipeName) { View rootView = getWindow().getDecorView().findViewById(android.R.id.content); addToWidget(rootView, recipeName); } public RecipeStepDetailViewFragment createRecipeStepDetailViewFragment(long stepId, List<Step> steps) { RecipeStepDetailViewFragment recipeStepDetailViewFragment = new RecipeStepDetailViewFragment(); Bundle arguments = new Bundle(); arguments.putLong(RecipeStepDetailViewFragment.STEP_ID, stepId); arguments.putSerializable(RecipeStepDetailViewFragment.STEPS, (ArrayList<Step>) steps); recipeStepDetailViewFragment.setArguments(arguments); return recipeStepDetailViewFragment; } private long getFirstStepId(List<Step> steps) { if (steps != null && steps.size() > 0) { return steps.get(FIRST_ITEM).id; } return STEP_NOT_FOUND; } private void addToWidget(View view, String recipeName) { Log.d(LOG_TAG, "Add Recipe to widget"); final long recipeId = getIntent().getLongExtra(RECIPE_ID, -1L); PreferenceManager .getDefaultSharedPreferences(this).edit().putLong(RECIPE_ID, recipeId) .apply(); Intent intent = new Intent(this, IngredientsWidgetProvider.class); intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE); int[] appWidgetIds = AppWidgetManager.getInstance(getApplication()) .getAppWidgetIds(new ComponentName(getApplication(), IngredientsWidgetProvider.class)); intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetIds); sendBroadcast(intent); String message = getString(R.string.added_to_widget, recipeName); Snackbar.make(view, message, Snackbar.LENGTH_LONG).show(); } }
true
6029b8fa8486c21630584e5d3908fb19e8a9d833
Java
jayramrout/Batch30
/CoreJava/src/basics/exceptionhandling/ude/WrongValueEnteredException.java
UTF-8
339
2.546875
3
[]
no_license
package basics.exceptionhandling.ude; /** * Created by jrout on 7/1/19. */ public class WrongValueEnteredException extends Exception { private String message; public WrongValueEnteredException(String message){ super(message); } @Override public String toString() { return super.toString(); } }
true
ffa949e4137a6533605e5ecd09fa3668eb892204
Java
arpit999/JsonParsingDemo
/app/src/main/java/com/production/hometech/jsonparsingdemo/fragment/GsonFragment.java
UTF-8
725
2.078125
2
[]
no_license
package com.production.hometech.jsonparsingdemo.fragment; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.production.hometech.jsonparsingdemo.R; /** * A simple {@link Fragment} subclass. */ public class GsonFragment extends Fragment { public GsonFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_gson, container, false); } }
true
13262fb4ee54dc634a81f16ac5b7379625357f94
Java
doasare/Algorithms-DataStructures_OOP
/week 2/Ex3Deconstructive.java
UTF-8
528
3.6875
4
[]
no_license
public class Ex3Deconstructive { //desconstructive times all numbers in array by 5 public static void main(String[] args) { int[] numbers = {7,11,13,8,5,10}; int[] b = new int[numbers.length]; b=changeOne(numbers,5); for(int i=0; i<b.length; i++) { System.out.println(b[i]); } } public static int [] changeOne(int[] y, int x) { for(int i=0; i<y.length; i++) { y[i]*=x; } return y; } }
true
58fd3fc92ca0dda0b03912e544bf4256e70ba84b
Java
edwin092/traffic-simulator
/TrafficSimulation/src/main/java/com/utcn/utils/TrafficSimulationUtil.java
UTF-8
4,940
3.25
3
[]
no_license
package com.utcn.utils; import com.utcn.models.Intersection; import com.utcn.view.TrafficSimulationView; import java.math.BigDecimal; import java.math.RoundingMode; import java.util.List; import java.util.Random; public class TrafficSimulationUtil { public static final double CONVERSION_UNIT = 2; // prevent this class from being instanced private TrafficSimulationUtil() { } /** * Convert a List of Integer to a new int[]. * * @param list the list of integers * @return the new int[] */ public static int[] convertList(List<Integer> list) { int[] x = new int[list.size()]; for (int i = 0; i < list.size(); i++) { x[i] = list.get(i); } return x; } /** * Convert a List of Integer to a new Integer[]. * * @param list the list of integers * @return the new Integer[] */ public static Integer[] convertListToIntegerList(List<Integer> list) { Integer[] x = new Integer[list.size()]; for (int i = 0; i < list.size(); i++) { x[i] = list.get(i); } return x; } /** * Returns a random int from given (min, max) interval. * * @param min min * @param max max * @return random int */ public static int randInt(int min, int max) { Random rand = new Random(); return rand.nextInt((max - min) + 1) + min; } /** * @param x1 * @param y1 * @param x2 * @param y2 * @return */ public static int distanceBetweenPoints(int x1, int y1, int x2, int y2) { return (int) Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)); } /** * Converts meters to pixels. * * @param x value in meters * @return value in pixels */ public static double convertMetersToPixels(double x) { return x / CONVERSION_UNIT; } /** * Converts pixels in meters. * * @param x value in pixels * @return value in meters */ public static double convertPixelsToMeters(double x) { return x * CONVERSION_UNIT; } /** * @param value * @param places * @return */ public static double round(double value, int places) { if (places < 0) throw new IllegalArgumentException(); BigDecimal bd = new BigDecimal(value); bd = bd.setScale(places, RoundingMode.HALF_UP); return bd.doubleValue(); } /** * @param x1 * @param y1 * @param x2 * @param y2 * @param currentDist * @return */ public static int[] getVehiclePosition(int x1, int y1, int x2, int y2, double currentDist) { int bigOrSmallX; int bigOrSmallY; if (x1 > x2) { // smaller bigOrSmallX = x2; } else { // bigger bigOrSmallX = -x2; } if (y1 > y2) { // smaller bigOrSmallY = y2; } else { // bigger bigOrSmallY = -y2; } double dx = Math.abs(x1 - x2); double dy = Math.abs(y1 - y2); double m = round(dy / dx, 2); double alpha = round(Math.atan(m), 2); double totalDist = distanceBetweenPoints(x1, y1, x2, y2); double dxN = round(Math.abs((totalDist - currentDist) * Math.cos(alpha)), 2); int xN = Math.abs((int) (bigOrSmallX + dxN)); double dyN = round(Math.abs((totalDist - currentDist) * Math.sin(alpha)), 2); int yN = Math.abs((int) (bigOrSmallY + dyN)); return new int[]{xN, yN}; } /** * @param view * @return */ public static SimulationGraph convertSimulaionEnvironmentToGraph(TrafficSimulationView view) { SimulationGraph simulationGraph = new SimulationGraph(); for (Intersection intersection : view.getIntersections()) { if (intersection.getSegmentNorthOut() != null) { simulationGraph.addEdge(intersection.getId(), intersection.getSegmentNorthOut().getIntersectionTo().getId()); } if (intersection.getSegmentSouthOut() != null) { simulationGraph.addEdge(intersection.getId(), intersection.getSegmentSouthOut().getIntersectionTo().getId()); } if (intersection.getSegmentEastOut() != null) { simulationGraph.addEdge(intersection.getId(), intersection.getSegmentEastOut().getIntersectionTo().getId()); } if (intersection.getSegmentVestOut() != null) { simulationGraph.addEdge(intersection.getId(), intersection.getSegmentVestOut().getIntersectionTo().getId()); } } return simulationGraph; } }
true
bc4f764ab9c9a20363c67e7be63fa3fe5e7bbdad
Java
Giova262/Algoritmos-III---Yugioh
/src/fiuba/modelo/efectos/efectoTrampa/EfectoTrampa.java
UTF-8
290
1.546875
2
[]
no_license
package fiuba.modelo.efectos.efectoTrampa; import fiuba.modelo.Jugador; import fiuba.modelo.cartas.CartaMonstruo; import fiuba.modelo.efectos.Efecto; public interface EfectoTrampa extends Efecto { public boolean activar(CartaMonstruo carta1, CartaMonstruo carta2, Jugador oponente); }
true
c08f71fe97142f766e391cf893ca694dc91c2780
Java
hovertclman/springSS
/src/main/java/com/kgc/utils/Dao.java
UTF-8
743
2.734375
3
[]
no_license
package com.kgc.utils; import java.util.List; public interface Dao<T> { /** * 功能 -完成增加 * @param t 将要增加的数据封装到t这个对象中 * @return */ public int insert(T t); /** * 完成修改 * @param t * @return */ public int update(T t); /** * 根据id来删除 * @param id * @return */ public int delete(int id); /** * 根据id来查询 * @param id * @return 将返回的记录实例化成对象 */ public T findById(int id); /**查询表中的所有记录,将每一条记录实例化成对象,再每个对象放到List中返回 * * @return */ public List<T> findAll(); }
true
c7091ef3abf7ae062e600e04ea8702786efb2d68
Java
freezaee/NetDiscovery
/extra/src/main/java/com/cv4j/netdiscovery/extra/queue/redis/RedisPriorityQueue.java
UTF-8
3,091
2.28125
2
[ "Apache-2.0" ]
permissive
package com.cv4j.netdiscovery.extra.queue.redis; import com.alibaba.fastjson.JSON; import com.cv4j.netdiscovery.core.domain.Request; import com.safframework.tony.common.utils.Preconditions; import org.apache.commons.codec.digest.DigestUtils; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import java.util.Set; /** * Created by tony on 2018/6/19. */ public class RedisPriorityQueue extends RedisQueue { private static final String ZSET_PREFIX = "zset_"; private static final String QUEUE_PREFIX = "queue_"; private static final String NORMAL_SUFFIX = "_normal"; private static final String PRIORITY_SUFFIX = "_priority"; public RedisPriorityQueue(String host) { super(host); } public RedisPriorityQueue(JedisPool pool) { super(pool); } @Override protected void pushWhenNoDuplicate(Request request) { Jedis jedis = pool.getResource(); try { if (request.getPriority() > 0) jedis.zadd(getZsetPriorityKey(request.getSpiderName()), request.getPriority(), request.getUrl()); else jedis.lpush(getQueueNormalKey(request.getSpiderName()), request.getUrl()); setExtrasInItem(jedis, request); } finally { pool.returnResource(jedis); } } @Override public synchronized Request poll(String spiderName) { Jedis jedis = pool.getResource(); try { String url = getRequest(jedis, spiderName); if (Preconditions.isBlank(url)) return null; return getExtrasInItem(jedis, url, spiderName); } finally { pool.returnResource(jedis); } } private String getRequest(Jedis jedis, String spiderName) { String url; Set<String> urls = jedis.zrevrange(getZsetPriorityKey(spiderName), 0, 0); if (urls.isEmpty()) { url = jedis.lpop(getQueueNormalKey(spiderName)); } else { url = urls.toArray(new String[0])[0]; jedis.zrem(getZsetPriorityKey(spiderName), url); } return url; } private String getZsetPriorityKey(String spiderName) { return ZSET_PREFIX + spiderName + PRIORITY_SUFFIX; } private String getQueueNormalKey(String spiderName) { return QUEUE_PREFIX + spiderName + NORMAL_SUFFIX; } private void setExtrasInItem(Jedis jedis, Request request) { if (request.getExtras() != null) { String field = DigestUtils.shaHex(request.getUrl()); String value = JSON.toJSONString(request); jedis.hset(getItemKey(request), field, value); } } private Request getExtrasInItem(Jedis jedis, String url, String spiderName) { String key = getItemKey(url); String field = DigestUtils.shaHex(url); byte[] bytes = jedis.hget(key.getBytes(), field.getBytes()); if (bytes != null) return JSON.parseObject(new String(bytes), Request.class); return new Request(url); } }
true
1aa3da03a29a0d518c7530713a13e5024091137a
Java
braveFeng/xian
/xian-httpclient/src/main/java/info/xiancloud/plugin/httpclient/apache_http/pool/IdlePoolMonitor.java
UTF-8
1,089
2.546875
3
[ "Apache-2.0" ]
permissive
package info.xiancloud.plugin.httpclient.apache_http.pool; import java.util.concurrent.TimeUnit; import org.apache.http.conn.HttpClientConnectionManager; import info.xiancloud.plugin.thread_pool.ThreadPoolManager; import info.xiancloud.plugin.util.LOG; public class IdlePoolMonitor { private final static long IDLETIME = 5000;// 多久检查一次 private final static int CLOSEEXPIRE = 30; // 空闲时间超过30秒就回收 private static HttpClientConnectionManager pool; public static IdlePoolMonitor build(HttpClientConnectionManager connMgr) { pool = connMgr; return new IdlePoolMonitor(); } public void monitor() { if (pool == null) throw new IllegalArgumentException("apache_httpclient连接池不能为空---"); ThreadPoolManager.scheduleAtFixedRate(new Runnable() { @Override public void run() { try { pool.closeExpiredConnections(); pool.closeIdleConnections(CLOSEEXPIRE, TimeUnit.SECONDS); } catch (Exception e) { LOG.error("apache_httpclient连接池长连接定时回收出错 : " + e); } } }, IDLETIME); } }
true
8d1846cca2f33a3d3edf240ad53fdc3616101ba1
Java
newbigTech/hryj-mall
/server/declare-server/src/main/java/com/hryj/entity/bo/declare/CebPayment.java
UTF-8
736
1.914063
2
[]
no_license
package com.hryj.entity.bo.declare; import com.baomidou.mybatisplus.annotations.TableField; import com.baomidou.mybatisplus.annotations.TableName; import lombok.Data; /** * @author 白飞 * @className: CebPayment * @description: * @create 2018/9/26 15:14 **/ @Data @TableName("dec_ceb_payment") public class CebPayment extends BaseEntity{ /** 支付企业备案代码 */ @TableField(value = "pay_code") private String payCode; /** 电商企业备案代码 */ @TableField(value = "ebc_code") private String ebcCode; /** 支付企业备案名称 */ @TableField(value = "pay_name") private String payName; /** 支付编号 */ @TableField(value = "pay_no") private String payNo; }
true
498599b941418b63a5e1f77414d0b6cb815aaa35
Java
j4cquesM/usine-sim
/GestionStock/Application/exception/NonExistantException.java
UTF-8
262
2.546875
3
[]
no_license
package exception; import models.*; import models.Element.Element; /** * * @author claude * */ public class NonExistantException extends Exception { public NonExistantException(Element e) { super("L'element " +e.getNom()+" n'existe pas en stock"); } }
true
867958e62e76f66584ec07362d099f871449b202
Java
kkzfl22/learing
/refactoring/src/test/java/com/liujun/legacy/code/parttwo/order209/notaddtest/param/constructparam/news/TestIndustrialFacility.java
UTF-8
947
2.453125
2
[]
no_license
package com.liujun.legacy.code.parttwo.order209.notaddtest.param.constructparam.news; import org.junit.jupiter.api.Test; import com.liujun.legacy.code.parttwo.order209.notaddtest.param.constructparam.base.Facility; import com.liujun.legacy.code.parttwo.order209.notaddtest.param.constructparam.base.IndustrialFacility; import com.liujun.legacy.code.parttwo.order209.notaddtest.param.constructparam.base.Permit; import com.liujun.legacy.code.parttwo.order209.notaddtest.param.constructparam.base.PermitViolation; /** * @author liujun * @version 0.0.1 */ public class TestIndustrialFacility { class AlwaysValidPermit extends Permit { public AlwaysValidPermit(String userName) { super(userName); } @Override public void validate() {} } @Test public void testValid() throws PermitViolation { Facility instance = new IndustrialFacility(1, "feifei", new AlwaysValidPermit("name")); instance.run(); } }
true
12da87a053fe2810584c38801749e37b45d9d487
Java
eetijain/otp-android
/src/in/aotp/OTPActivity.java
UTF-8
4,538
2.09375
2
[]
no_license
/* * One Time Password, for use with S/KEY logins. */ package in.aotp; import in.aotp.R; import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.view.MenuInflater; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.RadioGroup; import android.widget.TextView; /** * The main activity. * * TODO: Saved state, * TODO: Forget password. */ public class OTPActivity extends Activity implements OnClickListener { static final String SAVED_RESP_KEY = "otp_resp"; private TextView response_text; private TextView v_pass, v_seq, v_seed; private RadioGroup v_alg; private OTPParameters params; private String otp_resp; public OTPActivity() { params = new OTPParameters(); } private String computeResponse(OTPParameters params) throws Exception { Otp otp = new Otp(params); otp.calc(); otp_resp = new String(otp.toString()); return otp_resp; } public void restoreUserParams(OTPParameters p) { v_pass.setText(p.pass); v_alg.check(p.alg == Otp.MD5 ? R.id.otp_md5 : R.id.otp_md4); v_seq.setText(null); v_seed.setText(p.seed); } public void setUserParams(OTPParameters p) throws OTPParametersException { p.set(v_pass.getText().toString(), v_seed.getText().toString(), v_alg.getCheckedRadioButtonId() == R.id.otp_md4 ? Otp.MD4 : Otp.MD5, v_seq.getText().toString()); } public void onOk(View v) { try { setUserParams(params); computeResponse(params); response_text.setTextAppearance(response_text.getContext(), R.style.otp_response_style); response_text.setText(otp_resp); } catch (OTPParametersException e) { response_text.setTextAppearance(response_text.getContext(), R.style.otp_response_error); if (e.messageId() != 0) response_text.setText(e.messageId()); } catch (Exception e) { response_text.setText("Fail"); } } private void onReset(View v) { try { params.clear(); restoreUserParams(params); response_text.setTextAppearance(response_text.getContext(), R.style.otp_response_style); response_text.setText(R.string.noresp); otp_resp = null; } catch (Exception e) { response_text.setText("Epic Fail"); } } /** Button click */ public void onClick(View v) { int vid = v.getId(); if (vid == R.id.otp_ok) onOk(v); if (vid == R.id.otp_reset) onReset(v); } public void onSaveInstanceState(Bundle state) { super.onSaveInstanceState(state); if (otp_resp != null) state.putString(SAVED_RESP_KEY, otp_resp); } public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.main_menu, menu); return true; } /** Called when the activity is first created. */ public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Button button; button = (Button) findViewById(R.id.otp_ok); button.setOnClickListener(this); button = (Button) findViewById(R.id.otp_reset); button.setOnClickListener(this); response_text = (TextView) findViewById(R.id.otp_resp); v_pass = (TextView) findViewById(R.id.otp_pass); v_seq = (TextView) findViewById(R.id.otp_seq); v_seed = (TextView) findViewById(R.id.otp_seed); v_alg = (RadioGroup) findViewById(R.id.otp_alg); if (savedInstanceState != null) { otp_resp = savedInstanceState.getString(SAVED_RESP_KEY); if (otp_resp != null) { response_text. setTextAppearance(response_text.getContext(), R.style.otp_response_style); response_text.setText(otp_resp); } } } }
true
b9ada0accd10d7be46fd7d9dd57719a37c6800fb
Java
goodbetterbest101/paceman
/core/src/com/pacman/game/PacmanGame.java
UTF-8
577
2.140625
2
[]
no_license
package com.pacman.game; //import com.badlogic.gdx.ApplicationAdapter; //import com.badlogic.gdx.Gdx; //import com.badlogic.gdx.graphics.GL20; //import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.Game; public class PacmanGame extends Game { public SpriteBatch batch; //Texture img; @Override public void create () { batch = new SpriteBatch(); setScreen(new GameScreen(this)); } @Override public void render () { super.render(); } @Override public void dispose () { batch.dispose(); } }
true
dc64ae8ba4acc9141f8e0a2fb75f1cd6b1afff6f
Java
wubbleworld/wubble-world
/src/edu/isi/wubble/jgn/sheep/sidekick/Lexicon.java
UTF-8
649
2.5
2
[ "MIT" ]
permissive
package edu.isi.wubble.jgn.sheep.sidekick; import java.util.HashMap; import edu.isi.wubble.physics.entity.Entity; public class Lexicon { private HashMap<Entity,String> _nameMap = new HashMap<Entity,String>(); private HashMap<String,String> _classMap = new HashMap<String,String>(); public void processObjectNaming(Entity e, String name) { _nameMap.put(e, name); } public String getObjectName(Entity e) { return _nameMap.get(e); } public void processTypeNaming(Entity e, String name) { _classMap.put(e.getClass().getName(), name); } public String getTypeName(Entity e) { return _classMap.get(e.getClass().getName()); } }
true
b5c6a22c19533789e2010381a91247eb46202813
Java
ArtZoick/Spring
/day02/day02_eesy_01anno_ioc/src/main/java/top/zoick/dao/impl/AccountDaoImpl2.java
UTF-8
440
2.015625
2
[]
no_license
package top.zoick.dao.impl; import org.springframework.stereotype.Repository; import top.zoick.dao.IAccountDao; /** * 账户的持久层实现类 * @author zoick * @date 2019/7/28 14:50 */ @Repository("accountDao2") public class AccountDaoImpl2 implements IAccountDao { /** * 模拟保存账户 */ public void saveAccount() { System.out.println("Baocunle zhang hu222222222222"); } }
true
43ba6da244a7e43eec2a4c9a2b47f3b4fc7b51ad
Java
itowne/iaf-app
/iaf-war/src/main/java/newland/iaf/backstage/schedule/impl/LoanOrdTraceSchedule.java
UTF-8
2,342
2.046875
2
[]
no_license
package newland.iaf.backstage.schedule.impl; import java.util.Date; import java.util.List; import javax.annotation.Resource; import newland.iaf.backstage.schedule.ScheduleTaskImpl; import newland.iaf.base.model.LoanOrd; import newland.iaf.base.model.condition.LoanOrdCondition; import newland.iaf.base.model.dict.OrdStat; import newland.iaf.base.service.LoanOrdService; import newland.iaf.base.service.LoanOrdTrackService; import newland.iaf.base.service.impl.LoanOrdTrackServiceImpl; import org.apache.commons.collections.CollectionUtils; import org.hibernate.StaleObjectStateException; import org.ohuyo.commons.query.criterion.Page; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; @Service("schedule.loanOrdTrackSchedule") public class LoanOrdTraceSchedule extends ScheduleTaskImpl { @Resource(name = "loanOrdTrackService") private LoanOrdTrackService loanOrdTrackService; @Resource(name = "loanOrdService") private LoanOrdService loanOrdService; private Logger logger = LoggerFactory.getLogger(LoanOrdTraceSchedule.class); public LoanOrdTraceSchedule() { super("loarOrdSchedule"); } @Override protected void runImpl(Date date) throws Throwable { Page page = new Page(); page.setCapacity(100);// 设置每页显示数 page.setPageOffset(0); LoanOrdCondition cond = new LoanOrdCondition(); cond.setLeStat(OrdStat.PAID_UP_LOAN); for (;;) { List<LoanOrd> list = this.loanOrdService.queryOrdByCon(cond, page); if (CollectionUtils.isNotEmpty(list)) { for (LoanOrd ord : list) { try { try { this.loanOrdTrackService.trackLoanOrdExpire(ord); } catch (StaleObjectStateException e) { ord = this.loanOrdService.queryLoanOrdById(ord .getIloanOrd()); this.loanOrdTrackService.trackLoanOrdExpire(ord); } try { this.loanOrdTrackService.trackOrdAndPlanStat(ord); } catch (StaleObjectStateException e) { ord = this.loanOrdService.queryLoanOrdById(ord .getIloanOrd()); this.loanOrdTrackService.trackOrdAndPlanStat(ord); } } catch (Exception e) { logger.error(e.getMessage(), e); } } } else { break; } page.setPageOffset(page.getPageOffset() + 1); } } }
true
49b78ca7dd59e6be92f28022ef0b22c8800a3995
Java
rominasorayacanete/TP0
/src/main/java/viewModels/HistorialViewModel.java
UTF-8
435
1.992188
2
[]
no_license
package viewModels; import java.util.List; import org.uqbar.commons.utils.Observable; import domain.Fila; import domain.LectorModel; @Observable public class HistorialViewModel { private LectorModel modelo; public LectorModel getModelo(){ return modelo; } public void setModelo(LectorModel model){ modelo = model; } public List<Fila> getFilas(){ return modelo.obtenerFilas(); } }
true
b2742f595819d2de9012232fd15290f5e420adde
Java
rafaferruz/gq1x2
/src/java/com/gq2/domain/Team.java
UTF-8
2,244
2.8125
3
[]
no_license
package com.gq2.domain; import java.io.Serializable; import java.util.Comparator; /** * Define un objeto Team (Equipo) * * @author RAFAEL FERRUZ */ public class Team implements Serializable { protected int teaId; protected String teaCode; protected int teaStatus; protected String teaName; protected int teaRating; protected String teaEquivalentNames=""; public Team() { } public Team(int teaId) { this.teaId = teaId; } public String getTeaCode() { return teaCode; } public void setTeaCode(String teaCode) { this.teaCode = teaCode; } public int getTeaStatus() { return teaStatus; } public void setTeaStatus(int teaStatus) { this.teaStatus = teaStatus; } public int getTeaId() { return teaId; } public void setTeaId(int teaId) { this.teaId = teaId; } public String getTeaName() { return teaName; } public void setTeaName(String teaName) { this.teaName = teaName; } public int getTeaRating() { return teaRating; } public void setTeaRating(int teaRating) { this.teaRating = teaRating; } public String getTeaEquivalentNames() { return teaEquivalentNames; } public void setTeaEquivalentNames(String teaEquivalentNames) { this.teaEquivalentNames = teaEquivalentNames; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Team other = (Team) obj; if (this.teaId != other.teaId && (this.teaId == 0 || this.teaId != other.teaId)) { return false; } if (!this.teaCode.equals(other.teaCode) && (this.teaCode == null || !this.teaCode.equals(other.teaCode))) { return false; } return true; } @Override public int hashCode() { int hash = 5; hash = 83 * hash + (this.teaCode != null ? this.teaCode.hashCode() : 0); return hash; } /** * Comparador que ordena por la propiedad teaName de cada Team. */ public static Comparator<Team> getNameComparator() { return new Comparator<Team>() { @Override public int compare(Team c1, Team c2) { return c1.getTeaName().compareTo(c2.getTeaName()); } }; } }
true
fb63c60de0f2f9051f6c110b44ae7848f5ba6265
Java
vivek437/LeetCode
/String/check-if-the-sentence-is-pangram.java
UTF-8
473
2.640625
3
[]
no_license
class Solution { public boolean checkIfPangram(String s) { int a[] =new int[26]; int l = s.length(); int c =0; for(int i=0;i<l;i++){ char ch = s.charAt(i); int p = (int)ch; p = p%97; if(a[p] == 0){ a[p] = l; c++; } } if(c==26) return true; else return false; } }
true
318ec0a2194f889a075b04beba6fd6361c98ad13
Java
JeffersonCardenas/TP
/src/tp/pr5/instructions/MoveInstruction.java
UTF-8
1,932
3.375
3
[]
no_license
package tp.pr5.instructions; import tp.pr5.NavigationModule; import tp.pr5.RobotEngine; import tp.pr5.instructions.exceptions.InstructionExecutionException; import tp.pr5.instructions.exceptions.WrongInstructionFormatException; import tp.pr5.items.ItemContainer; /** * * @author Jefferson Cárdenas & Marco Antonio Palacios * Su ejecucion mueve el robot desde un lugar al siguiente en la direccion actual, esta instruccion * funciona si el usuario escribe MOVE o MOVER * */ public class MoveInstruction implements Instruction{ private ItemContainer theInventory; private NavigationModule theNavigation; private RobotEngine theEngine; /** * Constructora por defecto */ public MoveInstruction(){} /** * Parsea el string devolviendo una instancia de MoveInstruction o lanzando WrongInstructionFormatException */ public Instruction parse (String cad) throws WrongInstructionFormatException{ if (cad.equalsIgnoreCase("MOVE") || cad.equalsIgnoreCase("MOVER")) return new MoveInstruction(); else throw new WrongInstructionFormatException(); } /** * Devuelve una descripcion de la sintaxis de la instruccion */ public String getHelp(){ return (" MOVE|MOVER"); } /** * Configura el contexto actual, es decir, el robot engine y navigation module * @param engine: robot engine * @param navigation: la informacion sobre el juego * @param robotContainer: el inventario del robot * */ public void configureContext(RobotEngine engine,NavigationModule navigation,ItemContainer robotContainer){ this.theEngine = engine; this.theNavigation = navigation; this.theInventory = robotContainer; } /** * Mueve del lugar actual al siguiente en la direccion actual, la calle debe estar abierta para * poder realizar el movimiento */ public void execute() throws InstructionExecutionException{ this.theNavigation.move(); this.theEngine.addFuel(-5); this.theEngine.informaObservadorRobot(); } }
true
6ff633ecdb573d57c8af1412ecb5d4d7fe70213f
Java
guestlinelabs/ApplicationInsights-Java
/web/src/main/java/com/microsoft/applicationinsights/web/internal/correlation/TelemetryCorrelationUtils.java
UTF-8
15,638
1.703125
2
[ "MIT" ]
permissive
/* * ApplicationInsights-Java * Copyright (c) Microsoft Corporation * All rights reserved. * * MIT License * 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 com.microsoft.applicationinsights.web.internal.correlation; import com.microsoft.applicationinsights.TelemetryConfiguration; import com.microsoft.applicationinsights.internal.logger.InternalLogger; import com.microsoft.applicationinsights.telemetry.RequestTelemetry; import com.microsoft.applicationinsights.web.internal.RequestTelemetryContext; import com.microsoft.applicationinsights.web.internal.ThreadContext; import org.apache.commons.lang3.exception.ExceptionUtils; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; import java.util.UUID; import java.util.concurrent.ThreadLocalRandom; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class TelemetryCorrelationUtils { public static final String CORRELATION_HEADER_NAME = "Request-Id"; public static final String CORRELATION_CONTEXT_HEADER_NAME = "Correlation-Context"; public static final String REQUEST_CONTEXT_HEADER_NAME = "Request-Context"; public static final String REQUEST_CONTEXT_HEADER_APPID_KEY = "appId"; public static final String REQUEST_CONTEXT_HEADER_ROLENAME_KEY = "roleName"; public static final int REQUESTID_MAXLENGTH = 1024; private TelemetryCorrelationUtils() {} /** * Resolves correlation ID's by parsing well-known correlation headers in the request. * @param request The servlet request. * @param requestTelemetry The request telemetry to be populated with correlation ID's. */ public static void resolveCorrelation(HttpServletRequest request, HttpServletResponse response, RequestTelemetry requestTelemetry) { try { if (request == null) { InternalLogger.INSTANCE.error("Failed to resolve correlation. request is null."); return; } if (response == null) { InternalLogger.INSTANCE.error("Failed to resolve correlation. response is null."); return; } if (requestTelemetry == null) { InternalLogger.INSTANCE.error("Failed to resolve correlation. requestTelemetry is null."); return; } String rootId = null; String parentId = null; String currentId = null; String requestId = request.getHeader(CORRELATION_HEADER_NAME); if (requestId == null || requestId.isEmpty()) { // no incoming requestId, no parent. rootId = generateRootId(); currentId = '|' + rootId + '.'; } else { parentId = requestId; rootId = extractRootId(parentId); currentId = generateId(parentId); } requestTelemetry.setId(currentId); requestTelemetry.getContext().getOperation().setId(rootId); requestTelemetry.getContext().getOperation().setParentId(parentId); // let us resolve the context now. resolveCorrelationContext(request, requestTelemetry); //add the target appId for the response header addTargetAppIdForResponseHeader(response); } catch(Exception ex) { InternalLogger.INSTANCE.error("Failed to resolve correlation. Exception information: " + ex); InternalLogger.INSTANCE.trace("Stack trace generated is %s", ExceptionUtils.getStackTrace(ex)); } } /** * Generates a child Id for dependencies. Dependencies are children of requests and, therefore, their ID's * reflect this. The generated ID is based on the current request scope (stored in TLS). * @return The child Id. */ public static String generateChildDependencyId() { try { RequestTelemetryContext context = ThreadContext.getRequestTelemetryContext(); RequestTelemetry requestTelemetry = context.getHttpRequestTelemetry(); String parentId = requestTelemetry.getContext().getOperation().getParentId(); // if parentId is non-hierarchical, it means the incoming requestId // does not follow hierarchical convention, so we must not modify the children ID's. if (parentId != null && parentId.length() > 0 && !isHierarchicalId((parentId))) { return requestTelemetry.getContext().getOperation().getParentId(); } return requestTelemetry.getId() + context.incrementChildId() + "."; } catch (Exception ex) { InternalLogger.INSTANCE.error("Failed to generate child ID. Exception information: " + ex); InternalLogger.INSTANCE.trace("Stack trace generated is %s", ExceptionUtils.getStackTrace(ex)); } return null; } /** * Retrieves the currently stored correlation context from the request context. * @return The correlation context as a string. */ public static String retrieveCorrelationContext() { CorrelationContext context = ThreadContext.getRequestTelemetryContext().getCorrelationContext(); return context.toString(); } /** * Retrieves the appId (in correlation format) for the current active config's instrumentation key. */ public static String retrieveApplicationCorrelationId() { String instrumentationKey = TelemetryConfiguration.getActive().getInstrumentationKey(); String appId = InstrumentationKeyResolver.INSTANCE.resolveInstrumentationKey(instrumentationKey); //it's possible the appId returned is null (e.g. async task is still pending or has failed). In this case, just //return and let the next request resolve the ikey. if (appId == null) { InternalLogger.INSTANCE.trace("Application correlation Id could not be retrieved (e.g. task may be pending or failed)"); return ""; } return REQUEST_CONTEXT_HEADER_APPID_KEY + "=" + appId; } /** * Given a request context, it generates a new dependency target, possibly including the appId found in * the given Request-Context. * @param requestContext - the Request-Context header value * @return the dependency target */ public static String generateChildDependencyTarget(String requestContext) { if (requestContext == null || requestContext.isEmpty()) { InternalLogger.INSTANCE.trace("generateChildDependencyTarget: won't continue as requestContext is null or empty."); return ""; } String instrumentationKey = TelemetryConfiguration.getActive().getInstrumentationKey(); if (instrumentationKey == null || instrumentationKey.isEmpty()) { InternalLogger.INSTANCE.error("Failed to generate target correlation. InstrumentationKey is null or empty."); return ""; } String target = generateSourceTargetCorrelation(instrumentationKey, requestContext); if (target == null) { return ""; // we want an empty string instead of null so it plays nicer with bytecode injection } return target; } /** * Resolves the source of a request based on request header information and the appId of the current * component, which is retrieved via a query to the AppInsights service. * @param request The servlet request. * @param requestTelemetry The request telemetry in which source will be populated. * @param instrumentationKey The instrumentation key for the current component. */ public static void resolveRequestSource(HttpServletRequest request, RequestTelemetry requestTelemetry, String instrumentationKey) { try { if (request == null) { InternalLogger.INSTANCE.error("Failed to resolve correlation. request is null."); return; } if (requestTelemetry == null) { InternalLogger.INSTANCE.error("Failed to resolve correlation. requestTelemetry is null."); return; } if (requestTelemetry.getSource() != null) { InternalLogger.INSTANCE.trace("Skip resolving request source as it is already initialized."); return; } String requestContext = request.getHeader(REQUEST_CONTEXT_HEADER_NAME); if (requestContext == null || requestContext.isEmpty()) { InternalLogger.INSTANCE.info("Skip resolving request source as the following header was not found: " + REQUEST_CONTEXT_HEADER_NAME); return; } if (instrumentationKey == null || instrumentationKey.isEmpty()) { InternalLogger.INSTANCE.error("Failed to resolve correlation. InstrumentationKey is null or empty."); return; } String source = generateSourceTargetCorrelation(instrumentationKey, requestContext); requestTelemetry.setSource(source); } catch(Exception ex) { InternalLogger.INSTANCE.error("Failed to resolve request source. Exception information: " + ex); InternalLogger.INSTANCE.trace("Stack trace generated is %s", ExceptionUtils.getStackTrace(ex)); } } public static boolean isHierarchicalId(String id) { if (id == null || id.isEmpty()) { return false; } return id.charAt(0) == '|'; } /** * Extracts the correlation context information from the request headers and populates the request telemetry's * properties accordingly. It also saves the context in TLS for future use. * @param request The incoming request. * @param requestTelemetry The request telemetry item. */ private static void resolveCorrelationContext(HttpServletRequest request, RequestTelemetry requestTelemetry) { // resolve baggages (Correlation-Context) @SuppressWarnings("unchecked") Enumeration<String> baggages = request.getHeaders(CORRELATION_CONTEXT_HEADER_NAME); if (baggages == null) { InternalLogger.INSTANCE.warn("Could not access header information: " + CORRELATION_CONTEXT_HEADER_NAME); return; } CorrelationContext currentCorrelationContext = ThreadContext.getRequestTelemetryContext().getCorrelationContext(); while (baggages.hasMoreElements()) { String baggage = baggages.nextElement(); currentCorrelationContext.append(baggage); Map<String, String> propertyBag = getPropertyBag(baggage); currentCorrelationContext.getMappings().putAll(propertyBag); requestTelemetry.getProperties().putAll(propertyBag); } } /** * Adds a response header for the Request-Context. * @param response The servlet's response. */ private static void addTargetAppIdForResponseHeader(HttpServletResponse response) { if (response.containsHeader(REQUEST_CONTEXT_HEADER_NAME)) { return; } String appId = retrieveApplicationCorrelationId(); if (appId == null || appId.isEmpty()) { return; } response.addHeader(REQUEST_CONTEXT_HEADER_NAME, appId); } /** * Extracts the appId/roleName out of requestContext and compares it with the current appId. It then * generates the appropriate source or target. */ private static String generateSourceTargetCorrelation(String instrumentationKey, String requestContext) { String appId = getKeyValueHeaderValue(requestContext, REQUEST_CONTEXT_HEADER_APPID_KEY); String roleName = getKeyValueHeaderValue(requestContext, REQUEST_CONTEXT_HEADER_ROLENAME_KEY); if (appId == null && roleName == null) { return null; } String myAppId = InstrumentationKeyResolver.INSTANCE.resolveInstrumentationKey(instrumentationKey); //it's possible the appId returned is null (e.g. async task is still pending or has failed). In this case, just //return and let the next request resolve the ikey. if (myAppId == null) { InternalLogger.INSTANCE.trace("Could not generate source/target correlation as the appId could not be resolved (e.g. task may be pending or failed)"); return null; } String result = null; if (appId != null && !appId.equals(myAppId)) { result = appId; } if (roleName != null) { if (result != null) { result += " | roleName:" + roleName; } else { result = "roleName:" + roleName; } } return result; } /** * Extracts the value of a "Key-Value" type of header. For example, for a header with value: "foo=bar, name=joe", * we can extract "joe" with a call to this method passing the key "name". * @param headerFullValue The entire header value. * @param key They key for which to extract the value * @return The extracted value */ private static String getKeyValueHeaderValue(String headerFullValue, String key) { return getPropertyBag(headerFullValue).get(key); } private static Map<String, String> getPropertyBag(String baggage) { Map<String, String> result = new HashMap<String, String>(); String[] pairs = baggage.split(","); for (String pair : pairs) { String[] keyValuePair = pair.trim().split("="); if (keyValuePair.length == 2) { String key = keyValuePair[0].trim(); String value = keyValuePair[1].trim(); result.put(key, value); } } return result; } private static String extractRootId(String parentId) { // ported from .NET's System.Diagnostics.Activity.cs implementation: // https://github.com/dotnet/corefx/blob/master/src/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/Activity.cs int rootEnd = parentId.indexOf('.'); if (rootEnd < 0) { rootEnd = parentId.length(); } int rootStart = parentId.charAt(0) == '|' ? 1 : 0; return parentId.substring(rootStart, rootEnd); } private static String generateRootId() { UUID guid = UUID.randomUUID(); long least = guid.getLeastSignificantBits(); long most = guid.getMostSignificantBits(); return Long.toHexString(most) + Long.toHexString(least); } private static String generateId(String parentId) { String sanitizedParentId = sanitizeParentId(parentId); String suffix = generateSuffix(); //handle overflow if (sanitizedParentId.length() + suffix.length() > REQUESTID_MAXLENGTH) { return shortenId(sanitizedParentId, suffix); } return sanitizedParentId + suffix + "_"; } private static String shortenId(String parentId, String suffix) { // ported from .NET's System.Diagnostics.Activity.cs implementation: // https://github.com/dotnet/corefx/blob/master/src/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/Activity.cs int trimPosition = REQUESTID_MAXLENGTH - 9; // make room for suffix + delimiter while (trimPosition > 1) { if (parentId.charAt(trimPosition - 1) == '.' || parentId.charAt(trimPosition - 1) == '_') break; trimPosition--; } // parentId is not a valid requestId, so generate one. if (trimPosition == 1) { return "|" + generateRootId() + "."; } return parentId.substring(0, trimPosition) + suffix + '#'; } private static String sanitizeParentId(String parentId) { String result = parentId; if (!isHierarchicalId(parentId)) { result = "|" + result; } char lastChar = parentId.charAt(parentId.length() - 1); if (lastChar != '.' && lastChar != '_') { result = result + '.'; } return result; } private static String generateSuffix() { // using ThreadLocalRandom instead of Random to avoid multi-threaded contention which would // result in poor performance. int randomNumber = ThreadLocalRandom.current().nextInt(); return String.format("%08x", randomNumber); } }
true
28feea04e72b0f9a7f2fca73605a426f30b36a23
Java
RonitSawant/Student-Management-System-using-JDBC
/OptFrame.java
UTF-8
1,258
2.71875
3
[]
no_license
import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.io.*; class OptFrame extends JFrame { Container c; JButton btnAdd , btnView , btnUp , btnDel , btnLo ; OptFrame() { c = getContentPane(); c.setLayout(new FlowLayout()); btnAdd = new JButton("Add"); btnView = new JButton("View"); btnUp = new JButton("Update"); btnDel = new JButton("Delete"); btnLo = new JButton("Log Out"); c.add(btnAdd); c.add(btnView); c.add(btnUp); c.add(btnDel); c.add(btnLo); ActionListener a1 = (ae) -> { AddFrame a = new AddFrame(); dispose(); }; btnAdd.addActionListener(a1); //Add action listener ActionListener a2 = (ae) -> { System.exit(1); dispose(); }; btnLo.addActionListener(a2); //Logout action listener ActionListener a3 = (ae) -> { ViewFrame a = new ViewFrame(); dispose(); }; btnView.addActionListener(a3); //View action listener ActionListener a4 = (ae) -> { DelFrame a = new DelFrame(); dispose(); }; btnDel.addActionListener(a4); //Delete action listener ActionListener a5 = (ae) -> { UpdateFrame a = new UpdateFrame(); dispose(); }; btnUp.addActionListener(a5); //Update action listener setTitle("Options"); setSize(250,300); setLocationRelativeTo(null); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); } }
true
96d4a8a4307f8e3c38b021ee0a5c0ed282373e7f
Java
karmelosng/TheKsimulator3
/src/com/karmelos/ksimulator/view/swing/AboutPanel.java
UTF-8
8,944
2.359375
2
[]
no_license
package com.karmelos.ksimulator.view.swing; /** *AboutPanel: contains information on the name,version and contact information of the of application * * @author Adebayo Adeniyan * */ public class AboutPanel extends javax.swing.JPanel { /** * Creates new form AboutPanel */ public AboutPanel() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); jLabel7 = new javax.swing.JLabel(); jLabel8 = new javax.swing.JLabel(); jScrollPane1 = new javax.swing.JScrollPane(); jTextPane1 = new javax.swing.JTextPane(); jPanel1.setMinimumSize(new java.awt.Dimension(400, 500)); jPanel1.setPreferredSize(new java.awt.Dimension(400, 500)); jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/karmelos/ksimulator/2ndbaricon/kicon big.png"))); // NOI18N jLabel2.setFont(new java.awt.Font("Trebuchet MS", 1, 20)); // NOI18N jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel2.setText("K Simulator"); jLabel3.setBackground(new java.awt.Color(255, 255, 255)); jLabel3.setFont(new java.awt.Font("Trebuchet MS", 1, 12)); // NOI18N jLabel3.setText("Version 1"); jLabel4.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N jLabel4.setText("Copyright (C) 2012-2013 Karmelos Nigeria Limited"); jLabel5.setFont(new java.awt.Font("Trebuchet MS", 1, 13)); // NOI18N jLabel5.setText("All Rights Reserved"); jLabel6.setFont(new java.awt.Font("Trebuchet MS", 1, 13)); // NOI18N jLabel6.setText("Tel: +2348083343115"); jLabel7.setFont(new java.awt.Font("Trebuchet MS", 1, 13)); // NOI18N jLabel7.setText("Web: http://www.karmelos.com"); jLabel8.setFont(new java.awt.Font("Trebuchet MS", 1, 13)); // NOI18N jLabel8.setText("E-mail: info@karmelos.com"); jTextPane1.setEditable(false); jTextPane1.setBackground(new java.awt.Color(240, 240, 240)); jTextPane1.setBorder(null); jTextPane1.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N jTextPane1.setText(" This computer program is protected by copyright law and international treaties.Unauthorized reproduction or distribution of this program, or any portion of it, may result in severe civil and criminal penalties, and will be prosecuted to the maximum extent possible under law."); jTextPane1.setAutoscrolls(false); jScrollPane1.setViewportView(jTextPane1); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 183, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE)) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(108, 108, 108) .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 146, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(139, 139, 139) .addComponent(jLabel1)) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(155, 155, 155) .addComponent(jLabel3)) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(88, 88, 88) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel7) .addComponent(jLabel8, javax.swing.GroupLayout.PREFERRED_SIZE, 205, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(115, 115, 115) .addComponent(jLabel5))) .addContainerGap(99, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 333, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(20, 20, 20)) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(20, 20, 20) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel3) .addGap(28, 28, 28) .addComponent(jLabel4) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel5) .addGap(18, 18, 18) .addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 15, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel7) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel8) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 400, Short.MAX_VALUE) .addContainerGap()) ); }// </editor-fold>//GEN-END:initComponents // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel8; private javax.swing.JPanel jPanel1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTextPane jTextPane1; // End of variables declaration//GEN-END:variables }
true
9a9a992b38534489f44656cdeef471b15c2765a7
Java
masiuchi/mt-data-api-client-java
/src/main/java/com/masiuchi/mtdataapi/APIRequest.java
UTF-8
2,711
2.59375
3
[ "MIT" ]
permissive
package com.masiuchi.mtdataapi; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.ProtocolException; import java.net.URL; import java.nio.charset.Charset; public class APIRequest { private Endpoint endpoint; public APIRequest(Endpoint endpoint) { this.endpoint = endpoint; } public String send(String accessToken, CallOptions options) throws IOException { URL uri = new URL(endpoint.requestUrl(options)); String json = ""; HttpURLConnection connection = null; try { connection = (HttpURLConnection) uri.openConnection(); connection.setRequestMethod(endpoint.verb.toString()); if (accessToken != null && !accessToken.isEmpty()) { connection.setRequestProperty("X-MT-Authorization", "MTAuth accessToken=" + accessToken); } if (endpoint.verb == Endpoint.Verb.POST || endpoint.verb == Endpoint.Verb.PUT) { String parameterString = ""; for (String key : options.keySet()) { if (!parameterString.isEmpty()) { parameterString += "&"; } parameterString += key + "=" + options.get(key); } PrintWriter printWriter = new PrintWriter(connection.getOutputStream()); printWriter.print(parameterString); printWriter.close(); } int code = connection.getResponseCode(); if (code != HttpURLConnection.HTTP_OK) { return ""; } InputStreamReader isr = new InputStreamReader(connection.getInputStream(), Charset.forName("UTF-8")); BufferedReader reader = null; try { reader = new BufferedReader(isr); String line; while ((line = reader.readLine()) != null) { json += line; } } catch (IOException e) { throw(e); } finally { try { if (reader != null) { reader.close(); } } catch (IOException e) { throw(e); } finally { isr.close(); } } } catch (IOException e) { throw (e); } finally { if (connection != null) { connection.disconnect(); } } return json; } }
true
1e9306ca915961f73dca7e3de1f370426acd1cd5
Java
Evoi95/ISPW_BSO_Project
/src/main/java/boundary/BoundaryReportPage.java
UTF-8
7,559
2.109375
2
[]
no_license
package boundary; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.net.URL; import java.sql.SQLException; import java.util.ResourceBundle; import controller.ControllerReportGiornali; import controller.ControllerReportLibri; import controller.ControllerReportRiviste; import controller.ControllerUserPage; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.layout.Pane; import javafx.stage.Stage; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.*; public class BoundaryReportPage implements Initializable { @FXML private Pane pane; @FXML private Label header; @FXML private Button totaleB; @FXML private Button libroB; @FXML private Button raccoltaB; @FXML private Button giornaliB; @FXML private Button buttonI; @FXML private Button rivisteB; @FXML private TextArea ta; private ControllerReportLibri cRL; private ControllerReportGiornali cRG; private ControllerReportRiviste cRR; private ControllerUserPage cUP; @FXML private void totale() throws SQLException { ta.clear(); try { cRL.generaReportLibri(); cRG.generaReportGiornali(); cRR.generaReportRiviste(); cUP.getUtenti(); } catch (IOException e) { } catch (SQLException e) { } BufferedReader readerL = null; try { readerL = new BufferedReader(new FileReader("ReportFinale\\riepilogoLibro.txt")); String line = readerL.readLine(); while(line!=null) { ta.appendText(line.concat("\n")); System.out.println(line); line = readerL.readLine(); } } catch (FileNotFoundException e) { } catch (IOException e) { } finally { try { readerL.close(); } catch (IOException e) { } } BufferedReader readerG = null; try { readerG = new BufferedReader(new FileReader("ReportFinale\\riepilogoGiornali.txt")); String line1 = readerG.readLine(); while(line1!=null) { ta.appendText(line1.concat("\n")); System.out.println(line1); line1 = readerG.readLine(); } } catch (IOException e) { } finally { try { readerG.close(); } catch (IOException e) { } } BufferedReader reader = null; try { reader = new BufferedReader(new FileReader("ReportFinale\\riepilogoRiviste.txt")); } catch (FileNotFoundException e) { } String line2 = null; try { line2 = reader.readLine(); while(line2!=null) { ta.appendText(line2.concat("\n")); System.out.println(line2); try { line2 = reader.readLine(); } catch (IOException e) { } } }catch(IOException e) { e.getCause(); } finally { try { reader.close(); } catch (IOException e) { } } BufferedReader reader3 = null; try { reader3 = new BufferedReader(new FileReader("ReportFinale\\riepilogoUtenti.txt")); } catch (FileNotFoundException e) { } String line3 = null; try { line3 = reader3.readLine(); while(line3!=null) { ta.appendText(line3.concat("\n")); System.out.println(line3); try { line3 = reader3.readLine(); } catch (IOException e) { } }}catch(IOException e) { e.getMessage(); } finally { try { reader3.close(); } catch (IOException e) { } } } @FXML private void reportLibri() throws IOException { ta.clear(); try { cRL.generaReportLibri(); } catch (IOException | SQLException e) { } BufferedReader reader = new BufferedReader(new FileReader("ReportFinale\\riepilogoLibro.txt")); String line = reader.readLine(); // ta.appendText("\tEcco il report dei libri\t \n"); while(line!=null) { ta.appendText(line.concat("\n")); System.out.println(line); line = reader.readLine(); } reader.close(); } @FXML private void raccolta() throws IOException, SQLException { ta.clear(); cRL.generaReportLibri(); cRG.generaReportGiornali(); cRR.generaReportRiviste(); BufferedReader readerL = new BufferedReader(new FileReader("ReportFinale\\riepilogoLibro.txt")); String line = readerL.readLine(); while(line!=null) { ta.appendText(line.concat("\n")); System.out.println(line); line = readerL.readLine(); } readerL.close(); BufferedReader readerG = new BufferedReader(new FileReader("ReportFinale\\riepilogoGiornali.txt")); String line1 = readerG.readLine(); while(line1!=null) { ta.appendText(line1.concat("\n")); System.out.println(line1); line1 = readerG.readLine(); } readerG.close(); BufferedReader reader = new BufferedReader(new FileReader("ReportFinale\\riepilogoRiviste.txt")); String line2 = reader.readLine(); while(line2!=null) { ta.appendText(line2.concat("\n")); System.out.println(line2); line2 = reader.readLine(); } reader.close(); } @FXML private void reportGiornali() throws IOException { ta.clear(); try { cRG.generaReportGiornali(); } catch (IOException|SQLException e) { } BufferedReader reader = new BufferedReader(new FileReader("ReportFinale\\riepilogoGiornali.txt")); String line = reader.readLine(); while(line!=null) { ta.appendText(line.concat("\n")); System.out.println(line); line = reader.readLine(); } reader.close(); } @FXML private void indietro() throws IOException { Stage stage; Parent root; stage = (Stage) buttonI.getScene().getWindow(); root = FXMLLoader.load(getClass().getResource("adminPage.fxml")); stage.setTitle("Benvenuto nella schermata del riepilogo dei libri"); // Parent root = FXMLLoader.load(getClass().getResource("compravendita.fxml")); Scene scene = new Scene(root); stage.setScene(scene); stage.show(); } @FXML private void reportRiviste() throws IOException { ta.clear(); try { cRR.generaReportRiviste(); } catch (IOException e) { } catch (SQLException e) { } BufferedReader readerR = new BufferedReader(new FileReader("ReportFinale\\riepilogoRiviste.txt")); String line2 = readerR.readLine(); while(line2!=null) { ta.appendText(line2.concat("\n")); System.out.println(line2); line2 = readerR.readLine(); } readerR.close(); } @Override public void initialize(URL location, ResourceBundle resources) { cRL=new ControllerReportLibri(); cRG=new ControllerReportGiornali(); cRR=new ControllerReportRiviste(); cUP=new ControllerUserPage(); } }
true
8ea777787495ff6880a8edc1a918951f8218510a
Java
SmartyMJ/Chapter7Exercises
/Chapter7HW/src/exercises4_14_16/Question16.java
UTF-8
894
3.484375
3
[]
no_license
//Class for Part B package exercises4_14_16; import java.util.Scanner; public class Question16 { //Method for Part A public static double getOrderTotal(int bp, int nb){ double totalPrice; if (bp + nb >= 12) totalPrice = 14.0 * (bp + nb); else if (bp + nb >= 3) totalPrice = 15.95 * (bp + nb); else if (bp == 1 && nb == 1) totalPrice = 37.95; else totalPrice = 18.95 * bp + 21.95 * nb; return totalPrice; } public static void main(String[] args){ Scanner orderInput = new Scanner(System.in); System.out.println("Enter the number of \"Be Prepared\" you would like to purchase: "); int bePrepared = orderInput.nextInt(); System.out.println("Enter the number of \"Next Best\" you would like to purchase: "); int nextBest = orderInput.nextInt(); System.out.println("The total cost is $" + getOrderTotal(bePrepared,nextBest) + "."); } }
true
8f21b0731b25db78c3abd7464f33f492c9059c3a
Java
iksflow/study-java
/src/training/stream/SequencialVsParallelExample.java
UHC
1,454
3.78125
4
[]
no_license
package training.stream; import java.util.Arrays; import java.util.List; public class SequencialVsParallelExample { // ó public static void work(int value) { try { Thread.sleep(10); } catch (InterruptedException e) { } } // ó public static long testSequencial(List<Integer> list) { long start = System.nanoTime(); list.stream().forEach(a -> work(a)); long end = System.nanoTime(); long runTime = end - start; return runTime; } // ó public static long testparallel(List<Integer> list) { long start = System.nanoTime(); list.stream().parallel().forEach(a -> work(a)); long end = System.nanoTime(); long runTime = end - start; return runTime; } public static void main(String[] args) { // TODO Auto-generated method stub // ҽ ÷ List<Integer> list = Arrays.asList(0, 1, 2, 3, 4, 5, 6, 7, 8, 9); // Ʈ óð ϱ long timeSequencial = testSequencial(list); // Ʈ óð ϱ long timeParallel = testparallel(list); System.out.println("S : " + timeSequencial); System.out.println("P : " + timeParallel); if (timeSequencial < timeParallel) { System.out.println(" ׽Ʈ : ó "); } else { System.out.println(" ׽Ʈ : ó "); } } }
true
098d20fbb87f28e426e0c5ceacef1b4241bc16e0
Java
julienmangeot/TDhibernate1
/src/dao/IFormationDao.java
UTF-8
267
1.976563
2
[]
no_license
package dao; import java.util.List; import model.Formation; import model.Lieu; public interface IFormationDao { public boolean createFormation(Formation formation); public List<Formation> showFormations(); public List<Formation> getFormations(Lieu lieu); }
true
40ad52c017381507d9e7564ebabf9736e4a38d2a
Java
UndCover/LoveMusic
/app/src/main/java/com/undcover/lovemusic/ui/presenter/LrcListPresenter.java
UTF-8
4,639
2.09375
2
[]
no_license
package com.undcover.lovemusic.ui.presenter; import android.media.MediaMetadataRetriever; import com.undcover.lovemusic.base.BaseMvpPresenter; import com.undcover.lovemusic.provider.LrcProvider; import com.undcover.lovemusic.provider.bean.SongSimpleInfo; import com.undcover.lovemusic.ui.model.LrcListViewModel; import com.undcover.lovemusic.ui.model.MediaInfoViewModel; import com.undcover.lovemusic.ui.view.LrcListActivity; import com.undcover.lovemusic.util.SmartLog; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.disposables.Disposable; import static android.os.Environment.getExternalStorageDirectory; public class LrcListPresenter extends BaseMvpPresenter<LrcListViewModel> { @Override public LrcListViewModel getViewModelInstance() { return new LrcListViewModel(); } public void getLrcList(String keyword) { LrcProvider.getInstance().search(keyword) .observeOn(AndroidSchedulers.mainThread()) .doOnSubscribe(disposable -> mViewModel.getLrcListItem().clear()) .subscribe(songs -> { mViewModel.addLrcListItem(songs); getEmitter().onNext(LrcListActivity.ACT_DATA_REFRESH); }); } public void getLrcList() { getLrcList(mViewModel.getKeyword()); } public void searchLrc(String songName) { LrcProvider.getInstance().search(getMediaInfo(songName)) .observeOn(AndroidSchedulers.mainThread()) .doOnSubscribe(disposable -> mViewModel.getLrcListItem().clear()) .subscribe(songs -> { mViewModel.addLrcListItem(songs); getEmitter().onNext(LrcListActivity.ACT_DATA_REFRESH); }); } private MediaInfoViewModel getMediaInfo(String songName) { MediaInfoViewModel mediaInfo = new MediaInfoViewModel(); MediaMetadataRetriever mmr = new MediaMetadataRetriever(); String str = getExternalStorageDirectory() + "/Download/" + songName; SmartLog.d(TAG, "str:" + str); try { mmr.setDataSource(str); String title = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE); // api level 10, 即从GB2.3.3开始有此功能 String album = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ALBUM); String mime = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_MIMETYPE); String artist = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST); String duration = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION); // 播放时长单位为毫秒 String bitrate = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_BITRATE); // 从api level 14才有,即从ICS4.0才有此功能 String date = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DATE); mediaInfo.setName(songName); mediaInfo.setTitle(title); mediaInfo.setAlbum(album); mediaInfo.setArtist(artist); mediaInfo.setDuration(duration); mediaInfo.setMime(mime); mediaInfo.setBitrate(bitrate); mediaInfo.setDate(date); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalStateException e) { e.printStackTrace(); } return mediaInfo; } public void fetchLrc(SongSimpleInfo lrc) { Disposable disposable = LrcProvider.getInstance().fetch(lrc) .observeOn(AndroidSchedulers.mainThread()) .subscribe(lrcBean -> { if (lrcBean == null) { return; } mViewModel.setLrc(lrcBean.getLrc()); mViewModel.setLrcTrans(lrcBean.getLrcTrans()); getEmitter().onNext(LrcListActivity.ACT_LRC_DIALOG); }); } public void fetchCombineLrc(SongSimpleInfo lrc) { Disposable disposable = LrcProvider.getInstance().fetchLyrics(lrc) .observeOn(AndroidSchedulers.mainThread()) .subscribe(lyricsBean -> { if (lyricsBean == null) { return; } String lrcString = lyricsBean.toString(); SmartLog.d(TAG, lrcString); mViewModel.setLrc(lrcString); mViewModel.setLrcTrans(null); getEmitter().onNext(LrcListActivity.ACT_LRC_DIALOG); }); } }
true
f89f43a4557ae9e6b83182cfb4a6921830d63aa4
Java
datteswararao/TicketServiceProject
/src/com/walmart/tickets/SeatReserveMain.java
UTF-8
7,905
2.984375
3
[]
no_license
package com.walmart.tickets; import java.util.ArrayList; import java.util.Hashtable; import java.util.Iterator; import java.util.List; import java.util.Random; import java.util.Scanner; import java.util.Timer; public class SeatReserveMain implements TicketService { final static int rows = 7, cols = 4; static char[][] seats = new char[rows][cols]; static Scanner scan = new Scanner(System.in); static Hashtable<Integer, SeatHold> seatHoldHash = new Hashtable<Integer, SeatHold>(); static Hashtable<Integer, String> seatReserved = new Hashtable<Integer, String>(); public SeatReserveMain() { // this will initialize the seats with row numbers and alphabet letters. char seatLetter = 'A'; for (int i = 0; i < seats.length; i++) { for (int j = 0; j < seats[i].length; j++) seats[i][j] = seatLetter++; seatLetter = 'A'; } } public static void main(String[] args) { SeatReserveMain q = new SeatReserveMain(); SeatHold seatHoldObj = null; displayMenu(); int menuChoice; menuChoice = scan.nextInt(); scan.nextLine(); while (menuChoice <= 3) { switch (menuChoice) { case 1: System.out.println("How many seats you want to hold?"); int seatHoldSize = scan.nextInt(); scan.nextLine(); if (seatHoldSize <= q.numSeatsAvailable()) { System.out.println("Please give us your emailID?"); String emailID = scan.next(); scan.nextLine(); seatHoldObj = q.findAndHoldSeats(seatHoldSize, emailID); Timer timer = new Timer(); timer.schedule(new CleanUpTask(seatHoldHash), 0, 1000); } q.printSeats(seats); displayMenu(); menuChoice = scan.nextInt(); break; case 2: System.out.println("Enter your SeatID:"); int seatHoldID = scan.nextInt(); scan.nextLine(); System.out.println("Enter your EmailID:"); String emailID = scan.next(); scan.nextLine(); boolean canConfirm = false; canConfirm = q.CheckSeatID(seatHoldID); String confirmationID = null; if (canConfirm) { System.out.println("You want to reserve tickets ? (Y/N) :"); String canReserve = scan.next(); if (canReserve.toUpperCase().equalsIgnoreCase("Y")) { confirmationID = q.reserveSeats(seatHoldID, emailID); System.out.println("Your seats were confirmed. Here is the confimation ID :" + confirmationID); } else q.cancelHoldSeats(seatHoldID); } q.printSeats(seats); displayMenu(); menuChoice = scan.nextInt(); break; case 3: System.out.println("Here are all available seating (H - HELD, R - RESERVED)!"); q.printSeats(seats); displayMenu(); menuChoice = scan.nextInt(); break; case 4: System.out.println("Have a wonderful day!"); System.exit(0); } } scan.close(); } public static void displayMenu() { System.out.println("Choose an Option: "); System.out.println("1. Hold Seats!"); System.out.println("2. Confirm Seat with SeatID!"); System.out.println("3. Display All Available Seats!"); System.out.println("4. Quit!"); } public boolean CheckSeatID(int seatHoldID) { SeatHold seatHoldObj = null; seatHoldObj = seatHoldHash.get(seatHoldID); if (null != seatHoldObj) { System.out.println(seatHoldObj.getseatHoldId()); List<String> seatsHeld = seatHoldObj.getSeats(); if (seatsHeld.size() != 0) { Iterator<String> itr = seatsHeld.iterator(); System.out.println("Here are the ticket, you held with the reservation :" + seatHoldID); while (itr.hasNext()) { System.out.print(itr.next() + " "); } return true; } // System.out.println(" "+seatHoldObj.getSeats()) }else { System.out.println("SeatHoldID " + seatHoldID+" doesn't exists anymore!!!"); } return false; } public void printSeats(char[][] seats) { for (int i = 0; i < rows; i++) { System.out.print((i + 1) + " "); for (int j = 0; j < cols; j++) System.out.print(seats[i][j] + " "); System.out.println(); } } public static boolean checkSeatAvailability(char[][] saSeatArray, int row, int col) { boolean available = false; if ((saSeatArray[row - 1][col - 1] == 'H') || (saSeatArray[row - 1][col - 1] == 'R')) { available = false; } else available = true; return available; } public static boolean isAllFull(char[][] saSeatArray) { for (int row = 0; row < rows; row++) { for (int col = 0; col < cols; col++) { if (saSeatArray[row][col] == 'H' || saSeatArray[row][col] == 'R') return true; else return false; } } return true; } @Override public int numSeatsAvailable() { int count = 0; for (int row = 0; row < rows; row++) { for (int col = 0; col < cols; col++) { if (seats[row][col] != 'H' || seats[row][col] != 'R') { count++; } } } return count; } @Override public SeatHold findAndHoldSeats(int numSeats, String customerEmail) { List<String> holdSeats = new ArrayList<String>(); System.out.println("Pick your seats to Hold: "); // Scanner scanHold = new Scanner(System.in); for (int seat = 0; seat < numSeats; seat++) { String seatHoldStr = null; boolean seatTakenAlready = false; // seat taken already by someone // else!!! do { seatHoldStr = scan.next(); scan.nextLine(); int row = Integer.parseInt(seatHoldStr.substring(0, 1)); char col = seatHoldStr.charAt(1); int col_int = -1; if (Character.isLowerCase(col)) col_int = (int) col - (int) 'a' + 1; if (Character.isUpperCase(col)) col_int = (int) col - (int) 'A' + 1; if (checkSeatAvailability(seats, row, col_int)) { seats[row - 1][col_int - 1] = 'H'; // temp hold holdSeats.add(seatHoldStr); System.out.println(" Seat " + row + col + " is held for you!!! "); seatTakenAlready = false; } else { System.out.println( "Sorry! The Seat " + row + col + " is NOT available. Please look up for another seat."); seatTakenAlready = true; } } while (seatTakenAlready); } // scanHold.close(); SeatHold seatHoldObj = new SeatHold(customerEmail, holdSeats); System.out.println("Use this Seat Held ID :" + seatHoldObj.getseatHoldId() + " for your final reservation!!!"); seatHoldHash.put(seatHoldObj.getseatHoldId(), seatHoldObj); return seatHoldObj; } @Override public String reserveSeats(int seatHoldId, String customerEmail) { SeatHold seatHoldObj = null; seatHoldObj = seatHoldHash.get(seatHoldId); List<String> seatsHeld = seatHoldObj.getSeats(); Iterator<String> itr = seatsHeld.iterator(); while (itr.hasNext()) { String selectedSeat = (String) itr.next(); int row = Integer.parseInt(selectedSeat.substring(0, 1)); char col = selectedSeat.charAt(1); int col_int = (int) col - (int) 'A' + 1; seats[row - 1][col_int - 1] = 'R'; } Random rand = new Random(); int randInt = rand.nextInt(1000000) + 1; seatReserved.put(randInt, customerEmail); return randInt + ""; } public void cancelHoldSeats(int seatHoldID) { SeatHold seatHoldObj = null; seatHoldObj = seatHoldHash.get(seatHoldID); List<String> seatsHeld = seatHoldObj.getSeats(); Iterator itr = seatsHeld.iterator(); while (itr.hasNext()) { String selectedSeat = (String) itr.next(); int row = Integer.parseInt(selectedSeat.substring(0, 1)); char col = selectedSeat.charAt(1); int col_int = (int) col - (int) 'A' + 1; seats[row - 1][col_int - 1] = (char) (col_int + 64); // REASSIGN BACK THE // ASCII // CHAR TO // THE // SEATING } seatHoldHash.remove(seatHoldID); } }
true
7cae0b7cfcdc48c8a5b9f30f52242ffdc3501ce0
Java
xingchen010/husky-service-v1.0.0
/husky-parent/husky-web/src.main.java/com/husky/app/App.java
UTF-8
942
1.984375
2
[]
no_license
package com.husky.app; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.web.support.SpringBootServletInitializer; import org.springframework.context.annotation.ComponentScan; @ComponentScan(basePackages = {"com.husky"}) @SpringBootApplication(exclude= {DataSourceAutoConfiguration.class,HibernateJpaAutoConfiguration.class}) public class App extends SpringBootServletInitializer{ @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) { return builder.sources(App.class); } public static void main(String[] args) { SpringApplication.run(App.class, args); } }
true
005cb07ba540a54fa4adf92cab81e3f493aa0624
Java
GaoYaNan0331/gao
/jiekouhuidiaologin/src/main/java/test/baway/com/jiekouhuidiaologin/V/MainActivity.java
UTF-8
2,103
2.234375
2
[]
no_license
package test.baway.com.jiekouhuidiaologin.V; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ProgressBar; import android.widget.Toast; import test.baway.com.jiekouhuidiaologin.P.LoginPresenterImpl; import test.baway.com.jiekouhuidiaologin.R; public class MainActivity extends AppCompatActivity implements LoginView, View.OnClickListener { private EditText mUsername; private EditText mPassword; private ProgressBar mProgress; private Button mBtn; private LoginPresenterImpl mPresenter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); } private void initView() { mUsername = (EditText) findViewById(R.id.username); mPassword = (EditText) findViewById(R.id.password); mProgress = (ProgressBar) findViewById(R.id.progress); mBtn = (Button) findViewById(R.id.btn); mBtn.setOnClickListener(this); mPresenter = new LoginPresenterImpl(this); } @Override protected void onDestroy() { mPresenter.onDestroy(); super.onDestroy(); } @Override public void showProgress() { mProgress.setVisibility(View.VISIBLE); } @Override public void hideProgress() { mProgress.setVisibility(View.GONE); } @Override public void setUsernameError() { mUsername.setError("用户名错误,请进行确认"); } @Override public void setPasswordError() { mPassword.setError("密码错误"); } @Override public void navigateToHome() { Toast.makeText(this, "login success", Toast.LENGTH_SHORT).show(); } @Override public void onClick(View view) { mPresenter.validateCredentials(mUsername.getText().toString(), mPassword.getText().toString()); // Toast.makeText(this, "点击登陆啦!", Toast.LENGTH_SHORT).show(); } }
true
c0487ca90fdb53c279c7ceedc8a51fbf8a4e25e0
Java
JosueSantos49/SISPROMAPER-Gestao-de-Projetos
/Tkcsapcd_cadastros/src/br/com/tkcsapcd/model/command/AtualizarMetricas.java
ISO-8859-1
1,786
2.421875
2
[]
no_license
/* Autor: Josu da Conceio Santos E-mail: conceicaojosue@outlook.com.br Ano: 2015 */ package br.com.tkcsapcd.model.command; import java.sql.SQLException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import br.com.tkcsapcd.model.bean.Metricas; import br.com.tkcsapcd.model.dao.InterfaceMetricasDAO; public class AtualizarMetricas implements InterfaceCommand { private InterfaceMetricasDAO metricasDAO; public AtualizarMetricas(InterfaceMetricasDAO metricasDAO) { super(); this.metricasDAO = metricasDAO; } @Override public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception { try { Metricas metricas = new Metricas(); metricas.setCodigo(Integer.valueOf(request.getParameter("codigo"))); metricas.setIdMetricas(request.getParameter("idMetricas")); metricas.setNomeMetrica(request.getParameter("nomeMetrica")); metricas.setIndiceMetrica(request.getParameter("indiceMetrica")); metricas.setValorReferenciaHora(request.getParameter("valorReferenciaHora")); metricas.setValorHoraCalculadaDia(request.getParameter("valorHoraCalculadaDia")); metricasDAO.atualizar(metricas); request.setAttribute("mensagem", "Mtrica: ("+metricas.getIdMetricas()+") atualizado com sucesso!"); } catch (SQLException e) { request.setAttribute("mensagem", "Problema com a atualizao: "+e.getMessage()); e.printStackTrace(); }catch (NumberFormatException e) { request.setAttribute("mensagem", "Valor invlido: "+e.getMessage()); } request.setAttribute("titulo", "Atualizao - Mtrica"); return "TkcsapcdController?cmd=consultarMetricas";//Pagina de Retorno (pagina consulta funcionario) } }
true
bf400f1b419610a41258654ace78789d9f1f648c
Java
sinhasonalkumar/corecs
/src/main/java/corecs/dynamicprogramming/ropecutting/RopeCuttingDPV2.java
UTF-8
1,053
3.4375
3
[]
no_license
package corecs.dynamicprogramming.ropecutting; public class RopeCuttingDPV2 { public static void main(String[] args) { System.out.println(max_product_from_cut_pieces(5)); } public static long max_product_from_cut_pieces(int n) { long[] dpTable = new long[n+1]; // Base Case Rope of length 0. Means no rope. So maxProduct = 1 dpTable[0] = 1; long maxProduct = Long.MIN_VALUE; long maxProductSoFar = Integer.MIN_VALUE; int choiceToCutRopeUntilLength; for (int curRopeLength = 1; curRopeLength <= n; curRopeLength++) { // Because rope has to be cut at least once if(curRopeLength == n) { choiceToCutRopeUntilLength = n-1; }else { choiceToCutRopeUntilLength = curRopeLength; } for (int cut = 1; cut <= choiceToCutRopeUntilLength; cut++) { maxProductSoFar = cut * dpTable[curRopeLength - cut]; maxProduct = Math.max(maxProduct, maxProductSoFar); } dpTable[curRopeLength] = maxProduct; maxProductSoFar = Integer.MIN_VALUE; } return dpTable[n]; } }
true
eabfdd1fc4507741bbac73c78b116e26cd8754c7
Java
CapeSepias/hippo-cms
/api/src/main/java/org/hippoecm/frontend/plugins/standards/list/ListColumn.java
UTF-8
6,720
1.75
2
[ "Apache-2.0", "GPL-3.0-only", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-free-unknown", "LicenseRef-scancode-sencha-dev-floss-exception", "LicenseRef-scancode-public-domain", "BSD-2-Clause", "MIT" ]
permissive
/* * Copyright 2008-2015 Hippo B.V. (http://www.onehippo.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 org.hippoecm.frontend.plugins.standards.list; import java.util.Comparator; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import org.apache.wicket.AttributeModifier; import org.apache.wicket.ajax.AjaxEventBehavior; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.extensions.markup.html.repeater.data.grid.ICellPopulator; import org.apache.wicket.extensions.markup.html.repeater.data.table.AbstractColumn; import org.apache.wicket.markup.repeater.Item; import org.apache.wicket.model.IDetachable; import org.apache.wicket.model.IModel; import org.apache.wicket.request.cycle.RequestCycle; import org.hippoecm.frontend.model.event.IEvent; import org.hippoecm.frontend.model.event.IObservable; import org.hippoecm.frontend.model.event.IObserver; import org.hippoecm.frontend.plugin.IPluginContext; import org.hippoecm.frontend.plugins.standards.list.datatable.ListDataTable; import org.hippoecm.frontend.plugins.standards.list.resolvers.AbstractListAttributeModifier; import org.hippoecm.frontend.plugins.standards.list.resolvers.CssClass; import org.hippoecm.frontend.plugins.standards.list.resolvers.IListCellRenderer; import org.hippoecm.frontend.plugins.standards.list.resolvers.NameRenderer; /** * Definition of a column in a {@link ListDataTable}. Can be used to define sorting, * cell renderers and attribute modifiers that will be applied to the repeater {@link Item}. * By default, the renderer used is the {@link NameRenderer}, that renders the (translated) * name of a JCR node. */ public class ListColumn<T> extends AbstractColumn<T, String> { private Comparator<T> comparator; private IListCellRenderer<T> renderer; private AbstractListAttributeModifier<T> attributeModifier; private String cssClass; private boolean isLink = true; private IPluginContext context; private List<IObserver<?>> observers; public ListColumn(IModel<String> displayModel, String sortProperty) { super(displayModel, sortProperty); } @Override public String getCssClass() { return cssClass; } public void setCssClass(String cssClass) { this.cssClass = cssClass; } public void setComparator(Comparator<T> comparator) { this.comparator = comparator; } public Comparator<T> getComparator() { return comparator; } public void setRenderer(IListCellRenderer<T> renderer) { this.renderer = renderer; } public IListCellRenderer<T> getRenderer() { return renderer; } public void setAttributeModifier(AbstractListAttributeModifier<T> attributeModifier) { this.attributeModifier = attributeModifier; } public void setLink(boolean isLink) { this.isLink = isLink; } void init(IPluginContext context) { this.context = context; this.observers = new LinkedList<>(); } void destroy() { if (context != null) { for (IObserver observer : observers) { context.unregisterService(observer, IObserver.class.getName()); } observers.clear(); context = null; } } @Override public void detach() { if (observers != null) { for (IObserver observer : observers) { IObservable observable = observer.getObservable(); if (observable instanceof IDetachable) { ((IDetachable) observable).detach(); } } } super.detach(); } protected boolean isLink() { return isLink; } @Override public void populateItem(Item<ICellPopulator<T>> item, String componentId, IModel<T> model) { addLinkBehavior(item, model); addCssClasses(item); addCell(item, componentId, model); } protected void addCell(Item<ICellPopulator<T>> item, String componentId, IModel<T> model) { final ListCell cell = new ListCell(componentId, model, renderer, attributeModifier, context); if (attributeModifier != null) { AttributeModifier[] columnModifiers = attributeModifier.getColumnAttributeModifiers(); if (columnModifiers != null) { for (final AttributeModifier columnModifier : columnModifiers) { if (columnModifier == null) { continue; } item.add(columnModifier); if (columnModifier instanceof IObservable && context != null) { IObserver observer = new IObserver<IObservable>() { public IObservable getObservable() { return (IObservable) columnModifier; } public void onEvent(Iterator<? extends IEvent<IObservable>> events) { AjaxRequestTarget target = RequestCycle.get().find(AjaxRequestTarget.class); if (target != null) { target.add(cell); } } }; context.registerService(observer, IObserver.class.getName()); observers.add(observer); } } } } item.add(cell); } protected void addLinkBehavior(final Item<ICellPopulator<T>> item, final IModel<T> model) { if (isLink()) { item.add(new AjaxEventBehavior("onclick") { @Override protected void onEvent(AjaxRequestTarget target) { ListDataTable dataTable = item.findParent(ListDataTable.class); dataTable.getSelectionListener().selectionChanged(model); } }); } } protected void addCssClasses(Item<ICellPopulator<T>> item) { if (isLink()) { item.add(CssClass.append("link")); } } }
true
44c6257d66a37fd0980eca8381f25fb86af5de12
Java
DavidC0rtes/sige
/src/activos/transformadores/ModeloTransformador.java
UTF-8
622
2.5625
3
[ "MIT" ]
permissive
package activos.transformadores; import db.JDBCConnection; import java.util.*; public class ModeloTransformador { private JDBCConnection DB; public ModeloTransformador(JDBCConnection conn) { this.DB = conn; } public boolean writeData(HashMap<String, String> datos) { String sql = "insert into transformadores (capacidad,estado,serial,id_subestacion) " + "values(?,?,?,?)"; String[] params = { datos.get("capacidad"), datos.get("estado"), datos.get("serial"), datos.get("id_subestacion") }; if (DB.updateRecord(sql, params) == 1) { return true; } return false; } }
true
ba5e7199b7f45ed6a22387d75913a77d6fa067c8
Java
zoack-adventure/zoack
/app/src/main/java/com/verisence/zoackadventures/adapters/PaymentPagerAdapter.java
UTF-8
934
2.34375
2
[ "MIT" ]
permissive
package com.verisence.zoackadventures.adapters; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import androidx.fragment.app.FragmentPagerAdapter; import com.verisence.zoackadventures.UI.PaymentInquiryFragment; import com.verisence.zoackadventures.models.Payment; import java.util.ArrayList; public class PaymentPagerAdapter extends FragmentPagerAdapter { private ArrayList<Payment> mPayments; public PaymentPagerAdapter(FragmentManager fm, ArrayList<Payment> payments) { super(fm); mPayments = payments; } @Override public Fragment getItem(int position){ return PaymentInquiryFragment.newInstance(mPayments.get(position)); } @Override public int getCount(){ return mPayments.size(); } @Override public CharSequence getPageTitle(int position){ return mPayments.get(position).getHotel().getName(); } }
true
5bebb57d98a95408915d62e120a7472f00d0adc7
Java
faheemkalsekar/ShiftEasy
/app/src/main/java/com/gadgetmedia/shifteasy/mvp/data/Shift.java
UTF-8
2,600
2.46875
2
[]
no_license
package com.gadgetmedia.shifteasy.mvp.data; import android.arch.persistence.room.ColumnInfo; import android.arch.persistence.room.Entity; import android.arch.persistence.room.PrimaryKey; import android.support.annotation.NonNull; import android.support.annotation.Nullable; /** * Immutable model class for a Shift. */ @Entity(tableName = "shifts") public class Shift { /* "id": 1, "start": "2018-02-25T22:21:31+11:00", "end": "2018-02-25T22:21:31+11:00", "startLatitude": "33.8688", "startLongitude": "151.2093", "endLatitude": "33.8688", "endLongitude": "151.2093", "image": "https://unsplash.it/500/500?random" */ @PrimaryKey @ColumnInfo(name = "id") private final int mId; @NonNull @ColumnInfo(name = "start") private final String mStartTime; @NonNull @ColumnInfo(name = "end") private final String mEndTime; @Nullable @ColumnInfo(name = "startLatitude") private final String mStartLatitude; @Nullable @ColumnInfo(name = "startLongitude") private final String mStartLongitude; @Nullable @ColumnInfo(name = "endLatitude") private final String mEndLatitude; @Nullable @ColumnInfo(name = "endLongitude") private final String mEndLongitude; @Nullable @ColumnInfo(name = "image") private final String mImage; public Shift(final int mId, @NonNull final String mStartTime, @NonNull final String mEndTime, @Nullable final String mStartLatitude, @Nullable final String mStartLongitude, @Nullable final String mEndLatitude, @Nullable final String mEndLongitude, @Nullable final String mImage) { this.mId = mId; this.mStartTime = mStartTime; this.mEndTime = mEndTime; this.mStartLatitude = mStartLatitude; this.mStartLongitude = mStartLongitude; this.mEndLatitude = mEndLatitude; this.mEndLongitude = mEndLongitude; this.mImage = mImage; } public int getId() { return mId; } @Nullable public String getStartTime() { return mStartTime; } @Nullable public String getEndTime() { return mEndTime; } @Nullable public String getStartLatitude() { return mStartLatitude; } @Nullable public String getStartLongitude() { return mStartLongitude; } @Nullable public String getEndLatitude() { return mEndLatitude; } @Nullable public String getEndLongitude() { return mEndLongitude; } @Nullable public String getImage() { return mImage; } }
true
4988b90128d03abdd3f63db478b3d60a647815f5
Java
pammypammy95/core_java
/src/database/MyClass.java
UTF-8
1,611
3.375
3
[]
no_license
package database; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Scanner; public class MyClass { Connection con = null; Statement st = null; ResultSet rs = null; PreparedStatement ps = null; void getData() throws SQLException{ Statement st = con.createStatement(); ResultSet rs = st.executeQuery("" + "select * from employee"); while(rs.next()) // check for the next record System.out.println(rs.getInt(1) + " " + rs.getString(2) + " " + rs.getString(3)); con.close(); } // end of getData void insertData() throws SQLException{ con = DBConnection.myConnection(); ps = con.prepareStatement("insert into employee values(?,?,?)"); Scanner sc = new Scanner(System.in); System.out.println("Enter empID, empName and address : "); int empID = sc.nextInt(); String empName = sc.next(); String address = sc.next(); Employee ref = new Employee(); ref.setEmpID(empID); ref.setEmpName(empName); ref.setAddress(address); ps.setInt(1, ref.getEmpID()); ps.setString(2, ref.getEmpName()); ps.setString(3, ref.getAddress()); //ps.setInt(1, 101); // 1 specifies the first parameter in the query //ps.setString(2, "Daryl"); //ps.setString(3, "Bedok"); //set and get from pojo int i = ps.executeUpdate(); System.out.println(i + " records instead"); } }
true
01a5cc20b39e7c045ae81f22639f38c33c36bfde
Java
niupuyue/IYingLibrary
/mylibrary/src/main/java/com/niupuyue/mylibrary/utils/NetStatusUtility.java
UTF-8
6,145
2.765625
3
[]
no_license
package com.niupuyue.mylibrary.utils; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.telephony.TelephonyManager; import java.lang.reflect.Method; /** * Coder: niupuyue (牛谱乐) * Date: 2019/6/12 * Time: 23:02 * Desc: 网络环境工具类 * Version: */ public class NetStatusUtility { private static String TAG = NetStatusUtility.class.getSimpleName(); /** * 网络类型枚举 */ public enum NetType { None(1), Mobile(2), Wifi(4), Other(8); public int netType; NetType(int value) { this.netType = value; } } public enum NetWorkType { UnKown(-1), Wifi(1), Net2G(2), Net3G(3), Net4G(4), Net5G(5); public int value; NetWorkType(int value) { this.value = value; } } /** * 获取ConnectivityManager对象 * * @param context * @return */ public static ConnectivityManager getConnectivityManager(Context context) { return (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); } /** * 获取TelephonyManager对象 * * @param context * @return */ public static TelephonyManager getTelephonyManager(Context context) { return (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); } /** * 判断网络连接是否有效 * * @param context * @return 不管是wifi还是mobile net 只要当前有连接状态,就返回true */ public static boolean isConnected(Context context) { NetworkInfo info = getConnectivityManager(context).getActiveNetworkInfo(); return info != null && info.isConnected(); } /** * 判断是否有网络正在连接中 * * @param context * @return */ public static boolean isConnectedOrConnecting(Context context) { NetworkInfo[] infos = getConnectivityManager(context).getAllNetworkInfo(); if (infos != null) { for (NetworkInfo info : infos) { if (info.isConnectedOrConnecting()) return true; } } return false; } /** * 获取当前网络连接类型 * * @param context * @return */ public static NetType getConnectedType(Context context) { NetworkInfo info = getConnectivityManager(context).getActiveNetworkInfo(); if (info != null) { switch (info.getType()) { case ConnectivityManager.TYPE_WIFI: return NetType.Wifi; case ConnectivityManager.TYPE_MOBILE: return NetType.Mobile; default: return NetType.Other; } } return NetType.None; } /** * 判断是否存在有效wifi连接 * * @param context * @return */ public static boolean isWifiConnected(Context context) { NetworkInfo info = getConnectivityManager(context).getActiveNetworkInfo(); return info != null && info.getType() == ConnectivityManager.TYPE_WIFI && info.isConnected(); } /** * 判断是否存在有效移动网络连接 * * @param context * @return */ public static boolean isMobileConnected(Context context) { NetworkInfo info = getConnectivityManager(context).getActiveNetworkInfo(); return info != null && info.getType() == ConnectivityManager.TYPE_MOBILE && info.isConnected(); } /** * 判断是否有可用状态的wifi,以下情况之一返回false * 1. 设备wifi开关关闭 * 2. 已经打开飞行模式 * 3. 设备所在的区域没有信号覆盖 * 4. 设备在漫游区域,且关闭了网络漫游 * * @param context * @return */ public static boolean isWifiAvailable(Context context) { NetworkInfo[] infos = getConnectivityManager(context).getAllNetworkInfo(); if (infos != null && infos.length > 0) { for (NetworkInfo info : infos) { if (info.getType() == ConnectivityManager.TYPE_WIFI) { return info.isAvailable(); } } } return false; } /** * 判断有无可用状态的移动网络,注意关掉设备移动网络直接不影响此函数。 * 也就是即使关掉移动网络,那么移动网络也可能是可用的(彩信等服务),即返回true。 * 以下情况它是不可用的,将返回false: * 1. 设备打开飞行模式; * 2. 设备所在区域没有信号覆盖; * 3. 设备在漫游区域,且关闭了网络漫游。 * * @param context * @return */ public static boolean isMobileAvailable(Context context) { NetworkInfo[] infos = getConnectivityManager(context).getAllNetworkInfo(); if (infos != null && infos.length > 0) { for (NetworkInfo info : infos) { if (info.getType() == ConnectivityManager.TYPE_MOBILE) { return info.isAvailable(); } } } return false; } /** * 设备是否打开移动网络开关 * * @param context * @return */ public static boolean isMobileEnabled(Context context) { try { Method getMobileDataEnabledMethod = ConnectivityManager.class.getDeclaredMethod("getMobileDataEnabled"); getMobileDataEnabledMethod.setAccessible(true); return (Boolean) getMobileDataEnabledMethod.invoke(getConnectivityManager(context)); } catch (Exception ex) { ex.printStackTrace(); } return false; } /** * 检查网络是否为可用状态 * * @param context * @return */ public static boolean isNetAvailable(Context context) { return isWifiAvailable(context) || (isMobileAvailable(context) && isMobileEnabled(context)); } }
true
2fe12cf16b6e3c29e5cb59ced8207c9bc095168f
Java
zhengchengrong/myworkproject
/app/src/main/java/com/eaphone/g08android/http/APIUrl/NewsApi.java
UTF-8
2,413
1.828125
2
[]
no_license
package com.eaphone.g08android.http.APIUrl; import com.eaphone.g08android.bean.FAQ; import com.eaphone.g08android.bean.Info; import com.eaphone.g08android.bean.InfoComment; import com.eaphone.g08android.bean.InfoDetail; import com.eaphone.g08android.entity.NewsType; import com.hpw.mvpframe.base.ResultBase; import java.util.List; import retrofit2.http.DELETE; import retrofit2.http.GET; import retrofit2.http.POST; import retrofit2.http.Path; import retrofit2.http.Query; import rx.Observable; /** * 项目名称:心相随 * 类描述: * 创建人:zlq * 创建时间:2017/8/29 11:16 * 修改人:Administrator * 修改时间:2017/8/29 11:16 * 修改备注: */ public interface NewsApi { /*--------------------------------news-------------------------------------*/ String NEWSBASE = "news/v1/"; //资讯类型 @GET(NEWSBASE + "newsType") Observable<ResultBase<List<NewsType>>> loadNewsType(); //资讯列表 @GET(NEWSBASE + "newsType/{newsTypeId}/news") Observable<ResultBase<List<Info>>> loadInfo(@Path("newsTypeId") String newsTypeId, @Query("page_index") String page_index, @Query("page_size") String page_size); //资讯详情 @GET(NEWSBASE + "newsType/{newsTypeId}/news/{newsId}") Observable<ResultBase<InfoDetail>> loadInfoDetail(@Path("newsTypeId") String newsTypeId, @Path("newsId") String newsId); //资讯评论列表 @GET(NEWSBASE + "news/{info_id}/comments/") Observable<ResultBase<List<InfoComment>>> loadInfoListComment(@Path("info_id") String info_id,@Query("page_index") String page_index, @Query("page_size") String page_size); //资讯评论 @POST(NEWSBASE + "news/{info_id}/comments/") Observable<ResultBase> loadInfoComment(@Path("info_id") String infoId, @Query("content") String content, @Query("commentsId") String commentsId); //点赞 @POST(NEWSBASE + "news/{newsId}/comments/{commentsId}/zan") Observable<ResultBase> loadZan(@Path("newsId") String newsId, @Path("commentsId") String commentsId); //取消赞 @DELETE(NEWSBASE + "news/{newsId}/comments/{commentsId}/zan") Observable<ResultBase> loadCancelZan(@Path("newsId") String newsId, @Path("commentsId") String commentsId); @GET(NEWSBASE + "FAQ") Observable<ResultBase<List<FAQ>>> loadFAQ(); @GET(NEWSBASE + "FAQ/{id}") Observable<ResultBase<FAQ>> loadFAQDetail(@Path("id") String id); }
true
4110f0f76d72f690c311ebcde5971d2b05fb177d
Java
rhkd6351/Panorama
/src/main/java/org/zerock/service/UserServiceImpl.java
UTF-8
2,128
2.484375
2
[]
no_license
package org.zerock.service; import lombok.AllArgsConstructor; import lombok.extern.log4j.Log4j; import org.springframework.stereotype.Service; import org.zerock.domain.UserVO; import org.zerock.mapper.UserMapper; import java.util.List; @Log4j @Service @AllArgsConstructor public class UserServiceImpl implements UserService { UserMapper mapper; @Override public void register(UserVO vo) throws FoolException { try{ mapper.insert(vo); }catch(Exception e){ log.info("회원등록에 실패하였습니다."); throw new FoolException(); } log.info("신규회원 등록이 완료되었습니다."); } public class FoolException extends RuntimeException { } @Override public UserVO get(String userId) { UserVO vo = mapper.read(userId); if(vo == null){ log.info("회원정보를 가져오지 못하였습니다."); return null; } log.info("회원정보를 성공적으로 로드하였습니다."); return vo; } @Override public boolean remove(String userId) { if(mapper.delete(userId) == 0){ log.info("회원정보 제거에 실패하였습니다."); return false; }else { log.info("회원정보 제거에 성공하였습니다."); return true; } } @Override public boolean modify(UserVO vo) { if(mapper.update(vo) == 0){ log.info("회원정보 변경에 실패하였습니다."); return false; }else { log.info("회원정보 변경에 성하였습니다."); return true; } } @Override public List<UserVO> getList() { log.info("회원정보 로드에 성공하였습니다."); return mapper.getList(); } @Override public UserVO login(String userId, String userPw) { UserVO vo = mapper.read(userId); if(vo == null) return null; if(vo.getUserPw().equals(userPw)) return vo; return null; } }
true
b705d18c848e53892c871b5bde6b04d270d5de7b
Java
damianpumar/BowlingGameKataOutsideIn
/src/main/java/Parser.java
UTF-8
753
2.96875
3
[]
no_license
import java.util.ArrayList; import java.util.List; public class Parser { private final List<FrameParser> frameParsers; public Parser(String[] rollsParsed) { this.frameParsers = new ArrayList() { { add(new StrikeParser(rollsParsed)); add(new SpareParser(rollsParsed)); add(new MissedParser(rollsParsed)); add(new NumberParser(rollsParsed)); } }; } public Frame evaluate(int positionToAnalyze) { Frame frame = null; for (FrameParser parser : this.frameParsers) { frame = parser.evaluate(positionToAnalyze); if (frame != null) break; } return frame; } }
true
37ec7c3225fe9e4ef0164b3343917c78fd24b6b1
Java
STAMP-project/dspot-experiments
/benchmark/test/org/apache/druid/segment/realtime/firehose/LocalFirehoseFactoryTest.java
UTF-8
2,576
1.96875
2
[]
no_license
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.druid.segment.realtime.firehose; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.List; import org.apache.druid.data.input.Firehose; import org.apache.druid.data.input.Row; import org.apache.druid.data.input.impl.DimensionsSpec; import org.apache.druid.data.input.impl.StringInputRowParser; import org.apache.druid.data.input.impl.TimestampSpec; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; public class LocalFirehoseFactoryTest { @Rule public final TemporaryFolder temporaryFolder = new TemporaryFolder(); private LocalFirehoseFactory factory; @Test public void testConnect() throws IOException { try (final Firehose firehose = factory.connect(new StringInputRowParser(new org.apache.druid.data.input.impl.CSVParseSpec(new TimestampSpec("timestamp", "auto", null), new DimensionsSpec(DimensionsSpec.getDefaultSchemas(Arrays.asList("timestamp", "a")), new ArrayList(), new ArrayList()), ",", Arrays.asList("timestamp", "a"), false, 0), StandardCharsets.UTF_8.name()), null)) { final List<Row> rows = new ArrayList<>(); while (firehose.hasMore()) { rows.add(firehose.nextRow()); } Assert.assertEquals(5, rows.size()); rows.sort(Comparator.comparing(Row::getTimestamp)); for (int i = 0; i < 5; i++) { final List<String> dimVals = rows.get(i).getDimension("a"); Assert.assertEquals(1, dimVals.size()); Assert.assertEquals((i + "th test file"), dimVals.get(0)); } } } }
true
f4c3ea9023052e88d5bf416197fdcbe62de65bac
Java
verhas/jamal
/jamal-snippet/src/main/java/javax0/jamal/snippet/Download.java
UTF-8
2,122
2.546875
3
[ "Apache-2.0" ]
permissive
package javax0.jamal.snippet; import javax0.jamal.api.BadSyntax; import javax0.jamal.api.Input; import javax0.jamal.api.Macro; import javax0.jamal.api.Processor; import javax0.jamal.tools.FileTools; import javax0.jamal.tools.Scanner; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; public class Download implements Macro, Scanner { @Override public String evaluate(Input in, Processor processor) throws BadSyntax { final var scanner = newScanner(in, processor); final var to = scanner.file(null, "file"); scanner.done(); final var reference = in.getReference(); final var fromName = FileTools.absolute(reference, in.toString().trim()); try (final var fos = new FileOutputStream(to.file())) { final var bytes = FileTools.getFileBinaryContent(fromName, true, processor); fos.write(bytes); } catch (IOException ioException) { throw new BadSyntax(String.format("There was an IOException downloading the file '%s' to '%s'", fromName, to.get()), ioException); } return ""; } @Override public String getId() { return "download"; } } /* snippet Download This macro downloads a resource from a URL and saves it to a file. The format of the macro is {%sample/ {@download (file="file name") URL} %} There is one parameter: * `file` should specify the file where to save the content of the downloaded file. The URL is given after the option. [NOTE] ==== . There is a similar functionality macro in the `jamal-io` module. That macro is called `io:copy`. This macro cannot append to a file, will not create the directory if it does not exist and you cannot control the use of cache. This macro will not use the Jamal download cache. . Technically, the URL can specify any file name that you could `include`. You can specify the usual `maven:`, `res:`, etc. prefixes in addition to `https:`. . This macro is intended to be used together with the macro `memoize`. For this reason it does not use the cache mechanism of Jamal. ==== end snippet*/
true
997a3b70cc80b5dc893d7395d9bc1561451c2707
Java
fernedingd/ChessReferee
/src/Player/Player.java
UTF-8
986
2.890625
3
[]
no_license
package Player; import ChessField.ChessFieldHelper; import ChessField.ChessFieldViewRepresentation; import ChessField.Move; import Pieces.Color; public abstract class Player { public Color color; ChessFieldViewRepresentation viewRepresentation; String displayElement; public void initialize(ChessFieldViewRepresentation viewRepresentation, String displayElement, Color color) { this.viewRepresentation = viewRepresentation; this.displayElement = displayElement; this.color = color; } public abstract void getNextMove(ChessFieldHelper chessFieldHelper, Move lastMove); public String getDisplayElement() { return displayElement; } public void setDisplayElement(String displayElement) { this.displayElement = displayElement; } public Color getColor() { return color; } public void setColor(Color color) { this.color = color; } public abstract boolean isHuman(); }
true
71485e640c85d5cc25a1719c563d5b73c831d1f9
Java
JadsonFeitosa/Hot_Pizza
/src/view/TelaUsuario.java
ISO-8859-1
8,014
2.21875
2
[]
no_license
package view; import java.awt.Color; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPasswordField; import javax.swing.JTextField; import DTO.FuncionariosDTO; import controller.BotoesGeral; import controller.CampoGeral; import controller.ControlFuncionarios; import controller.FonteBem; public class TelaUsuario extends Principal{ /** * */ private static final long serialVersionUID = 2341624009284424660L; private JTextField cod; private JTextField nome; private JPasswordField senha; private JTextField senha2; private JComboBox<String> boxCargo; private JComboBox<String> boxNivel; private JCheckBox administrador; public TelaUsuario(boolean band,String tela, int index) { setTitle("Cadastro de fuincionarios"); setBounds(400, 50, 500, 650); setResizable(false); setDefaultCloseOperation(DISPOSE_ON_CLOSE); textField(this); botao(band,tela, index); jLabels(); blackgroud(); setVisible(true); repaint(); } public void blackgroud() { JLabel contabil = new JLabel(new ImageIcon("Icon/fundocad.png")); contabil.setBounds(1,1,500,650); add(contabil); } private void jLabels () { JLabel nome = new JLabel("CADASTRO DE FUNCIONRIOS"); nome.setFont(new Font("Times New Roman",Font.ITALIC,25)); nome.setForeground(Color.WHITE); nome.setBounds(50, 1, 500, 30); add(nome); JLabel label1 = new FonteBem("Codigo",10 , 40); add(label1); JLabel label = new FonteBem("Nome", 10, 100); add(label); JLabel end =new FonteBem("Cargo", 10, 180); add(end); JLabel label2 =new FonteBem("Senha", 10, 310); add(label2); JLabel cel =new FonteBem("Nilvel", 10, 250); add(cel); } public void textField(JFrame janela) { cod = new CampoGeral("",10, 70, 100, 25); cod.setToolTipText("Codigo de Identificao"); janela.add(cod); cod.setEnabled(false); cod.setText(""+ControlFuncionarios.contIdFun()); nome = new CampoGeral("",10, 130, 300, 25); nome.setToolTipText("nome"); janela.add(nome); String [] listaCargo= {"Gerente","Atendente","Pizzaiolo","Motoboy", "Servios gerais"}; boxCargo =new JComboBox<String>(listaCargo); boxCargo.setBounds(70,180,100,30); if(ControlFuncionarios.ContTamanho()==0) { boxCargo.setVisible(false); } else boxCargo.setVisible(true); add(boxCargo); String [] listaNivel= {"Maximo","Medio","Minimo","Nada"}; boxNivel =new JComboBox<String>(listaNivel); boxNivel.setBounds(70,250,100,30); add(boxNivel); senha = new JPasswordField(""); senha.setBounds(10, 335, 150, 25); senha.setToolTipText("Digite senha"); janela.add(senha); senha2 = new JTextField(""); senha2.setBounds(10, 335, 150, 25); senha2.setToolTipText("Digite senha"); janela.add(senha2); } private void botao(boolean band1,String tela,int index) { BotoesGeral ed= new BotoesGeral("<html>Editar<html>",new ImageIcon("Icon/editarfun.png"),80,400,100,110); ed.repaint(); if(!tela.equals("Editar")) { ed.setVisible(false); } else { ed.setVisible(true); ControlFuncionarios p = new ControlFuncionarios(); cod.setText(""+index); nome.setText(p.ConsultarFun(index).getNome()); boxCargo.setSelectedItem(p.ConsultarFun(index).getCargo()); boxNivel.setSelectedItem(p.ConsultarFun(index).getNivel()); senha.setText(p.ConsultarFun(index).getSenha()); } add(ed); ed.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { FuncionariosDTO editado = new FuncionariosDTO(); editado.setCod(Integer.parseInt(cod.getText())); editado.setNome(nome.getText().toUpperCase()); editado.setCargo((String) boxCargo.getSelectedItem()); editado.setSenha(senha.getText()); editado.setNivel((String)boxNivel.getSelectedItem()); ControlFuncionarios.conteditarFun(editado); JOptionPane.showMessageDialog(null, "Funcinario editado com sucesso!", "Alerta",JOptionPane.INFORMATION_MESSAGE); dispose(); new ViewlFuncionarios(); } }); BotoesGeral botao1 = new BotoesGeral("<html>Salvar<html>",new ImageIcon("Icon/salvarfun.png"),80,400,100,110); botao1.repaint(); add(botao1); if(tela.contentEquals("Editar")) { botao1.setVisible(false); } else botao1.setVisible(true); botao1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { if(cod.getText().equals("") || nome.getText().equals("")|| senha.getText().equals("")||boxNivel.getSelectedItem().equals("")||boxCargo.getSelectedItem().equals("")) { JOptionPane.showMessageDialog(null, "Campo Vazio", "Alerta",JOptionPane.ERROR_MESSAGE); } else if(administrador.isSelected()==true) { FuncionariosDTO editado = new FuncionariosDTO(); editado.setCod(Integer.parseInt(cod.getText())); editado.setNome(nome.getText().toUpperCase()); editado.setCargo("Administrador"); editado.setSenha(senha.getText()); editado.setNivel((String)boxNivel.getSelectedItem()); ControlFuncionarios.contFuncionarios(editado); JOptionPane.showMessageDialog(null, "Admisttrador cadastrado com sucesso!", "Alerta",JOptionPane.INFORMATION_MESSAGE); dispose(); new ViewLogin(); } else { FuncionariosDTO editado = new FuncionariosDTO(); editado.setCod(Integer.parseInt(cod.getText())); editado.setNome(nome.getText().toUpperCase()); editado.setCargo((String) boxCargo.getSelectedItem()); editado.setSenha(senha.getText()); editado.setNivel((String)boxNivel.getSelectedItem()); ControlFuncionarios.contFuncionarios(editado); JOptionPane.showMessageDialog(null, "Funcinario cadastrado com sucesso!", "Alerta",JOptionPane.INFORMATION_MESSAGE); cod.setText(""); nome.setText(""); senha.setText(""); cod.requestFocus(); dispose(); new ViewlFuncionarios(); } }catch(ExceptionFuncionarioCad a) { cod.requestFocus(); } } }); JButton botao2 = new BotoesGeral("Cancelar",new ImageIcon("Icon/apagrafun.png"),230,400,100,110); botao2.setToolTipText("Voltar"); botao2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { dispose(); new ViewlFuncionarios(); } } ); add(botao2); administrador = new JCheckBox("Administrador"); administrador.setOpaque(true); administrador.setVisible(band1); administrador.setSelected(band1); administrador.setEnabled(false); administrador.setBackground(new Color(255,198,91)); administrador.setBounds(10, 380, 150, 30); add(administrador); JLabel olho = new JLabel(new ImageIcon("Icon/olhof.png")); olho.setBounds(55,300,50,50); add(olho); olho.addMouseListener(new MouseListener() { public void mouseClicked(MouseEvent e) { } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } public void mousePressed(MouseEvent e) { olho.setIcon(new ImageIcon("Icon/olhoa.png")); senha.setVisible(false); senha2.setText(senha.getText()); senha2.setVisible(true); } public void mouseReleased(MouseEvent e) { olho.setIcon(new ImageIcon("Icon/olhof.png")); senha.setVisible(true); senha2.setVisible(false); } }); } }
true
4bc4aca356ab52b4e33fb310618533f73aac4183
Java
caowei120919/baseAndroid
/app/src/main/java/com/zj/wz/wbyx/wbyxAndroid/view/BindPhoneView.java
UTF-8
330
1.53125
2
[]
no_license
package com.zj.wz.wbyx.wbyxAndroid.view; import com.zj.wz.wbyx.baseandroid.mvp.base.MvpView; /** * FileName: WXEntryView * Author: 曹伟 * Date: 2019/11/25 13:37 * Description: */ public interface BindPhoneView extends MvpView { void sendMessageSuccess(); void sendMessageFailed(); void LoginSuccess(); }
true
6f24f1d22235b8e868c4eda0b33cf9fc43cec95e
Java
puneteamsangsoftwares/SanguineERP
/src/com/sanguine/webbanquets/bean/clsAdvanceStatusReportBean.java
UTF-8
1,550
1.851563
2
[]
no_license
package com.sanguine.webbanquets.bean; public class clsAdvanceStatusReportBean { private String strReceiptNo; private String strReservationNo; private String strCustomerCode; private String strPname; private String strSettlementDesc; private String dteBookingDate; private double dblReceiptAmt; public String getDteBookingDate() { return dteBookingDate; } public void setDteBookingDate(String dteBookingDate) { this.dteBookingDate = dteBookingDate; } public String getStrReceiptNo() { return strReceiptNo; } public void setStrReceiptNo(String strReceiptNo) { this.strReceiptNo = strReceiptNo; } public String getStrReservationNo() { return strReservationNo; } public void setStrReservationNo(String strReservationNo) { this.strReservationNo = strReservationNo; } public String getStrCustomerCode() { return strCustomerCode; } public void setStrCustomerCode(String strCustomerCode) { this.strCustomerCode = strCustomerCode; } public String getStrPname() { return strPname; } public void setStrPname(String strPname) { this.strPname = strPname; } public String getStrSettlementDesc() { return strSettlementDesc; } public void setStrSettlementDesc(String strSettlementDesc) { this.strSettlementDesc = strSettlementDesc; } public double getDblReceiptAmt() { return dblReceiptAmt; } public void setDblReceiptAmt(double dblReceiptAmt) { this.dblReceiptAmt = dblReceiptAmt; } }
true
8f338c9e762fbe5e7ba0c39264cf30da894f891c
Java
ulises-jeremias/pdytr
/practica-4/resources/given/jade/examples/jade/src/examples/mobile/ServeIncomingMessagesBehaviour.java
UTF-8
4,666
2.71875
3
[ "LGPL-2.1-only", "LGPL-2.0-or-later", "MIT" ]
permissive
/***************************************************************** JADE - Java Agent DEvelopment Framework is a framework to develop multi-agent systems in compliance with the FIPA specifications. Copyright (C) 2000 CSELT S.p.A. GNU Lesser General Public License 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, version 2.1 of the License. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *****************************************************************/ package examples.mobile; import jade.core.Agent; import jade.core.Location; import jade.core.behaviours.SimpleBehaviour; import jade.lang.acl.ACLMessage; import jade.lang.acl.MessageTemplate; import java.util.StringTokenizer; /** This behaviour of the Agent serves all the received messages. In particular, the following expressions are accepted as content of "request" messages: - (move <destination>) to move the Agent to another container. Example (move Front-End) or (move (:location (:name Container-1) (:transport-protocol JADE-IPMT) (:transport-address IOR:0000...) )) - (exit) to request the agent to exit - (stop) to stop the counter - (continue) to continue counting @author Giovanni Caire - CSELT S.p.A @version $Date: 2008-10-09 14:04:02 +0200 (gio, 09 ott 2008) $ $Revision: 6051 $ */ class ServeIncomingMessagesBehaviour extends SimpleBehaviour { ServeIncomingMessagesBehaviour(Agent a) { super(a); } public boolean done() { return false; } public void action() { ACLMessage msg; MessageTemplate mt = MessageTemplate.MatchPerformative(ACLMessage.REQUEST); // Get a message from the queue or wait for a new one if queue is empty msg = myAgent.receive(mt); if (msg == null) { block(); return; } else { String replySentence = ""; // Get action to perform //String s = msg.getContent(). StringTokenizer st = new StringTokenizer(msg.getContent(), " ()\t\n\r\f"); String action = (st.nextToken()).toLowerCase(); // EXIT if (action.equals("exit")) { System.out.println("They requested me to exit (Sob!)"); // Set reply sentence replySentence = "\"OK exiting\""; myAgent.doDelete(); } // STOP COUNTING else if (action.equals("stop")) { System.out.println("They requested me to stop counting"); ((MobileAgent) myAgent).stopCounter(); // Set reply sentence replySentence = "\"OK stopping\""; } // CONTINUE COUNTING else if (action.equals("continue")) { System.out.println("They requested me to continue counting"); ((MobileAgent) myAgent).continueCounter(); // Set reply sentence replySentence = "\"OK continuing\""; } // MOVE TO ANOTHER LOCATION else if (action.equals("move")) { String destination = st.nextToken(); System.out.println(); Location dest = new jade.core.ContainerID(destination, null); System.out.println("They requested me to go to " + destination); // Set reply sentence replySentence = "\"OK moving to " + destination+" \""; // Prepare to move ((MobileAgent)myAgent).nextSite = dest; myAgent.doMove(dest); } // CLONE TO ANOTHER LOCATION else if (action.equals("clone")) { String destination = st.nextToken(); System.out.println(); Location dest = new jade.core.ContainerID(destination, null); System.out.println("They requested me to clone myself to " + destination); // Set reply sentence replySentence = "\"OK cloning to " + destination+" \""; // Prepare to move ((MobileAgent)myAgent).nextSite = dest; myAgent.doClone(dest, "clone"+((MobileAgent)myAgent).cnt+"of"+myAgent.getName()); } // SAY THE CURRENT LOCATION else if (action.equals("where-are-you")) { System.out.println(); Location current = myAgent.here(); System.out.println("Currently I am running on "+current.getName()); // Set reply sentence replySentence = current.getName(); } // Reply ACLMessage replyMsg = msg.createReply(); replyMsg.setPerformative(ACLMessage.INFORM); replyMsg.setContent(replySentence); myAgent.send(replyMsg); } return; } }
true
9016f38c24b4d019d64bb39bba9398713e62f39c
Java
idiottiger/beluga
/tools/db-tools/src/com/idiot2ger/beluga/dbtools/Table.java
UTF-8
1,432
2.796875
3
[]
no_license
package com.idiot2ger.beluga.dbtools; import java.util.ArrayList; import java.util.List; public class Table implements IDump { String name; List<Column> columns = new ArrayList<Column>(); private Table() { } public static class TableBuilder { private Table mTable; public TableBuilder(String name) { mTable = new Table(); mTable.name = name; } public synchronized TableBuilder addColumn(Column column) { if (column != null && !mTable.columns.contains(column)) { mTable.columns.add(column); } return this; } public synchronized TableBuilder addColumns(List<Column> columns) { if (columns != null) { for (Column column : columns) { addColumn(column); } } return this; } public Table build() { return mTable; } } @Override public String getDumpSql() { StringBuffer buffer = new StringBuffer(); buffer.append("CREATE TABLE "); buffer.append("\"" + name + "\" (\n"); int size = columns.size(); for (int i = 0; i < size; i++) { buffer.append(columns.get(i).getDumpSql() + ((i == size - 1) ? "" : ",") + "\n"); } buffer.append(");\n"); return buffer.toString(); } public String getName() { return name; } public List<Column> getColumns() { return columns; } }
true
b0422f4785e5b659e99d37ed34513c0f06ce0375
Java
AnaLisboaCotovio/JavaBasics
/areaSRCTnoInput.java
UTF-8
1,275
3.8125
4
[]
no_license
public class areaSRCTnoInput { public static void main(String [] args) { //Variables //Square double square_side = 10; //Rectangle double rectangle_height = 5; double rectangle_width = 10; //Circle double circle_radius = 10; //Triangle double triangle_base = 10; double triangle_height = 20; //Calculation of the areas double square_area = Math.pow(square_side, 2); //Square double rectangle_area = rectangle_height * rectangle_width; //Rectangle double circle_area = Math.PI * Math.pow(circle_radius, 2); //Circle double triangle_area = (triangle_base * triangle_height) / 2; //Prints of the areas System.out.println("The square's area is " + (double) Math.round(square_area * 1000) / 1000 + "cm"); //Square System.out.println("The rectangle's area is " + (double) Math.round(rectangle_area * 1000) / 1000 + "cm"); //Rectangle System.out.println("The circle's area is " + (double) Math.round(circle_area * 1000) / 1000 + "cm"); //Circle System.out.println("The triangle's area is " + (double) Math.round(triangle_area * 1000) / 1000 + "cm"); //Triangle } }
true
ca31077187c7e48db8cef33ac5999efecfdb1b3f
Java
ut9731/basic
/src/Basic/Sample1.java
UTF-8
367
3.1875
3
[]
no_license
package Basic; public class Sample1 { int a; int b; public static void addition(int a, int b) { //int a=10; //int b=20; int c=a+b; System.out.println(c); } public static void sub(int a, int b) { int k=a-b; System.out.print(k); } public static void main(String[] args) { addition(10,20); sub(56,265); } }
true
be96c63c8e9a80050ba2550ca22576334b8a8eeb
Java
Hongjooahn/bigjavastudy
/java13/src/jdbc/Search.java
UTF-8
343
2.140625
2
[]
no_license
package jdbc; import javax.swing.JOptionPane; public class Search { public static void main(String[] args) throws Exception { MemberDAO db = new MemberDAO(); String id = JOptionPane.showInputDialog("ID 입력"); String[] mem = db.select(id); for(String s: mem){ System.out.println(s); } db.select(id); } }
true
cf6c83e254ca8bf3dc767eaad3d5d030c1e8f9f9
Java
pradeepsaiu/reading-sensors
/TrackMe/app/src/main/java/com/example/pradeepsaiuppula/TrackMe/StepCounter.java
UTF-8
371
2.453125
2
[]
no_license
package com.example.pradeepsaiuppula.TrackMe; /** * Created by pradeepsaiuppula on 2/7/17. */ public class StepCounter implements Sensor { float count; public float getCount() { return count; } public void setData(float count){ this.setCount(count); } public void setCount(float count) { this.count = count; } }
true
aaa8323071baadd80a1c111b59344d22e06ee9f6
Java
issyu-summer/demo-all
/design-pattern/src/main/java/adapter/design/anything/can/fly/Dog.java
UTF-8
854
3.5625
4
[]
no_license
package adapter.design.anything.can.fly; /** * @author issyu 30320182200070 * @date 2021/1/25 18:55 */ public class Dog { private DefaultDogAdapter defaultDogAdapter; public Dog(){ defaultDogAdapter = new DefaultDogAdapter() { @Override public void eat() { System.out.println("this dog can eat"); } @Override public void sleep(){ System.out.println("this dog can sleep"); } }; } /** * <--不需要全部实现接口提供的方法时 --> * 狗不想执行全部的动作,只想吃和睡 * 狗的动作缺省为吃 */ public void action(){ this.defaultDogAdapter.eat(); this.defaultDogAdapter.sleep(); System.out.println("this dog can't run and jump"); } }
true
89e57c25edbc967ca0fac689a7ebe084770d623c
Java
qiuxin-qx/bankroll-api
/bankroll-api/src/main/java/com/goldbao/bankroll/model/homs/HomsQueryEntrust.java
UTF-8
6,309
1.726563
2
[]
no_license
package com.goldbao.bankroll.model.homs; import com.goldbao.bankroll.model.Model; import javax.persistence.AttributeOverride; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Table; import java.io.Serializable; /** * @author shuyu.fang */ @Entity @Table(name = "bk_homs_query_entrust") @AttributeOverride(name = "id", column = @Column(name = "operator_id")) public class HomsQueryEntrust extends Model implements Serializable { private static final long serialVersionUID = 6948095801108951658L; @Column(name = "batch_no") private String batchNo; @Column(name = "entrust_no") private String entrustNo; @Column(name = "fund_account") private String fundAccount; @Column(name = "combine_id") private String combineId; @Column(name = "instruct_no") private String instructNo; @Column(name = "instruct_mod_no") private String instructmodNo; @Column(name = "stock_code") private String stockCode; @Column(name = "exchange_type") private String exchangeType; @Column(name = "stock_account") private String stockAccount; @Column(name = "seat_no") private String seatNo; @Column(name = "invest_way") private String investWay; @Column(name = "entrust_direction") private String entrustDirection; @Column(name = "entrust_price") private String entrustPrice; @Column(name = "entrust_amount") private String entrustAmount; @Column(name = "entrust_time") private String entrustTime; @Column(name = "report_time") private String reportTime; @Column(name = "business_amount") private String businessAmount; @Column(name = "business_balance") private String businessBalance; @Column(name = "withdraw_amount") private String withdrawAmount; @Column(name = "amentrust_status") private String amentrustStatus; @Column(name = "cancel_info") private String cancelInfo; @Column(name = "asset_id") private String assetId; @Column(name = "position_str") private String positionStr; public String getBatchNo() { return batchNo; } public void setBatchNo(String batchNo) { this.batchNo = batchNo; } public String getEntrustNo() { return entrustNo; } public void setEntrustNo(String entrustNo) { this.entrustNo = entrustNo; } public String getFundAccount() { return fundAccount; } public void setFundAccount(String fundAccount) { this.fundAccount = fundAccount; } public String getCombineId() { return combineId; } public void setCombineId(String combineId) { this.combineId = combineId; } public String getInstructNo() { return instructNo; } public void setInstructNo(String instructNo) { this.instructNo = instructNo; } public String getInstructmodNo() { return instructmodNo; } public void setInstructmodNo(String instructmodNo) { this.instructmodNo = instructmodNo; } public String getStockCode() { return stockCode; } public void setStockCode(String stockCode) { this.stockCode = stockCode; } public String getExchangeType() { return exchangeType; } public void setExchangeType(String exchangeType) { this.exchangeType = exchangeType; } public String getStockAccount() { return stockAccount; } public void setStockAccount(String stockAccount) { this.stockAccount = stockAccount; } public String getSeatNo() { return seatNo; } public void setSeatNo(String seatNo) { this.seatNo = seatNo; } public String getInvestWay() { return investWay; } public void setInvestWay(String investWay) { this.investWay = investWay; } public String getEntrustDirection() { return entrustDirection; } public void setEntrustDirection(String entrustDirection) { this.entrustDirection = entrustDirection; } public String getEntrustPrice() { return entrustPrice; } public void setEntrustPrice(String entrustPrice) { this.entrustPrice = entrustPrice; } public String getEntrustAmount() { return entrustAmount; } public void setEntrustAmount(String entrustAmount) { this.entrustAmount = entrustAmount; } public String getEntrustTime() { return entrustTime; } public void setEntrustTime(String entrustTime) { this.entrustTime = entrustTime; } public String getReportTime() { return reportTime; } public void setReportTime(String reportTime) { this.reportTime = reportTime; } public String getBusinessAmount() { return businessAmount; } public void setBusinessAmount(String businessAmount) { this.businessAmount = businessAmount; } public String getBusinessBalance() { return businessBalance; } public void setBusinessBalance(String businessBalance) { this.businessBalance = businessBalance; } public String getWithdrawAmount() { return withdrawAmount; } public void setWithdrawAmount(String withdrawAmount) { this.withdrawAmount = withdrawAmount; } public String getAmentrustStatus() { return amentrustStatus; } public void setAmentrustStatus(String amentrustStatus) { this.amentrustStatus = amentrustStatus; } public String getCancelInfo() { return cancelInfo; } public void setCancelInfo(String cancelInfo) { this.cancelInfo = cancelInfo; } public String getAssetId() { return assetId; } public void setAssetId(String assetId) { this.assetId = assetId; } public String getPositionStr() { return positionStr; } public void setPositionStr(String positionStr) { this.positionStr = positionStr; } }
true
a99b4880d95f8b88ef898f5d358511024003f7ca
Java
myles800/ApplicationFrameworkWebshop
/src/main/java/ehb/applicationframeworkwebshop/Repository/CartRepository.java
UTF-8
320
1.890625
2
[]
no_license
package ehb.applicationframeworkwebshop.Repository; import ehb.applicationframeworkwebshop.Model.Cart; import ehb.applicationframeworkwebshop.Model.User; import org.springframework.data.repository.CrudRepository; public interface CartRepository extends CrudRepository<Cart,Integer> { Cart findByUser(User user); }
true
d4b6866406b866aba96b91b76c809864056ffc65
Java
elkyur/mafia
/mafia/src/GraphicInterface/DataManager/PelaajaTietokantaManageri.java
UTF-8
1,804
2.328125
2
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package GraphicInterface.DataManager; import java.io.IOException; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JPanel; import mafia.hahmot.Pelaaja; import mafia.peli.TietokantaHallinta.TietokantaManageri; /** * * Tämä on Pelaajan paneeli joka extendaa yleistä graafiasta tietokanta managerii */ public class PelaajaTietokantaManageri extends abstractManager { public PelaajaTietokantaManageri(TietokantaManageri rakentaja, TietokantaALiRajapinta luonti, String k) { super(rakentaja, luonti, k); } @Override public void Kaanna(ArrayList<Object> objectit) { ArrayList<String> abc = super.palautaRivit(); ArrayList<Pelaaja> pelaajat = new ArrayList<Pelaaja>(); abc.clear(); for (Object pelaaja : objectit) { Pelaaja p = (Pelaaja) pelaaja; pelaajat.add(p); abc.add(p.PalautaNimi() + ", " + p.palautaStatistiikka().palautaPelinLkm() + ", " + p.palautaStatistiikka().palautaVoittojenLkm()); } super.palautaTietokantaManageri().asetaPelaajat(pelaajat); } @Override public void KirjoitaTiedostoon() { ArrayList<Pelaaja> pelaajat = new ArrayList<Pelaaja>(); for (Object object : super.palautaObjectit()) { Pelaaja p = (Pelaaja) object; pelaajat.add(p); } super.palautaTietokantaManageri().asetaPelaajat(pelaajat); try { super.palautaTietokantaManageri().UudistaPelaajat(); } catch (IOException ex) { Logger.getLogger(PelaajaTietokantaManageri.class.getName()).log(Level.SEVERE, null, ex); } } }
true
7d298c74e8d7bb08467e94a0617f2ebc26a8c159
Java
stefanbirkner/jenkinsfile-runner
/vanilla-package/src/test/java/io/jenkins/jenkinsfile/runner/vanilla/SmokeTest.java
UTF-8
5,168
2.484375
2
[ "MIT" ]
permissive
package io.jenkins.jenkinsfile.runner.vanilla; import org.apache.commons.io.FileUtils; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.junit.contrib.java.lang.system.SystemErrRule; import org.junit.contrib.java.lang.system.SystemOutRule; import org.junit.rules.TemporaryFolder; import org.junit.rules.Timeout; import java.io.File; import java.nio.charset.Charset; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.CoreMatchers.*; public class SmokeTest { @Rule public TemporaryFolder tmp = new TemporaryFolder(); @Rule public final SystemOutRule systemOut = new SystemOutRule().enableLog(); @Rule public final SystemErrRule systemErr = new SystemErrRule().enableLog(); @Rule public Timeout globalTimeout = Timeout.seconds(120); @Test public void helloWorld() throws Throwable { File jenkinsfile = tmp.newFile("Jenkinsfile"); FileUtils.writeStringToFile(jenkinsfile, "echo 'Hello, world!'", Charset.defaultCharset()); int result = JFRTestUtil.runAsCLI(jenkinsfile); assertThat("JFR should be executed successfully", result, equalTo(0)); assertThat(systemOut.getLog(), containsString("Hello, world!")); } @Test public void shouldFailWithWrongJenkinsfile() throws Throwable { File jenkinsfile = new File(tmp.getRoot(), "Jenkinsfile"); int result = JFRTestUtil.run(jenkinsfile); assertThat("JFR should fail when there is no Jenkinsfile", result, not(equalTo(0))); assertThat(systemOut.getLog(), containsString("does not exist")); } // TODO: uncomment once JFR can do something about timeouts internally @Test @Ignore public void shouldHangWhenPipelineHangs() throws Throwable { File jenkinsfile = new File(tmp.getRoot(), "Jenkinsfile"); FileUtils.writeStringToFile(jenkinsfile, "stage('Hang!') {\n" + " node {\n" + " while(true) {\n" + " // it hangs\n" + " }\n" + " }\n" + "}", Charset.defaultCharset()); int result = JFRTestUtil.run(jenkinsfile); assertThat("JFR should fail when there is no Jenkinsfile", result, not(equalTo(0))); } @Test public void pipelineExecutionFails() throws Throwable { File jenkinsfile = tmp.newFile("Jenkinsfile"); FileUtils.writeStringToFile(jenkinsfile, "node {\n" + " currentBuild.result = 'FAILED'\n" + "}", Charset.defaultCharset()); int result = JFRTestUtil.runAsCLI(jenkinsfile); assertThat("JFR should fail when there is no Jenkinsfile", result, not(equalTo(0))); assertThat(systemOut.getLog(), containsString("Finished: FAILURE")); } @Test public void pipelineExecutionUnstable() throws Throwable { File jenkinsfile = tmp.newFile("Jenkinsfile"); FileUtils.writeStringToFile(jenkinsfile, "node {\n" + " currentBuild.result = 'UNSTABLE'\n" + "}", Charset.defaultCharset()); int result = JFRTestUtil.runAsCLI(jenkinsfile); assertThat("JFR should fail when there is no Jenkinsfile", result, not(equalTo(0))); assertThat(systemOut.getLog(), containsString("Finished: UNSTABLE")); } @Test public void pipelineBadSyntax() throws Throwable { File jenkinsfile = tmp.newFile("Jenkinsfile"); FileUtils.writeStringToFile(jenkinsfile, "pipeline {\n" + " agent any\n" + " parameters {\n" + " string(name: 'param1', defaultValue: '', description: 'Greeting message')\n" + " string(name: 'param2', defaultValue: '', description: '2nd parameter')\n" + " }\n" + " stages {\n" + " stage('Build') {\n" + " // Missing steps, then it fails\n" + " echo 'Hello world!'\n" + " echo \"Value for param1: ${params.param1}\"\n" + " echo \"Value for param2: ${params.param2}\"\n" + " }\n" + " }\n" + "}", Charset.defaultCharset()); int result = JFRTestUtil.runAsCLI(jenkinsfile); assertThat("JFR should fail when there is no Jenkinsfile", result, not(equalTo(0))); assertThat(systemOut.getLog(), not(containsString("[Pipeline] End of Pipeline"))); assertThat(systemOut.getLog(), containsString("Finished: FAILURE")); assertThat(systemOut.getLog(), containsString("Unknown stage section")); } @Test public void shouldSupportDataboundMethods() throws Throwable { File jenkinsfile = tmp.newFile("Jenkinsfile"); FileUtils.writeStringToFile(jenkinsfile, "node {\n" + " checkout scm\n" + "}\n", Charset.defaultCharset()); int result = JFRTestUtil.runAsCLI(jenkinsfile); assertThat("JFR should be executed successfully", result, equalTo(0)); } }
true
3ac4e4065c94f7108402db2799010ac036904f03
Java
csgvsjay1000/FLY
/FLY-Monitor/Monitor-Demo/src/main/java/ivg/cn/monitor/jmx/Hello.java
UTF-8
363
2.546875
3
[]
no_license
package ivg.cn.monitor.jmx; public class Hello implements HelloMBean{ private String name = "fly"; public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String printHello() { return "Hello, "+name; } @Override public String printHello(String who) { return "Hello, "+who; } }
true
8630c647d9f6cdddace2e7d4605864b4c64e4e74
Java
Q-100/java_study
/src/JavaStudy_210131_polymorphism1.java
UTF-8
2,134
3.9375
4
[]
no_license
import java.util.Scanner; public class JavaStudy_210131_polymorphism1 { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); buyer b = new buyer(); b.money = 10000; b.bonus = 0; Tv2 tv = new Tv2(); Computer c = new Computer(); Audio a = new Audio(); /* tv.price = 5000; tv.bonus = 10; c.price = 3000; c.bonus = 5; a.bonus = 30; a.price = 1000; */ int flag = 1; while (b.money>0){ System.out.println("무엇을 구매하시겠습니까?"); System.out.println("1. Tv"); System.out.println("2. Computer"); System.out.println("3. Audio"); int check = scanner.nextInt(); if (check == 1){ b.buy(tv); } else if(check == 2){ b.buy(c); } else{ b.buy(a); } System.out.println("남은 돈은"+b.money+"이며"+"보너스는"+b.bonus+"입니다."); } System.out.println("돈이 부족합니다."); } } class buyer{ int money; int bonus; void buy(Product p){ // Product는 티비 컴퓨터 오디오 모두의 조상이여서 다형성을 이용해 여러 참조변수를 한번에 매개변수로 받을수 있다. this.money -= p.price; this.bonus += p.bonus; System.out.println(p.toString()+"를 구매하셨습니다."); } } class Product{ int price; int bonus; Product(int price){ this.price = price; } } class Tv2 extends Product{ Tv2(){ super(1000); // Tv2인스턴스가 만들어졌고 그안의 price에 1000원이 저장된거임(super) } public String toString(){ return "Tv"; } } class Computer extends Product{ Computer(){ super(3000); } public String toString(){ return "Computer"; } } class Audio extends Product{ Audio(){ super(500); } public String toString(){ return "Audio"; } }
true
3c41510635a5675cc7a33dc04270638b19b795a3
Java
LuciaBRguez/Bus-ticket
/src/main/java/impl/miw/business/reservamanager/ReservaManager.java
ISO-8859-10
4,561
1.914063
2
[]
no_license
package impl.miw.business.reservamanager; import org.springframework.beans.factory.annotation.Autowired; import com.miw.business.ReservaManagerService; import com.miw.business.ViajeManagerService; import com.miw.model.DatosPago; import com.miw.model.Extras; import com.miw.model.IdReserva; import com.miw.model.Reserva; import com.miw.model.Viaje; import com.miw.model.ViajeElegido; import com.miw.persistence.ReservaDataService; public class ReservaManager implements ReservaManagerService { @Autowired private ReservaDataService reservaDataService = null; public void setReservaDataService(ReservaDataService reservaDataService) { System.out.println("Setting viajeDataService bean"); this.reservaDataService = reservaDataService; } @Autowired private ViajeManagerService viajeManagerService = null; public void setViajeManagerService(ViajeManagerService viajeManagerService) { System.out.println("Setting viajeDataService bean"); this.viajeManagerService = viajeManagerService; } public void creaReserva(ViajeElegido viajeElegido, ViajeElegido viajeElegidoIda, Extras extras, DatosPago datosPago) throws Exception { Reserva reserva = new Reserva(); IdReserva idReserva = new IdReserva(); // Viaje elegido reserva.setId_ida(viajeElegidoIda.getId_ida()); reserva.setVuelta(viajeElegido.isVuelta()); reserva.setNum_viajeros(viajeElegido.getNum_viajeros()); // Extras reserva.setBicicleta(extras.isBicicleta()); reserva.setMascota(extras.isMascota()); reserva.setTabla_surf(extras.isTabla_surf()); reserva.setEsquies(extras.isEsquies()); reserva.setSeguro(extras.isSeguro()); // Datos pago reserva.setNombre(datosPago.getNombre()); reserva.setApellidos(datosPago.getApellidos()); reserva.setTipo_identificacion(datosPago.getTipo_identificacion()); reserva.setIdentificacion(datosPago.getIdentificacion()); reserva.setEmail(datosPago.getEmail()); this.reservaDataService.creaReserva(reserva); this.viajeManagerService.updateIda(viajeElegidoIda.getId_ida(), viajeElegido.getNum_viajeros(), true); //Aadimos el id de reserva a nuestro objeto reserva idReserva.setId(this.reservaDataService.getId()); } public void creaReservaIdavuelta(ViajeElegido viajeElegido, ViajeElegido viajeElegidoIdaVuelta, Extras extras, DatosPago datosPago) throws Exception { Reserva reserva = new Reserva(); IdReserva idReserva = new IdReserva(); // Viaje elegido reserva.setId_ida(viajeElegidoIdaVuelta.getId_ida()); reserva.setVuelta(viajeElegido.isVuelta()); reserva.setId_vuelta(viajeElegidoIdaVuelta.getId_vuelta()); reserva.setNum_viajeros(viajeElegido.getNum_viajeros()); // Extras reserva.setBicicleta(extras.isBicicleta()); reserva.setMascota(extras.isMascota()); reserva.setTabla_surf(extras.isTabla_surf()); reserva.setEsquies(extras.isEsquies()); reserva.setSeguro(extras.isSeguro()); // Datos pago reserva.setNombre(datosPago.getNombre()); reserva.setApellidos(datosPago.getApellidos()); reserva.setTipo_identificacion(datosPago.getTipo_identificacion()); reserva.setIdentificacion(datosPago.getIdentificacion()); reserva.setEmail(datosPago.getEmail()); this.reservaDataService.creaReservaIdaVuelta(reserva); this.viajeManagerService.updateIdaVuelta(viajeElegidoIdaVuelta.getId_ida(), viajeElegidoIdaVuelta.getId_vuelta(), viajeElegido.getNum_viajeros(), true); //Aadimos el id de reserva a nuestro objeto reserva idReserva.setId(this.reservaDataService.getId()); } public Integer getId() throws Exception { return this.reservaDataService.getId(); } public boolean eliminarReserva(String email, Integer id) throws Exception { if(this.existeReserva(email, id)) { Reserva reserva = this.getReserva(email,id); Viaje viajeIda = this.viajeManagerService.getViaje(reserva.getId_ida()); if(reserva.isVuelta()) { Viaje viajeVuelta=this.viajeManagerService.getViaje(reserva.getId_vuelta()); this.viajeManagerService.updateIdaVuelta(viajeIda.getId(), viajeVuelta.getId(), reserva.getNum_viajeros(), false); } else { this.viajeManagerService.updateIda(viajeIda.getId(), reserva.getNum_viajeros(), false); } this.reservaDataService.eliminarReserva(email, id); return true; }else { return false; } } public boolean existeReserva(String email, Integer id) throws Exception { return this.reservaDataService.existeReserva(email, id); } public Reserva getReserva(String email, Integer id) throws Exception { return this.reservaDataService.getReserva(email, id); } }
true
88b214e21d9f2f7a8f40301454242a42113e083e
Java
KaminskiJakub/Tommy-Burgers
/src/MainBurger.java
UTF-8
853
3.703125
4
[]
no_license
public class MainBurger { public static void main(String[] args) { ClassicBurger classicBurger1 = new ClassicBurger("Classico", "beef", 2.25, "wheat"); double price = classicBurger1.itemizeBurger(); classicBurger1.addBurgerAddition1("Tomato", 0.35); classicBurger1.addBurgerAddition2("Lettuce", 0.50); classicBurger1.addBurgerAddition3("Cheese", 1); System.out.println("Total burger price is: "+ classicBurger1.itemizeBurger() + " euro."); VegeBurger vegeBurger1 = new VegeBurger("soy chop", 5); vegeBurger1.addBurgerAddition1("Arugula", 0.7); vegeBurger1.addVegeAddition1("Courgette", 1.25); System.out.println("Total VegeBurger price is: " + vegeBurger1.itemizeBurger()); ExtraBurger extraBurger1 = new ExtraBurger(); extraBurger1.addBurgerAddition3("Should not do this", 50.50); extraBurger1.itemizeBurger(); } }
true
f9e9b61209de358c28f4d16a9a0484946d259bad
Java
tilenp/JavaConcurrency
/synchronization/solveWithImmutability/ImmutableObject.java
UTF-8
363
2.890625
3
[]
no_license
public class ImmutableObject { private final int number; private final int encodedNumber; public ImmutableObject(int number, int encodedNumber) { this.number = number; this.encodedNumber = encodedNumber; } public Integer getEncodedNumber(int number) { return this.number == number ? encodedNumber : null; } }
true
7d8f23803a071835969aa045727494c4d3f87243
Java
workspaceit/pmc-android
/app/src/main/java/com/workspaceit/photoclubbingme/activity/MainActivity.java
UTF-8
7,300
1.796875
2
[]
no_license
package com.workspaceit.photoclubbingme.activity; import android.app.ActivityOptions; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Bitmap; import android.graphics.Color; import android.os.Build; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.MenuItem; import android.view.View; import uk.co.chrisjenx.calligraphy.CalligraphyContextWrapper; import com.workspaceit.photoclubbingme.EventBus.LocationItemClickEventBus; import com.workspaceit.photoclubbingme.R; import com.workspaceit.photoclubbingme.activity.fragments.LocationTabFragmentHolder; import com.workspaceit.photoclubbingme.adapter.EventAdapter; import com.workspaceit.photoclubbingme.adapter.FolderAdapter; import com.workspaceit.photoclubbingme.adapter.PagerAdapter; import com.workspaceit.photoclubbingme.adapter.ThumbnailAdapter; import android.support.design.widget.TabLayout; import android.support.v4.view.ViewPager; import android.view.Menu; import android.widget.Toast; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import org.greenrobot.eventbus.ThreadMode; public class MainActivity extends AppCompatActivity implements View.OnClickListener, FolderAdapter.ItemClickListener, ThumbnailAdapter.ItemClickListener { private EventAdapter eventAdapter; private ThumbnailAdapter thumbnailAdapter; private Toolbar toolbar; private SharedPreferences sharedPref; // tab page adapter private PagerAdapter adapter; private ViewPager viewPager; private boolean isLoggedIn=false; @Override protected void attachBaseContext(Context newBase) { super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase)); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); getSupportActionBar().setDisplayShowTitleEnabled(false); TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout); tabLayout.addTab(tabLayout.newTab().setText("Locations")); tabLayout.addTab(tabLayout.newTab().setText("Events")); tabLayout.addTab(tabLayout.newTab().setText("SlideShows")); tabLayout.setTabGravity(TabLayout.GRAVITY_FILL); viewPager = (ViewPager) findViewById(R.id.pager); // create the pager adapter only if it the first time it loaded if (adapter == null) { adapter = new PagerAdapter(getSupportFragmentManager()); } for(int i=0; i<tabLayout.getTabCount(); i++) { tabLayout.getTabAt(i).setText(adapter.getPageTitle(i)); tabLayout.getTabAt(i).setCustomView(R.layout.tab_text); } viewPager.setAdapter(adapter); viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout)); tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() { @Override public void onTabSelected(TabLayout.Tab tab) { final TabLayout.Tab finalTab = tab; runOnUiThread(new Runnable() { @Override public void run() { viewPager.setCurrentItem(finalTab.getPosition()); } }); } @Override public void onTabUnselected(TabLayout.Tab tab) { } @Override public void onTabReselected(TabLayout.Tab tab) { } }); sharedPref = this.getSharedPreferences("MyData", Context.MODE_PRIVATE); isLoggedIn=sharedPref.getBoolean("isLoggedIn",false); EventBus.getDefault().register(this); } @Override protected void onDestroy() { super.onDestroy(); EventBus.getDefault().unregister(this); } @Subscribe(threadMode = ThreadMode.MAIN) public void onMessageEvent(LocationItemClickEventBus event) { Fragment targetFragment = adapter.getItem(0); if (targetFragment instanceof LocationTabFragmentHolder) { LocationTabFragmentHolder locationTab = (LocationTabFragmentHolder) targetFragment; locationTab.showFragment(LocationTabFragmentHolder.USE_FRAGMENT_EVENTS, true); } } @Override public boolean onCreateOptionsMenu(Menu menu) { //getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); // if (id == R.id.action_settings) { // return true; // } return super.onOptionsItemSelected(item); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.loc_name: case R.id.city_count: case R.id.recent_locations: Fragment targetFragment = adapter.getItem(0); if (targetFragment instanceof LocationTabFragmentHolder) { LocationTabFragmentHolder locationTab = (LocationTabFragmentHolder) targetFragment; locationTab.showFragment(LocationTabFragmentHolder.USE_FRAGMENT_VENUE, true); } //startActivity(new Intent(this,FolderActivity.class)); break; } if(v.getId() == R.id.event_name){ startActivity(new Intent(this,FolderActivity.class)); } } @Override public void onFolderClick(View view, int position) { startActivity(new Intent(this, FolderActivity.class)); } @Override public void onThumbnailClick(View view, int position) { Bundle b = null; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { //b = ActivityOptions.makeScaleUpAnimation(view, 0, 0, view.getWidth(), // view.getHeight()).toBundle(); Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888); bitmap.eraseColor(Color.parseColor("#211f49")); b = ActivityOptions.makeThumbnailScaleUpAnimation(view, bitmap, 0, 5).toBundle(); } startActivity(new Intent(this, FolderActivity.class), b); } @Override public void onThumbnailLongClick(View view, int position) { // if(!thumbnailAdapter.is_in_action_mode){ // toolbar.getMenu().clear(); // toolbar.inflateMenu(R.menu.multi_selected_menu); // // thumbnailAdapter.is_in_action_mode = true; // thumbnailAdapter.notifyDataSetChanged(); // }else{ // toolbar.getMenu().clear(); // thumbnailAdapter.is_in_action_mode = false; // thumbnailAdapter.notifyDataSetChanged(); // } } }
true
6abec2d45c337a3c9f676b6d5cd6d025cb85dd12
Java
rikinpatoliya/android-5
/apps/air/src/main/java/com/ttdevs/air/MainActivityBack.java
UTF-8
8,802
2.015625
2
[ "MIT" ]
permissive
//package com.ttdevs.air; // //import android.bluetooth.BluetoothAdapter; //import android.bluetooth.BluetoothClass; //import android.bluetooth.BluetoothDevice; //import android.bluetooth.BluetoothServerSocket; //import android.bluetooth.BluetoothSocket; //import android.content.BroadcastReceiver; //import android.content.Context; //import android.content.Intent; //import android.content.IntentFilter; //import android.os.Bundle; //import android.support.design.widget.FloatingActionButton; //import android.support.v7.app.AppCompatActivity; //import android.support.v7.widget.Toolbar; //import android.view.Menu; //import android.view.MenuItem; //import android.view.View; //import android.widget.Toast; // //import java.io.IOException; //import java.io.InputStream; //import java.io.OutputStream; //import java.util.Set; //import java.util.UUID; // //public class MainActivityBack extends AppCompatActivity { // // private static final int REQUEST_ENABLE_BT = 2333; // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_main); // Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); // setSupportActionBar(toolbar); // // FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); // fab.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View view) { // findBluetooth(); // // } // }); // // IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); // registerReceiver(mReceiver, filter); // } // // @Override // public boolean onCreateOptionsMenu(Menu menu) { // getMenuInflater().inflate(R.menu.main, menu); // return true; // } // // @Override // public boolean onOptionsItemSelected(MenuItem item) { // int id = item.getItemId(); // if (id == R.id.action_settings) { // return true; // } // return super.onOptionsItemSelected(item); // } // // @Override // protected void onActivityResult(int requestCode, int resultCode, Intent data) { // super.onActivityResult(requestCode, resultCode, data); // // // TODO: 2017/1/20 // } // // @Override // protected void onDestroy() { // super.onDestroy(); // // unregisterReceiver(mReceiver); // } // // private void findBluetooth() { // BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); // if (null == mBluetoothAdapter) { // Toast.makeText(this, "mBluetoothAdapter is null", Toast.LENGTH_SHORT).show(); // return; // } // if (!mBluetoothAdapter.isEnabled()) { // Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); // startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); // return; // } // //// {// 启用可发现 //// Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); //// discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300); //// startActivity(discoverableIntent); //// } // // Toast.makeText(this, "BluetoothAdapter enable", Toast.LENGTH_SHORT).show(); // Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices(); // if (pairedDevices.size() > 0) { // for (BluetoothDevice device : pairedDevices) { // String msg = device.getName() + "::" + device.getAddress(); // System.err.println(">>>>> " + msg); // } // } //// new AcceptThread().start(); // //// { //// if (mBluetoothAdapter.isDiscovering()) { //// mBluetoothAdapter.cancelDiscovery(); //// } //// mBluetoothAdapter.startDiscovery(); //// } // // sendMessage(mBluetoothAdapter); // } // // private void sendMessage(BluetoothAdapter mBluetoothAdapter) { // String PROTOCOL_SCHEME_RFCOMM = "btspp"; // UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb"); // String address = "20:16:11:16:99:43"; // // try { // BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address); // BluetoothSocket socket = device.createRfcommSocketToServiceRecord(uuid); //// BluetoothServerSocket serverSocket = mBluetoothAdapter.listenUsingRfcommWithServiceRecord(PROTOCOL_SCHEME_RFCOMM, uuid); //// BluetoothSocket socket = serverSocket.accept(); // socket.connect(); // OutputStream out = socket.getOutputStream(); // out.write("12345".getBytes()); // out.flush(); // // InputStream in = socket.getInputStream(); // byte[] buffer = new byte[1024]; // int bytes; // while (true) { // try { // // Read from the InputStream // bytes = in.read(buffer); // System.out.println("<><><><><>" + bytes); // // out.write("67890".getBytes()); // out.flush(); // } catch (IOException e) { // e.printStackTrace(); // } // } // } catch (Exception e) { // e.printStackTrace(); // } // } // // // private final BroadcastReceiver mReceiver = new BroadcastReceiver() { // @Override // public void onReceive(Context context, Intent intent) { // String action = intent.getAction(); // if (BluetoothDevice.ACTION_FOUND.equals(action)) { // BluetoothClass clazz = intent.getParcelableExtra(BluetoothDevice.EXTRA_CLASS); // BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); // // String msg = device.getName() + "::" + device.getAddress(); // System.err.println(">>>>>found: " + msg); // } // } // }; // // // class AcceptThread extends Thread { // private String NAME_SECURE = "BluetoothChatSecure"; // private UUID MY_UUID_SECURE = UUID.fromString("00002a37-0000-1000-8000-00805f9b34fb"); // private UUID HC_06 = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb"); // private BluetoothServerSocket mmServerSocket; // private BluetoothAdapter mAdapter; // private BluetoothSocket socket = null; // // public AcceptThread() { // mAdapter = BluetoothAdapter.getDefaultAdapter(); // } // // @Override // public void run() { // try { // mmServerSocket = mAdapter.listenUsingRfcommWithServiceRecord(NAME_SECURE, MY_UUID_SECURE); // socket = mmServerSocket.accept(); // System.err.println(">>>>> accept"); // new ReceiveDataThread(socket).start(); // mmServerSocket.close(); // } catch (IOException e) { // e.printStackTrace(); // } // // } // } // // private class ReceiveDataThread extends Thread { // private final BluetoothSocket mmSocket; // private final InputStream mmInStream; // private final OutputStream mmOutStream; // // public ReceiveDataThread(BluetoothSocket socket) { // mmSocket = socket; // InputStream tmpIn = null; // OutputStream tmpOut = null; // // try { // tmpIn = socket.getInputStream(); // tmpOut = socket.getOutputStream(); // } catch (IOException e) { // e.printStackTrace(); // } // // mmInStream = tmpIn; // mmOutStream = tmpOut; // } // // @Override // public void run() { // byte[] buffer = new byte[1024]; // int bytes; // while (true) { // try { // // Read from the InputStream // bytes = mmInStream.read(buffer); // System.out.println("<><><><><>" + bytes); // } catch (IOException e) { // e.printStackTrace(); // } // } // } // // public void write(byte[] buffer) { // try { // mmOutStream.write(buffer); // } catch (IOException e) { // e.printStackTrace(); // } // } // // public void cancel() { // try { // mmSocket.close(); // } catch (IOException e) { // e.printStackTrace(); // } // } // } //}
true
a1e20f47e5b947ab3f9e942ec54b530fdc58bea5
Java
jimcoles/actionable
/actionables-pmc-ref/src/main/java/com/oculussoftware/bus/mkt/prod/StdFeatureTrashColl.java
UTF-8
3,742
1.992188
2
[ "Apache-2.0" ]
permissive
package com.oculussoftware.bus.mkt.prod; import com.oculussoftware.api.repi.*; import com.oculussoftware.api.sysi.*; import java.util.*; /** * Filename: StdFeatureTrashColl.java * Date: 7/17/00 * Description: * * Copyright 1-31-2000 Oculus Software. All Rights Reserved. * * @author Cuihua Zhang * @version 1.2 */ public class StdFeatureTrashColl extends StdFeatureColl { /* * Change Activity * * Issue number Programmer Date Description */ //----------------------------- Public Constructor ------------------------- /** Default constructor just initializes the product list */ protected String COL_STDFEATLINKID = "STDFEATURELINKID"; public StdFeatureTrashColl() throws OculusException { super(); } protected StdFeatureTrashColl(Comparator sortCrit) throws OculusException { super (sortCrit); } //------------------------ Protected Methods -------------------------------- protected String getLoadQuery() throws ORIOException { return " SELECT feat.OBJECTID, feat.GUID AS FEAT_GUID, feat.CLASSID AS FEAT_CLASSID, feat.STATEID AS FEAT_STATEID, "+ "feat.ACCESSID AS FEAT_ACCESSID, feat.CREATORID AS FEAT_CREATORID, feat.CREATIONDATE AS FEAT_CREATIONDATE, feat.DELETESTATE AS FEAT_DELETESTATE, "+ "feat.FILEATTACHED AS FEAT_FILEATTACHED, feat.LINKATTACHED AS FEAT_LINKATTACHED, feat.DISCUSSATTACHED AS FEAT_DISCUSSATTACHED,"+ "feat.DEPENDENCIES, feat.ISSTANDARD, feat.LATESTREVISIONID, feat.VISIBLEID, feat.FEATURETYPEID, feat.ENGRSPECATTACHED,"+ "link.OBJECTID AS STDFEATLINKID, link.GUID AS LINK_GUID, link.CLASSID AS LINK_CLASSID, link.STATEID AS LINK_STATEID, "+ "link.ACCESSID AS LINK_ACCESSID, link.CREATORID AS LINK_CREATORID, link.CREATIONDATE AS LINK_CREATIONDATE, link.DELETESTATE, "+ "link.FILEATTACHED AS LINK_FILEATTACHED, link.LINKATTACHED AS LINK_LINKATTACHED, link.DISCUSSATTACHED AS LINK_DISCUSSATTACHED, "+ "link.FEATUREID AS LINK_FEATUREID,link.STDCOLLECTIONID,"+ "stdc.OBJECTID AS STDCID, stdc.GUID AS STDC_GUID, stdc.CLASSID AS STDC_CLASSID, stdc.STATEID AS STDC_STATEID, "+ "stdc.ACCESSID AS STDC_ACCESSID, stdc.CREATORID AS STDC_CREATORID, stdc.CREATIONDATE AS STDC_CREATIONDATE, stdc.DELETESTATE, "+ "stdc.FILEATTACHED AS STDC_FILEATTACHED, stdc.LINKATTACHED AS STDC_LINKATTACHED, stdc.DISCUSSATTACHED AS STDC_DISCUSSATTACHED, "+ "stdc.PARENTCOLLID AS STDC_PARENTID" + " FROM ((FEATURE feat LEFT OUTER JOIN STDFEATURELINK link ON feat.OBJECTID = link.FEATUREID) "+ " LEFT OUTER JOIN STANDARDSCOLLECTION stdc ON link.STDCOLLECTIONID = stdc.OBJECTID) "+ " WHERE stdc.DELETESTATE = "+DeleteState.NOT_DELETED.getIntValue()+ " AND link.DELETESTATE = " +DeleteState.DELETED.getIntValue(); } //------------------- IBusinessObjectList Methods -------------------------- public IRCollection setSort(Comparator sortCrit) throws OculusException { StdFeatureTrashColl sortedList = new StdFeatureTrashColl(sortCrit); sortedList._items.addAll(this._items); return sortedList; } //----------------- IPoolable Methods ------------------------------------ /** Returns a duplicate IProductList object, but without the ObjectContext */ public Object clone() { StdFeatureTrashColl featList = null; try { featList = new StdFeatureTrashColl(); featList.setIID(_iid); featList._items = this._items; featList.reset(); } catch (OculusException orioExp) {} return featList; } }
true
77ffa42ede7757bc2e7ae947d88c825265017251
Java
MengkZhang/ebook
/newapp/src/main/java/com/tzpt/cloudlibrary/modle/remote/newdownload/core/interceptor/connect/RedirectInterceptor.java
UTF-8
3,099
2.34375
2
[]
no_license
package com.tzpt.cloudlibrary.modle.remote.newdownload.core.interceptor.connect; import android.support.annotation.NonNull; import com.tzpt.cloudlibrary.modle.remote.newdownload.PDownload; import com.tzpt.cloudlibrary.modle.remote.newdownload.core.connection.DownloadConnection; import com.tzpt.cloudlibrary.modle.remote.newdownload.core.download.DownloadChain; import com.tzpt.cloudlibrary.modle.remote.newdownload.core.exception.InterruptException; import com.tzpt.cloudlibrary.modle.remote.newdownload.core.interceptor.Interceptor; import java.io.IOException; import java.net.HttpURLConnection; import java.net.ProtocolException; /** * Created by Administrator on 2018/8/6. */ public class RedirectInterceptor implements Interceptor.Connect { /** * How many redirects and auth challenges should we attempt? Chrome follows 21 redirects; * Firefox, curl, and wget follow 20; Safari follows 16; and HTTP/1.0 recommends 5. */ static final int MAX_REDIRECT_TIMES = 10; /** * The target resource resides temporarily under a different URI and the user agent MUST NOT * change the request method if it performs an automatic redirection to that URI. */ private static final int HTTP_TEMPORARY_REDIRECT = 307; /** * The target resource has been assigned a new permanent URI and any future references to this * resource ought to use one of the enclosed URIs. */ private static final int HTTP_PERMANENT_REDIRECT = 308; @NonNull @Override public DownloadConnection.Connected interceptConnect(DownloadChain chain) throws IOException { int redirectCount = 0; String url; DownloadConnection connection; while (true) { if (chain.getCache().isInterrupt()) { throw InterruptException.SIGNAL; } final DownloadConnection.Connected connected = chain.processConnect(); final int code = connected.getResponseCode(); if (!isRedirect(code)) { return connected; } if (++redirectCount >= MAX_REDIRECT_TIMES) { throw new ProtocolException("Too many redirect requests: " + redirectCount); } url = connected.getResponseHeaderField("Location"); if (url == null) { throw new ProtocolException( "Response code is " + code + " but can't find Location field"); } chain.releaseConnection(); connection = PDownload.with().connectionFactory().create(url); chain.setConnection(connection); chain.setRedirectLocation(url); } } private static boolean isRedirect(int code) { return code == HttpURLConnection.HTTP_MOVED_PERM || code == HttpURLConnection.HTTP_MOVED_TEMP || code == HttpURLConnection.HTTP_SEE_OTHER || code == HttpURLConnection.HTTP_MULT_CHOICE || code == HTTP_TEMPORARY_REDIRECT || code == HTTP_PERMANENT_REDIRECT; } }
true
72abb03a8742b5073377a3e40bc8f8edcc42d43b
Java
Vladnsk/JavaWebinar
/src/LoadTester.java
UTF-8
1,777
3.3125
3
[]
no_license
/** * Created by Владислав on 29.07.2017. */ public class LoadTester extends SoftwareTester { String skills; LoadTester(String firstName, String lastName, int age, char sex, int experience, String education) { super(firstName, lastName, age, sex, experience, education); } LoadTester(String firstName, String lastName, int age, char sex, int experience, String education, String skills) { super(firstName, lastName, age, sex, experience, education); this.skills = skills; } LoadTester(String name, String secondName, int salary) { super(name, secondName, salary); } public String getSkills(){ return this.skills; } public void setSkills(String skills){ this.skills = skills; } @Override public void printSoftwareTester(){ super.printSoftwareTester(); } public void printFullInfo(){ super.printSoftwareTester(); System.out.println("Навыки: " + getSkills()); System.out.println("---------------------------------"); } public int fullSalary(int bonus){ int result = getSalary() + 2500 * this.experience + bonus; return result; } public int [][] mirrorArray(int [][] mass){ int [][] array = new int[mass.length][mass.length]; for (int i = 0; i < mass.length; i++) { for (int j = 0; j < mass[i].length; j++) { array[i][j] = mass[i][mass.length-j-1]; } } for (int i = 0; i < array.length; i++) { for (int j = 0; j < array[i].length; j++) { System.out.print(array[i][j] + " "); } System.out.println(); } return array; } }
true
8abbefdfd87f1788137f2042585cdb8fec13bce7
Java
ducxomme/rent-room-market
/app/src/main/java/com/example/huuduc/intership_project/ui/activity/add_room/CreateRoomActivity.java
UTF-8
14,868
1.765625
2
[]
no_license
package com.example.huuduc.intership_project.ui.activity.add_room; import android.Manifest; import android.app.AlertDialog; import android.content.Intent; import android.content.pm.PackageManager; import android.net.Uri; import android.os.Bundle; import android.provider.MediaStore; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.example.huuduc.intership_project.R; import com.example.huuduc.intership_project.data.listener.ImageListener; import com.example.huuduc.intership_project.data.listener.OnItemClickListener; import com.example.huuduc.intership_project.data.model.Room; import com.example.huuduc.intership_project.data.network.model_response.DistrictResponse; import com.example.huuduc.intership_project.data.network.model_response.WardResponse; import com.example.huuduc.intership_project.ui.activity.district.DistrictActivity; import com.example.huuduc.intership_project.ui.activity.ward.WardActivity; import com.example.huuduc.intership_project.ui.adapter.ImageAdapter; import com.example.huuduc.intership_project.ui.base.BaseActivity; import com.example.huuduc.intership_project.utils.Constant; import com.example.huuduc.intership_project.utils.DatabaseService; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import cn.pedant.SweetAlert.SweetAlertDialog; public class CreateRoomActivity extends BaseActivity implements ICreRoomView { @BindView(R.id.toolbar) Toolbar toolbar; @BindView(R.id.edPrice) EditText edPrice; @BindView(R.id.edArea) EditText edArea; @BindView(R.id.edRoomEmpty) EditText edRoomEmpty; @BindView(R.id.edDistrict) EditText edDistrict; @BindView(R.id.edWard) EditText edWard; @BindView(R.id.edAddress) EditText edAddress; @BindView(R.id.edPhone) EditText edPhone; @BindView(R.id.edDescription) EditText edDescription; @BindView(R.id.btnUpImage) Button btnUpImage; @BindView(R.id.btnUpRoom) Button btnUpRoom; @BindView(R.id.rvListImage) RecyclerView rvListImage; private List<String> listImage; private ImageAdapter mImageAdapter; CreRoomPresenter mPresenter; private DistrictResponse district; private WardResponse ward; // chup anh private String userChoosenTask; private Uri filePath = null; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_new_room); ButterKnife.bind(this); addControls(); } @OnClick({R.id.edDistrict, R.id.edWard, R.id.btnUpImage, R.id.btnUpRoom}) void onClick(View view) { switch (view.getId()) { case R.id.edDistrict: mPresenter.getAllDistrict(); break; case R.id.edWard: if (district != null) { mPresenter.getAllWard(district.getDistrictid()); } break; case R.id.btnUpImage: handleImage(); break; case R.id.btnUpRoom: String roomPrice = edPrice.getText().toString().trim(); String roomArea = edArea.getText().toString().trim(); String roomEmpty = edRoomEmpty.getText().toString().trim(); String roomAddress = edAddress.getText().toString().trim(); String phone = edPhone.getText().toString().trim(); String description = edDescription.getText().toString().trim(); if (TextUtils.isEmpty(roomPrice) || TextUtils.isEmpty(roomArea) || TextUtils.isEmpty(roomEmpty) || TextUtils.isEmpty(roomAddress) || TextUtils.isEmpty(phone) || TextUtils.isEmpty(description) || district == null || ward == null || listImage.size() == 0) { showMessage("Thông báo", "Bạn vui lòng nhập đủ thông tin", SweetAlertDialog.WARNING_TYPE); } else { btnUpRoom.setEnabled(false); btnUpImage.setEnabled(false); showLoading("Đang đăng phòng"); mPresenter.pushImageToStorage(listImage, new ImageListener() { @Override public void success(List<String> listImageUrl) { listImage.clear(); listImage.addAll(listImageUrl); // get date public DateFormat df = new SimpleDateFormat("dd/MM/yyyy"); Date today = Calendar.getInstance().getTime(); // Set gia tri de qua Presenter Room room = new Room(); room.setAddress(roomAddress); room.setArea(Integer.valueOf(roomArea)); room.setDate_public(df.format(today)); room.setDescription(description); room.setDistrictId(String.valueOf(district.getDistrictid())); room.setDistrict(district.getType() + " " + district.getName()); room.setImage(listImage.get(0)); room.setPhone(phone); room.setPrice(Integer.valueOf(roomPrice)); room.setPublic(true); room.setRating("0"); room.setRoom_empty(Integer.valueOf(roomEmpty)); room.setUser_id(DatabaseService.getUserID()); room.setWardId(String.valueOf(ward.getWardid())); room.setWard(ward.getType() + " " + ward.getName()); mPresenter.pushNewRoom(listImageUrl, room, district, ward); } @Override public void failed(String error) { showMessage("Thông báo", "Lỗi lưu ảnh lên CSDL", SweetAlertDialog.WARNING_TYPE); } }); } break; } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == RESULT_OK) { if (requestCode == Constant.REQUEST_CODE) { if (data.getParcelableExtra(Constant.DISTRICT) != null) { district = data.getParcelableExtra(Constant.DISTRICT); edDistrict.setText(district.toString()); } if (data.getParcelableExtra(Constant.WARD) != null) { ward = data.getParcelableExtra(Constant.WARD); edWard.setText(ward.toString()); } } else if (requestCode == Constant.REQUEST_CAMERA) { filePath = data.getData(); // FirebaseStorage.getInstance().getReference().child("Photos/").child(filePath.getLastPathSegment()) // .putFile(filePath) // .addOnSuccessListener(taskSnapshot -> { // Uri downloadUrl = taskSnapshot.getDownloadUrl(); // Log.e("DownloadUrl", downloadUrl.toString()); // }); listImage.add(filePath.toString()); Log.e("lisImage", listImage.toString()); mImageAdapter.notifyDataSetChanged(); } else if (requestCode == Constant.SELECT_FILE) { filePath = data.getData(); Log.e("filePath", filePath.toString()); // FirebaseStorage.getInstance().getReference().child("Photos/").child(filePath.getLastPathSegment()) // .putFile(filePath) // .addOnSuccessListener(taskSnapshot -> { // Uri downloadUrl = taskSnapshot.getDownloadUrl(); // Log.e("DownloadUrl", downloadUrl.toString()); // }); listImage.add(filePath.toString()); mImageAdapter.notifyDataSetChanged(); } } } private void addControls() { setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setTitle("Đăng phòng"); listImage = new ArrayList<>(); mPresenter = new CreRoomPresenter(this); mImageAdapter = new ImageAdapter(this, listImage, new OnItemClickListener() { @Override public void onClick(int pos) { if (listImage.size() != 0) listImage.remove(pos); mImageAdapter.notifyItemRemoved(pos); } @Override public void onLikeClick(int pos) { } @Override public void roomClick(Room room) { } }); rvListImage.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false)); rvListImage.setAdapter(mImageAdapter); } @Override public boolean onSupportNavigateUp() { onBackPressed(); return true; } @Override public void onBackPressed() { super.onBackPressed(); finish(); } @Override public void showListDistrict(List<DistrictResponse> listDistrict) { Log.e("listDistrict", listDistrict.size() + ""); Bundle bundle = new Bundle(); bundle.putParcelableArrayList(Constant.LIST_DISTRICT_BUNDLE, (ArrayList) listDistrict); bundle.putParcelable(Constant.DISTRICT, district); this.goNextScreen(DistrictActivity.class, bundle, Constant.REQUEST_CODE); } @Override public void showListWard(List<WardResponse> listWard) { Log.e("listWard", listWard.size() + ""); Bundle bundle = new Bundle(); bundle.putParcelableArrayList(Constant.LIST_WARD_BUNDLE, (ArrayList) listWard); bundle.putParcelable(Constant.WARD, ward); this.goNextScreen(WardActivity.class, bundle, Constant.REQUEST_CODE); } @Override public void pushRoomSuccess() { hideLoading(); showMessage("Thông báo", "Đăng phòng thành công", SweetAlertDialog.SUCCESS_TYPE); finish(); } public void handleImage() { final CharSequence[] items = {"Take Photo", "Choose from Library", "Cancel"}; AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Add Photo!"); final Boolean result = ContextCompat.checkSelfPermission(this, android.Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED; Log.d("RESULT", result.toString()); builder.setItems(items, (dialog, i) -> { if (items[i].equals("Take Photo")) { userChoosenTask = "Take Photo"; if (checkCamPermission()) cameraIntent(); } else if (items[i].equals("Choose from Library")) { userChoosenTask = "Choose from Library"; if (checkGaleryPermission()) galleryIntent(); } else if (items[i].equals("Cancel")) { dialog.dismiss(); } }); builder.show(); } public Boolean checkCamPermission() { if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.CAMERA}, Constant.REQUEST_CAMERA); return false; } else { return true; } } private void cameraIntent() { Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); startActivityForResult(intent, Constant.REQUEST_CAMERA); } private void galleryIntent() { Intent intent = new Intent(); intent.setType("image/*"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(Intent.createChooser(intent, "Select File"), Constant.SELECT_FILE); } public Boolean checkGaleryPermission() { if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE}, Constant.SELECT_FILE); return false; } else { return true; } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); switch (requestCode) { case Constant.REQUEST_CAMERA: if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) { cameraIntent(); } } else { Toast.makeText(this, "Can't get camera because of permission denied", Toast.LENGTH_LONG).show(); } break; case Constant.SELECT_FILE: if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { galleryIntent(); } } else { Toast.makeText(this, "Can't get gallery because of permission denied", Toast.LENGTH_LONG).show(); } break; } } }
true
4b9717a4c7d383dd1011b5f442d89b5fdfcdb5dd
Java
frsierrag/DangerZone
/app/src/main/java/com/grupo5/dangerzone/use_cases/CasosUsoLocalizacion.java
UTF-8
5,817
2.015625
2
[]
no_license
package com.grupo5.dangerzone.use_cases; import android.Manifest; import android.annotation.SuppressLint; import android.app.Activity; import android.content.DialogInterface; import android.content.pm.PackageManager; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.util.Log; import androidx.appcompat.app.AlertDialog; import androidx.core.app.ActivityCompat; import com.grupo5.dangerzone.Aplicacion; import com.grupo5.dangerzone.R; import com.grupo5.dangerzone.model.GeoPunto; import com.grupo5.dangerzone.presentation.AdaptadorLugares; import static android.content.Context.LOCATION_SERVICE; public class CasosUsoLocalizacion implements LocationListener { private static final String TAG = "DangerZone"; private Activity actividad; private int codigoPermiso; private LocationManager manejadorLoc; private Location mejorLoc; private GeoPunto posicionActual; private AdaptadorLugares adaptador; private static final long DOS_MINUTOS = 2 * 60 * 1000; public CasosUsoLocalizacion(Activity actividad, int codigoPermiso) { this.actividad = actividad; this.codigoPermiso = codigoPermiso; manejadorLoc = (LocationManager) actividad.getSystemService( LOCATION_SERVICE); posicionActual = ((Aplicacion) actividad.getApplication()).posicionActual; adaptador = ((Aplicacion) actividad.getApplication()).adaptador; ultimaLocalizazion(); } public boolean hayPermisoLocalizacion() { return (ActivityCompat.checkSelfPermission(actividad, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED); } @SuppressLint("MissingPermission") void ultimaLocalizazion() { if (hayPermisoLocalizacion()) { if (manejadorLoc.isProviderEnabled(LocationManager.GPS_PROVIDER)) { actualizaMejorLocaliz(manejadorLoc.getLastKnownLocation( LocationManager.GPS_PROVIDER)); } if (manejadorLoc.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) { actualizaMejorLocaliz(manejadorLoc.getLastKnownLocation( LocationManager.NETWORK_PROVIDER)); } } else { solicitarPermiso(Manifest.permission.ACCESS_FINE_LOCATION, "Sin el permiso localización no puedo mostrar la distancia a los lugares.", codigoPermiso, actividad); } } public static void solicitarPermiso(final String permiso, String justificacion, final int requestCode, final Activity actividad) { if (ActivityCompat.shouldShowRequestPermissionRationale(actividad, permiso)) { new AlertDialog.Builder(actividad) .setTitle("Solicitud de permiso en la app") .setMessage(justificacion) .setIcon(R.mipmap.icon_app) .setPositiveButton("Ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { ActivityCompat.requestPermissions(actividad,new String[]{permiso}, requestCode); } }) .show(); } else { ActivityCompat.requestPermissions(actividad, new String[]{permiso}, requestCode); } } public void permisoConcedido() { ultimaLocalizazion(); activarProveedores(); adaptador.notifyDataSetChanged(); } @SuppressLint("MissingPermission") private void activarProveedores() { if (hayPermisoLocalizacion()) { if (manejadorLoc.isProviderEnabled(LocationManager.GPS_PROVIDER)) { manejadorLoc.requestLocationUpdates(LocationManager.GPS_PROVIDER, 20 * 1000, 5, (LocationListener) this); } if (manejadorLoc.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) { manejadorLoc.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 10 * 1000, 10, (LocationListener) this); } } else { solicitarPermiso(Manifest.permission.ACCESS_FINE_LOCATION, "Sin el permiso localización no puedo mostrar la distancia a los lugares de la app.", codigoPermiso, actividad); } } @Override public void onLocationChanged(Location location) { Log.d(TAG, "Nueva localización: "+ location); actualizaMejorLocaliz(location); adaptador.notifyDataSetChanged(); } @Override public void onStatusChanged(String provider, int status, Bundle extras) { Log.d(TAG, "Cambia estado: " + provider); activarProveedores(); } @Override public void onProviderEnabled(String provider) { Log.d(TAG, "Se habilita: "+ provider); activarProveedores(); } @Override public void onProviderDisabled(String provider) { Log.d(TAG, "Se deshabilita: "+ provider); activarProveedores(); } private void actualizaMejorLocaliz(Location localiz) { if (localiz != null && (mejorLoc == null || localiz.getAccuracy() < 2 * mejorLoc.getAccuracy() || localiz.getTime() - mejorLoc.getTime() > DOS_MINUTOS)) { Log.d(TAG, "Nueva mejor localización"); mejorLoc = localiz; posicionActual.setLatitud(localiz.getLatitude()); posicionActual.setLongitud(localiz.getLongitude()); } } public void activar() { if (hayPermisoLocalizacion()) activarProveedores(); } public void desactivar() { if (hayPermisoLocalizacion()) manejadorLoc.removeUpdates(this); } }
true
e678e6b246f84abcb4f652b0d57bbde4e753497f
Java
repid2/onedaysProject
/onedaysPrj/src/com/onedays/controller/MemberController.java
UTF-8
4,237
2.265625
2
[]
no_license
package com.onedays.controller; import java.io.IOException; import java.io.PrintWriter; import java.lang.ProcessBuilder.Redirect; import java.util.Calendar; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.eclipse.jdt.internal.compiler.ast.ThrowStatement; import com.onedays.service.MemberServiceImpl; import com.onedays.service.PlanServiceImpl; import com.onedays.vo.MemberDto; /** * Servlet implementation class MemberController */ @WebServlet("/member.do") public class MemberController extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public MemberController() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String url ="WEB-INF/jsp/"; // serviceimpl의 한 객체 선언(하나가지고 돌려쓰기) MemberServiceImpl service = MemberServiceImpl.getInstance(); HttpSession session = request.getSession(); MemberDto dto = new MemberDto(); PrintWriter out = response.getWriter(); String user_id = request.getParameter("user_id"); String user_pwd = request.getParameter("user_pwd"); String sid = (String)session.getAttribute("user_id"); //System.out.println(user_id); //System.out.println(user_pwd); //Cookie cookie = new Cookie("id", id); String login_chk = request.getParameter("login_chk"); // 로그인 판별 여부 int idChk = 0; // 정보 수정, 삭제 여부 int memChk = 0; // 정보 입력 if(user_id != null && user_pwd != null && sid == null) { // 정보 뽑기 idChk = service.login(user_id,user_pwd); // 로그인 맞을 경우 1을 반환 if(idChk == 1 ) { session.setAttribute("user_id", user_id); session.setAttribute("memberdto", service.memberInfo(user_id)); idChk = 0; }else { idChk = 2; out.print("no"); } } String para = request.getParameter("para"); // System.out.println("para ="+para); System.out.println("sid = "+sid); if(para != null && sid != null) { if(para.equals("modify")) { url += "memmod.jsp"; }else if(para.equals("mypage")) { url += "mypage.jsp"; }else if(para.equals("logout")) { session.invalidate(); url += "main.jsp"; }else if(para.equals("login")) { url += "main.jsp"; }else if(para.equals("mem_mod")) { dto.setEmail(request.getParameter("user_email")); dto.setPwd(request.getParameter("user_pwd")); dto.setPhone(request.getParameter("user_phone")); dto.setId(request.getParameter("user_id")); memChk = service.memMod(dto, sid); // System.out.println(memChk); if(memChk == 1) { session.setAttribute("memberdto", service.memberInfo(sid)); url+="mypage.jsp"; }else { url+="memmod.jsp"; } }else if(para.equals("delete")){ PlanServiceImpl service_p = PlanServiceImpl.getInstance(); service_p.plan_all_del(sid); memChk = service.memDel(sid); if(memChk == 1) { System.out.println(sid+"는 삭제되었습니다."); session.invalidate(); }else { System.out.println(sid+"는 삭제되지 않았습니다."); } url += "main.jsp"; } }else { // 로그인 여부 if(sid == null) { url += "login.jsp"; }else { url += "main.jsp"; } } if(idChk == 0) { RequestDispatcher dispatcher = request.getRequestDispatcher(url); dispatcher.forward(request, response); } } }
true
c74dc3ed39b2fd2c56c7d95f3af4e9a43d9d1a05
Java
nuhah100/GraphViewer
/app/src/main/java/classes/Derivative.java
UTF-8
1,028
2.96875
3
[]
no_license
package classes; import android.annotation.SuppressLint; public class Derivative extends Function { // Initalize function @SuppressLint("DefaultLocale") public Derivative(String fx) { super( String.format( "(%s-(%s))/%f",fx.replaceAll("x", String.format("(x+%f)", Function.DivA)) ,fx ,Function.DivA ) ); System.out.println(String.format( "(%s-(%s))/%f",fx.replaceAll("x", String.format("(x+%f)", Function.DivA)) ,fx ,Function.DivA )); } // Update function @Override public void updateFunction(String fx) { @SuppressLint("DefaultLocale") String divT = String.format( "(%s-(%s))/%f",fx.replaceAll("x", String.format("(x+%f)", Function.DivA)) ,fx ,Function.DivA ); super.updateFunction(divT); System.out.println(divT); } }
true
f5b415fb412cec7a6e0eb95dde21e95eaab52429
Java
Airbroub2019/JAVA
/TP1 (JAVA)/Autocar.java
UTF-8
674
3.046875
3
[]
no_license
public class Autocar extends Vehicule { private int nombrePassagers; private float volume; public Autocar (String modele, int anneeAchat, float prixAchat, String numeroImmat, char permis, int nombrePassagers, float volume) { super(modele,anneeAchat,prixAchat,numeroImmat,permis); this.nombrePassagers=nombrePassagers; this.volume=volume; } public void afficherAutocar() { super.afficherVehicule(); System.out.println(nombrePassagers); System.out.println(volume); } public boolean peutTransporterPassagers(int nombrePassagers, float volumeMoyen) { return (this.nombrePassagers>=nombrePassagers && volume>=nombrePassagers*volumeMoyen); } }
true
eb2a9a91aba158a9b82b94fcffee44ed3275f06b
Java
ChennakeshavaNT/Java
/Lab Programs/program11.java
UTF-8
1,024
3.1875
3
[]
no_license
import java.util.*; public class program11 { static int x[]=new int[50]; static int s[]=new int[50]; static int flag=0,d; static void sumofsub(int l,int k,int r) { int i; x[k]=1; if(l+s[k]==d) { flag=1; for(i=1;i<=k;i++) { if(x[i]==1) System.out.print(s[i]+"\t"); } System.out.println(); } else { if(l+s[k]+s[k+1]<=d) { sumofsub(l+s[k],k+1,r-s[k]); } if((l+r-s[k] >=d) && (l+s[k+1]<=d)) x[k]=0; sumofsub(l,k+1,r-s[k]); } } public static void main(String args[]) { int n,sum=0,i; System.out.println("Enter n"); Scanner sc=new Scanner(System.in); n=sc.nextInt(); System.out.println("Enter the numbers:"); for(i=1;i<=n;i++) s[i]=sc.nextInt(); System.out.println("Enter the max sum"); d=sc.nextInt(); for(i=1;i<=n;i++) sum+=s[i]; if((sum<d)||(s[1]>d)) System.out.println("No subset"); else { System.out.println("Subsets are:"); sumofsub(0,1,sum); if(flag==0) System.out.println("No subsets possible"); } } }
true
6c8357b16bb02abf39b69150ab8d3dcc1e0fe8b9
Java
AndersonMarquess/Debts-management-api
/src/test/java/com/andersonmarques/debts_api/controllers/UserControllerBuilder.java
UTF-8
1,247
2.28125
2
[]
no_license
package com.andersonmarques.debts_api.controllers; import com.andersonmarques.debts_api.models.AccountCredentials; import com.andersonmarques.debts_api.models.User; import com.andersonmarques.debts_api.models.UserBuilder; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.ResponseEntity; public class UserControllerBuilder { private TestRestTemplate client; private HttpHeaders headers; private User user; public UserControllerBuilder(TestRestTemplate client, HttpHeaders headers) { this.client = client; this.headers = headers; this.user = new UserBuilder().build(); } public UserControllerBuilder withUser(User user) { this.user = user; return this; } public ResponseEntity<User> post() { return client.postForEntity("/v1/users", new HttpEntity<User>(user, headers), User.class); } public ResponseEntity<Void> login(String email, String password) { AccountCredentials account = new AccountCredentials(); account.setEmail(email); account.setPassword(password); return client.postForEntity("/login", new HttpEntity<AccountCredentials>(account, headers), Void.class); } }
true
8e108dc4be382079bfdc79dbeabafc24f41fbeda
Java
ankygupta949/testpro
/src/main/java/App/Test.java
UTF-8
745
2.609375
3
[]
no_license
package App; import java.io.UnsupportedEncodingException; import java.math.BigDecimal; import java.net.URLEncoder; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; import java.time.LocalDate; import java.util.Arrays; public class Test { public static void main(String[] args) { BigDecimal payoutId = new BigDecimal("157322245567"); System.out.println(payoutId); } private static String encode(String url) { try { String encodeURL= URLEncoder.encode(url, "UTF-8" ); return encodeURL; } catch (UnsupportedEncodingException e) { return "Issue while encoding" +e.getMessage(); } } }
true
48ac7437b5f77c4a20967a84ea547440fda354ff
Java
Meanz/MeanWorks-Engine
/src/org/meanworks/engine/render/opengl/VertexBufferArray.java
UTF-8
1,627
2.8125
3
[]
no_license
package org.meanworks.engine.render.opengl; import org.lwjgl.opengl.ARBVertexArrayObject; import org.lwjgl.opengl.GL11; import org.lwjgl.util.glu.GLU; import org.meanworks.engine.EngineLogger; public class VertexBufferArray { /* * The id of the Vertex Array Object */ private int bufferArrayId; /** * Constructor for this vertex buffer array */ public VertexBufferArray() { this.create(); } /** * Check whether this vertex buffer array is valid * * @return */ public boolean isValid() { return bufferArrayId > 0; } /** * Bind this vertex buffer array */ public void bind() { ARBVertexArrayObject.glBindVertexArray(bufferArrayId); } /** * Unbind this vertex buffer array */ public void unbind() { ARBVertexArrayObject.glBindVertexArray(0); } /** * Create this vertex buffer array * * @return */ public boolean create() { bufferArrayId = ARBVertexArrayObject.glGenVertexArrays(); int errorCode = GL11.glGetError(); if (errorCode != 0) { EngineLogger .error("Could not create vertex array object (VertexBufferArray) " + GLU.gluErrorString(errorCode)); return false; } return true; } /** * Delete this vertex buffer array * * @return */ public boolean delete() { ARBVertexArrayObject.glDeleteVertexArrays(bufferArrayId); int errorCode = GL11.glGetError(); if (errorCode != 0) { EngineLogger .error("Could not delete vertex array object (VertexBufferArray(" + bufferArrayId + "))"); return false; } return true; } }
true
917309d6b24b7ceac5e5e3cafcd6c38099ddc87b
Java
ht18279132700/workspace
/wenda/src/main/java/cn/com/pcauto/wenda/util/excel/IsNotExcelFileException.java
UTF-8
512
2.09375
2
[]
no_license
package cn.com.pcauto.wenda.util.excel; /** * * @author chensy */ public class IsNotExcelFileException extends RuntimeException { private static final long serialVersionUID = 1L; public IsNotExcelFileException() { } public IsNotExcelFileException(String message) { super(message); } public IsNotExcelFileException(Throwable cause) { super(cause); } public IsNotExcelFileException(String message, Throwable cause) { super(message, cause); } }
true
e119aff3121a43d0d22222ef43bae9b8e30eeba0
Java
ShaunvWyk/translateapi
/src/main/java/assignment/translator/domain/Language.java
UTF-8
749
2.328125
2
[]
no_license
package assignment.translator.domain; import com.fasterxml.jackson.annotation.JsonInclude; @JsonInclude(JsonInclude.Include.NON_NULL) public class Language { private String displayName; private String languageCode; public Language(String languageCode, String displayName) { this.displayName = displayName; this.languageCode = languageCode; } public Language(String languageCode) { this.languageCode = languageCode; } public String getDisplayName() { return displayName; } public String getLanguageCode() { return languageCode; } public void setDisplayName(String displayName) { this.displayName = displayName; } }
true
4be0f66991b80d31436ffeab0cf6fd9ff4c9e5a5
Java
nurhafizahshukri/zerorisk_project1
/src/java/Bean/userloginBean.java
UTF-8
1,239
2.5
2
[]
no_license
package Bean; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import mvc.util.DBConnection; public class userloginBean { private String username; private String pass; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPass() { return pass; } public void setPass(String pass) { this.pass = pass; } public static boolean LoginUser(String username,String pass) { boolean check =false; try { DBConnection conn=new DBConnection(); Connection con= conn.createConnection(); //assert con != null; PreparedStatement ps1 =con.prepareStatement("select * from register where username=? and password=?"); ps1.setString(1, username); ps1.setString(2, pass); ResultSet rs1 =ps1.executeQuery(); check = rs1.next(); con.close(); }catch(Exception e){e.printStackTrace();} return check; } }
true
be4523f877fe8f16ce4389aa1b7776c8bf63b1ab
Java
Tellsealu/testManage
/test-system/system-web/src/main/java/com/njust/utils/Custemhandler.java
UTF-8
1,280
2.21875
2
[]
no_license
package com.njust.utils; import com.alibaba.excel.metadata.CellData; import com.alibaba.excel.metadata.Head; import com.alibaba.excel.write.metadata.holder.WriteSheetHolder; import com.alibaba.excel.write.style.column.AbstractColumnWidthStyleStrategy; import org.apache.poi.ss.usermodel.Cell; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.List; public class Custemhandler extends AbstractColumnWidthStyleStrategy { private static final int MAX_COLUMN_WIDTH = 255; //the maximum column width in Excel is 255 characters public Custemhandler() { } @Override protected void setColumnWidth(WriteSheetHolder writeSheetHolder, List<CellData> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) { if (isHead && cell.getRowIndex() != 0) { int columnWidth = cell.getStringCellValue().getBytes().length; if (columnWidth > MAX_COLUMN_WIDTH) { columnWidth = MAX_COLUMN_WIDTH; } else { columnWidth = columnWidth + 3; } writeSheetHolder.getSheet().setColumnWidth(cell.getColumnIndex(), columnWidth * 256); } } private final static Logger logger = LoggerFactory.getLogger(Custemhandler.class); }
true
f1494a0bc1d721b17dc1b9ac255b51dfa7b49ad1
Java
AnthonyChyrko/TAT_JAVA_Chyrko_Task2
/TAT_JAVA_Chyrko_Task2/src/com/epam/library/runner/Runner.java
UTF-8
3,747
2.421875
2
[]
no_license
package com.epam.library.runner; import com.epam.library.bean.User; import com.epam.library.controller.Controller; public class Runner { public static void main(String[] args) { User user = User.getInstance(); // user.setUser(login, password, "IN" , "SA"); //user in system // user.setUser("����", "password2", "IN" , "U"); //user in system // user.setUser(3, "Semas", "qwerty", "IN" , "A"); //user in system // user.setUser("Anton", "password4", "IN" , "SA"); //user in system // String request = "command=show_all_books&login=Ѹ��&access=A"; //���������� ��� ����� // String request = "command=add_book&title=MyFirstBook1&author=Chyrko Anton" // + "&genre=fantasy&year=2017&quantity=1"; // �������� ����� String request1 = "command=registration&login=Perswe123w3&password=pAss11"; // ����������� ����� // String request1 = "command=sign_in&login=Semas&password=qwerty"; // ���� � ������� // String request = "command=sign_out&login=Anton"; // ����� �� ������� // String request = "command=edit_Login&login=Sema"; // ������������� login // String request = "command=edit_Password&password=newPassword"; // ������������� password // String request = "command=edit_access&login=Kol&access=U"; // ������������� access // String request = "command=ban_user&login=Ѹ��&signIn=BAN"; // ban User // String request = "command=add_book&title=SuperBookFree2&author=Somebody Else&year=2016&genre=fantastik&quantity=11&availability=Y"; //add new book // String request1 = "command=EDIT_ORDER_BOOKS_LIST&ACTION_COMMAND=Add_book&B_ID=4"; //edit orderBooksList ���� ��������� �� ����� ����� // String request2 = "command=EDIT_ORDER_BOOKS_LIST&ACTION_COMMAND=Add_book&B_ID=4"; //edit orderBooksList ���� ��������� �� ����� ����� // String request3 = "command=EDIT_ORDER_BOOKS_LIST&ACTION_COMMAND=remove_book&B_ID=5"; //edit orderBooksList ���� ��������� �� ����� ����� // String request4 = "command=EDIT_ORDER_BOOKS_LIST&ACTION_COMMAND=remove_book&B_ID=6"; //edit orderBooksList ���� ��������� �� ����� ����� // String request3 = "command=ADD_SUBSCRIPTION&"; //subscription ����� ��������� � ���� ������ // String request4 = "command=REMOVE_SUBSCRIPTION&U_ID=3&B_ID=6"; //subscription ����� ��������� � ���� ������ // String request = "command=BOOK_AVAILABILITY&title=SuperBook3&availability=Y&author=andCompany&year=2017&genre=fantastik&quantity=50&book_id=4&"; //book availability // String request = "command=edit_book&title=SuperBook&author=Anton&genre=fantastikAndProgramming&quantity=49&book_id=8&"; //edit dook Controller contr = new Controller(); System.out.println(contr.executeTask(request1)+"\n--------------------------------------------------------------------------\n"); // System.out.println(contr.executeTask(request2)+"\n--------------------------------------------------------------------------\n"); // System.out.println(contr.executeTask(request3)+"\n--------------------------------------------------------------------------\n"); // System.out.println(contr.executeTask(request4)+"\n--------------------------------------------------------------------------\n"); System.out.println("current user"+user.toString()); } }
true
0d5998d02eecc8fb4016a53500b60f34704f9d0e
Java
KarLel/Pie-Chart-Program
/IntroFrame.java
UTF-8
2,488
3.3125
3
[]
no_license
/* Karthik Lella * Gallatin - 2 * 2/29/2016 */ import java.awt.*; import javax.swing.*; import javax.swing.event.*; import java.awt.event.*; @SuppressWarnings("serial") /** * Creates the welcome frame * @author karth */ public class IntroFrame extends JFrame implements MouseListener, ActionListener{ private JPanel panel; private JTextField numElements; private JButton addButton; /** * Creates the welcome frame */ public IntroFrame(){ panel = new JPanel(); numElements = new JTextField("How many elements are there? "); addButton = new JButton("Add"); numElements.addMouseListener(this); addButton.addMouseListener(this); numElements.addActionListener(this); addButton.addActionListener(this); setTitle("Mixing Ingredients!"); setSize(350, 70); setLocationRelativeTo(null); setResizable(false); setDefaultCloseOperation(EXIT_ON_CLOSE); panel.add(numElements); panel.add(addButton); add(panel, BorderLayout.SOUTH); setVisible(true); } /** * Returns the number of elements * @return the number of elements */ public int getNumElements(){ return Integer.parseInt(numElements.getText()); } /** * MouseEvent when the mouse is clicked */ public void mouseClicked(MouseEvent e) { if(e.getSource().equals(numElements)){ if(numElements.getText().equals("How many elements are there? ")) numElements.setText(""); } } /** * MouseEvent when the mouse enters a component */ public void mouseEntered(MouseEvent e) { if(e.getSource().equals(addButton)) addButton.setForeground(Color.BLUE); } /** * MouseEvent when the mouse exits a component */ public void mouseExited(MouseEvent e) { if(e.getSource().equals(addButton)) addButton.setForeground(Color.BLACK); } /** * Not used */ public void mousePressed(MouseEvent e) { } /** * Not used */ public void mouseReleased(MouseEvent e) { } /** * ActionEvent completes an action */ public void actionPerformed(ActionEvent e) { if(e.getSource().equals(addButton)){ if(getNumElements()>0){ dispose(); InstantiateFrame frame = new InstantiateFrame(getNumElements()); } else JOptionPane.showMessageDialog(null,"Please Enter a value greater than 0"); } } /** * Main method for staring the program */ public static void main(String[] args){ IntroFrame frame = new IntroFrame(); } }
true
efa721793295266dbd74a2de944c267946a89223
Java
mozita/waldbrand-website
/project/web/src/main/java/de/waldbrand/app/website/api/PoisGenerator.java
UTF-8
3,708
1.914063
2
[]
no_license
// Copyright 2021 Sebastian Kuerten // // This file is part of waldbrand-website. // // waldbrand-website 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. // // waldbrand-website 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 waldbrand-website. If not, see <http://www.gnu.org/licenses/>. package de.waldbrand.app.website.api; import static de.waldbrand.app.website.lbforst.PoiUtil.only; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.locationtech.jts.geom.Envelope; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import de.topobyte.adt.geo.BBox; import de.topobyte.adt.geo.BBoxString; import de.topobyte.webgun.util.ParameterUtil; import de.topobyte.webpaths.WebPath; import de.waldbrand.app.website.ApiEndpoint; import de.waldbrand.app.website.Website; import de.waldbrand.app.website.icons.Icon; import de.waldbrand.app.website.icons.IconMapping; import de.waldbrand.app.website.lbforst.WesType; import de.waldbrand.app.website.lbforst.model.Data; import de.waldbrand.app.website.lbforst.model.Poi; import de.waldbrand.app.website.osm.PoiType; import de.waldbrand.app.website.osm.model.OsmPoi; public class PoisGenerator implements ApiEndpoint { private HttpServletRequest request; public PoisGenerator(HttpServletRequest request) { this.request = request; } @Override public void respond(WebPath path, HttpServletResponse response, Map<String, String[]> parameters) throws IOException { String bbox = ParameterUtil.get(parameters, "bbox"); String argType = ParameterUtil.get(parameters, "type"); boolean useOsm = true; boolean useForst = true; if ("osm".equals(argType)) { useForst = false; } else if ("forst".equals(argType)) { useOsm = false; } BBox box = BBoxString.parse(bbox).toBbox(); Envelope envelope = box.toEnvelope(); PoiMarkers markers = new PoiMarkers(); Data data = Website.INSTANCE.getData(); if (useOsm) { for (PoiType type : PoiType.values()) { Icon icon = IconMapping.get(type); List<OsmPoi> pois = filterOsm(data.getTypeToPois().get(type), envelope); markers.add(type, icon.getName(), pois); } } if (useForst) { for (WesType type : WesType.values()) { if (type == WesType.GEPLANT) { continue; } Icon icon = IconMapping.get(type); markers.add("forst-" + type.getId(), icon.getName(), filterLbf( only(data.getPois(), type.getId()), envelope)); } } GsonBuilder builder = new GsonBuilder(); Gson gson = builder.setPrettyPrinting().create(); response.setCharacterEncoding("UTF-8"); response.getWriter().write(gson.toJson(markers)); } private Iterable<Poi> filterLbf(Iterable<Poi> pois, Envelope envelope) { List<Poi> results = new ArrayList<>(); for (Poi poi : pois) { if (envelope.contains(poi.getCoordinate())) { results.add(poi); } } return results; } private List<OsmPoi> filterOsm(Iterable<OsmPoi> pois, Envelope envelope) { List<OsmPoi> results = new ArrayList<>(); for (OsmPoi poi : pois) { if (envelope.contains(poi.getLon(), poi.getLat())) { results.add(poi); } } return results; } }
true
4c5c5cc0a138bc6232ae59f2758ff75a182b401b
Java
codemonkey2019/cryptotool
/src/main/java/com/cryptotool/cipher/symmetric/CipherNoIv.java
UTF-8
4,351
2.796875
3
[]
no_license
package com.cryptotool.cipher.symmetric; import com.cryptotool.block.Padding; import com.cryptotool.block.Pattern; import com.cryptotool.block.SE; import com.cryptotool.cipher.MyCipher; import com.cryptotool.util.KeyUtils; import com.cryptotool.util.MyUtils; import lombok.Getter; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.jetbrains.annotations.NotNull; import javax.crypto.Cipher; import javax.crypto.CipherInputStream; import javax.crypto.CipherOutputStream; import javax.crypto.SecretKey; import java.io.*; import java.security.Security; /** * MyCipher接口的实现类,封装了实现对称加密算法的确定性模式的实现,即ECB模式 */ public class CipherNoIv implements MyCipher { private SE algorithm; private Pattern mode; private Padding padding; private Cipher cipher; @Getter private SecretKey key; static { Security.addProvider(new BouncyCastleProvider()); } public CipherNoIv(SE algorithm, Pattern mode, Padding padding, byte[] key) throws Exception { if (!Pattern.ECB.equals(mode)){ throw new Exception("错误的工作模式"); } this.algorithm = algorithm; this.mode = mode; this.padding = padding; this.key= KeyUtils.toSecretKey(algorithm,key); this.cipher = Cipher.getInstance(MyUtils.prase(algorithm, mode, padding)); } /** * 加密算法 * * @param data 明文数据 * @return 密文数据 * @throws Exception */ @Override @NotNull public byte[] encrypt(@NotNull byte[] data) { try { this.cipher.init(1,key); byte[] out = this.cipher.doFinal(data); return out; } catch (Exception e) { e.printStackTrace(); } return new byte[0]; } /** * 解密算法 * * @param data 明文数据 * @return 密文数据 * @throws Exception */ @Override @NotNull public byte[] decrypt(@NotNull byte[] data){ try { this.cipher.init(2,key); byte[] out = this.cipher.doFinal(data); return out; } catch (Exception e) { e.printStackTrace(); } return new byte[0]; } /** * * @param inPath * @param outPath * @throws Exception */ @Override public void encryptFile(@NotNull String inPath, @NotNull String outPath) { File file = new File(inPath); if (file.exists()){ try { this.cipher.init(1, key); BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file)); FileOutputStream os = new FileOutputStream(outPath); CipherOutputStream cos = new CipherOutputStream(os, this.cipher); BufferedOutputStream bos = new BufferedOutputStream(cos); byte[] b = new byte[1024]; int r; while ((r=bis.read(b))!=-1){ bos.write(b,0,r); } bis.close(); bos.close(); } catch (Exception e) { e.printStackTrace(); } }else { throw new RuntimeException("文件不存在"); } } /** * * @param inPath * @param outPath * @throws Exception */ @Override public void decryptFile(@NotNull String inPath, @NotNull String outPath) { File file = new File(inPath); if (file.exists()){ try { this.cipher.init(2,key); InputStream is = new FileInputStream(file); CipherInputStream cis = new CipherInputStream(is,this.cipher); BufferedInputStream bis = new BufferedInputStream(cis); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(outPath)); byte[] b = new byte[1024]; int r; while ((r=bis.read(b))!=-1){ bos.write(b,0,r); } bis.close(); bos.close(); } catch (Exception e) { e.printStackTrace(); } }else { throw new RuntimeException("文件不存在"); } } }
true
2609933ef304ab3bb357e3b9b11eb15bdd9085a2
Java
cothong/kraken-rules
/kraken-model-dsl-converter/src/test/java/kraken/model/dsl/converter/ExternalContextDefinitionConversionTest.java
UTF-8
5,280
2.21875
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2019 EIS Ltd and/or one of its affiliates. * * 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 kraken.model.dsl.converter; import kraken.model.context.Cardinality; import kraken.model.context.external.ExternalContextDefinition; import kraken.model.context.external.ExternalContextDefinitionAttribute; import kraken.model.context.external.ExternalContextDefinitionAttributeType; import kraken.model.factory.RulesModelFactory; import kraken.model.resource.builder.ResourceBuilder; import org.junit.Test; import java.util.Arrays; import static junit.framework.TestCase.assertEquals; /** * Unit tests to test conversion of {@code ExternalContextDefinition}'s to string. * * @author Tomas Dapkunas * @since 1.3.0 */ public class ExternalContextDefinitionConversionTest { private static final String SEPARATOR = System.lineSeparator(); private static final RulesModelFactory RULES_MODEL_FACTORY = RulesModelFactory.getInstance(); private final DSLModelConverter converter = new DSLModelConverter(); @Test public void shouldConvertSingleExternalContexts() { ExternalContextDefinition externalContext = createExternalContext( "ExternalContextDefinition", "PhysicalNamespace", createAttribute( "stringAttribute", createAttributeType("STRING", true, Cardinality.MULTIPLE) ), createAttribute( "keys", createAttributeType("STRING", true, Cardinality.MULTIPLE) ), createAttribute( "values", createAttributeType("STRING", true, Cardinality.MULTIPLE) ) ); String convertedString = convert(externalContext); assertEquals( "ExternalEntity ExternalContextDefinition {" + SEPARATOR + " STRING* keys" + SEPARATOR + " STRING* values" + SEPARATOR + " STRING* stringAttribute" + SEPARATOR + "}" + SEPARATOR + SEPARATOR, convertedString); } @Test public void shouldConvertMultipleExternalContexts() { ExternalContextDefinition eCtx = createExternalContext("ExternalContextDefinition", "PhysicalNamespace", createAttribute("otherContext", createAttributeType("OtherContext", false, Cardinality.SINGLE))); ExternalContextDefinition othCtx = createExternalContext("OtherContext", "PhysicalNamespace", createAttribute("stringAttribute", createAttributeType("STRING", true, Cardinality.SINGLE))); String convertedString = convert(eCtx, othCtx); assertEquals( "ExternalEntity ExternalContextDefinition {" + SEPARATOR + " OtherContext otherContext" + SEPARATOR + "}" + SEPARATOR + SEPARATOR + "ExternalEntity OtherContext {" + SEPARATOR + " STRING stringAttribute" + SEPARATOR + "}" + SEPARATOR + SEPARATOR, convertedString); } private String convert(ExternalContextDefinition... externalContextDefinition) { return converter.convert(ResourceBuilder.getInstance() .addExternalContextDefinitions(Arrays.asList(externalContextDefinition)) .build()); } private ExternalContextDefinition createExternalContext(String name, String namespace, ExternalContextDefinitionAttribute... attributes) { ExternalContextDefinition eCtx = RULES_MODEL_FACTORY.createExternalContextDefinition(); eCtx.setName(name); eCtx.setPhysicalNamespace(namespace); Arrays.stream(attributes) .forEach(attribute -> eCtx.getAttributes().put(attribute.getName(), attribute)); return eCtx; } private ExternalContextDefinitionAttribute createAttribute(String attributeName, ExternalContextDefinitionAttributeType type) { ExternalContextDefinitionAttribute attribute = RULES_MODEL_FACTORY.createExternalContextDefinitionAttribute(); attribute.setName(attributeName); attribute.setType(type); return attribute; } private ExternalContextDefinitionAttributeType createAttributeType(String typeName, Boolean isPrimitive, Cardinality cardinality) { ExternalContextDefinitionAttributeType type = RULES_MODEL_FACTORY.createExternalContextDefinitionAttributeType(); type.setType(typeName); type.setPrimitive(isPrimitive); type.setCardinality(cardinality); return type; } }
true
2ba1f0b82b7f6c897f5803ce0f43a61bff393193
Java
zhongym/ssh
/src/main/java/jdkcontext/ClassLoader.java
UTF-8
721
2.359375
2
[]
no_license
package jdkcontext; import org.apache.commons.lang.StringUtils; import java.io.*; /** * Created by zhong on 2016/9/20. */ public class ClassLoader { public static void main(String[] args) throws IOException { /** * 输出当前类来自哪个jar包 */ String path = StringUtils.class.getResource("").getPath(); System.out.println(path); BufferedInputStream resourceAsStream = (BufferedInputStream) ClassLoader.class.getClassLoader().getResourceAsStream("appConfig.local.properties"); BufferedReader br=new BufferedReader(new InputStreamReader(resourceAsStream)); System.out.println(new String(br.readLine().getBytes("utf-8"),"utf-8")); } }
true
f185af63041cbc2cc41fd6194ed265f319b36baa
Java
brktan/github-rest-api
/src/main/java/com/buraktan/githubapi/GithubRestApiApplication.java
UTF-8
2,589
2.203125
2
[]
no_license
package com.buraktan.githubapi; import com.buraktan.githubapi.client.ContributorsClient; import com.buraktan.githubapi.client.FollowersClient; import com.buraktan.githubapi.client.RepositoryClient; import com.buraktan.githubapi.domain.Contributors; import com.buraktan.githubapi.domain.Repository; import com.buraktan.githubapi.util.CSVWriter; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import java.util.ArrayList; import java.util.Collections; import java.util.logging.Level; import java.util.logging.Logger; @SpringBootApplication public class GithubRestApiApplication implements ApplicationRunner { @Value("${organization}") private String organization; @Value("${mostforked}") private String mostforked; @Value("${topcontributors}") private String topcontributors; private final static Logger LOGGER = Logger.getLogger(Logger.class.getName()); private final RepositoryClient repositoryClient = new RepositoryClient(); private final ContributorsClient contributorsClient = new ContributorsClient(); private final FollowersClient followersClient = new FollowersClient(); public static void main(String[] args) { SpringApplication.run(GithubRestApiApplication.class, args); } @Override public void run(ApplicationArguments args) throws Exception { LOGGER.log(Level.INFO, "Organization Name: " + organization); LOGGER.log(Level.INFO, "Most Forked: " + mostforked); LOGGER.log(Level.INFO, "Top Contributors: " + topcontributors); int mf = Integer.parseInt(mostforked); int tc = Integer.parseInt(topcontributors); ArrayList<Repository> repositoryArray = repositoryClient.getRepositoryArray(organization, mf); ArrayList<Contributors> contributorsArray = contributorsClient.getContributorsArray(mf, tc, repositoryArray); followersClient.getFollowersArray(mf, contributorsArray); String[] header = {"Id", "RepositoryName", "ForkCount", "HTMLURL", "Description", "ContributorURL"}; String[] header2 = {"Name", "ContributorsCount", "FollowersURL", "Followers"}; CSVWriter csvWriter = new CSVWriter(); csvWriter.writer(organization, Collections.singleton(repositoryArray), header); csvWriter.writer("users", Collections.singleton(contributorsArray), header2); } }
true
c0d40e6f1cea6dff609b434fc38083f3a48c3f0e
Java
siashan/saascloud-master
/saascloud-provider-api/saascloud-provider-api-uac/src/main/java/com/han/saascloud/provider/api/service/UserService.java
UTF-8
526
1.789063
2
[]
no_license
package com.han.saascloud.provider.api.service; import com.han.saascloud.provider.api.hystrix.UserServiceFallback; import org.springframework.cloud.netflix.feign.FeignClient; import org.springframework.web.bind.annotation.GetMapping; /** * @Author: kfc * @Description: <br/> * Date:Create in 2019/4/3 11:11 * @Modified By: */ @FeignClient(value = "person-service",fallback = UserServiceFallback.class) // 服务提供方应用的名称 public interface UserService { @GetMapping("test") public void test(); }
true
afa9e3497b73f3dbbb82c4f2285c80660199b83f
Java
ZWareDevelopment/ZWare.cc
/src/main/java/dev/zihasz/client/feature/traits/IToggleable.java
UTF-8
227
1.890625
2
[ "Unlicense" ]
permissive
package dev.zihasz.client.feature.traits; public interface IToggleable { void enable(); void disable(); void toggle(); boolean isEnabled(); void setEnabled(boolean enabled); void onEnable(); void onDisable(); }
true
7ab0d3f6af7a6e6d35b24c4e7be826655b48f66b
Java
nsn/tasktree
/src/main/java/com/nightspawn/tasktree/business/tasks/daos/FindTasksDAO.java
UTF-8
191
1.804688
2
[]
no_license
package com.nightspawn.tasktree.business.tasks.daos; import java.util.List; import com.nightspawn.tasktree.dtos.Task; public interface FindTasksDAO { public List<Task> getAllTasks(); }
true
d06a196aca7ff4ed263a96bed08cf719734a19ad
Java
argonavisbr/EIP-Course
/eip-course/Message-Router-Examples/src/main/java/br/com/argonavis/eipcourse/router/cbr/FileAdapter.java
UTF-8
4,795
2.78125
3
[]
no_license
package br.com.argonavis.eipcourse.router.cbr; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileReader; import java.io.FilenameFilter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.Reader; import java.io.StringWriter; import java.io.Writer; import java.util.ArrayList; import java.util.List; import javax.jms.BytesMessage; import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.Destination; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.MessageProducer; import javax.jms.Session; import javax.naming.Context; import javax.naming.InitialContext; public class FileAdapter { private File directory; public FileAdapter(File directory) throws JMSException { this.directory = directory; } public void send(List<Message> messages, MessageProducer producer) { try { for(Message message: messages) { System.out.println("Sending message"); producer.send(message); } System.out.println(messages.size() + " messages sent!"); } catch(JMSException e){ System.err.println("JMS Exception: " + e); } } public List<Message> createMessages(Session session, List<File> files) throws JMSException { List<Message> messages = new ArrayList<>(); for(File file: files) { Message message = null; boolean valid = true; String type = file.getName().substring(file.getName().lastIndexOf('.')+1).toLowerCase(); if(type.equals("xml") || type.equals("txt")) { String data = readChars(file); message = session.createTextMessage(data); } else if (type.equals("png")) { byte[] data = readBytes(file); message = session.createBytesMessage(); ((BytesMessage)message).writeBytes(data); } else { valid = false; } if(valid) { message.setLongProperty("Length", file.length()); message.setStringProperty("Name", file.getName()); message.setStringProperty("Type", type); messages.add(message); file.delete(); } } return messages; } public List<File> loadFiles() { List<File> files = new ArrayList<>(); String[] fileNames = directory.list(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.endsWith(".xml") || name.endsWith(".png") || name.endsWith(".txt"); } }); if(fileNames != null && fileNames.length > 0) { for(String fileName : fileNames) { files.add(new File(directory, fileName)); } } return files; } public byte[] readBytes(File file) { InputStream in = null; OutputStream out = null; try { in = new FileInputStream(file); out = new ByteArrayOutputStream(); byte[] buffer = new byte[4096]; int len = in.read(buffer); while(len > 0) { out.write(buffer, 0, len); len = in.read(buffer); } out.flush(); return buffer; } catch (IOException e) { e.printStackTrace(); return null; } finally { try { in.close(); out.close(); } catch (IOException e) {} } } public String readChars(File file) { Reader reader = null; Writer writer = null; try { reader = new FileReader(file); writer = new StringWriter(); char[] buffer = new char[4096]; int len = reader.read(buffer); while(len > 0) { writer.write(buffer, 0, len); len = reader.read(buffer); } writer.flush(); return writer.toString(); } catch (IOException e) { e.printStackTrace(); return null; } finally { try { reader.close(); writer.close(); } catch (IOException e) {} } } public static void main(String[] args) throws Exception { FileAdapter adapter = new FileAdapter(new File("/tmp/jms/inbox")); Context ctx = new InitialContext(); ConnectionFactory factory = (ConnectionFactory)ctx.lookup("ConnectionFactory"); Destination queue = (Destination)ctx.lookup("inbound-channel"); Connection con = factory.createConnection(); con.start(); int polls = 12; while(polls > 0) { System.out.println("Checking for files... " + polls + " polls left."); Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer producer = session.createProducer(queue); List<File> files = adapter.loadFiles(); if(!files.isEmpty()) { List<Message> messages = adapter.createMessages(session, files); adapter.send(messages, producer); } Thread.sleep(5000); // wait 5 seconds --polls; } con.close(); } }
true
c2ecf1fa63ea11c2b2e5dcad386a19c2e9395f27
Java
mnikitin77/Algorithms
/src/main/java/com/mvnikitin/lesson2/tasks/Task_46.java
UTF-8
551
3.203125
3
[]
no_license
package com.mvnikitin.lesson2.tasks; import java.io.IOException; import java.math.BigDecimal; import java.math.RoundingMode; import java.util.Scanner; public class Task_46 { public static void main(String[] argv) throws IOException { new Task_46().run(); } public void run() throws IOException{ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); sc.close(); System.out.println(new BigDecimal("2.7182818284590452353602875"). setScale(n, RoundingMode.HALF_EVEN)); } }
true
5cc08eab4ad633248d2daa73a3f8d25e2b490a2a
Java
Mu-L/dagli
/math-distribution/src/main/java/com/linkedin/dagli/math/distribution/Deduplication.java
UTF-8
1,558
3.421875
3
[ "BSD-2-Clause", "BSD-3-Clause", "MIT", "Apache-2.0", "LicenseRef-scancode-public-domain" ]
permissive
package com.linkedin.dagli.math.distribution; /** * Operations that modify a discrete distribution may result in multiple entries with the same label (event). Because a * discrete distribution effectively maps a label to a probability, such duplicative entries must be resolved. This * enum controls <i>how</i> they should be resolved. */ public enum Deduplication { /** * You assert that there are no duplicates. Checking for duplicate labels is relatively expensive (typically * requiring use of either a hashtable or O(n^2) equality checks) so, if you know for certain that no duplicate labels * will result from an operation, this will improve efficiency. Java asserts will be used to check this; asserts are * typically enabled in a JVM during testing but not production/at scale. */ NONE, /** * If multiple entries (label and probability pairs) share the same label, the highest probability associated with * that label will be used. * * For example, if the distribution is {@code "A" -> 0.3} and {@code "B" -> 0.5}, and we map both events' labels to * "C", the resulting distribution would be {@code "C" -> 0.5}. */ MAX, /** * If multiple entries (label and probability pairs) share the same label, the label is associated with the <b>sum</b> * of all probabilities associated with that label. * * For example, if the distribution is {@code "A" -> 0.3} and {@code "B" -> 0.5}, and we map all labels to "C", the * resulting distribution would be {@code "C" -> 0.8}. */ MERGE, }
true
88a55acdf161da5cdd3c6be9b63b7e5ae727083b
Java
iqihao/fastboot
/src/main/java/net/ioage/app/fastboot/FastbootApplication.java
UTF-8
703
1.75
2
[]
no_license
package net.ioage.app.fastboot; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration; @SpringBootApplication @MapperScan({"net.ioage.app.fastboot.auth.mapper","net.ioage.app.fastboot.module.*.mapper"}) @EnableAutoConfiguration(exclude = ErrorMvcAutoConfiguration.class) public class FastbootApplication { public static void main(String[] args) { SpringApplication.run(FastbootApplication.class, args); } }
true
f2d92a49b003f7b6d79d4aff4cae38e860670b4a
Java
renaldhiwahyu/jadwal-moklet
/app/src/main/java/id/sch/smktelkom_mlg/project/xiirpl101112131/jadwalmoklet/SQLite/DBHelper.java
UTF-8
2,216
2.40625
2
[]
no_license
package id.sch.smktelkom_mlg.project.xiirpl101112131.jadwalmoklet.SQLite; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; /** * Created by Adinda Rizqi on 11/4/2016. */ public class DBHelper extends SQLiteOpenHelper { // Table Name public static final String TABLE_NAME = "myJadwal_out"; // Table column //public static final String myID = "myID"; public static final String HARI = "Hari"; public static final String JP_01 = "JP_01"; public static final String JP_02 = "JP_02"; public static final String JP_03 = "JP_03"; public static final String JP_04 = "JP_04"; public static final String JP_05 = "JP_05"; public static final String JP_06 = "JP_06"; public static final String JP_07 = "JP_07"; public static final String JP_08 = "JP_08"; public static final String JP_09 = "JP_09"; public static final String JP_10 = "JP_10"; public static final String JP_11 = "JP_11"; public static final String JP_12 = "JP_12"; // Database Information static final String DB_NAME = "JadwalMoklet.DB"; // database version static final int DB_VERSION = 1; // Creating table query private static final String CREATE_TABLE = "create table " + TABLE_NAME + "(" + //myID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + HARI + " TEXT," + JP_01 + " VARCHAR," + JP_02 + " VARCHAR," + JP_03 + " VARCHAR," + JP_04 + " VARCHAR," + JP_05 + " VARCHAR," + JP_06 + " VARCHAR," + JP_07 + " VARCHAR," + JP_08 + " VARCHAR," + JP_09 + " VARCHAR," + JP_10 + " VARCHAR," + JP_11 + " VARCHAR," + JP_12 + " VARCHAR);"; public DBHelper(Context context) { super(context, DB_NAME, null, DB_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(CREATE_TABLE); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME); onCreate(db); } }
true