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
8eca98a7ad7f8ee35464f2c2dfe145cae33c3c30
Java
spzhong/qianbangzhu
/app/.svn/pristine/8e/8eca98a7ad7f8ee35464f2c2dfe145cae33c3c30.svn-base
UTF-8
5,391
1.804688
2
[]
no_license
package com.quqian.activity.more; import java.util.HashMap; import java.util.List; import java.util.Map; import android.app.AlertDialog; import android.app.Dialog; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.example.quqian.R; import com.quqian.activity.LoginActivity; import com.quqian.activity.MainActivity; import com.quqian.activity.index.IndexActivity; import com.quqian.base.BaseActivity; import com.quqian.been.UserMode; import com.quqian.http.RequestFactory; import com.quqian.http.RequestPool; import com.quqian.http.RequestThreadAbstract; import com.quqian.lockq.GestureVerifyActivity; import com.quqian.util.CommonUtil; import com.quqian.util.HttpResponseInterface; import com.quqian.util.ProcessDialogUtil; import com.quqian.util.StaticVariable; import com.quqian.util.Tool; public class SheZhiActivity extends BaseActivity implements OnClickListener, HttpResponseInterface { // 修改手势密码 private TextView xiugai = null; // 检查更新 private TextView jiancha = null; // 退出按钮 private Button btn = null; private Dialog juhua = null; @Override protected int layoutId() { // TODO Auto-generated method stub return R.layout.main_more_shezhi; } @Override protected void initView() { // TODO Auto-generated method stub super.initView(); setTitle("设置"); showBack(); juhua = new ProcessDialogUtil(SheZhiActivity.this); xiugai = (TextView) findViewById(R.id.more_shezhi_tv1); jiancha = (TextView) findViewById(R.id.more_shezhi_tv2); btn = (Button) findViewById(R.id.more_shezhi_btn); } @Override protected void initViewListener() { // TODO Auto-generated method stub super.initViewListener(); titleBarBack.setOnClickListener(this); xiugai.setOnClickListener(this); jiancha.setOnClickListener(this); btn.setOnClickListener(this); } @Override public void onClick(View arg0) { // TODO Auto-generated method stub switch (arg0.getId()) { case R.id.title_bar_back: // 返回按钮 SheZhiActivity.this.finish(); anim_right_out(); break; case R.id.more_shezhi_tv1: // 修改手势密码 UserMode user = Tool.getUser(this); if(user == null){ //跳转到登录页面, startActivity(new Intent(SheZhiActivity.this,LoginActivity.class)); }else{ //跳转到校验手势 Intent intent = new Intent(SheZhiActivity.this,GestureVerifyActivity.class); intent.putExtra("type", "jiaoyan"); startActivity(intent); } break; case R.id.more_shezhi_tv2: loadHttp_banbengengxi(); break; case R.id.more_shezhi_btn: // 退出按钮.清除登录账户密码,回到首页 clearLogin(); Intent intent3 = new Intent(this, MainActivity.class); StaticVariable.put(StaticVariable.sv_toIndex, "1"); startActivity(intent3); finish(); anim_right_out(); break; default: break; } } // 清除登录账户,仅仅是登录人的登录状态, private void clearLogin() { CommonUtil.clearByKey(SheZhiActivity.this, "loginState", "", ""); } // 登录--网络请求 private Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { // TODO Auto-generated method stub super.handleMessage(msg); juhua.cancel(); switch (msg.what) { case 0: Toast.makeText(SheZhiActivity.this, msg.getData().getString("errMsg"), 1000).show(); break; case 1: // 停止菊花 Toast.makeText(SheZhiActivity.this,"当前版本是最新版本", 1000).show(); break; case 2: Toast.makeText(SheZhiActivity.this, msg.getData().getString("msg"), 1000).show(); break; default: break; } } }; // 检测版本更新 private void loadHttp_banbengengxi() { juhua.show(); Map<String, String> map = new HashMap<String, String>(); map.put("urlTag", "2");// 可不传(区分一个activity多个请求) map.put("isLock", "0");// 0不锁,1是锁 map.put("type", "android");// 类型 RequestThreadAbstract thread = RequestFactory.createRequestThread(35, map, SheZhiActivity.this, mHandler); RequestPool.execute(thread); } @Override public void httpResponse_success(Map<String, String> map, List<Object> list, Object jsonObj) { // TODO Auto-generated method stub Message msg2 = new Message(); msg2.what = 1; mHandler.sendMessage(msg2); } @Override public void httpResponse_fail(Map<String, String> map, String msg, Object jsonObj) { // TODO Auto-generated method stub Message msg2 = new Message(); msg2.what = 2; Bundle bundle = new Bundle(); bundle.putString("msg", msg); msg2.setData(bundle); mHandler.sendMessage(msg2); } }
true
b56632100d8e9abe145c4898b1ebc432bd4a7770
Java
shloknangia/MemeLife
/app/src/main/java/com/rajatgoyal/memelife/MainActivity.java
UTF-8
3,584
2.09375
2
[]
no_license
package com.rajatgoyal.memelife; import android.content.Intent; import android.media.Image; import android.net.Uri; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.Toast; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.firebase.storage.FirebaseStorage; import com.google.firebase.storage.StorageReference; import com.squareup.picasso.Picasso; import java.util.Random; public class MainActivity extends AppCompatActivity { ImageView image, download, share; Button next; private StorageReference storageRef; private StorageReference appfestRef; private int MAX; private int counter; private Uri imageUri; ProgressBar progress; FrameLayout frame; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); storageRef = FirebaseStorage.getInstance().getReference(); appfestRef = storageRef.child("Appfest"); image = (ImageView) findViewById(R.id.image); download = (ImageView) findViewById(R.id.download); download.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { download(); } }); share = (ImageView) findViewById(R.id.share); share.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { share(); } }); next = (Button) findViewById(R.id.next); next.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { next(); } }); progress = (ProgressBar) findViewById(R.id.progress); progress.setVisibility(View.GONE); frame = (FrameLayout) findViewById(R.id.frame); MAX = 49; counter = 0; next(); } public void share() { Intent intent = new Intent(Intent.ACTION_SEND); intent.setType("image/jpeg"); intent.putExtra(Intent.EXTRA_STREAM, imageUri); startActivity(Intent.createChooser(intent, "Share Image")); } public void download() { Toast.makeText(this, "Image downloaded.", Toast.LENGTH_SHORT).show(); } public void next() { progress.setVisibility(View.VISIBLE); frame.setVisibility(View.GONE); int temp = (counter+1)%MAX; counter = (temp==0)?MAX:temp; appfestRef.child(counter + ".jpeg").getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() { @Override public void onSuccess(Uri uri) { // Got the download url progress.setVisibility(View.GONE); frame.setVisibility(View.VISIBLE); imageUri = uri; // Toast.makeText(MainActivity.this, imageUri.toString(), Toast.LENGTH_SHORT).show(); Picasso.with(getApplication()).load(uri).into(image); } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { // Handle any errors } }); } }
true
0743053bc3afa3c2aead418e5de34b9e9ad51373
Java
344436738/cms
/cms/.svn/pristine/af/af63f2fb747a5411d28cd57ebf8c0a758b4cf70b.svn-base
UTF-8
689
1.945313
2
[]
no_license
package com.leimingtech.mobile.entity.appapi.feedback; import com.leimingtech.mobile.entity.appapi.BaseApiEntity; import com.wordnik.swagger.annotations.ApiModel; import com.wordnik.swagger.annotations.ApiModelProperty; import javax.xml.bind.annotation.XmlRootElement; /** * Created by hejiping on 2017/5/23. */ @ApiModel(value="反馈实体" , description = "feedBackApiEntity") @XmlRootElement(name="root") public class FeedBackApiEntity extends BaseApiEntity { @ApiModelProperty(value="数据") private FeedBackList ret; @Override public FeedBackList getRet() { return ret; } public void setRet(FeedBackList ret) { this.ret = ret; } }
true
5fd00430a028aaccc5824103864af4cad216cfec
Java
tectronics/lotteryanalysis
/lotteryanalysis/java/main/src/com/rb/lottery/analysis/client/UI/listener/BetTypeListener.java
UTF-8
1,260
2.328125
2
[]
no_license
/** * @文件名称: BetTypeListener.java * @类路径: com.rb.lottery.analysis.client.UI.listener * @描述: TODO * @作者: robin * @时间: 2011-11-22 下午04:45:42 * @版本: 1.0.0 */ package com.rb.lottery.analysis.client.UI.listener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import javax.swing.JOptionPane; import com.rb.lottery.analysis.client.UI.MainFrame; import com.rb.lottery.analysis.common.MessageConstants; import com.rb.lottery.analysis.common.SystemConstants; /** * @类功能说明: * @类修改者: * @修改日期: * @修改说明: * @作者: robin * @创建时间: 2011-11-22 下午04:45:42 * @版本: 1.0.0 */ public class BetTypeListener implements ItemListener { public BetTypeListener() { super(); } /* * (non-Javadoc) * * @see * java.awt.event.ItemListener#itemStateChanged(java.awt.event.ItemEvent) */ @Override public void itemStateChanged(ItemEvent e) { // origin // String item = e.getItem().toString(); // 选项改变分2步,A选择取消,B选择选中 // 选择选中事件 if (e.getStateChange() == ItemEvent.SELECTED) { MainFrame.getInstance().betTypeChange(); } } }
true
412aeb28e3ad179b4e8f91dcaf47ddea24ec28b8
Java
ShiRan233/JavaDesign
/src/main/java/com/example/cy/config/AlipayConfig.java
UTF-8
1,506
1.945313
2
[]
no_license
package com.example.cy.config; /** * 支付宝配置信息 * @author linhongcun * */ public class AlipayConfig { //开发者中心 / 研发服务 / 沙箱环境 / 沙箱应用/ 信息配置/ 必看部分/ APPID(填自己的,下面都是改过的~) public static String app_id = "2016092600597995"; //开发者中心 / 研发服务 / 沙箱环境 / 沙箱应用/ 信息配置/ 必看部分/ 生成公钥时对应的私钥(填自己的,下面都是改过的~) public static String private_key = "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCnxIMZbA65kvvcX+cXtVMYFrv/DqFZ3/E7DCypMm4LPeWL20Jxk/MF0UfuXk+PM9VgDaqYo64rTRJeKGUaaPLEPZC2MCEiwrNKLGMm65BzTcOpSMQUNXJJrGgCkvOW71XJW35hoybrDsx8Tj8owhB7T8axHz9naoL6Q5Oti0X/JwOuwFiLmyJeGhsrVCPsDprWWoBTJPscUmW26Y0+gadfnIm3WOX4ttsjTRCLr3B6jlwq/upHqwWhv2mEncZW+HGNfBpxJBibVW4LEdvXhYKcK+QNzhDjHZWhx3c8ILMUdOqyS1635Gh6rVCuL+WEldEonP71ie9sGWTBsaMSQJtTAgMBAAECggEAP52ppLMv5jiRHqCTDY9pYeIFCZNvpZfgbmaQbNw9lC+1YlITIORcK+GO6BmFC6U5DQJBpT2z5qGEDIY+yEPxgm5h+GPJvNedisvIEVMT5FUhk4iPKaaWns8sZYV5rss0eXUjODzYnhtveNdm5bqo60l162YQ8dMWtXV4gz8jnLt+YgZCkUxH7AQnC7OPptpAa5WZpbMpaFRGXBHfMHqLQ073xK9RLtRditD2YfzwxLqaBfEkI2VTGZcrJEx3yrUOq8GRjZUg6yjAJukZwklj5pgRyijsTFtcZ6XE3aaU4+hAdGLH/Ku292Dzvv0OZItmID7VIvTZglXLyGJN9R7JSQKBgQDRGTYBTtxKyz3FLI8uRFvnD7qvYS89BimzsYOtAE1gAHKrAZm/rHZXtS5+CKNXnT3sqpyzfdPBIxaolmN83tFJ7O4jRHv5ahec57Az7bUuadTI2xVnYtOCMQFXvniPawfxZDomM2fMXf/lgI5FRX6JNQUDbXfbAdUyWJ3hNbSE5QKBgQDNZgNwGV8+LCpRHSRWKiKlC+vrp1FnOv1e9RalLnTEqKlhPhW0CybekJKId/MGqlQqzmJWOQeGRSIoiYZ3ApBmd7UBL5NG5rl+B7BPe27LGHQCDNCuJOjANITuNGN+2uQ6uPkE2fNBNidS+HfHG4Bzj556kg2FkFENRaZXtigT1wKBgCEJvbm5Lx92O31TDBCAZpD8sD+TuHYI6j/lNWv5V0Bq8bNJXnSlmFFFZGIvlTd7tdQWJQpLQFEM7UCX+oI5ZpIqqHnUEU6YT8DP7sxVq8H4oNFXpGsgd1Dj01V81+m5PJkMgA+XIbhtxcgKZvBVCag+Q1uGSWDGSlxZGiECblJtAoGAcR2JLycJ6Ldx5pHh/QHfan2SQ4k1r2AxQSZAfl+DNvqbrU3/rdOmaFO+HyHP2Q/comZeiZWGq09PbHuwbcIfvA6YxDprJVTTOrEJS/xyG68v1CEym3UAKTnDK1v2n1n07tIHccCF0pf8OBlV/XUL3JhvcpkUkUXVHTYKUaujjqkCgYBj+gaK1CSURJu2KZx4oud86EaUVTyD6A1qTi27oFaxfEn08R8XSO4Ni9KJdLY0q48BsmjRyIhhFjCkr7NWV3Y2xOMHq3X0xmHCTlcWL8wr0rJhuZJHe1CTxRv1+KAE3mwFHQlZbcPyOTCNq17jSi/nrKLnKi2HoMBB3P0iJZYIrw=="; //Controller Mapping:得放到服务器上,且使用域名解析 IP public static String notify_url = "http://127.0.0.1:8888/alipay/returnUrl"; //Controller Mapping:得放到服务器上,且使用域名解析 IP public static String return_url = "http://127.0.0.1:8888/alipay/notifyUrl"; //开发者中心 / 研发服务 / 沙箱环境 / 沙箱应用/ 信息配置/ 必看部分/ 支付宝网关(注意沙箱alipaydev,正式则为 alipay) public static String url = "https://openapi.alipaydev.com/gateway.do"; public static String charset = "UTF-8"; public static String format = "json"; //开发者中心 / 研发服务 / 沙箱环境 / 沙箱应用/ 信息配置/ 必看部分/ 公钥(填自己的,下面都是改过的~) public static String public_key = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA2tOz8k+7V9ef5WSZRP+ZSQ7siVTYx6/rhZ25z1fda4QWuKr0ek9+WZNMXyLkV96JmtrHZwf5xFDR21RBei78PsQzTpZJY6c7H2tjmZjeCjJK4CCu4QoytRMUZWPKHR0gsizPH1SPwGNURXq2ygqw+XiccHontDljVd7r0t3gMotYYLds2yL4sDEp22Gs4RDsmuHWqay3ORJHVxTWmByurGPBaFbfe4vw1pK1ipjxhWLlYr6nn00qgiq8Xo2/WUULc3jJtoVmF+SJe+n8m3Kusy0x1c+VbR06de5ZsLB1AwlQjE6W14511ULvpWDDnxJyyT74b+ZMSQB9WqFiIkIGNQIDAQAB"; public static String signtype = "RSA2"; }
true
a1c34c53861328d69eaef85263ab3936325a5af7
Java
arsrm/Dp1
/src/dao/DaoDistributionCenter.java
UTF-8
780
1.71875
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package dao; import Model.Distribution_Center; import java.util.ArrayList; import java.util.List; /** * * @author Luigi */ public interface DaoDistributionCenter { public ArrayList<Distribution_Center> distribution_centerGetQry(); public Distribution_Center distribution_centerGet(Integer idDistribution_Center); public Distribution_Center distribution_centerGet(String name); public void distribution_centerUpd(Distribution_Center distribution_center); public List<Object[]> distribution_centerCbo(); }
true
e0a72fec660c8cef88166b3905b785eb62e549e1
Java
vportascarta/petite-caisse-backend
/src/main/java/com/nivtech/petitecaisse/controller/payload/DashboardResponse.java
UTF-8
1,452
2
2
[]
no_license
package com.nivtech.petitecaisse.controller.payload; import org.springframework.data.util.Pair; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; public class DashboardResponse { private Double amountInRegisters; private Double amountInDebts; private Double amountInProducts; private Integer productsInStock; private List<Pair<String, Long>> pastSales; public Double getAmountInRegisters() { return amountInRegisters; } public void setAmountInRegisters(Double amountInRegisters) { this.amountInRegisters = amountInRegisters; } public Double getAmountInDebts() { return amountInDebts; } public void setAmountInDebts(Double amountInDebts) { this.amountInDebts = amountInDebts; } public Double getAmountInProducts() { return amountInProducts; } public void setAmountInProducts(Double amountInProducts) { this.amountInProducts = amountInProducts; } public Integer getProductsInStock() { return productsInStock; } public void setProductsInStock(Integer productsInStock) { this.productsInStock = productsInStock; } public List<Pair<String, Long>> getPastSales() { return pastSales; } public void setPastSales(List<Pair<String, Long>> pastSales) { this.pastSales = pastSales; } }
true
f92810e26455958a42df0bbfc8fd29aa2d5bab6f
Java
penguibear/project-orlando-bloom
/monster.java
UTF-8
394
2.875
3
[]
no_license
public class monster{ int ATK, DEF, HP; String NAME; public monster(String inName, int inATK, int inDEF, int inHP){ NAME = inName; ATK = inATK; DEF = inDEF; HP = inHP; } //This is my class for creating monsters. I should use this for most of the monsters public int getATK(){return this.ATK;} public int getDEF(){return this.DEF;} public int getHP(){return this.HP;} }
true
f937f3771b26e9e0114a60f6bfd04ac43013d186
Java
Draywer/NetologyJava
/JavaBase/src/main/java/ru/idcore/basejava/task0221/Matrix.java
UTF-8
2,012
3.84375
4
[]
no_license
package ru.idcore.basejava.task0221; public class Matrix { public int m;//размер матрицы public int n;//размер матрицы public int[][] ints; public Matrix(int m) { this.m = m; this.ints = new int[m][]; } public Matrix(int m, int n) { this(m); this.n = n; this.ints = new int[m][n]; } //генератор случайных чисел public int random(int a, int b) { return a + (int) (Math.random() * (b - a)); } //заполнение матрицы случайными числами public void fillRandomInt(int a, int b) { for (int i = 0; i < this.m; i++) { for (int j = 0; j < this.n; j++) { this.ints[i][j] = this.random(a, b); } } } //вывод матрицы public void printMatrix() { for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { System.out.printf("%5s" ,this.ints[i][j]); } System.out.println(); } } //вращение против часовой стрелки public int[][] counterClockwiseRotation() { int temp = this.m; this.m = this.n; this.n = temp; int[][] intsRotated = new int[this.m][this.n]; for (int i = 0; i < this.m; i++) { for (int j = 0; j < this.n; j++) { intsRotated[i][j] = this.ints[j][this.m - i -1]; } } return intsRotated; } //вращение по часовой стрелке public int[][] clockWiseRotation() { int temp = this.m; this.m = this.n; this.n = temp; int[][] intsRotated = new int[this.m][this.n]; for (int i = 0; i < this.m; i++) { for (int j = 0; j < this.n; j++) { intsRotated[i][j] = this.ints[this.n - j- 1][i]; } } return intsRotated; } }
true
af1e2f3efb6878985e8ad9a941897058f453e8f3
Java
jingzizhuang1/codelet-cloud
/commons/src/main/java/net/codelet/cloud/event/BaseBroadcastEvent.java
UTF-8
260
1.703125
2
[]
no_license
package net.codelet.cloud.event; /** * 广播事件基类。 * @param <P> 携带数据的范型 */ public abstract class BaseBroadcastEvent<P> extends BaseRemoteApplicationEvent<P> { private static final long serialVersionUID = 3310751945116332966L; }
true
bdb87766a1ca53cb660036cbebe85314f4589a05
Java
taxiubu/AD36_NguyenHuuHuan_JSONDemo
/app/src/main/java/com/example/jsondemo/MainActivity.java
UTF-8
3,563
2.375
2
[]
no_license
package com.example.jsondemo; import androidx.appcompat.app.AppCompatActivity; import android.annotation.SuppressLint; import android.os.Bundle; import android.widget.ImageView; import android.widget.TextView; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity { String jsonWeather, jsonMain, nameLocated, timezone; ImageView imWeather; List<Weather> listWeather; TextView tvLocated, tvTime, tvWeather, tvTemp; String json= "{\"coord\": { \"lon\": 139,\"lat\": 35}, \"weather\": [ { \"id\": 800, \"main\": \"Clear\", \"description\": \"clear sky\", \"icon\": \"01n\" } ]," + " \"base\": \"stations\", \"main\": { \"temp\": 289.92, \"pressure\": 1009, \"humidity\": 92, \"temp_min\": 288.71, \"temp_max\": 290.93 }, \"wind\": { \"speed\": 0.47, \"deg\": 107.538 }, \"clouds\": { \"all\": 2 }, \"dt\": 1560350192," + " \"sys\": { \"type\": 3, \"id\": 2019346, \"message\": 0.0065, \"country\": \"JP\", \"sunrise\": 1560281377, \"sunset\": 1560333478 }, \"timezone\": 32400, \"id\": 1851632, \"name\": \"Shuzenji\", \"cod\": 200 }"; @SuppressLint("ResourceAsColor") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tvLocated= findViewById(R.id.tvLocated); tvTime= findViewById(R.id.tvTime); tvWeather= findViewById(R.id.tvWeather); tvTemp= findViewById(R.id.tvTemp); listWeather= new ArrayList<>(); try { JSONObject object= new JSONObject(json); jsonWeather= object.getString("weather"); jsonMain= object.getString("main"); nameLocated= object.getString("name"); timezone= object.getString("timezone"); tvLocated.setText(nameLocated); int time= Integer.valueOf(timezone); tvTime.setText(TimeZone(time)); } catch (JSONException e) { e.printStackTrace(); } try { JSONObject obMain= new JSONObject(jsonMain); String temp= obMain.getString("temp"); float tempC= Float.valueOf(temp) - 273.15f; tempC= Math.round(tempC*10)/10; tvTemp.setText(String.valueOf(tempC)+" C"); } catch (JSONException e) { e.printStackTrace(); } try { JSONArray jsonArray= new JSONArray(jsonWeather); for(int i=0; i<jsonArray.length(); i++){ JSONObject object= jsonArray.getJSONObject(i); String id= object.getString("id"); String main= object.getString("main"); String strDes= object.getString("description"); String icon= object.getString("icon"); listWeather.add(new Weather(id, main, strDes, icon)); } tvWeather.setText(listWeather.get(0).getDes()); } catch (JSONException e) { e.printStackTrace(); } } private String TimeZone(int time){ int hour= time/3600; int sec= time%3600; int minu= sec/60; String minute, session; if(minu<10) minute= "0"+String.valueOf(minu); else minute= String.valueOf(minu); if(hour<13) session= "AM"; else session="PM"; return "Time: "+hour+":"+minute+" "+session; } }
true
207806ce180357e95ecb4efa5fa2a5369a07e896
Java
waking999/dynamicproblems
/src/main/java/au/edu/cdu/dynamicproblems/exception/ExceedLongMaxException.java
UTF-8
230
2.078125
2
[]
no_license
package au.edu.cdu.dynamicproblems.exception; public class ExceedLongMaxException extends Exception { private static final long serialVersionUID = 1L; public ExceedLongMaxException(String msg){ super(msg); } }
true
a243accf5738d05cda363154e1f5ba26d2128a73
Java
odpi/egeria
/open-metadata-implementation/access-services/digital-service/digital-service-api/src/main/java/org/odpi/openmetadata/accessservices/digitalservice/properties/UserIdentityProperties.java
UTF-8
3,936
2.34375
2
[ "CC-BY-4.0", "Apache-2.0" ]
permissive
/* SPDX-License-Identifier: Apache-2.0 */ /* Copyright Contributors to the ODPi Egeria project. */ package org.odpi.openmetadata.accessservices.digitalservice.properties; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import java.util.Objects; import static com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.NONE; import static com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.PUBLIC_ONLY; /** * UserIdentityProperties describes an element that is linked to a single userId. */ @JsonAutoDetect(getterVisibility=PUBLIC_ONLY, setterVisibility=PUBLIC_ONLY, fieldVisibility=NONE) @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown=true) public class UserIdentityProperties extends ReferenceableProperties { private static final long serialVersionUID = 1L; private String userId = null; private String distinguishedName = null; /** * Default constructor */ public UserIdentityProperties() { super(); } /** * Copy/clone constructor * * @param template object to copy */ public UserIdentityProperties(UserIdentityProperties template) { super(template); if (template != null) { this.userId = template.getUserId(); this.distinguishedName = template.getDistinguishedName(); } } /** * Return the identifier of the user's account * * @return string */ public String getUserId() { return userId; } /** * Return the identifier of the user's account. * * @param userId string */ public void setUserId(String userId) { this.userId = userId; } /** * Return the unique name in LDAP. * * @return string name */ public String getDistinguishedName() { return distinguishedName; } /** * Set up the unique name in LDAP. * * @param distinguishedName string name */ public void setDistinguishedName(String distinguishedName) { this.distinguishedName = distinguishedName; } /** * JSON-style toString. * * @return list of properties and their values. */ @Override public String toString() { return "UserIdentityProperties{" + "qualifiedName='" + getQualifiedName() + '\'' + ", additionalProperties=" + getAdditionalProperties() + ", typeName='" + getTypeName() + '\'' + ", extendedProperties=" + getExtendedProperties() + ", userId='" + userId + '\'' + ", distinguishedName='" + distinguishedName + '\'' + '}'; } /** * Equals method that returns true if containing properties are the same. * * @param objectToCompare object to compare * @return boolean result of comparison */ @Override public boolean equals(Object objectToCompare) { if (this == objectToCompare) { return true; } if (objectToCompare == null || getClass() != objectToCompare.getClass()) { return false; } if (! super.equals(objectToCompare)) { return false; } UserIdentityProperties that = (UserIdentityProperties) objectToCompare; return Objects.equals(userId, that.userId) && Objects.equals(distinguishedName, that.distinguishedName); } /** * Just use the GUID for the hash code as it should be unique. * * @return int code */ @Override public int hashCode() { return Objects.hash(super.hashCode(), userId, distinguishedName); } }
true
30429ecc0c95d861850b6dc1a2dc0e48671297b6
Java
tandaica0612/MARDJAVA
/mard-frontend/src/main/java/com/nsw/dao/HibernateTokenRepositoryImpl.java
UTF-8
866
2.109375
2
[]
no_license
package com.nsw.dao; import java.util.Date; import org.springframework.security.web.authentication.rememberme.PersistentRememberMeToken; import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; @Repository("tokenRepositoryDao") @Transactional public class HibernateTokenRepositoryImpl implements PersistentTokenRepository { @Override public void createNewToken(PersistentRememberMeToken token) { } @Override public PersistentRememberMeToken getTokenForSeries(String seriesId) { return null; } @Override public void removeUserTokens(String username) { } @Override public void updateToken(String seriesId, String tokenValue, Date lastUsed) { } }
true
8093eb2d165fa42bef26274bac34b9736c2363b9
Java
TronYY/MC
/src/MC07/TestBabai.java
GB18030
987
3.15625
3
[]
no_license
package MC07; import java.math.BigDecimal; import java.util.Scanner; public class TestBabai { public static void main(String[] args) { // TODO Auto-generated method stub @SuppressWarnings("resource") Scanner input=new Scanner(System.in); System.out.println("άn="); int n=input.nextInt(); int i,j; BigDecimal[][] A = new BigDecimal[n][n+1];//ΪҪ BigDecimal[] B=new BigDecimal[n]; BigDecimal[][] t=new BigDecimal[2][n]; for (i=0;i<n;i++) { System.out.println(""+(i+1)+""); for (j=0;j<n;j++) A[j][i]=input.nextBigDecimal(); } System.out.println("w"); for (i=0;i<n;i++) B[i]=input.nextBigDecimal(); Babai babai=new Babai(n,A,B); t=babai.solve(A,B); for (i=0;i<n;i++) System.out.println("t["+(i+1)+"]="+t[0][i]); System.out.print("wΪv=("); for (i=0;i<n;i++) System.out.print(t[1][i]+" "); System.out.print(")"); } }
true
4331e5c6fd3dd0d815b3aa7f166b7de59fc653cb
Java
AgNO3/code
/runtime/eventlog/eu.agno3.runtime.eventlog.elasticsearch/src/main/java/eu/agno3/runtime/eventlog/elasticsearch/QueryParamBuilder.java
UTF-8
1,958
2.140625
2
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
/** * © 2015 AgNO3 Gmbh & Co. KG * All right reserved. * * Created: 02.05.2015 by mbechler */ package eu.agno3.runtime.eventlog.elasticsearch; import org.elasticsearch.index.query.QueryBuilder; import org.joda.time.DateTime; /** * @author mbechler * */ public class QueryParamBuilder { private QueryParams params = new QueryParams(); /** * */ private QueryParamBuilder () {} /** * * @return the constructed params */ public QueryParams build () { return this.params; } /** * @return a param builder */ public static final QueryParamBuilder get () { return new QueryParamBuilder(); } /** * @param types * @return this */ public QueryParamBuilder type ( String... types ) { this.params.setTypes(types); return this; } /** * @param query * @return this */ public QueryParamBuilder query ( QueryBuilder query ) { this.params.setCustomQuery(query); return this; } /** * @param from * @return this */ public QueryParamBuilder from ( DateTime from ) { this.params.setStartDate(from); return this; } /** * @param to * @return this */ public QueryParamBuilder to ( DateTime to ) { this.params.setEndDate(to); return this; } /** * * @param offset * @return this */ public QueryParamBuilder pageFrom ( int offset ) { this.params.setPageFrom(offset); return this; } /** * * @param pageSize * @return this */ public QueryParamBuilder pageSize ( int pageSize ) { this.params.setPageSize(pageSize); return this; } /** * @return this */ public QueryParamBuilder filterDuplicates () { this.params.setIncludeDuplicates(false); return this; } }
true
2a02f939da32508eecee15129c71b38ddb344642
Java
tuntdxx/apiPortalTraining
/src/main/java/com/vnpt/iot/portal/jwt/JwtTokenProvider.java
UTF-8
3,447
2.296875
2
[]
no_license
package com.vnpt.iot.portal.jwt; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.stream.Collectors; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import com.vnpt.iot.portal.config.CustomUserDetails; import com.vnpt.iot.portal.utils.CommonUtils; import io.jsonwebtoken.Claims; import io.jsonwebtoken.ExpiredJwtException; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.MalformedJwtException; import io.jsonwebtoken.SignatureAlgorithm; import io.jsonwebtoken.UnsupportedJwtException; import lombok.extern.slf4j.Slf4j; /** * @author Trinh Dinh Tuan : Developer * @Email tuantdxyz@gmail.com * @Version 1.0.0 Sep 1, 2020 */ @Component @Slf4j public class JwtTokenProvider { // millisecond to minute, set 15 minus // private final long JWT_EXPIRATION = 15 * 60000; @Value("${spring.jwt.expiration}") private int JWT_EXPIRATION; // private final String JWT_SECRET = "VNPT_IOT_PORTAL"; // @Value("${spring.jwt.secret}") // private String JWT_SECRET; // // @Value("${spring.jwt.secret.local}") // private String JWT_SECRET_LOCAL; // create JWT from User public String generateToken(CustomUserDetails userDetails, String server) { Date now = new Date(); Date expiryDate = new Date(now.getTime() + JWT_EXPIRATION); // get list roles List<String> listRoles = new ArrayList<String>(); List<String> roles = userDetails.getUser().getRoles().stream().map(role -> role.getPrivileges()) .collect(Collectors.toList()); for (int i = 0; i < roles.size(); i++) { String[] part = roles.get(i).split(","); for (int j = 0; j < part.length; j++) { String role = part[j]; listRoles.add(role); } } log.info("List roles gen with Jwt: " + listRoles.toString()); // get secret jwt with server String secret = CommonUtils.getSecret(server); // create JWT token return Jwts.builder().setSubject(userDetails.getUser().getId()).claim("roles", listRoles).setIssuedAt(now) .setExpiration(expiryDate).signWith(SignatureAlgorithm.HS512, secret).compact(); } // get infor user from JWT Token public String getUserIdFromJWT(String token, String secret) { Claims claims = Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody(); return claims.getSubject(); } // check JWT Token public boolean validateToken(String authToken, String server) { try { String secret = CommonUtils.getSecret(server); Jwts.parser().setSigningKey(secret).parseClaimsJws(authToken); return true; } catch (MalformedJwtException ex) { log.error("Invalid JWT token" + ex.getMessage()); // throw new PortalException(EnumValues.StatusProtocolEnum.STATUS_608.code, EnumValues.StatusProtocolEnum.STATUS_608.message); } catch (ExpiredJwtException ex) { log.error("Expired JWT token" + ex.getMessage()); // throw new PortalException(EnumValues.StatusProtocolEnum.STATUS_401.code, EnumValues.StatusProtocolEnum.STATUS_401.message); } catch (UnsupportedJwtException ex) { log.error("Unsupported JWT token" + ex.getMessage()); // throw new PortalException(EnumValues.StatusProtocolEnum.STATUS_609.code, EnumValues.StatusProtocolEnum.STATUS_609.message); } catch (IllegalArgumentException ex) { log.error("JWT claims string is empty." + ex.getMessage()); // throw new PortalException(EnumValues.StatusProtocolEnum.STATUS_610.code, EnumValues.StatusProtocolEnum.STATUS_610.message); } return false; } }
true
b55418ffe0482163e79dc312d780f10b71183952
Java
encinas008/patients-manager
/dao/src/main/java/org/encinas/dao/repository/PatientDao.java
UTF-8
315
1.960938
2
[]
no_license
package org.encinas.dao.repository; import org.encinas.dao.entity.Patient; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository public interface PatientDao extends JpaRepository<Patient, Integer> { Patient findPatientByDni(String dni); }
true
6c2e4e7e43c4cf1c0b25b664c554e7c99aa3e3d5
Java
cunhazera/coderadar
/coderadar-core/src/main/java/io/reflectoring/coderadar/projectadministration/port/driver/module/get/ListModulesOfProjectUseCase.java
UTF-8
322
1.726563
2
[ "MIT" ]
permissive
package io.reflectoring.coderadar.projectadministration.port.driver.module.get; import io.reflectoring.coderadar.projectadministration.ProjectNotFoundException; import java.util.List; public interface ListModulesOfProjectUseCase { List<GetModuleResponse> listModules(Long projectId) throws ProjectNotFoundException; }
true
8806139d9a9fe05150632e3e85a903b04bcd624c
Java
google/oboe
/apps/OboeTester/app/src/main/java/com/mobileer/oboetester/AudioRecordThread.java
UTF-8
5,036
2.4375
2
[ "Apache-2.0" ]
permissive
/* * Copyright (C) 2013 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.mobileer.oboetester; import android.media.AudioDeviceInfo; import android.media.AudioFormat; import android.media.AudioRecord; import android.media.MediaRecorder; /** * Abstract class for recording. * Call processBuffer(buffer) when data is read. */ class AudioRecordThread implements Runnable { private static final String TAG = "AudioRecordThread"; private final int mSampleRate; private final int mChannelCount; private Thread mThread; protected boolean mGo; private AudioRecord mRecorder; private CircularCaptureBuffer mCaptureBuffer; protected float[] mBuffer = new float[256]; private static int AUDIO_FORMAT = AudioFormat.ENCODING_PCM_FLOAT; private Runnable mTask; private int mTaskCountdown; private boolean mCaptureEnabled = true; private AudioDeviceInfo mDeviceInfo; public AudioRecordThread(int frameRate, int channelCount, int maxFrames) { mSampleRate = frameRate; mChannelCount = channelCount; mCaptureBuffer = new CircularCaptureBuffer(maxFrames); } private void createRecorder() { int channelConfig = (mChannelCount == 1) ? AudioFormat.CHANNEL_IN_MONO : AudioFormat.CHANNEL_IN_STEREO; int audioFormat = AudioFormat.ENCODING_PCM_FLOAT; int minRecordBuffSizeInBytes = AudioRecord.getMinBufferSize(mSampleRate, channelConfig, audioFormat); mRecorder = new AudioRecord( MediaRecorder.AudioSource.VOICE_RECOGNITION, mSampleRate, channelConfig, audioFormat, 2 * minRecordBuffSizeInBytes); mRecorder.setPreferredDevice(mDeviceInfo); if (mRecorder.getState() == AudioRecord.STATE_UNINITIALIZED) { throw new RuntimeException("Could not make the AudioRecord - UNINITIALIZED"); } } @Override public void run() { startAudioRecording(); while (mGo) { int result = handleAudioPeriod(); if (result < 0) { mGo = false; } } stopAudioRecording(); } public void startAudio() { if (mThread == null) { mGo = true; mThread = new Thread(this); mThread.start(); } } public void stopAudio() { mGo = false; if (mThread != null) { try { mThread.join(1000); } catch (InterruptedException e) { e.printStackTrace(); } mThread = null; } } public int getSampleRate() { return mSampleRate; } /** * @return number of samples read or negative error */ private int handleAudioPeriod() { int numSamplesRead = mRecorder.read(mBuffer, 0, mBuffer.length, AudioRecord.READ_BLOCKING); if (numSamplesRead <= 0) { return numSamplesRead; } else { if (mTaskCountdown > 0) { mTaskCountdown -= numSamplesRead; if (mTaskCountdown <= 0) { mTaskCountdown = 0; new Thread(mTask).start(); // run asynchronously with audio thread } } if (mCaptureEnabled) { return mCaptureBuffer.write(mBuffer, 0, numSamplesRead); } else { return numSamplesRead; } } } private void startAudioRecording() { stopAudioRecording(); createRecorder(); mRecorder.startRecording(); } private void stopAudioRecording() { if (mRecorder != null) { mRecorder.stop(); mRecorder.release(); mRecorder = null; } } /** * Schedule task to be run on its own thread when numSamples more samples have been recorded. * * @param numSamples * @param task */ public void scheduleTask(int numSamples, Runnable task) { mTask = task; mTaskCountdown = numSamples; } public void setCaptureEnabled(boolean captureEnabled) { mCaptureEnabled = captureEnabled; } public int readMostRecent(float[] buffer) { return mCaptureBuffer.readMostRecent(buffer); } public void setInputDevice(AudioDeviceInfo deviceInfo) { mDeviceInfo = deviceInfo; } }
true
0a3a7c9457b29cd484a668c94945cdbe426ab542
Java
SmartI18N/SmartI18N
/smarti18n/smarti18n-vaadin/src/main/java/org/smarti18n/vaadin/components/RootMenu.java
UTF-8
1,301
2.28125
2
[ "Apache-2.0" ]
permissive
package org.smarti18n.vaadin.components; import org.smarti18n.vaadin.utils.VaadinUtils; import com.vaadin.server.Resource; import com.vaadin.ui.Button; import com.vaadin.ui.HorizontalLayout; import com.vaadin.ui.Label; import com.vaadin.ui.themes.ValoTheme; public class RootMenu extends HorizontalLayout { public RootMenu(final String menuTitleText) { setPrimaryStyleName(ValoTheme.MENU_ROOT); setWidth(100, Unit.PERCENTAGE); final Label menuTitle = new Label(menuTitleText); addComponent(menuTitle); } public RootMenu addMenuItem(final String menuItemText, final Resource icon, final String viewId) { return addMenuItem(menuItemText, icon, () -> VaadinUtils.navigateTo(viewId)); } public RootMenu addMenuItem( final String menuItemText, final Resource icon, final MenuItemClickListener clickListener) { final Button menuItem = new Button(menuItemText); // menuItem.setIcon(icon); menuItem.setSizeUndefined(); menuItem.setPrimaryStyleName(ValoTheme.MENU_ITEM); menuItem.addClickListener(event -> clickListener.click()); addComponent(menuItem); return this; } public interface MenuItemClickListener { void click(); } }
true
94aa23bba8fb61602ac6c87f5013d6c77d5eb04c
Java
akmishra30/java-projects
/design-patterns/src/main/java/com/makhir/java/patterns/creational/singleton/LazyInitializationApproach.java
UTF-8
414
2.921875
3
[]
no_license
package com.makhir.java.patterns.creational.singleton; /** * This class shows lazy initialization of instance. * */ public class LazyInitializationApproach { private static LazyInitializationApproach instance; private LazyInitializationApproach() {} public static LazyInitializationApproach getInstance(){ if(instance == null) instance = new LazyInitializationApproach(); return instance; } }
true
f991639a3262b3aaff1d3c3d9100eb995bffcd4c
Java
yhsim98/HANCALL
/src/main/java/repository/ParticipantMapper.java
UTF-8
575
2.03125
2
[]
no_license
package repository; import domain.Participant; import org.springframework.stereotype.Repository; import java.util.List; @Repository public interface ParticipantMapper { List<Participant> getParticipantsList(Long boardId); void insertParticipant(Participant participant); void deleteParticipant(Participant participant); Participant getParticipant(Participant participant); void deleteAllParticipantInBoard(Long boardId); int countParticipants(Long boardId); int isDeleted(Participant participant); void restore(Participant participant); }
true
628903ad589b27318a2d25f684ae6e04e43df35a
Java
SirSalad/ChatBrawl
/src/main/java/be/woutzah/chatbrawl/races/types/ContestantRace.java
UTF-8
1,415
2.328125
2
[]
no_license
package be.woutzah.chatbrawl.races.types; import be.woutzah.chatbrawl.contestants.ContestantsManager; import be.woutzah.chatbrawl.leaderboard.LeaderboardManager; import be.woutzah.chatbrawl.races.RaceManager; import be.woutzah.chatbrawl.rewards.RewardManager; import be.woutzah.chatbrawl.settings.SettingManager; import be.woutzah.chatbrawl.time.TimeManager; import org.bukkit.event.EventHandler; import org.bukkit.event.player.PlayerJoinEvent; public abstract class ContestantRace extends Race { protected ContestantsManager contestantsManager; public ContestantRace(RaceType type, RaceManager raceManager, SettingManager settingManager, RewardManager rewardManager, TimeManager timeManager, ContestantsManager contestantsManager, LeaderboardManager leaderboardManager) { super(type, raceManager, settingManager, rewardManager, timeManager,leaderboardManager); this.contestantsManager = contestantsManager; } @Override public void beforeRaceStart() { contestantsManager.fillOnlinePlayers(); } @Override public void afterRaceEnd() { super.afterRaceEnd(); contestantsManager.removeOnlinePlayers(); } @EventHandler public void addContestant(PlayerJoinEvent e) { if (!isActive()) return; contestantsManager.addContestant(e.getPlayer().getUniqueId()); } }
true
dbcd66a0168f39c09db6693855bd1027598bcccc
Java
Zero-Jzy/AsmJavaWeb1
/src/main/java/entity/User.java
UTF-8
6,068
2.359375
2
[]
no_license
package entity; import model.UserModel; import org.hibernate.annotations.CreationTimestamp; import javax.persistence.*; import java.sql.Date; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Set; @Entity @Table(name = "User") public class User { @Id private String username; @Column private String password; @CreationTimestamp private Date createdAt; @OneToOne @JoinColumn(name="infor_user_id") private UserInfomation userInfomation; @OneToMany(fetch = FetchType.LAZY, mappedBy = "user") private Set<FeedBack> feedBacks = new HashSet<FeedBack>(); @ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL) @JoinTable(name = "role_user", joinColumns = { @JoinColumn(name = "username") }, inverseJoinColumns = {@JoinColumn(name = "role_id") }) private Set<Role> roles = new HashSet<Role>(); private HashMap<String, ArrayList<String>> errors = null; public User() { } public User(String username, String password, UserInfomation userInfomation) { this.username = username; this.password = password; this.userInfomation = userInfomation; } public UserInfomation getUserInfomation() { return userInfomation; } public void setUserInfomation(UserInfomation userInfomation) { this.userInfomation = userInfomation; } public Set<FeedBack> getFeedBacks() { return feedBacks; } public void setFeedBacks(Set<FeedBack> feedBacks) { this.feedBacks = feedBacks; } public Set getRoles() { return roles; } public void setRoles(Set roles) { this.roles = roles; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public boolean isUser(){ Set<Role> userRoles = this.roles; boolean resulte = false; for(Role role: userRoles){ if (role.getId().equals(1)) resulte = true; } return resulte; } public boolean isAdmin(){ Set<Role> userRoles = this.roles; boolean resulte = false; for(Role role: userRoles){ if (role.getId().equals(2)) resulte = true; } return resulte; } public boolean isValid() { validate(); return errors.size() == 0; } public void validate() { UserModel model = new UserModel(); ArrayList<User> userArrayList = model.getALl(); if (errors == null) { errors = new HashMap<String, ArrayList<String>>(); } ArrayList<String> usernameErrors = this.errors.get("username"); if (usernameErrors == null) { usernameErrors = new ArrayList<String>(); } if (this.username == null || this.username.length() == 0) { usernameErrors.add("User name is requeid!"); } for (User user :userArrayList){ if (user.getUsername().equals(this.username)){ usernameErrors.add("Username has been used!"); } } if (this.username.length() < 2 || this.username.length() > 30) { usernameErrors.add("UserName must be between 2 and 30 in length!"); } if (usernameErrors.size() > 0) errors.put("username", usernameErrors); ArrayList<String> passwordErrors = this.errors.get("password"); if (passwordErrors == null) { passwordErrors = new ArrayList<String>(); } if (this.password == null || this.password.length() == 0) { passwordErrors.add("Password is requeid!"); } if (this.password.length() < 2 || this.password.length() > 30) { passwordErrors.add("Password must be between 2 and 30 in length!"); } if (passwordErrors.size() > 0) errors.put("password", passwordErrors); ArrayList<String> fullnameErrors = this.errors.get("fullname"); if (fullnameErrors == null) { fullnameErrors = new ArrayList<String>(); } if (this.userInfomation.getFullName() == null || this.userInfomation.getFullName().length() == 0) { fullnameErrors.add("Full Name is requeid!"); } if (this.userInfomation.getFullName().length() < 2 || this.userInfomation.getFullName().length() > 30) { fullnameErrors.add("Full Name must be between 2 and 30 in length!"); } if (fullnameErrors.size() > 0) errors.put("fullname", fullnameErrors); ArrayList<String> emailErrors = this.errors.get("email"); if (emailErrors == null) { emailErrors = new ArrayList<String>(); } for (User user :userArrayList){ if (user.getUserInfomation().getEmail().equals(this.userInfomation.getEmail())){ emailErrors.add("Email has been used!"); } } if (this.userInfomation.getEmail() == null || this.userInfomation.getEmail().length() == 0) { emailErrors.add("Email is requeid!"); } if (this.userInfomation.getEmail().length() < 2 || this.userInfomation.getEmail().length() > 30) { emailErrors.add("Email must be between 2 and 30 in length!"); } if (emailErrors.size() > 0) errors.put("email", emailErrors); ArrayList<String> phoneErrors = this.errors.get("phone"); if (phoneErrors == null) { phoneErrors = new ArrayList<String>(); } if (this.userInfomation.getEmail() == null || this.userInfomation.getEmail().length() == 0) { phoneErrors.add("Phone is requeid!"); } if (phoneErrors.size() > 0) errors.put("phone", phoneErrors); } public HashMap<String, ArrayList<String>> getErrors() { return errors; } }
true
ce2f0aa391fa09150f81d38a1ae6f03e7a4a25a6
Java
chinonn/239920
/AssignmentOne/src/assignmentone/CountFiles.java
UTF-8
1,527
2.90625
3
[]
no_license
//Semester: #A171 //Course: #STIW3054 //Group: #A //Task: #Assignment1 //Matrik: #239920 //Name: #Kok Chin Onn package assignmentone; import java.io.File; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.LinkedList; public class CountFiles { public String[] countJavaFile; String Path="C:\\Users\\User\\Documents\\NetBeansProjects\\AssignmentOne\\Folder"; public CountFiles() { Collection<File> all = new ArrayList<>(); addFile(new File(Path), all); Collection<File> a = all; countJavaFile = searchJava(a); } static void addFile(File file, Collection<File> all) { File[] children = file.listFiles(); if (children != null) { for (File child : children) { all.add(child); addFile(child, all); } } } static String[] searchJava(Collection<File> listAllFileName){ LinkedList<String> file = new LinkedList(); Iterator<File> a = listAllFileName.iterator(); File b; while (a.hasNext()) { b = a.next(); if (b.getName().contains(".java")) { file.add(b.getAbsolutePath()); } } String[] countJavaFile; countJavaFile = new String[file.size()]; for (int i = 0; i < file.size(); i++) { countJavaFile[i] = file.get(i); } return countJavaFile; } }
true
53d6a2e63bd1ebf30d891a48a3c379f9dedeca07
Java
swjiyane/LikiwiSmart
/app/src/main/java/com/example/codetribe/likiwismart/User.java
UTF-8
1,811
2.46875
2
[]
no_license
package com.example.codetribe.likiwismart; /** * Created by CodeTribe on 7/27/2017. */ public class User { private String userName; private String nexOfKin1; private String nexOfKin2; private String cell1; private String cell2; private String userEmail; private String userPassword; public User() { } public User(String userName, String nexOfKin1, String nexOfKin2, String cell1, String cell2, String userEmail, String userPassword) { this.userName = userName; this.nexOfKin1 = nexOfKin1; this.nexOfKin2 = nexOfKin2; this.cell1 = cell1; this.cell2 = cell2; this.userEmail = userEmail; this.userPassword = userPassword; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getNexOfKin1() { return nexOfKin1; } public void setNexOfKin1(String nexOfKin1) { this.nexOfKin1 = nexOfKin1; } public String getNexOfKin2() { return nexOfKin2; } public void setNexOfKin2(String nexOfKin2) { this.nexOfKin2 = nexOfKin2; } public String getCell1() { return cell1; } public void setCell1(String cell1) { this.cell1 = cell1; } public String getCell2() { return cell2; } public void setCell2(String cell2) { this.cell2 = cell2; } public String getUserEmail() { return userEmail; } public void setUserEmail(String userEmail) { this.userEmail = userEmail; } public String getUserPassword() { return userPassword; } public void setUserPassword(String userPassword) { this.userPassword = userPassword; } }
true
9db3fbba8e1e25a87b217360efdd5dd5f4464c30
Java
dengpan20/gmat-app
/app/src/main/java/org/zywx/wbpalmstar/widgetone/uex11597450/callback/ICallBack.java
UTF-8
140
1.6875
2
[ "Apache-2.0" ]
permissive
package org.zywx.wbpalmstar.widgetone.uex11597450.callback; public interface ICallBack<T> { void onSuccess(T t); void onFail(); }
true
a24cfbbdc506e70b88e7c414dd89d374799636d4
Java
RonnieLusso/Barrel-Run---OOP-Final
/Barrel Run/src/Main/Window.java
UTF-8
684
2.765625
3
[]
no_license
package Main; import java.awt.Dimension; import java.awt.Toolkit; import javax.swing.JFrame; public class Window extends JFrame { private static final long serialVersionUID = 1L; private static Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); public static final int WIDTH = 550, HEIGHT = 550; public Window() { setTitle("Barrel Run - Goals: Avoid the Barrels! - Controls: WASD, Arrow Keys"); setSize(WIDTH, HEIGHT); setLocation((int) (screenSize.getWidth() / 2) - (WIDTH / 2), (int) (screenSize.getHeight() / 2) - (HEIGHT / 2)); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setResizable(false); setVisible(true); } }
true
8135c648aca3af8e2fa3994c9596ed11fa0862f9
Java
pedro-mello30/DesignPattern
/Builder/src/MealBuilder.java
UTF-8
156
2.328125
2
[ "MIT" ]
permissive
public interface MealBuilder { public void buildMainItem(); public void buildSideItem(); public void buildDrink(); public Meal getMeal(); }
true
21bf61ba6cebf96de9fab273028754e27ce7af52
Java
vivekisongit/efictive-java-training
/Mini-Project/com.vkr.bookstore/src/main/java/com/vkr/bookstore/repository/BookRepository.java
UTF-8
771
2.03125
2
[]
no_license
package com.vkr.bookstore.repository; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import com.vkr.bookstore.bookstoremodel.Book; import com.vkr.bookstore.utils.Constants; /** * @author Vivek Kumar * @version 1.0 * @Date 9/11/2020 */ public interface BookRepository extends JpaRepository<Book, String> { @Query(value =Constants.QUERY_ON_BOOK, nativeQuery = true) List<Book> findByAuthorContainingIgnoreCase(String authorNamePart); @Query(value = Constants.QUERY_BOOK_REVIEW_BY_ISBN, nativeQuery = true) List<Object> reviewbyIsbn(String isbn); @Query(value = Constants.QUERY_FIND_BOOK_BY_PRICE, nativeQuery = true) List<Book> findbookByPrice(int min, int max); }
true
5cfcb70e32b663db87737856096372dab0dc25e5
Java
Guray00/IngegneriaInformatica
/TERZO ANNO/MATERIE A SCELTA/Programmazione avanzata/A.A Precedente/Prove pratiche/prg-compiti-2018/2018-07-03/esercizio1/Descrizione.java
UTF-8
481
3.1875
3
[]
no_license
public class Descrizione { private String produttore; private int numero; public Descrizione(String p, int n) { produttore = p; numero = n; } public boolean corrisponde(Pezzo pez) { return corrispondeProd(pez.getProduttore()) && corrispondeNum(pez.getNumero()); } private boolean corrispondeProd(String pezProd) { return produttore.equals(pezProd); } private boolean corrispondeNum(int pezNum) { return numero == pezNum; } }
true
f6462e82fa693f03fdca405a88a549a18b6e726d
Java
bipin-k/selenium-impl
/src/test/java/example_01/LaunchChromeBrowser.java
UTF-8
950
2.484375
2
[]
no_license
package example_01; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.testng.annotations.AfterSuite; import org.testng.annotations.BeforeSuite; import org.testng.annotations.Test; public class LaunchChromeBrowser { WebDriver driver; // Config path to get the current working directory of the repo String CURRENT_DIRECTORY= System.getProperty("user.dir"); String baseurl= "https://www.google.co.in/"; @BeforeSuite public void setup(){ // Config path for chrome driver System.setProperty("webdriver.chrome.driver", CURRENT_DIRECTORY+"/driver/chromedriver/mac/chromedriver"); driver= new ChromeDriver(); driver.manage().window().maximize(); } @Test public void test() throws InterruptedException{ driver.get(baseurl); Thread.sleep(5000); } @AfterSuite public void quit(){ driver.quit(); } }
true
3ef7225e6deef1dfaa487b2ad8709891875ba106
Java
raulmontesdeoca12/AppAsiel
/src/obed77/Splash_principal.java
UTF-8
8,955
2.28125
2
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package obed77; import BaseDeDatos.ConexionBD; import com.sun.awt.AWTUtilities; import java.awt.Color; import static java.awt.Frame.MAXIMIZED_BOTH; import java.awt.Image; import java.awt.Shape; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.geom.RoundRectangle2D; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.Timer; /** * * @author Saito */ public class Splash_principal extends javax.swing.JFrame implements Runnable { private Timer timer; int i=0; Shape shape = null; Validación p ; public Splash_principal() { initComponents(); shape = new RoundRectangle2D.Float(0,0,this.getWidth(),this.getHeight(),20,20); AWTUtilities.setWindowShape(this, shape); } public Image getIconImage() { Image retValue = Toolkit.getDefaultToolkit(). getImage(ClassLoader.getSystemResource("Imagenes/LogoObed77.png")); return retValue; } /** * 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() { Configurar = new javax.swing.JButton(); lab_texto = new javax.swing.JLabel(); btn_cerrar = new javax.swing.JButton(); progreso = new javax.swing.JProgressBar(); jLabel1 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("¡Cargando Obed77!"); setBackground(new java.awt.Color(255, 255, 255)); setIconImage(getIconImage()); setMinimumSize(new java.awt.Dimension(690, 260)); setUndecorated(true); setResizable(false); getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); Configurar.setText("Configuración"); Configurar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ConfigurarActionPerformed(evt); } }); getContentPane().add(Configurar, new org.netbeans.lib.awtextra.AbsoluteConstraints(450, 230, 120, -1)); getContentPane().add(lab_texto, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 230, 230, 30)); btn_cerrar.setText("Cerrar"); btn_cerrar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btn_cerrarActionPerformed(evt); } }); getContentPane().add(btn_cerrar, new org.netbeans.lib.awtextra.AbsoluteConstraints(580, 230, 100, -1)); progreso.setBackground(new java.awt.Color(255, 255, 255)); progreso.setForeground(new java.awt.Color(0, 204, 51)); progreso.setBorderPainted(false); progreso.setFocusable(false); getContentPane().add(progreso, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 260, 690, -1)); jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/SplashPrincipalO77.jpg"))); // NOI18N getContentPane().add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, -1, 260)); pack(); setLocationRelativeTo(null); }// </editor-fold>//GEN-END:initComponents private void ConfigurarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ConfigurarActionPerformed Ventana_Ajustes_Splash va = new Ventana_Ajustes_Splash(); va.setVisible(true); // TODO add your handling code here: }//GEN-LAST:event_ConfigurarActionPerformed private void btn_cerrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_cerrarActionPerformed System.exit(0); // TODO add your handling code here: }//GEN-LAST:event_btn_cerrarActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(Splash_principal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Splash_principal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Splash_principal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Splash_principal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new Splash_principal().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables public javax.swing.JButton Configurar; public javax.swing.JButton btn_cerrar; public javax.swing.JLabel jLabel1; public javax.swing.JLabel lab_texto; public javax.swing.JProgressBar progreso; // End of variables declaration//GEN-END:variables @Override public void run() { Configurar.setVisible(false); btn_cerrar.setVisible(false); this.setLocationRelativeTo(null); this.setVisible(true); timer = new Timer(40,new ActionListener() { public void actionPerformed(ActionEvent o) { i+=1; progreso.setValue(i); if(i==10) { lab_texto.setText("Cargando Aplicación..."); } if(i==30) { lab_texto.setText("Conectando a la Base de Datos..."); try{ ConexionBD parametros = new ConexionBD(); Class.forName(parametros.getDriver()); Connection con = DriverManager.getConnection(parametros.getUrl(), parametros.getUser(), parametros.getPass()); lab_texto.setText("Conectado con la Base de Datos..."); }catch(SQLException ex) { Logger.getLogger(Principal.class.getName()).log(Level.SEVERE, null, ex); lab_texto.setText("Error al conectar con la Base de Datos..."); timer.stop(); progreso.setValue(100); progreso.setForeground(Color.red); Configurar.setVisible(true); btn_cerrar.setVisible(true); } catch (ClassNotFoundException ex) { Logger.getLogger(Principal.class.getName()).log(Level.SEVERE, null, ex); lab_texto.setText("Error al conectar con la Base de Datos..."); timer.stop(); Configurar.setVisible(true); btn_cerrar.setVisible(true); } } if(i==80) { lab_texto.setText("Ejecutando Aplicación..."); } if(i==100) { p = new Validación(); } cek(); } }); timer.start(); } private void cek() { if(i==100) { timer.stop(); this.dispose(); p.setVisible(true); } } }
true
07a6cbe5ed5bcd816baeeda9816a2251cdfff0c2
Java
ramonNobrega/Redes_Digitais_Controle_de_Notas
/src/main/java/redes_digitais_controle_de_notas/business/entity/DesempenhoBimestralBC.java
UTF-8
914
1.992188
2
[]
no_license
package redes_digitais_controle_de_notas.business.entity; import redes_digitais_controle_de_notas.domain.entity.DesempenhoBimestral; import redes_digitais_controle_de_notas.persistence.entity.DesempenhoBimestralDAO; import java.util.*; import javax.inject.Inject; import br.gov.frameworkdemoiselle.stereotype.BusinessController; import br.gov.frameworkdemoiselle.transaction.Transactional; import br.gov.frameworkdemoiselle.template.DelegateCrud; @BusinessController public class DesempenhoBimestralBC extends DelegateCrud<DesempenhoBimestral, Integer, DesempenhoBimestralDAO> { private static final long serialVersionUID = 1L; public List<DesempenhoBimestral> findByExample(DesempenhoBimestral example) { return getDelegate().findByExample(example); } public List<DesempenhoBimestral> findByCriteria(java.util.Map<String, Object> parameters) { return getDelegate().findByCriteria(parameters); } }
true
eb7991174b6228bd223ee9cbe18edd33739b3bf8
Java
JananiVelmurugan/tl-jun-batch
/designpatterns-main/designpatterns/src/com/training/l/AudiobookDelivery.java
UTF-8
147
1.523438
2
[]
no_license
package com.training.l; class AudiobookDelivery extends BookDelivery { @Override void getDeliveryLocations() { /* can't be implemented */ } }
true
0ecc9e1f453ec17b427660b4eb69fb2705b738b6
Java
JonatanGonzalez09/Parcial-AREP
/src/main/java/edu/escuelaing/arep/app/App.java
UTF-8
575
2.890625
3
[]
no_license
package edu.escuelaing.arep.app; import java.util.ArrayList; public class App { MergeSort mS = new MergeSort(); public int getSum(ArrayList<Float> lista){ int suma = 0; for (int i = 0; i < lista.size(); i++){ suma+= lista.get(i); } return suma; } public ArrayList<Float> listaOrdenada(float arreF[]){ mS.sort(arreF, 0, arreF.length-1); ArrayList<Float> arr = new ArrayList<Float>(); int n = arreF.length; for (int i=0; i<n; ++i) arr.add(arreF[i]); return arr; } }
true
db89078a3a1cf4d6e317df7886fc30d51f0e7a00
Java
APPBMS/AppInfoStstem
/src/com/service/devuser/DevUserServiceImpl.java
UTF-8
496
2.0625
2
[]
no_license
package com.service.devuser; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.dao.devuser.DevUserMapper; import com.entity.DevUser; @Service public class DevUserServiceImpl implements DevUserService { @Resource private DevUserMapper mapper; @Override public DevUser login(String devCode, String devPassword){ // TODO Auto-generated method stub DevUser user = mapper.getLoginUser(devCode,devPassword); return user; } }
true
e96b1bc9f12766b05a6b4a424372246c0334ca63
Java
AlexStoicaDev/OnlineShop
/src/main/java/ro/msg/learning/shop/exceptions/UserNotFoundException.java
UTF-8
200
1.882813
2
[]
no_license
package ro.msg.learning.shop.exceptions; public class UserNotFoundException extends BaseException { public UserNotFoundException(String msg, Object actual) { super(msg, actual); } }
true
2a1f8434faa34a5e5e9b27c15714dc9b0bad81c5
Java
Bhupendrasinha/LoginApp
/app/src/main/java/com/example/bhupendrasinha/loginapp/fbloginfragment.java
UTF-8
3,162
2.125
2
[]
no_license
package com.example.bhupendrasinha.loginapp; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import android.widget.Toast; import com.facebook.AccessToken; import com.facebook.CallbackManager; import com.facebook.FacebookCallback; import com.facebook.FacebookException; import com.facebook.FacebookSdk; import com.facebook.Profile; import com.facebook.login.LoginResult; import com.facebook.login.widget.LoginButton; public class fbloginfragment extends Fragment { CallbackManager callbackManager; public fbloginfragment() { // Required empty public constructor } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); FacebookSdk.sdkInitialize(getActivity().getApplicationContext()); callbackManager = CallbackManager.Factory.create(); Toast.makeText(getActivity(),"OnCreate",Toast.LENGTH_LONG).show(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_fbloginfragment, container, false); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); callbackManager.onActivityResult(requestCode, resultCode, data); } @Override public void onViewCreated(final View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); // Inflate the layout for this fragment LoginButton loginButton = (LoginButton) view.findViewById(R.id.login_button); loginButton.setReadPermissions("user_friends"); // If using in a fragment loginButton.setFragment(this); // Other app specific specialization // Callback registration loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() { @Override public void onSuccess(LoginResult loginResult) { // App code AccessToken at = loginResult.getAccessToken(); Toast.makeText(getActivity(),at.toString(),Toast.LENGTH_LONG).show(); Profile pf = Profile.getCurrentProfile(); TextView tx = (TextView) view.findViewById(R.id.loginfragtext); Log.d("Profile",pf.getName()); if(pf!=null) { tx.setText("Welcome" + pf.getName()); } } @Override public void onCancel() { // App code Toast.makeText(getActivity(),"Cancel",Toast.LENGTH_LONG).show(); } @Override public void onError(FacebookException exception) { // App code Toast.makeText(getActivity(),"Error",Toast.LENGTH_LONG).show(); } }); } }
true
2691dda1f017603bcb5153582b44b25faacfa543
Java
rgtodd/gc-sfms
/sfms/sfms.web/src/main/java/sfms/web/schemas/StarModelField.java
UTF-8
5,150
1.789063
2
[ "MIT" ]
permissive
package sfms.web.schemas; public class StarModelField { public static final String KEY = "KEY"; public static final String CATALOG_ID = "CATALOG_ID"; public static final String CLUSTER_KEY = "CLUSTER_KEY"; public static final String SECTOR_KEY = "SECTOR_KEY"; public static final String HIPPARCOS_ID = "HIPPARCOS_ID"; public static final String HENRY_DRAPER_ID = "HENRY_DRAPER_ID"; public static final String HARVARD_REVISED_ID = "HARVARD_REVISED_ID"; public static final String GLIESE_ID = "GLIESE_ID"; public static final String BAYER_FLAMSTEED_ID = "BAYER_FLAMSTEED_ID"; public static final String PROPER_NAME = "PROPER_NAME"; public static final String RIGHT_ASCENSION = "RIGHT_ASCENSION"; public static final String DECLINATION = "DECLINATION"; public static final String DISTANCE = "DISTANCE"; public static final String PROPER_MOTION_RIGHT_ASCENSION = "PROPER_MOTION_RIGHT_ASCENSION"; public static final String PROPER_MOTION_DECLINATION = "PROPER_MOTION_DECLINATION"; public static final String RADIAL_VELOCITY = "RADIAL_VELOCITY"; public static final String MAGNITUDE = "MAGNITUDE"; public static final String ABSOLUTE_MAGNITUDE = "ABSOLUTE_MAGNITUDE"; public static final String SPECTRUM = "SPECTRUM"; public static final String COLOR_INDEX = "COLOR_INDEX"; public static final String X = "X"; public static final String Y = "Y"; public static final String Z = "Z"; public static final String VX = "VX"; public static final String VY = "VY"; public static final String VZ = "VZ"; public static final String RIGHT_ASCENSION_RADIANS = "RIGHT_ASCENSION_RADIANS"; public static final String DECLINATION_RADIANS = "DECLINATION_RADIANS"; public static final String PROPER_MOTION_RIGHT_ASCENSION_RADIANS = "PROPER_MOTION_RIGHT_ASCENSION_RADIANS"; public static final String PROPER_MOTION_DECLINATION_RADIANS = "PROPER_MOTION_DECLINATION_RADIANS"; public static final String BAYER_ID = "BAYER_ID"; public static final String FLAMSTEED = "FLAMSTEED"; public static final String CONSTALLATION = "CONSTALLATION"; public static final String COMPANION_STAR_ID = "COMPANION_STAR_ID"; public static final String PRIAMRY_STAR_ID = "PRIAMRY_STAR_ID"; public static final String MULTIPLE_STAR_ID = "MULTIPLE_STAR_ID"; public static final String LUMINOSITY = "LUMINOSITY"; public static final String VARIABLE_STAR_DESIGNATION = "VARIABLE_STAR_DESIGNATION"; public static final String VARIABLE_MINIMUM = "VARIABLE_MINIMUM"; public static final String VARIABLE_MAXIMUM = "VARIABLE_MAXIMUM"; public static final String XYZ = "XYZ"; public String getKey() { return KEY; } public String getCatalogId() { return CATALOG_ID; } public String getClusterKey() { return CLUSTER_KEY; } public String getSectorKey() { return SECTOR_KEY; } public String getHipparcosId() { return HIPPARCOS_ID; } public String getHenryDraperId() { return HENRY_DRAPER_ID; } public String getHarvardRevisedId() { return HARVARD_REVISED_ID; } public String getGlieseId() { return GLIESE_ID; } public String getBayerFlamsteedId() { return BAYER_FLAMSTEED_ID; } public String getProperName() { return PROPER_NAME; } public String getRightAscension() { return RIGHT_ASCENSION; } public String getDeclination() { return DECLINATION; } public String getDistance() { return DISTANCE; } public String getProperMotionRightAscension() { return PROPER_MOTION_RIGHT_ASCENSION; } public String getProperMotionDeclination() { return PROPER_MOTION_DECLINATION; } public String getRadialVelocity() { return RADIAL_VELOCITY; } public String getMagnitude() { return MAGNITUDE; } public String getAbsoluteMagnitude() { return ABSOLUTE_MAGNITUDE; } public String getSpectrum() { return SPECTRUM; } public String getColorIndex() { return COLOR_INDEX; } public String getX() { return X; } public String getY() { return Y; } public String getZ() { return Z; } public String getVX() { return VX; } public String getVY() { return VY; } public String getVZ() { return VZ; } public String getRightAcensionRadians() { return RIGHT_ASCENSION_RADIANS; } public String getDeclinationRadians() { return DECLINATION_RADIANS; } public String getProperMotionRightAscensionRadians() { return PROPER_MOTION_RIGHT_ASCENSION_RADIANS; } public String getProperMotionDeclinationRadians() { return PROPER_MOTION_DECLINATION_RADIANS; } public String getBayerId() { return BAYER_ID; } public String getFlamsteed() { return FLAMSTEED; } public String getConstellation() { return CONSTALLATION; } public String getCompanionStarId() { return COMPANION_STAR_ID; } public String getPrimaryStarId() { return PRIAMRY_STAR_ID; } public String getMultipleStarId() { return MULTIPLE_STAR_ID; } public String getLuminosity() { return LUMINOSITY; } public String getVariableStarDesignation() { return VARIABLE_STAR_DESIGNATION; } public String getVariableMinimum() { return VARIABLE_MINIMUM; } public String getVariableMaximum() { return VARIABLE_MAXIMUM; } public String getXYZ() { return XYZ; } }
true
79c58c3c9743aaeaca6d3b74d6f6a9514564c072
Java
mcparkk/Javastudy
/Test/src/ch05/cutstick.java
UTF-8
558
3.625
4
[]
no_license
package ch05; public class cutstick { public static void main(String[] args) { int[] stick = { 1, 2, 3, 4, 3, 3, 2, 1}; while (true) { int count = 0; int min = 0; for (int i : stick) { if (i > 0) { count++; min = i; } } if(count == 0) break; ​ System.out.println(count); for (int i : stick) { if (min > i && i > 0) min = i; } ​ for (int i = 0; i < stick.length; i++) { stick[i] -= min; } } } }
true
d098608989c4da3560a6cfaa7ba85ff15cc9b9a8
Java
scajas/servicioSeguridad
/ejbModule/ec/edu/epn/convenios/beans/ConvenioDAOImplement.java
UTF-8
7,615
2.34375
2
[]
no_license
package ec.edu.epn.convenios.beans; import java.util.Date; import java.util.List; import javax.ejb.LocalBean; import javax.ejb.Stateless; import javax.persistence.Query; import ec.edu.epn.convenios.entities.Convenio; import ec.edu.epn.generic.DAO.DaoGenericoImplement; /** * Session Bean implementation class ConvenioDAOImplement */ @Stateless @LocalBean public class ConvenioDAOImplement extends DaoGenericoImplement<Convenio> implements ConvenioDAO { @Override public List<Convenio> consultaconvenioFechas1(Date fechaDesde, Date fechaHasta) { try { String codConv = "%"; System.out.println("Entraaaaaaaaa la consulta de la busquedaaaaaaaaaa"); StringBuilder queryString = new StringBuilder("select conv from Convenio conv where conv.idConv like ?0 "); if (fechaDesde != null & fechaHasta != null) { queryString.append(" and conv.finTentativo BETWEEN ?1 AND ?2 "); } queryString.append("ORDER BY conv.idConv "); Query query = getEntityManager().createQuery(queryString.toString()); query.setParameter(0, "%" + codConv + "%"); if (fechaDesde != null & fechaHasta != null) { query.setParameter(1, fechaDesde); query.setParameter(2, fechaHasta); } System.out.println("Saleeeee de la consulta de la busquedaaaaaaaaaa"); return query.getResultList(); } catch (Exception e) { e.printStackTrace(); return null; } } @Override public List<Convenio> consultaconvenioAntesde(Date fecha) { try { String codConv = "%"; StringBuilder queryString = new StringBuilder("select conv from Convenio conv where conv.idConv like ?0 "); if (fecha != null ) { queryString.append(" and conv.fechaFirma > ?1 "); } queryString.append("ORDER BY conv.idConv "); Query query = getEntityManager().createQuery(queryString.toString()); query.setParameter(0, "%" + codConv + "%"); if (fecha != null ) { query.setParameter(1, fecha); } return query.getResultList(); } catch (Exception e) { e.printStackTrace(); return null; } } @SuppressWarnings("unchecked") @Override public List<Convenio> consultaconvenioFechas(Date fechaDesde, Date fechaHasta, int idorg) { String codConv = "%"; System.out.println("Entraaaaaaaaa la consulta de la busquedaaaaaaaaaa"); StringBuilder queryString = new StringBuilder( "select conv from Convenio conv, ConvOrganizacion org where conv.idConv like ?0 and org.convenio.idConv = conv.idConv "); if (fechaDesde == null & fechaHasta == null) { // System.out.println("RETORNA NULL"); return null; } if (fechaDesde != null & fechaHasta != null) { queryString.append(" and conv.finTentativo BETWEEN ?1 AND ?2 "); } if (idorg != 0) { queryString.append(" and org.organizacion.idOrganizacion = ?3 "); } queryString.append("ORDER BY conv.idConv "); Query query = getEntityManager().createQuery(queryString.toString()); query.setParameter(0, "%" + codConv + "%"); if (fechaDesde != null & fechaHasta != null) { query.setParameter(1, fechaDesde); query.setParameter(2, fechaHasta); } if (idorg != 0) { query.setParameter(3, idorg); } System.out.println("Saleeeee de la consulta de la busquedaaaaaaaaaa"); return query.getResultList(); } @SuppressWarnings("unchecked") @Override public List<Convenio> consultaconveniobyparams(String codigo, String titulo, String Objeto, int idAplicacion, int idAutoridad, String estado, String vigencia, int idDepartamento, String localidad, int idtipo, Date fechaDesde, Date fechaHasta, int idorganizacion, String tesis, String pasantias, String investigacion, String sprofesionales, String varios, String tipo) { System.out.println("Desde" + fechaDesde); System.out.println("Hasta" + fechaHasta); String observaciones = "%"; System.out.println("Entraaaaaaaaa la consulta de la busquedaaaaaaaaaa"); StringBuilder queryString = new StringBuilder( "select DISTINCT conv from Convenio conv, ConvOrganizacion org, Organizacion ga where conv.observaciones like ?0 and org.convenio.idConv = conv.idConv and ga.idOrganizacion = org.organizacion.idOrganizacion "); if (codigo != null) { queryString.append(" and conv.idConv like ?1 "); } if (titulo != null) { queryString.append(" and conv.tituloC like ?2 "); } if (Objeto != null) { queryString.append(" and conv.objetivoC like ?3 "); } if (idAutoridad != 0) { queryString.append(" and conv.autoridad.idAutoridad = ?5 "); } if (estado != null) { queryString.append(" and conv.estado like ?6 "); } if (vigencia != null) { queryString.append(" and conv.vigenciaEstados = ?7 "); } if (idDepartamento != 0) { queryString.append(" and conv.unidad.idUnidad = ?8 "); } if (localidad != null) { queryString.append(" and conv.geograficoC = ?9 "); } if (idtipo != 0) { queryString.append(" and conv.tipoC.idTipoc = ?10 "); } if (fechaDesde != null & fechaHasta != null) { queryString.append(" and conv.fechaFirma BETWEEN ?11 AND ?12 "); } if (idorganizacion != 0) { queryString.append(" and org.organizacion.idOrganizacion = ?13 "); } if (tesis != null) { queryString.append(" and conv.tesis like ?14 "); } if (pasantias != null) { queryString.append(" and conv.pasantias like ?15 "); } if (investigacion != null) { queryString.append(" and conv.investigacion like ?16 "); } if (sprofesionales != null) { queryString.append(" and conv.sprofesionales like ?17 "); } if (varios != null) { queryString.append(" and conv.varios like ?18 "); } if (tipo != null) { queryString.append(" and org.organizacion.tipo like ?19 "); } queryString.append("ORDER BY conv.idConv "); Query query = getEntityManager().createQuery(queryString.toString()); query.setParameter(0, "%" + observaciones + "%"); if (codigo != null) { query.setParameter(1, "%" + codigo + "%"); } if (titulo != null) { query.setParameter(2, "%" + titulo + "%"); } if (Objeto != null) { query.setParameter(3, "%" + Objeto + "%"); } if (idAutoridad != 0) { query.setParameter(5, idAutoridad); } if (estado != null) { query.setParameter(6, "%" + estado.trim() + "%"); } if (vigencia != null) { query.setParameter(7, vigencia); } if (idDepartamento != 0) { query.setParameter(8, idDepartamento); } if (localidad != null) { query.setParameter(9, localidad); } if (idtipo != 0) { query.setParameter(10, idtipo); } if (fechaDesde != null & fechaHasta != null) { query.setParameter(11, fechaDesde); query.setParameter(12, fechaHasta); } if (idorganizacion != 0) { query.setParameter(13, idorganizacion); } if (tesis != null) { query.setParameter(14, "%" + tesis + "%"); } if (pasantias != null) { query.setParameter(15, "%" + pasantias + "%"); } if (investigacion != null) { query.setParameter(16, "%" + investigacion + "%"); } if (sprofesionales != null) { query.setParameter(17, "%" + sprofesionales + "%"); } if (varios != null) { query.setParameter(18, "%" + varios + "%"); } if (tipo != null) { query.setParameter(19, "%" + tipo + "%"); } System.out.println("Saleeeee de la consulta de la busquedaaaaaaaaaa"); return query.getResultList(); } }
true
b8408a55315d9b407441f89930796dfa6c878329
Java
Sickly101/SpotMeServer
/src/main/java/com/entrox/spotmeserverrestful/model/AccessManager.java
UTF-8
6,856
2.34375
2
[]
no_license
package com.entrox.spotmeserverrestful.model; import com.entrox.spotmeserverrestful.dao.Access; import com.entrox.spotmeserverrestful.dao.Database; import com.entrox.spotmeserverrestful.dto.Grade; import com.entrox.spotmeserverrestful.dto.Route; import com.entrox.spotmeserverrestful.dto.Scale; import com.entrox.spotmeserverrestful.dto.Spot; import com.entrox.spotmeserverrestful.dto.User; import java.sql.Connection; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; public class AccessManager { public ArrayList<User> getUsers() throws Exception { ArrayList<User> userList = new ArrayList<User>(); Database db = new Database(); Connection con = db.getConnection(); Access access = new Access(); userList = access.getUsers(con); return userList; } public ArrayList<Spot> getSpots() throws Exception { ArrayList<Spot> spotList = new ArrayList<Spot>(); Database db = new Database(); Connection con = db.getConnection(); Access access = new Access(); spotList = access.getSpots(con); return spotList; } public User getUserById(int id) throws Exception{ User userObj = new User(); Database db = new Database(); Connection con = db.getConnection(); Access access = new Access(); userObj = access.getUserById(con, id); return userObj; } public Spot getSpotById(int id) throws Exception{ Spot spotObj = new Spot(); Database db = new Database(); Connection con = db.getConnection(); Access access = new Access(); spotObj = access.getSpotById(con, id); return spotObj; } public User getUserLogin(String login) throws Exception{ User userObj = new User(); Database db = new Database(); Connection con = db.getConnection(); Access access = new Access(); userObj = access.getUserForLogin(con, login); return userObj; } public ArrayList<Grade> getGrade() throws Exception { ArrayList<Grade> gradeList = new ArrayList<Grade>(); Database db = new Database(); Connection con = db.getConnection(); Access access = new Access(); gradeList = access.getGrades(con); return gradeList; } public ArrayList<Scale> getScales() throws Exception { ArrayList<Scale> scaleList = new ArrayList<Scale>(); Database db = new Database(); Connection con = db.getConnection(); Access access = new Access(); scaleList = access.getScales(con); return scaleList; } public ArrayList<Route> getRoutes() throws Exception { ArrayList<Route> routeList = new ArrayList<Route>(); Database db = new Database(); Connection con = db.getConnection(); Access access = new Access(); routeList = access.getRoutes(con); return routeList; } public Route getRouteById(int id) throws Exception{ Route routeObj = new Route(); Database db = new Database(); Connection con = db.getConnection(); Access access = new Access(); routeObj = access.getRouteById(con, id); return routeObj; } //insert public void insertUser(User user) throws Exception { Database db = new Database(); Connection con = db.getConnection(); Access access = new Access(); access.insertUser(con, user); } public void insertTestUser() throws Exception { Database db = new Database(); Connection con = db.getConnection(); Access access = new Access(); access.insertTestUser(con); } public void insertBase64() throws Exception { Database db = new Database(); Connection con = db.getConnection(); Access access = new Access(); access.insertBase64(con); } public void insertScale(Scale scale) throws Exception { Database db = new Database(); Connection con = db.getConnection(); Access access = new Access(); access.insertScale(con, scale); } public String insertSpot(Spot spot){ String response = ""; Database db = new Database(); Connection con = null; try { con = db.getConnection(); } catch (Exception ex) { response = ex.getMessage(); } Access access = new Access(); response = access.insertSpot(con, spot); return response; } public String insertRoute(Route route){ String response = ""; Database db = new Database(); Connection con = null; try { con = db.getConnection(); } catch (Exception ex) { response = ex.getMessage(); } Access access = new Access(); response = access.insertRoute(con, route); return response; } public void insertGrade(Grade grade) throws Exception { Database db = new Database(); Connection con = db.getConnection(); Access access = new Access(); access.insertGrade(con, grade); } /* public void insertStaticGrades() throws Exception{ Database db = new Database(); Connection con = db.getConnection(); Access access = new Access(); access.insertStaticGrades(con); } */ //Delete public String deleteSpot(int id) throws Exception{ String result =""; Database db = new Database(); Connection con = db.getConnection(); Access access = new Access(); result = access.deleteSpot(con, id); return result; } public String deleteRoute(int id) throws Exception{ String result =""; Database db = new Database(); Connection con = db.getConnection(); Access access = new Access(); result = access.deleteRoute(con, id); return result; } //sync public ArrayList<Spot> syncSpots(long lastmodified) throws Exception{ ArrayList<Spot> spotList = new ArrayList<Spot>(); Database db = new Database(); Connection con = db.getConnection(); Access access = new Access(); spotList = access.syncSpots(con, lastmodified); return spotList; } public ArrayList<Route> syncRoutes(long lastmodified) throws Exception{ ArrayList<Route> routeList = new ArrayList<Route>(); Database db = new Database(); Connection con = db.getConnection(); Access access = new Access(); routeList = access.syncRoutes(con, lastmodified); return routeList; } }
true
7e94e1934d27aac132aca6eb9a8f6d08b57d6716
Java
youzizzz/MyBlog
/MyBlog/src/main/java/com/youzi/MyBlog/shiro/CredentialsMatcher.java
UTF-8
2,253
2.296875
2
[]
no_license
package com.youzi.MyBlog.shiro; import java.util.Date; import java.util.UUID; import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.AuthenticationInfo; import org.apache.shiro.authc.AuthenticationToken; import org.apache.shiro.authc.ExcessiveAttemptsException; import org.apache.shiro.authc.UsernamePasswordToken; import org.apache.shiro.authc.credential.SimpleCredentialsMatcher; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import com.youzi.MyBlog.entity.LoginLog; import com.youzi.MyBlog.entity.User; import com.youzi.MyBlog.service.LoginLogService; import com.youzi.MyBlog.util.JedisUtils; @Configuration public class CredentialsMatcher extends SimpleCredentialsMatcher { @Autowired private LoginLogService loginLogService; @Override public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) { String username = (String) token.getPrincipal(); String count=JedisUtils.get(username); int counts=0; if(null==count||"".equals(count)) { JedisUtils.set(username,"0",1000*1000); }else { counts=Integer.parseInt(count); } UsernamePasswordToken utoken = (UsernamePasswordToken) token; // 获得用户输入的密码:(可以采用加盐(salt)的方式去检验) String inPassword = new String(utoken.getPassword()); // inPassword = MD5Encoder.encode(inPassword.getBytes()); // 获得数据库中的密码 String dbPassword = (String) info.getCredentials(); Boolean bool=super.doCredentialsMatch(utoken, info); if(counts>=5) { throw new ExcessiveAttemptsException(); } if(bool) { JedisUtils.del(username); //记录登录次数 LoginLog log=new LoginLog(); log.setId(UUID.randomUUID().toString()); log.setLoginDate(new Date()); log.setUserId(JedisUtils.get("loginUserId")); log.setUserName(username); loginLogService.addLog(log); }else { counts++; JedisUtils.set(username, counts+"",1000*1000); } JedisUtils.del("loginUserId"); // 进行密码的比对 return bool; } public CredentialsMatcher() { super(); // TODO Auto-generated constructor stub } }
true
855fca334760b97d57299eda5b31bb54a33b8d43
Java
georgeerol/CloneReddit
/src/main/java/com/georgeerol/CloneReddit/repository/PostRepository.java
UTF-8
546
1.929688
2
[]
no_license
package com.georgeerol.CloneReddit.repository; import com.georgeerol.CloneReddit.model.Post; import com.georgeerol.CloneReddit.model.Subreddit; import com.georgeerol.CloneReddit.model.User; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import java.util.List; /** * Created by George Fouche on 8/25/20. */ @Repository public interface PostRepository extends JpaRepository<Post, Long> { List<Post> findAllBySubreddit(Subreddit subreddit); List<Post> findByUser(User user); }
true
ba02a46974aad3508dc63ad1194744ce88a9e59f
Java
michi949/EvChargingServer
/src/main/java/at/fhooe/mc/server/Repository/LoadingStationRepository.java
UTF-8
432
2.109375
2
[]
no_license
package at.fhooe.mc.server.Repository; import at.fhooe.mc.server.Data.Car; import at.fhooe.mc.server.Data.LoadingStation; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; /** * Car connection to Database. * Possibility to add own methodes for the database. */ @Repository public interface LoadingStationRepository extends CrudRepository<LoadingStation, Integer> { }
true
d1887abd2d957a8f06037f321ddd824ed52371c1
Java
CalypsoCubesat/SPELL-GUI-4.0.2-SRC
/com.astra.ses.spell.gui/src/com/astra/ses/spell/gui/views/controls/master/executors/IExecutorsTable.java
UTF-8
1,025
2.03125
2
[]
no_license
package com.astra.ses.spell.gui.views.controls.master.executors; public interface IExecutorsTable { /*************************************************************************** * Apply the defined fonts to the control **************************************************************************/ public void applyFonts(); /*************************************************************************** * Refresh the table item for the given procedure id **************************************************************************/ public void refreshItem(String procId); /*************************************************************************** * Refresh all table items **************************************************************************/ public void refreshAll(); /*************************************************************************** * Get the selected procedure **************************************************************************/ public String[] getSelectedProcedures(); }
true
428321be3408078a0093c38566008f6c90f6c31d
Java
AyaYasser/task
/src/main/java/com/bankmisr/tennis/repository/repo/ParticipantRepo.java
UTF-8
719
2.046875
2
[]
no_license
package com.bankmisr.tennis.repository.repo; import com.bankmisr.tennis.repository.model.MatchEntity; import com.bankmisr.tennis.repository.model.ParticipantEntity; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; import org.springframework.data.repository.query.QueryByExampleExecutor; import org.springframework.stereotype.Repository; /** * @author Aya Yasser */ @Repository public interface ParticipantRepo extends CrudRepository<ParticipantEntity, Integer>, QueryByExampleExecutor<ParticipantEntity> { @Query(value="select count(*) from participants where date = ?1 ",nativeQuery = true) int getNoParticipantsPerDay(String date); }
true
cc040d4eb1294354fe5b5f9222d8c6b8fe03724f
Java
jasonbakker084/SpringBootCoffeeFW
/src/main/java/com/teamcoffee/coffeeflavourwheel/repository/TastedCoffeeRepository.java
UTF-8
325
1.796875
2
[]
no_license
package com.teamcoffee.coffeeflavourwheel.repository; import com.teamcoffee.coffeeflavourwheel.model.TastedCoffee; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.repository.CrudRepository; public interface TastedCoffeeRepository extends CrudRepository<TastedCoffee, Long> { }
true
1d374ae79c042484bf8e822403f582d28fce77ad
Java
17ec084/grade3-1
/groupStudy/superCommon/src/superCommon/throwables/FlexibleMSGRuntimeException.java
UTF-8
897
2.765625
3
[]
no_license
package superCommon.throwables; public class FlexibleMSGRuntimeException extends RuntimeException { public FlexibleMSGRuntimeException(Object...objects) { super(prints(objects)); //Super prints objects. //スーパーコンストラクタが可変長引数を出力する } static String prints(Object...objects) { return FlexibleMSGRuntimeException.prints(objects); } //スーパーコンストラクタたち public FlexibleMSGRuntimeException() {} public FlexibleMSGRuntimeException(String message) {super(message);} public FlexibleMSGRuntimeException(Throwable cause) {super(cause);} public FlexibleMSGRuntimeException(String message, Throwable cause) {super(message, cause);} public FlexibleMSGRuntimeException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {super(message, cause, enableSuppression, writableStackTrace);} }
true
69610a7d9b61afe638625a3d4c1219cef3e966a9
Java
TimmyCDevelopment/Plugin_Template
/src/me/timmyc/template/commands/ExampleCommand.java
UTF-8
850
2.703125
3
[]
no_license
package me.timmyc.template.commands; import me.timmyc.template.MainClass; import me.timmyc.template.utilities.Utilities; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; public class ExampleCommand implements CommandExecutor { //Classes private MainClass plugin; //Instance of the main class public ExampleCommand(MainClass mainClass) {this.plugin = mainClass;} //Initializing the main class private Utilities utilities; //Instance of the Utilities class public ExampleCommand(Utilities utilities) {this.utilities = utilities;} //Initializing the Utilities class @Override public boolean onCommand(CommandSender sender, Command command, String s, String[] args) { //Command code goes here with return statement return true; } }
true
81c1491797e6942e343632fadd57a5f293b3f91e
Java
CSCfi/shibboleth-idp-oidc-extension
/idp-oidc-extension-impl/src/main/java/org/geant/idpextension/oidc/profile/impl/OIDCMetadataLookupHandler.java
UTF-8
5,414
1.765625
2
[ "Apache-2.0" ]
permissive
/* * Copyright (c) 2017 - 2020, GÉANT * * 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.geant.idpextension.oidc.profile.impl; import javax.annotation.Nonnull; import net.shibboleth.utilities.java.support.annotation.constraint.NonnullAfterInit; import net.shibboleth.utilities.java.support.component.ComponentInitializationException; import net.shibboleth.utilities.java.support.component.ComponentSupport; import net.shibboleth.utilities.java.support.logic.Constraint; import net.shibboleth.utilities.java.support.resolver.CriteriaSet; import net.shibboleth.utilities.java.support.resolver.ResolverException; import org.opensaml.messaging.context.MessageContext; import org.opensaml.messaging.handler.AbstractMessageHandler; import org.opensaml.messaging.handler.MessageHandlerException; import org.geant.idpextension.oidc.criterion.ClientIDCriterion; import org.geant.idpextension.oidc.messaging.context.OIDCMetadataContext; import org.geant.idpextension.oidc.metadata.resolver.ClientInformationResolver; import org.geant.idpextension.oidc.profile.context.navigate.DefaultClientIDLookupFunction; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Function; import com.nimbusds.oauth2.sdk.id.ClientID; import com.nimbusds.openid.connect.sdk.rp.OIDCClientInformation; /** * Handler for inbound OIDC protocol messages that attempts to locate OIDC metadata for a rp, and attaches it with a * {@link OIDCMetadataContext} as a child of a pre-existing instance of {@link MessagesContext}. */ @SuppressWarnings("rawtypes") public class OIDCMetadataLookupHandler extends AbstractMessageHandler { /** Logger. */ @Nonnull private final Logger log = LoggerFactory.getLogger(OIDCMetadataLookupHandler.class); /** Resolver used to look up OIDC client information. */ @NonnullAfterInit private ClientInformationResolver clientResolver; /** Strategy used to obtain the client id value for authorize/token request. */ @Nonnull private Function<MessageContext, ClientID> clientIDLookupStrategy; /** * Constructor. */ public OIDCMetadataLookupHandler() { clientIDLookupStrategy = new DefaultClientIDLookupFunction(); } /** * Set the strategy used to locate the client id of the request. * * @param strategy lookup strategy */ public void setClientIDLookupStrategy(@Nonnull final Function<MessageContext, ClientID> strategy) { ComponentSupport.ifInitializedThrowUnmodifiabledComponentException(this); clientIDLookupStrategy = Constraint.isNotNull(strategy, "ClientIDLookupStrategy lookup strategy cannot be null"); } /** * Set the {@link ClientInformationResolver} to use. * * @param resolver The resolver to use. */ public void setClientInformationResolver(@Nonnull final ClientInformationResolver resolver) { ComponentSupport.ifInitializedThrowUnmodifiabledComponentException(this); clientResolver = Constraint.isNotNull(resolver, "ClientInformationResolver cannot be null"); } /** {@inheritDoc} */ @Override protected void doInitialize() throws ComponentInitializationException { super.doInitialize(); if (clientResolver == null) { throw new ComponentInitializationException("ClientInformationResolver cannot be null"); } } /** {@inheritDoc} */ @Override protected void doInvoke(@Nonnull final MessageContext messageContext) throws MessageHandlerException { ComponentSupport.ifNotInitializedThrowUninitializedComponentException(this); // Resolve client id from inbound message final ClientID clientId = clientIDLookupStrategy.apply(messageContext); // Resolve metadata for client id final ClientIDCriterion clientCriterion = new ClientIDCriterion(clientId); final CriteriaSet criteria = new CriteriaSet(clientCriterion); try { final OIDCClientInformation clientInformation = clientResolver.resolveSingle(criteria); if (clientInformation == null) { log.warn("{} No client information returned for {}", getLogPrefix(), clientId); return; } final OIDCMetadataContext oidcCtx = new OIDCMetadataContext(); oidcCtx.setClientInformation(clientInformation); messageContext.addSubcontext(oidcCtx); // Based on that info we know 1) client is valid 2) we know valid // redirect uris log.debug("{} {} added to MessageContext as child of {}", getLogPrefix(), OIDCMetadataContext.class.getName(), messageContext.getClass().getName()); } catch (ResolverException e) { log.error("{} ResolverException thrown during client information lookup", getLogPrefix(), e); } } }
true
9ae7e3237f6e88eada51f08c50f9008b20e21c28
Java
simong/nakamura
/sandbox/opensso/src/main/java/org/sakaiproject/nakamura/opensso/OpenSsoHandler.java
UTF-8
3,658
2.09375
2
[ "Apache-2.0" ]
permissive
/** * Licensed to the Sakai Foundation (SF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The SF 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.sakaiproject.nakamura.opensso; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.methods.GetMethod; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.net.URLEncoder; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * A Handler class that encapsulates both extracting the userID from the request, and * formulating a redirect url to the central service. * * * The protocol is documented here * http://developers.sun.com/identity/reference/techart/troubleshooting2.html * */ public class OpenSsoHandler { private static final Logger LOGGER = LoggerFactory.getLogger(OpenSsoHandler.class); private HttpServletRequest request; private HttpServletResponse response; /** * @param request * @param response */ public OpenSsoHandler(HttpServletRequest request, HttpServletResponse response) { this.request = request; this.response = response; } /** * @throws IOException * */ public void sendAuthenticationFailed(String ssoServerUrl, String destination) throws IOException { StringBuffer location = request.getRequestURL(); location.append("?sakaiauth:login=2"); if (destination != null && destination.trim().length() > 0) { location.append("&d=").append(URLEncoder.encode(destination, "UTF-8")); } String returnUrl = URLEncoder.encode(location.toString(), "UTF-8"); response.sendRedirect(ssoServerUrl + returnUrl); } /** * @return */ public String getUserName() { String tokenId = null; Cookie[] cookies = request.getCookies(); for (Cookie cookie : cookies) { if ("iPlanetDirectoryPro".equals(cookie.getName())) { tokenId = cookie.getValue(); break; } } if (tokenId != null) { try { GetMethod get = new GetMethod("http://login.nyu.edu/sso/identity/isTokenValid?tokenid=" + tokenId); HttpClient httpClient = new HttpClient(); int returnCode = httpClient.executeMethod(get); String body = get.getResponseBodyAsString(); if (returnCode < 200 || returnCode >= 300) { return null; } else if ("boolean=true\n".equals(body)) { get = new GetMethod("http://login.nyu.edu/sso/identity/attributes?attributes_names=uid&subjectid=" + tokenId); returnCode = httpClient.executeMethod(get); body = get.getResponseBodyAsString(); if (returnCode < 200 || returnCode >= 300) { return null; } else { return body; } } else { return null; } } catch (IOException e) { LOGGER.error(e.getMessage(), e); return null; } } else { return null; } } }
true
09c6112a9b30418af5f08df89ab9c945e7cda34b
Java
ClawHub/venom
/venom-core/src/main/java/tk/clawhub/downloader/Idownloader.java
UTF-8
589
2.359375
2
[]
no_license
package tk.clawhub.downloader; import tk.clawhub.model.Page; import tk.clawhub.model.Request; import tk.clawhub.model.Task; /** * <Description>Idownloader <br> * * @author LiZhiming<br> * @version 1.0<br> * @taskId <br> * @date 2018 -07-24 <br> */ public interface Idownloader { /** * Download page. * * @param request the request * @param task the task * @return the page */ Page download(Request request, Task task); /** * Sets thread. * * @param threadNum the thread num */ void setThread(int threadNum); }
true
3065903c34e8e7484083fcd64d1e4af1f8193b7c
Java
vserdun/java_enterprise
/vadim.martsun/task_5/src/main/java/com/hillel/servlets/BankServlet.java
UTF-8
4,961
2.546875
3
[]
no_license
package com.hillel.servlets; import com.google.gson.Gson; import com.hillel.mapper.Mapper; import com.hillel.mapper.MapperImpl; import com.hillel.model.BankAcc; import com.hillel.model.Database; import com.hillel.model.Status; import com.hillel.model.requests.BankAccRequest; import lombok.extern.slf4j.Slf4j; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @Slf4j @WebServlet(name = "BankServlet", urlPatterns = {"/bank"}) public class BankServlet extends HttpServlet { private long accountId = 0; private Gson gson = new Gson(); private Mapper mapper = new MapperImpl(); private final String ACCOUNT_ID = "bankAccountId"; private Database database = Database.getInstance(); @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { String getParameter = request.getParameter(ACCOUNT_ID); Status status; if(getParameter == null){ status = new Status(true, "Found " + database.getAccounts().size() + " accounts"); response.getWriter().println(gson.toJson(database.getAccounts())); }else{ BankAcc extractedAccount = database.getAccounts().get(Long.parseLong(getParameter)); if(extractedAccount == null){ status = new Status(false,"There is no account with such id"); response.setStatus(404); }else { status = new Status(true, "The required account has been found"); response.setStatus(200); response.getWriter().println(gson.toJson(extractedAccount)); } } response.getWriter().println(gson.toJson(status)); } @Override protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws IOException{ response.setContentType("application/json"); Status status; String getParameter = request.getParameter(ACCOUNT_ID); if (getParameter != null) { BankAcc removedAccount = database.getAccounts().remove(Long.parseLong(getParameter)); if (removedAccount == null) { status = new Status(true, "There is no account with such id"); response.setStatus(404); } else { status = new Status(true, "The account has been deleted"); response.setStatus(200); } } else { status = new Status(false, ACCOUNT_ID + " parameter required"); response.setStatus(400); } response.getWriter().println(gson.toJson(status)); } @Override protected void doPut(HttpServletRequest request, HttpServletResponse response) throws IOException { response.setContentType("application/json"); Status status; String getParameter = request.getParameter(ACCOUNT_ID); if(getParameter == null){ status = new Status(false, "Failed"); response.setStatus(400); }else{ BankAccRequest bankAccRequest = gson.fromJson(request.getReader(), BankAccRequest.class); long accId = Long.parseLong(getParameter); BankAcc account = database.getAccounts().get(accId); if(account == null){ status = new Status(false, "Account has not been found"); response.setStatus(404); }else { BankAcc updatedAccount = mapper.mapBankAccount(bankAccRequest); if(updatedAccount.getUser() == null){ status = new Status(false, "Bad request"); response.setStatus(400); }else { database.getAccounts().put(accId, updatedAccount); status = new Status(true, "Account has been successfully updated"); response.setStatus(200); } } } response.getWriter().println(gson.toJson(status)); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { response.setContentType("application/json"); BankAccRequest bankAccRequest = gson.fromJson(request.getReader(), BankAccRequest.class); BankAcc bankAccount = mapper.mapBankAccount(bankAccRequest); Status status; if(bankAccount.getUser() != null){ database.getAccounts().put(accountId, bankAccount); accountId++; status = new Status(true, "A bank account has been added"); response.setStatus(200); }else { status = new Status(false, "No user with the specified id"); response.setStatus(404); } response.getWriter().println(gson.toJson(status)); } }
true
52b8bff67c569a597e077403477f23466c34c3ea
Java
qindaorong/aggregate-payment-channel
/server-demo/src/main/java/com/aggregate/framework/callback/YijiCallBackController.java
UTF-8
1,452
2.25
2
[]
no_license
package com.aggregate.framework.callback; import com.aggregate.framework.service.callback.YijiCallBackService; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @RestController @Slf4j public class YijiCallBackController { @Autowired private YijiCallBackService yijiCallBackService; /** * 验卡异步回调通知 * @param request * @param response */ @RequestMapping("/verifyBankCardCallBackNotify") public void verifyBankCardCallBackNotify(final HttpServletRequest request, HttpServletResponse response) { log.info("[YijiCallBackController].[verifyBankCardCallBackNotify] notify start"); try { Boolean flag = yijiCallBackService.verifyBankCardCallBack(request); if (flag) { log.info("[YijiCallBackController].[verifyBankCardCallBackNotify] notify success"); response.getWriter().write("SUCCESS"); } else { log.info("[YijiCallBackController].[verifyBankCardCallBackNotify] notify fail"); response.getWriter().write("FAIL"); } } catch (IOException e) { e.printStackTrace(); } } }
true
21fb8a4186c25d6d21f7ae9d3103de720a95dae1
Java
malonewilliam2019/Escape-d
/Main.java
UTF-8
10,700
3.4375
3
[]
no_license
import java.util.Scanner; public class Main { public static Scanner scan; public static int movesLeft = 30; public static String output = "You find yourself in a large foyer. There is a door to the north. To the west is a bench against the wall. To the east is a chest on the floor. In the center of the room is a large candle. The candle is unlit."; public static boolean inFoyer = true; public static boolean inLibrary = false; public static boolean inConservatory = false; //foyer conditions public static boolean chestOpen = false; public static boolean hasMatches = false; public static boolean candleLit = false; public static boolean door1Locked = true; public static boolean door1Open = false; //library conditions public static boolean getPen = false; public static boolean getBook = false; public static boolean writeBook = false; public static boolean door2Locked = true; public static boolean door2Open = false; //conservatory conditions public static boolean playTrumpet = false; public static boolean playPiano = false; public static boolean playDrum = false; public static void main(String[] args) { System.out.printf("Welcome to The House. You have 30 moves to escape. There is a set of verbs and nouns that will allow you to leave in the format of verb (open, close, light, read, write, play, look, get, go), noun (door, room, bench, chest, candle, note, matches, bookshelf, book, pen, scroll, music, trumpet, piano, drum, lock) or direction (north, south, east, west). If your move yields no advancement, the previous command will likely repeat itself. Good luck.\n\n"); for (int i = 1; i < 31; i++) { gameUsage(); movesLeft--; if (playTrumpet && playPiano && playDrum) { break; } } if (playTrumpet && playPiano && playDrum) { System.out.printf("\nCongratulations! You have completed the escape room challenge successfully in with %d moves to spare.\n", movesLeft); } else { System.out.printf("\nYou have failed the escape room challenge. Try again."); } } public static void gameUsage() { if (inFoyer) { foyer(); } else if (inLibrary) { library(); } else if (inConservatory) { conservatory(); } } public static void foyer() { System.out.printf("%s You have %d moves left.\n>>", output, movesLeft); scan = new Scanner(System.in); String test = scan.nextLine(); switch (test) { case "look bench": output = "There is a note on the bench."; break; case "read note": output = "The note says, 'May my light show you the way.'"; break; case "look chest": if (chestOpen) { output = "There are matches in the chest."; } else { output = "the chest is closed."; } break; case "open chest": chestOpen = true; output = "The chest is now open. There is just a box of matches."; break; case "get matches": if (chestOpen) { hasMatches = true; output = "You have a box of matches."; } else { output = "How can you see what is inside the chest? It's closed."; } break; case "look candle": if (candleLit) { output = "The candle is burning, providing some light."; } else { output = "The candle is unlit"; } break; case "light candle": if (hasMatches) { candleLit = true; door1Locked = false; output = "The candle is lit. You heard a metal grinding sound from the north."; } else { output = "You don't have any matches."; } break; case "look door": if (!door1Locked) { if (door1Open) { output = "The door is unlocked and open."; } else { output = "The door is unlocked, but closed."; } } else { output = "The door is locked."; } break; case "open door": if (!door1Locked) { door1Open = true; output = "The north door is open."; } else { output = "The door is locked."; } break; case "go north": if (door1Open) { inFoyer = false; inLibrary = true; output = "You have left the foyer. On your way out, the door slammed and locked. You are now in the library and cannot return to the foyer. In the library there are stacks of books lining the shelves, a desk, a pen, and a scroll. There is another locked door to the north."; } else { output = "The door is closed."; } break; default : output = "You space out for a while pondering how to get out"; break; } } public static void library() { System.out.printf("%s You have %d moves left.\n>>", output, movesLeft); scan = new Scanner(System.in); String test = scan.nextLine(); switch (test) { case "look book": output = "The book is titled 'The Autobiography of ...' with the rest of the title empty."; break; case "look shelves": case "look shelf": output = "There is a grand book that sticks out from the others."; break; case "get pen": getPen = true; output = "You have acquired the pen."; break; case "read scroll": case "look scroll": output = "the scroll says, 'Share your story.'"; break; case "get book": if (getBook) { output = "You already have the book. Get busy writing."; } else { output = "You now have the blank book. Time to get creative."; getBook = true; } break; case "write book": case "write name": if (getPen && getBook) { writeBook = true; door2Locked = false; output = "You have completed the autobiography You heard a metal grinding sound from the north."; } else { output = "Get everything you need to write."; } break; case "look door": if (!door2Locked) { if (door2Open) { output = "The door is unlocked and open."; } else { output = "The door is unlocked, but closed."; } } else { output = "The door is locked."; } break; case "open door": if (!door2Locked) { door2Open = true; output = "The north door is open."; } break; case "go north": if (door2Open) { inLibrary = false; inConservatory = true; output = " You have left the library. On your way out, the door slammed and locked. You are now in the conservatory and cannot return to the library. In the conservatory there are there are three instruments: a trumpet, a piano, and a drum. There is a sheet of music on a stand."; } break; default: output = "You space out for a while pondering how to get out"; } } public static void conservatory() { System.out.printf("%s You have %d moves left.\n>>", output, movesLeft); scan = new Scanner(System.in); String test = scan.nextLine(); switch (test) { case "read music": output = "'Timbre, Tone, Time.'"; break; case "play trumpet": if (!playPiano && !playDrum) { playTrumpet = true; output = "Good thing you can play the trumpet. That was a perfect timbre."; } else { output = "Hmm... Something seems to be wrong with the trumpet. It isn't playing correctly."; playTrumpet = false; playPiano = false; playDrum = false; } break; case "play piano": if (playTrumpet && !playDrum) { playPiano = true; output = "Good thing you can play the piano. That was a perfect tone."; } else { output = "Hmm... Something seems to be wrong with the piano. It isn't playing correctly."; playTrumpet = false; playPiano = false; playDrum = false; } break; case "play drum": if (playTrumpet && playPiano) { playDrum = true; output = "Good thing you can play the drums. That was a perfect time."; } else { output = "Hmm... Something seems to be wrong with the drum. It isn't playing correctly."; playTrumpet = false; playPiano = false; playDrum = false; } break; default: output = "You space out for a while pondering how to get out"; } } }
true
dfb0894aa8f1590f51a5b2e9c21d925d21d422bd
Java
Oyveloper/cards_against_christmas_backend
/src/main/java/com/monsen/cards_against_christmas_backend/game/CACGameManager.java
UTF-8
1,379
2.859375
3
[]
no_license
package com.monsen.cards_against_christmas_backend.game; import com.monsen.cards_against_christmas_backend.data.entity.WhiteCard; import com.monsen.cards_against_christmas_backend.util.GameIdGenerator; import java.util.HashMap; import java.util.Map; public class CACGameManager { private Map<String, CACGame> games = new HashMap<>(); private GameIdGenerator idGenerator = new GameIdGenerator(); private HashMap<String, WhiteCard> knownCards = new HashMap<>(); public CACGame getGame(String id) { if (!this.games.containsKey(id)) { throw new IllegalStateException("Game" + " with id " + id + " does not exist"); } return this.games.get(id); } public boolean doesGameExist(String id) { return this.games.containsKey(id); } public CACGame createGame() throws IllegalStateException { String id = idGenerator.generateId(); while (this.games.containsKey(id)) { id = idGenerator.generateId(); } CACGame game = new CACGame(id); this.games.put(id, game); return game; } public void registerCard(WhiteCard card) { if (!this.knownCards.containsKey(card.getId())) { this.knownCards.put(card.getId(), card); } } public WhiteCard getCardById(String id) { return this.knownCards.get(id); } }
true
29252a5b26df9b3ed898c0d910b5d1b6088b8ada
Java
HUNTERS1984/tenposs_app_android
/Tenposs/app/src/main/java/jp/tenposs/tenposs/MainApplication.java
UTF-8
1,610
2.3125
2
[]
no_license
package jp.tenposs.tenposs; import android.app.Application; import android.content.Context; import android.os.Bundle; import android.os.Parcelable; import android.support.v4.app.FragmentManager; import java.io.Serializable; /** * Created by ambient on 7/26/16. */ public class MainApplication extends Application { static Context mContext = null; static FragmentManager mFragmentManager = null; private Bundle applicationBundle; public MainApplication() { super(); applicationBundle = new Bundle(); } public static void setContext(Context context) { mContext = context; } public static Context getContext() { return mContext; } public void putSerializable(String key, Serializable value) { applicationBundle.putSerializable(key, value); } public void putParcelable(String key, Parcelable value) { applicationBundle.putParcelable(key, value); } public Serializable getSerializable(String key) { return applicationBundle.getSerializable(key); } public Parcelable getParcelable(String key) { return applicationBundle.getParcelable(key); } public boolean containsKey(String key) { return applicationBundle.containsKey(key); } public void remove(String key) { applicationBundle.remove(key); } public static void setSupportFragmentManager(FragmentManager fragmentManager) { mFragmentManager = fragmentManager; } public static FragmentManager getSupportFragmentManager() { return mFragmentManager; } }
true
b4e0e8a858c9a670ffcdf3be877adcc52c056242
Java
fanysoft/Android_OpenStreeMap_CzechRepublic
/app/src/main/java/cz/vancura/openstreetmaps/model/KrajPOJO.java
UTF-8
824
2.390625
2
[]
no_license
package cz.vancura.openstreetmaps.model; public class KrajPOJO { String krajFileName; String krajNazev; int krajColor; public KrajPOJO(String krajFileName, String krajNazev, int krajColor) { this.krajFileName = krajFileName; this.krajNazev = krajNazev; this.krajColor = krajColor; } public String getKrajNazev() { return krajNazev; } public void setKrajNazev(String krajNazev) { this.krajNazev = krajNazev; } public String getKrajFileName() { return krajFileName; } public void setKrajFileName(String krajFileName) { this.krajFileName = krajFileName; } public int getKrajColor() { return krajColor; } public void setKrajColor(int krajColor) { this.krajColor = krajColor; } }
true
dd54f467a8aef9e980b0e07c99b80b3f8b223a3e
Java
pkpratik715/Reformix_Student_Management_SpringBoot
/studentmaintenance-main/studentmaintenance/src/main/java/com/te/studentmaintenance/service/StudentServiceImpl.java
UTF-8
1,096
2.09375
2
[]
no_license
package com.te.studentmaintenance.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.te.studentmaintenance.bean.StudentBean; import com.te.studentmaintenance.dao.StudentDAO; @Service public class StudentServiceImpl implements StudentService { @Autowired private StudentDAO dao; @Override public StudentBean getStudent(int user_Id) { // TODO Auto-generated method stub return dao.getStudent(user_Id); } @Override public boolean deleteStudent(int user_Id) { // TODO Auto-generated method stub return dao.deleteStudent(user_Id); } @Override public List<StudentBean> getAllStudents() { // TODO Auto-generated method stub return dao.getAllStudents(); } @Override public boolean addStudent(StudentBean bean) { // TODO Auto-generated method stub return dao.addStudent(bean); } @Override public boolean updateStudent(StudentBean bean) { // TODO Auto-generated method stub return dao.updateStudent(bean); } }
true
9f5f65582a7e8f250d135116d69defb7353c71d1
Java
tanbinh123/Dropbox_SpringBoot
/SpringBoot/src/main/java/com/service/UseractivityServices.java
UTF-8
671
1.71875
2
[]
no_license
package com.service; import com.entity.Folder; import com.entity.Users; import com.repository.DropBoxUsers; import com.repository.FolderRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class UseractivityServices { @Autowired private DropBoxUsers dropBoxUsers; public List<Users> findByuserid (String userid){ System.out.println("userid:"+userid); System.out.println("jay desai:"+dropBoxUsers.findByuserid(userid)); return dropBoxUsers.findByuserid(userid); } }
true
5c7ef8c8d504d1ba22c2b87a1c934f4b6b3fbbb5
Java
biziliavv/gha_automation
/src/test/java/pageobjects/BasePageObject.java
UTF-8
2,025
2.671875
3
[]
no_license
package pageobjects; import org.openqa.selenium.*; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.FluentWait; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import static setup.SeleniumDriver.getDriver; public class BasePageObject { private WebDriver driver; public BasePageObject(WebDriver driver) { this.driver = driver; } String link = "http://admin:publish@gha.dev.conciliolabs.com/"; public void openHomePage(){ getDriver().get(link); } public void clickOnExclusiveOffers(){ WebElement specialOffers = getDriver().findElement(By.xpath("//a[text()='Special Offers']")); specialOffers.click(); } public String getExlusivePageTitle(){ fluentWaitforElement(getDriver().findElement(By.xpath("//h3[@class='SpecialOffersTitle SpecialOffersTitle--posTop SpecialOffersTitle--dark']")), 50, 3); return getDriver().findElement(By.xpath("//h3[@class='SpecialOffersTitle SpecialOffersTitle--posTop SpecialOffersTitle--dark']")).getText(); } // Custom wait method for waiting until element is visible public WebElement fluentWaitforElement(WebElement element, int timoutSec, int pollingSec) { FluentWait<WebDriver> fWait = new FluentWait<WebDriver>(driver).withTimeout(timoutSec, TimeUnit.SECONDS) .pollingEvery(pollingSec, TimeUnit.SECONDS) .ignoring(NoSuchElementException.class, TimeoutException.class).ignoring(StaleElementReferenceException.class); for (int i = 0; i < 2; i++) { try { fWait.until(ExpectedConditions.visibilityOf(element)); fWait.until(ExpectedConditions.elementToBeClickable(element)); } catch (Exception e) { System.out.println("Element Not found trying again - " + element.toString().substring(70)); e.printStackTrace(); } } return element; } }
true
e1f4c1e982b1f5ecf87bb0f72821133dc2f0f36e
Java
dailien/backend
/src/main/java/app/datasource/RecipeDatasourceImpl.java
UTF-8
701
2.171875
2
[]
no_license
package app.datasource; import java.util.List; import javax.transaction.Transactional; import org.hibernate.Criteria; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import app.recipe.Recipe; @Repository @Transactional public class RecipeDatasourceImpl implements RecipeDatasource { @Autowired private SessionFactory sessionFactory; @Override public List<Recipe> findAll() { Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Recipe.class); criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY); return (List<Recipe>)criteria.list(); } }
true
c731eeaa4e53c32bc8965eb03c87530c55024333
Java
JolanYacht/nk
/src/main/java/com/ifrabbit/nk/express/service/impl/DealTypeServiceImpl.java
UTF-8
646
1.796875
2
[]
no_license
package com.ifrabbit.nk.express.service.impl; import com.ifrabbit.nk.express.domain.DealType; import com.ifrabbit.nk.express.repository.DealTypeRepository; import com.ifrabbit.nk.express.service.DealTypeService; import org.springframework.data.support.AbstractCrudService; import org.springframework.stereotype.Service; /** * Created with IDEA * author:SunJiaJian * Date:2018/9/5 * Time:13:40 */ @Service public class DealTypeServiceImpl extends AbstractCrudService<DealTypeRepository, DealType,Long> implements DealTypeService { public DealTypeServiceImpl(DealTypeRepository repository) { super(repository); } }
true
e910f65cf66f6492fdfe3f51e7da1995bf1e6509
Java
uk-gov-mirror/ONSdigital.census-rm-notify-processor
/src/main/java/uk/gov/ons/census/notifyprocessor/model/Contact.java
UTF-8
204
1.796875
2
[]
no_license
package uk.gov.ons.census.notifyprocessor.model; import lombok.Data; @Data public class Contact { private String title; private String forename; private String surname; private String telNo; }
true
d550fb56c6c28cc83e6e8c1694d4d43f435d2ac6
Java
RealWorld-Yuchen-Yang/DataStructuresAndAlgorithms
/src/main/binarytree/BinaryTreeZigZagLevelOrderTraversal.java
UTF-8
2,098
4.15625
4
[]
no_license
package main.binarytree; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Queue; /** * Given a binary tree, say * 3 * / \ * 9 20 * / \ * 15 7 * [ * [3], * [20, 9] * [15, 7] * ] * * Analysis: * This is Width First Traversal. * Also use a boolean to represent the odd/even of a row * say: * odd: true * even: false * @author yuchenyang * */ public class BinaryTreeZigZagLevelOrderTraversal { //solution1: recursive public static List<List<Integer>> recursiveSolution(TreeNode root) { List<List<Integer>> result = new ArrayList(); traverse(root, 1, result, true); return result; } private static void traverse(TreeNode root, int level, List<List<Integer>> result, boolean isOdd) { if(root == null) return; if(level > result.size()) result.add(new ArrayList()); if(isOdd) result.get(level - 1).add(root.val); else result.get(level - 1).add(0, root.val); traverse(root.left, level + 1, result, !isOdd); traverse(root.left, level + 1, result, !isOdd); } public static List<List<Integer>> iterativeSolution(TreeNode root) { List result = new ArrayList(); Queue<TreeNode> current = new LinkedList(); Queue<TreeNode> next= new LinkedList(); boolean isOdd = true; if(root == null) { return result; } else { current.offer(root); } while(!current.isEmpty()) { ArrayList<Integer> level = new ArrayList();//represents elements in a level while(!current.isEmpty()) { TreeNode node = current.poll(); level.add(node.val); //at the main time, construct the next level if(node.left != null) next.offer(node.left); if(node.right != null) next.offer(node.right); } //now it is time to construct the int[] representation of the level if(!isOdd) Collections.reverse(level); result.add(level); //move on to the next level isOdd = !isOdd; Queue tmp = current; current = next; next = tmp; } return result; } }
true
dfe1085f9a8bb3ec29c8b56b70eed20b598e456d
Java
anavruzjon/android-udemy-course
/MyCalc/app/src/main/java/com/akhmadov/mycalc/MainActivity.java
UTF-8
5,339
2.109375
2
[]
no_license
package com.akhmadov.mycalc; import android.graphics.Color; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.design.widget.NavigationView; import android.support.design.widget.TabLayout; import android.support.v4.view.GravityCompat; import android.support.v4.view.ViewPager; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.AppCompatActivity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.LinearLayout; import android.widget.Toast; public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener { private CalculatorTypePageAdapter mAdapter; private ViewPager mPager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); /*Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); */ DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); //drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED); //Lock swiping from left /*ActionBarDrawerToggle toggle = new ActionBarDrawerToggle( this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); drawer.addDrawerListener(toggle); toggle.syncState();*/ NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); navigationView.setNavigationItemSelectedListener(this); mAdapter = new CalculatorTypePageAdapter(getSupportFragmentManager()); mAdapter.addFragment(new MoreTabFragment(), ""); mAdapter.addFragment(new SimpleCalcTabFragment(), "Простой"); mAdapter.addFragment(new EngineerCalcTabFragment(), "Инженерный"); // It's only pager no tabView mPager = (ViewPager) findViewById(R.id.pager); mPager.setAdapter(mAdapter); final TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs); tabLayout.setupWithViewPager(mPager); //tabLayout.setSelectedTabIndicatorColor(Color.parseColor("#FF0000")); //tabLayout.setSelectedTabIndicatorHeight((int) (5 * getResources().getDisplayMetrics().density)); // by default tab (Simple) is selected TabLayout.Tab tab = tabLayout.getTabAt(1); if (tab != null) { tab.select(); } tabLayout.getTabAt(0).setIcon(R.drawable.ic_more); tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() { @Override public void onTabSelected(TabLayout.Tab tab) { DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); if (tab.getPosition() == 0){ drawer.openDrawer(GravityCompat.START); } } @Override public void onTabUnselected(TabLayout.Tab tab) { } @Override public void onTabReselected(TabLayout.Tab tab) { } }); LinearLayout layout = ((LinearLayout) ((LinearLayout) tabLayout.getChildAt(0)).getChildAt(0)); LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) layout.getLayoutParams(); layoutParams.weight = 0.3f; layout.setLayoutParams(layoutParams); drawer.addDrawerListener(new DrawerLayout.DrawerListener() { @Override public void onDrawerSlide(@NonNull View view, float v) { if (v != 0){ // It's just started opening TabLayout.Tab tab = tabLayout.getTabAt(1); if (tab != null) { tab.select(); } } } @Override public void onDrawerOpened(@NonNull View view) { TabLayout.Tab tab = tabLayout.getTabAt(1); if (tab != null) { tab.select(); } } @Override public void onDrawerClosed(@NonNull View view) { } @Override public void onDrawerStateChanged(int i) { } }); } @Override public void onBackPressed() { DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawer(GravityCompat.START); } else { super.onBackPressed(); } } @SuppressWarnings("StatementWithEmptyBody") @Override public boolean onNavigationItemSelected(MenuItem item) { // Handle navigation view item clicks here. int id = item.getItemId(); if (id == R.id.nav_camera) { // Handle the camera action } else if (id == R.id.nav_gallery) { } else if (id == R.id.nav_slideshow) { } else if (id == R.id.nav_manage) { } else if (id == R.id.nav_share) { } else if (id == R.id.nav_send) { } DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); drawer.closeDrawer(GravityCompat.START); return true; } }
true
04d636d8463e4d90651a5fbbf550aa412982c0a5
Java
karasio/suunnittelumallit
/src/command/Main.java
UTF-8
758
3.3125
3
[]
no_license
package command; public class Main { public static void main(String[] args) { Screen screen = new Screen(); Command up = new UpCommand(screen); Command down = new DownCommand(screen); Command stack = new CommandStack(); for (int i = 0; i < 3; i++) { stack.addCommand(up); stack.addCommand(down); } Button upButton = new Button(up); Button downButton = new Button(down); Button record = new Button(stack); System.out.println("Pressing up"); upButton.push(); System.out.println("Pressing down"); downButton.push(); System.out.println("Doing predefined program with recorded commands"); record.push(); } }
true
e7b9eadd8a9bec868fa360ef4318312ecb95d1a1
Java
kangyl/mycode
/code/src/main/java/com/kangyl/test/io/aio/SimpleReadHandler.java
UTF-8
800
2.5625
3
[]
no_license
/** * Copyright 2018 */ package com.kangyl.test.io.aio; import java.nio.ByteBuffer; import java.nio.channels.CompletionHandler; import java.nio.charset.Charset; /** * @author : kangyl(460720197@qq.com) * @date: 2018/8/22 */ public class SimpleReadHandler implements CompletionHandler<Integer, ByteBuffer> { private Charset charSet = Charset.forName("UTF-8"); private String decode(ByteBuffer byteBuffer) { return charSet.decode(byteBuffer).toString(); } @Override public void completed(Integer result, ByteBuffer attachment) { if (result > 0) { attachment.flip(); System.out.println(decode(attachment)); } } @Override public void failed(Throwable exc, ByteBuffer attachment) { exc.printStackTrace(); } }
true
774007d0bd49b7ffcf777e6b4703ce3307147eb7
Java
mwithers313/RoshamboLab
/Player2.java
UTF-8
476
2.875
3
[]
no_license
import java.util.Random; public class Player2 extends Player { @Override public String generateRoshambo(String input) { Random play = new Random(); int output = play.nextInt(4); if (output == 1) { return ("Rock"); } else if (output == 2) { return ("Paper"); } else { return ("Scissors"); } } @Override public String getName() { return "Phillip"; } }
true
a677aadde994dbd3ab40ccadfe696196a3d20e77
Java
killstealing/angularHighLevelBackend
/angularTaskMgrSpringBootMybatis/src/main/java/com/lmy/mapper/TaskMapper.java
UTF-8
241
1.75
2
[]
no_license
package com.lmy.mapper; import java.util.List; import com.lmy.pojo.Task; public interface TaskMapper { public List<Task> getTasksByTaskListId(int taskListId); public int doInsertTask(Task task); // public int doUpdateTask(Task task); }
true
2527f83b1de5fc0d6fe64472d335280bbcd531c0
Java
SantFlamel/printerFX
/src/sample/printserv/cut/PrintWithoutDialog.java
UTF-8
1,231
2.9375
3
[]
no_license
package sample.printserv.cut; import javax.print.PrintService; import java.awt.*; import java.awt.print.*; public class PrintWithoutDialog implements Printable { @Override public int print(Graphics g, PageFormat pf, int page) throws PrinterException { if (page > 0) { /* У нас только одна страница, а отсчёт начинается с нуля*/ return NO_SUCH_PAGE; } Font f = new Font("Roman", 0, 10); g.setFont(f); g.drawString("", 10, 100); return PAGE_EXISTS; } public PrintWithoutDialog(PrintService ps) { PrinterJob job = PrinterJob.getPrinterJob(); if(ps!=null){ try { job.setPrintService(ps); } catch (PrinterException e) { e.printStackTrace(); } // Выставляем printable job.setPrintable(this); // Инициируем печать try { job.print(); } catch (PrinterException e) { e.printStackTrace(); } }else { System.out.println("Принтер не найден"); } } }
true
bcf505101c844e18647de6f25355d373df979ac2
Java
derrickpehjh/CZ4045-NLP-Assignment
/src/part2/nounPhase.java
UTF-8
12,607
2.109375
2
[]
no_license
package part2; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Random; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import opennlp.tools.cmdline.parser.ParserTool; import opennlp.tools.parser.Parse; import opennlp.tools.parser.Parser; import opennlp.tools.parser.ParserFactory; import opennlp.tools.parser.ParserModel; import part1.HashMapSort; import part1.Json; import part1.SentenceSegmentation; import part1.TopProductsAndReviews; public class nounPhase { static String openNLPBinLocation = "libraries\\en-parser-chunking.bin"; static Map<String, Integer> nounPhrases = new HashMap<String, Integer>(); static Map<String, Integer> summaryPhrases1 = new HashMap<String, Integer>(); static Map<String, Integer> summaryPhrases2 = new HashMap<String, Integer>(); static Map<String, Integer> summaryPhrases3 = new HashMap<String, Integer>(); static List<String> top10List=new ArrayList<String>(); static List<String> chosen3=new ArrayList<String>(); static String JSONFile = "dataset\\nounPhaseSummarizer1.json"; static String JSONFile2 = "dataset\\nounPhaseSummarizer.json"; static int counter=0; static Map<String, Integer> JSONnounPhrases = new HashMap<String, Integer>(); static boolean enable; public static void main(String[] args) throws Exception { top10List=TopProductsAndReviews.retrieveReviewerorProductList("asin"); choose3(); // nounPhraseSummarizer(); RetrieveJson(); RemoveDuplicates(); print(); } public static void nounPhraseSummarizer(int startIndex,int endIndex) throws Exception, ParseException//Noun Phrase for specific index { int count=0,tracker=startIndex; Iterator<?> i = Json.readJSON(); while (i.hasNext()) { count++; System.out.println("Loop "+count); JSONObject obj = (JSONObject) i.next(); String productID=(String) obj.get("asin"); String review = (String) obj.get("reviewText"); if(count>startIndex && count<=endIndex) { String[] sentences=SentenceSegmentation.Getsentences(review); for(String sentence:sentences) { if(chosen3.contains(productID)) { int index=chosen3.indexOf(productID); index++; extracter(sentence,index); } else { extracter(sentence); } } if(count%500==0||!i.hasNext()) { writeToJson(tracker,count); tracker=count; } } if(count==endIndex)break; } System.out.println("Number of Review: "+count); System.out.println("\n" +"Number of unique Phrases: " + counter ); } public static void nounPhraseSummarizer() throws Exception, ParseException//General Noun Phrase { int count=0,tracker=0; Iterator<?> i = Json.readJSON(); while (i.hasNext()) { count++; System.out.println("Loop "+count); JSONObject obj = (JSONObject) i.next(); String productID=(String) obj.get("asin"); String review = (String) obj.get("reviewText"); String[] sentences=SentenceSegmentation.Getsentences(review); for(String sentence:sentences) { if(chosen3.contains(productID)) { int index=chosen3.indexOf(productID); index++; extracter(sentence,index); } else { extracter(sentence); } } if(count%500==0||!i.hasNext()) { writeToJson(tracker,count); tracker=count; } } System.out.println("Number of Review: "+count); System.out.println("\n" +"Number of unique Phrases: " + counter ); } public static void nounPhraseSummarizer(String id) throws Exception, ParseException//Noun Phrase for specific Product { int count=0,tracker=0; Iterator<?> i = Json.readJSON(); while (i.hasNext()) { count++; System.out.println("Loop "+count); JSONObject obj = (JSONObject) i.next(); String productID=(String) obj.get("asin"); String review = (String) obj.get("reviewText"); if(productID==id) { String[] sentences=SentenceSegmentation.Getsentences(review); for(String sentence:sentences) { int index=chosen3.indexOf(productID); index++; extracter(sentence,index); } } if(count%500==0||!i.hasNext()) { writeToJson(tracker,count); tracker=count; } } System.out.println("Number of Review: "+count); System.out.println("\n" +"Number of unique Phrases: " + counter ); } public static void extracter(String sentence1) { InputStream modelInParse = null; try { //load chunking model //from http://opennlp.sourceforge.net/models-1.5/ modelInParse = new FileInputStream(openNLPBinLocation); ParserModel model = new ParserModel(modelInParse); //create parse tree Parser parser = ParserFactory.create(model); Parse topParses[] = ParserTool.parseLine(sentence1, parser, 1); //call subroutine to extract noun phrases for (Parse p : topParses) getNounPhrases(p); } catch (IOException e) { e.printStackTrace(); } finally { if (modelInParse != null) { try { modelInParse.close(); } catch (IOException e) { } } } } public static void extracter(String sentence1,int num) { InputStream modelInParse = null; try { //load chunking model //from http://opennlp.sourceforge.net/models-1.5/ modelInParse = new FileInputStream(openNLPBinLocation); ParserModel model = new ParserModel(modelInParse); //create parse tree Parser parser = ParserFactory.create(model); Parse topParses[] = ParserTool.parseLine(sentence1, parser, 1); //call subroutine to extract noun phrases for (Parse p : topParses) { getNounPhrases2(p,num); getNounPhrases(p); } } catch (IOException e) { e.printStackTrace(); } finally { if (modelInParse != null) { try { modelInParse.close(); } catch (IOException e) { }}}} //recursively loop through tree, extracting noun phrases public static void getNounPhrases(Parse p) { if (p.getType().equals("NP")) { //NP=noun phrase String np=p.getCoveredText().toLowerCase(); if(!isSingleWord(np)) { if(nounPhrases.containsKey(np)) { int value=nounPhrases.get(np); value++; nounPhrases.put(np, value); } else{ nounPhrases.put(np, 1); } counter++; } } for (Parse child : p.getChildren()) getNounPhrases(child); } public static void getNounPhrases2(Parse p,int num) { if (p.getType().equals("NP")) { //NP=noun phrase String np=p.getCoveredText().toLowerCase(); if(!isSingleWord(np)) { if(num==1) { if(summaryPhrases1.containsKey(np)) { int value=summaryPhrases1.get(np); value++; summaryPhrases1.put(np, value); } else{ summaryPhrases1.put(np, 1); } } else if(num==2) { if(summaryPhrases2.containsKey(np)) { int value=summaryPhrases2.get(np); value++; summaryPhrases2.put(np, value); } else{ summaryPhrases2.put(np, 1); } } else if(num==3) { if(summaryPhrases3.containsKey(np)) { int value=summaryPhrases3.get(np); value++; summaryPhrases3.put(np, value); } else{ summaryPhrases3.put(np, 1); } } counter++; } } for (Parse child : p.getChildren()) getNounPhrases2(child,num); } public static void choose3 () { Random rand = new Random(); Boolean done=false; List<Integer> exclude=new ArrayList <Integer>(); int count=0; System.out.println("Chosen 3:"); while (!done) { int num =rand.nextInt(9); if(top10List.get(num)!=""&&!exclude.contains(num)) { exclude.add(num); count++; chosen3.add(top10List.get(num)); System.out.println(top10List.get(num)); top10List.remove(num); if(count==3)done=true; } } } public static Boolean isSingleWord(String sentence) { String[] tempArray = sentence.trim().split(" "); if(tempArray.length>1) { return false; } return true; } public static void RemoveDuplicates() { List<String>removalList = new ArrayList<String>(); for(String temp:summaryPhrases1.keySet()) { if(temp.contains(".")) { removalList.add(temp); } } for(String remove:removalList) { summaryPhrases1.remove(remove); } removalList.clear(); for(String temp:summaryPhrases2.keySet()) { if(temp.contains(".")) { removalList.add(temp); } } for(String remove:removalList) { summaryPhrases2.remove(remove); } removalList.clear(); for(String temp:summaryPhrases3.keySet()) { if(temp.contains(".")) { removalList.add(temp); } } for(String remove:removalList) { summaryPhrases3.remove(remove); } removalList.clear(); for(String temp:JSONnounPhrases.keySet()) { if(temp.contains(".")) { removalList.add(temp); } } for(String remove:removalList) { JSONnounPhrases.remove(remove); } removalList.clear(); } public static void print() { System.out.println("\n==================================="); System.out.println("Overall Summary Phrase Top 20 Contents: "); HashMapSort.sortDescending(JSONnounPhrases,"nounPhase"); System.out.println("\n==================================="); if(!summaryPhrases1.isEmpty()) { System.out.println("Summary Phrase 1 Top 20 Contents for product "+chosen3.get(0)); HashMapSort.sortDescending(summaryPhrases1,"nounPhase1"); System.out.println("\n==================================="); } if(!summaryPhrases2.isEmpty()) { System.out.println("Summary Phrase 2 Top 20 Contents for product "+chosen3.get(1)); HashMapSort.sortDescending(summaryPhrases2,"nounPhase2"); System.out.println("\n==================================="); } if(!summaryPhrases3.isEmpty()) { System.out.println("Summary Phrase 3 Top 20 Contents for product "+chosen3.get(2)); HashMapSort.sortDescending(summaryPhrases3,"nounPhase3"); System.out.println("\n==================================="); } } @SuppressWarnings("unchecked") public static void writeToJson(int start,int end) throws IOException { JSONObject obj = new JSONObject(); obj.put("Start", start); obj.put("End", end); JSONArray array = new JSONArray(); for(String nounPhrase:nounPhrases.keySet()) { JSONObject obj2 = new JSONObject(); obj2.put("Noun Phrase", nounPhrase); obj2.put("Count", nounPhrases.get(nounPhrase)); array.add(obj2); } nounPhrases.clear(); obj.put("Noun Phrase", array); try (BufferedWriter file = new BufferedWriter( new FileWriter(new File(JSONFile), true));) { file.write(obj.toJSONString()); System.out.println("Successfully Copied JSON Object to File..."); file.write(","); } } public static void RetrieveJson() throws IOException, ParseException { JSONParser jsonParser = new JSONParser(); FileReader reader = new FileReader(JSONFile2); JSONArray jsonArray = (JSONArray) jsonParser.parse(reader); Iterator<?> i = jsonArray.iterator(); List<Long> startList = new ArrayList<Long>(); List<Long> endList = new ArrayList<Long>(); while(i.hasNext()) { JSONObject obj = (JSONObject) i.next(); long start=(long) obj.get("Start"); long end = (long) obj.get("End"); if(!startList.contains(start)&&!endList.contains(end)) { startList.add(start); endList.add( end); } else continue; System.out.println("Start: "+start+" End: "+end); JSONArray array2= (JSONArray) obj.get("Noun Phrase"); for (int x=0;x<array2.size();x++) { JSONObject temp=(JSONObject) array2.get(x); String phrase=(String) temp.get("Noun Phrase"); long count= (long) temp.get("Count"); if(JSONnounPhrases.containsKey(phrase)) { int value=JSONnounPhrases.get(phrase); value=(int) (value+count); JSONnounPhrases.put(phrase, value); } else { JSONnounPhrases.put(phrase,(int) count); } } } } }
true
85d040de6847d76c788ff3300df295f8cf50ae8e
Java
Yuan720/testAndroid
/app/src/main/java/com/example/administrator/huayun/MyService.java
UTF-8
1,367
1.8125
2
[]
no_license
package com.example.administrator.huayun; import android.app.AlertDialog; import android.app.Service; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.res.Configuration; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Bundle; import android.os.IBinder; import android.support.annotation.ColorInt; import android.support.annotation.DrawableRes; import android.support.annotation.LayoutRes; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.view.InputQueue; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.SurfaceHolder; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.widget.Toast; import java.util.Timer; import java.util.zip.Inflater; public class MyService extends Service { @Override public void onCreate() { super.onCreate(); Toast.makeText(MyService.this,"服务已启动",Toast.LENGTH_LONG).show(); } public MyService() { } @Override public IBinder onBind(Intent intent) { // TODO: Return the communication channel to the service. throw new UnsupportedOperationException("Not yet implemented"); } }
true
e7475ca875efe15add442dd799e19a96c70332e6
Java
curtys/webprotege-attestation
/webprotege-server-core/src/main/java/edu/stanford/bmir/protege/web/server/match/LiteralAnnotationValueMatcher.java
UTF-8
2,996
2.328125
2
[ "BSD-2-Clause" ]
permissive
package edu.stanford.bmir.protege.web.server.match; import org.semanticweb.owlapi.model.OWLAnnotationValue; import org.semanticweb.owlapi.model.OWLLiteral; import javax.annotation.Nonnull; import java.util.function.Predicate; import java.util.regex.Pattern; import static com.google.common.base.Preconditions.checkNotNull; /** * Matthew Horridge * Stanford Center for Biomedical Informatics Research * 7 Jun 2018 */ public class LiteralAnnotationValueMatcher implements Matcher<OWLAnnotationValue> { @Nonnull private final Matcher<OWLLiteral> literalMatcher; public LiteralAnnotationValueMatcher(@Nonnull Matcher<OWLLiteral> literalMatcher) { this.literalMatcher = checkNotNull(literalMatcher); } @Override public boolean matches(@Nonnull OWLAnnotationValue value) { return value instanceof OWLLiteral && literalMatcher.matches((OWLLiteral) value); } public static Matcher<OWLAnnotationValue> forLexicalPattern(@Nonnull Pattern pattern) { return new LiteralAnnotationValueMatcher(LiteralMatcher.forLexicalPattern(pattern)); } public static Matcher<OWLAnnotationValue> forLexicalPredicate(Predicate<String> predicate) { return new LiteralAnnotationValueMatcher(LiteralMatcher.forPredicate(predicate)); } public static Matcher<OWLAnnotationValue> forHasAnyLangTag() { return new LiteralAnnotationValueMatcher(LiteralMatcher.forHasAnyLangTag()); } public static Matcher<OWLAnnotationValue> forIsXsdBooleanTrue() { return new LiteralAnnotationValueMatcher(LiteralMatcher.forXsdBooleanTrue()); } /** * Returns a matcher for annotation values that matches if the datatype is an OWL 2 datatype * and the lexical value is in the lexical space of the datatype. */ public static Matcher<OWLAnnotationValue> forIsNotInLexicalSpace() { return new LiteralAnnotationValueMatcher(new NotMatcher<>(new LiteralInLexicalSpaceMatcher())); } public static Matcher<OWLAnnotationValue> forHasTrailingWhiteSpace() { return forLexicalPattern(Pattern.compile("\\s+$")); } public static Matcher<OWLAnnotationValue> forHasRepeatedWhiteSpace() { return forLexicalPattern(Pattern.compile("\\s+")); } public static Matcher<OWLAnnotationValue> forAnyValue() { return OWLAnnotationValue::isLiteral; } public static Matcher<OWLAnnotationValue> forLangTagMatcher(Matcher<String> langTagMatcher) { return new LiteralAnnotationValueMatcher(new LiteralMatcher( lex -> true, langTagMatcher, dt -> true )); } public static Matcher<OWLAnnotationValue> forLexicalValueMatcher(Matcher<String> lexicalValueMatcher) { return new LiteralAnnotationValueMatcher( new LiteralMatcher( lexicalValueMatcher, langTag -> true, dt -> true ) ); } }
true
9acc4341ff98b4acee46c833df66b86ba560e4a1
Java
JordanVeraCCeiba/pagosNomina
/microservicio/dominio/src/test/java/com/ceiba/nomina/servicio/ServiciosNominaTest.java
UTF-8
2,278
2.375
2
[]
no_license
package com.ceiba.nomina.servicio; import com.ceiba.BasePrueba; import com.ceiba.dominio.excepcion.ExcepcionPagoDomingo; import com.ceiba.dominio.excepcion.ExcepcionSalario; import com.ceiba.nomina.modelo.entidad.Nomina; import com.ceiba.nomina.puerto.repositorio.RepositorioNomina; import com.ceiba.nomina.servicio.testdatabuilder.NominaTestDataBuilder; import org.junit.Test; import org.mockito.Mockito; import static org.junit.Assert.assertEquals; public class ServiciosNominaTest { @Test public void validarSalario() { // arrange Nomina nomina = new NominaTestDataBuilder().build(); RepositorioNomina repositorioNomina = Mockito.mock(RepositorioNomina.class); Mockito.when(repositorioNomina.validarSalario(Mockito.spy(nomina))).thenReturn(true); ServicioCrearNomina servicioCrearNomina = new ServicioCrearNomina(repositorioNomina); // act - assert BasePrueba.assertThrows(() -> servicioCrearNomina.validarSalario(nomina), ExcepcionSalario.class,"El salario debe ser igual al registrado o al ultimo actualizado"); } @Test public void validarFechaPago() { // arrange NominaTestDataBuilder nominaTestDataBuilder = new NominaTestDataBuilder().conFechaPago("20/06/2021"); // act - assert BasePrueba.assertThrows(() -> nominaTestDataBuilder.build(), ExcepcionPagoDomingo.class, "El pago no se puede realizar un domingo"); } @Test public void validarSalud() { // arrange Nomina nomina = new Nomina(); Double salud = nomina.calcularSalud(2_500_000D); // act - assert assertEquals(java.util.Optional.of(100_000D), java.util.Optional.of(salud)); } @Test public void validarPension() { // arrange Nomina nomina = new Nomina(); Double salud = nomina.calcularPension(2_500_000D); // act - assert assertEquals(java.util.Optional.of(100_000D), java.util.Optional.of(salud)); } @Test public void validarPagoEmpleado() { // arrange Nomina nomina = new Nomina(); Double sueldo = nomina.calcularSueldo(2_500_000D); // act - assert assertEquals(java.util.Optional.of(2_300_000D), java.util.Optional.of(sueldo)); } }
true
b2db6e532e53ce3a7ae6e1373e0bf8c94a3364ca
Java
aveave/java-school
/online-shop-backend/src/test/java/com/javaschool/onlineshop/service/impl/OrderServiceImplTest.java
UTF-8
4,324
2.046875
2
[]
no_license
package com.javaschool.onlineshop.service.impl; import com.javaschool.onlineshop.mappers.OrderMapper; import com.javaschool.onlineshop.model.dto.OrderDTO; import com.javaschool.onlineshop.model.dto.StatisticsDTO; import com.javaschool.onlineshop.model.entity.Order; import com.javaschool.onlineshop.repository.OrderElementRepository; import com.javaschool.onlineshop.repository.OrderRepository; import com.javaschool.onlineshop.repository.ProductRepository; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.test.context.junit4.SpringRunner; import java.time.LocalDate; import java.util.*; import static org.junit.Assert.*; @SpringBootTest @RunWith(SpringRunner.class) public class OrderServiceImplTest { @Autowired OrderServiceImpl orderService; @MockBean ProductRepository productRepository; @MockBean OrderRepository orderRepository; @MockBean OrderElementRepository orderElementRepository; @MockBean OrderMapper orderMapper; @Test public void findAllOrders() { List<Order> orderList = new ArrayList<>(); Order order = new Order(); orderList.add(order); Mockito.when(orderRepository.findAll()).thenReturn(orderList); Mockito.when(orderMapper.orderToOrderDTO(orderList.get(0))).thenReturn(new OrderDTO()); orderService.findAllOrders(); Mockito.verify(orderRepository, Mockito.atLeast(1)).findAll(); Mockito.verify(orderMapper, Mockito.atLeast(1)).orderToOrderDTO(order); } @Test public void findOrdersByEmail() { List<Order> orderList = new ArrayList<>(); Order order = new Order(); orderList.add(order); Mockito.when(orderRepository.findOrdersByCustomerEmailAddress("ivan@mail.ru")).thenReturn(orderList); Mockito.when(orderMapper.orderToOrderDTO(orderList.get(0))).thenReturn(new OrderDTO()); orderService.findOrdersByEmail("ivan@mail.ru"); Mockito.verify(orderRepository, Mockito.times(1)).findOrdersByCustomerEmailAddress("ivan@mail.ru"); Mockito.verify(orderMapper, Mockito.atLeast(1)).orderToOrderDTO(order); } @Test public void findOrderById() { Order order = new Order(); Mockito.when(orderRepository.getOne(5L)).thenReturn(order); Mockito.when(orderMapper.orderToOrderDTO(order)).thenReturn(new OrderDTO()); orderService.findOrderById(5L); Mockito.verify(orderRepository, Mockito.times(1)).getOne(5L); Mockito.verify(orderMapper, Mockito.times(1)).orderToOrderDTO(order); } @Test public void deleteOrder() { Mockito.doNothing().when(orderRepository).deleteById(4L); orderService.deleteOrder(4L); Mockito.verify(orderRepository, Mockito.times(1)).deleteById(4L); } @Test public void updateOrder() { Order order = new Order(); List<Order> orderList = new ArrayList<>(); orderList.add(new Order()); Mockito.when(orderRepository.getOne(6L)).thenReturn(order); Mockito.when(orderRepository.save(order)).thenReturn(order); Mockito.when(orderRepository.findAll()).thenReturn(orderList); Mockito.when(orderMapper.orderToOrderDTO(orderList.get(0))).thenReturn(new OrderDTO()); orderService.updateOrder(6L, "Rejected"); assertEquals("Rejected", order.getStatus()); Mockito.verify(orderRepository, Mockito.times(1)).getOne(6L); Mockito.verify(orderRepository, Mockito.times(1)).save(order); Mockito.verify(orderRepository, Mockito.times(1)).findAll(); Mockito.verify(orderMapper, Mockito.atLeast(1)).orderToOrderDTO(orderList.get(0)); } @Test public void findSalesSumInEachCategory() { List<StatisticsDTO> statisticsDTOList = new ArrayList<>(); LocalDate date = LocalDate.now().minusMonths(1); Mockito.when(orderRepository.findSalesSumInEachCategory(date)).thenReturn(statisticsDTOList); orderService.findSalesSumInEachCategory(); Mockito.verify(orderRepository, Mockito.times(1)).findSalesSumInEachCategory(date); } }
true
53bc2b63491f098dedba9b76f86b0d128c53bf06
Java
newSue/direwolves
/cli/src/main/java/com/edgar/direwolves/cli/shell/api/ApiUtils.java
UTF-8
1,395
2.578125
3
[ "Apache-2.0" ]
permissive
package com.edgar.direwolves.cli.shell.api; import io.vertx.core.json.JsonArray; import io.vertx.core.json.JsonObject; import io.vertx.ext.shell.command.CommandProcess; /** * Created by Edgar on 2017/6/19. * * @author Edgar Date 2017/6/19 */ class ApiUtils { static void writeApi(CommandProcess process, JsonObject jsonObject) { process.write(String.format("%s\n", "api").replace(" ", "-")); process.write(String.format(" %-40s%-8s%-30s\n", "name", "method", "path")); process.write(String.format(" %-40s%-8s%-30s\n", jsonObject.getString("name"), jsonObject.getString("method"),jsonObject.getString("path"))); process.write(String.format("%s\n", "endpoints").replace(" ", "-")); JsonArray endpoints = jsonObject.getJsonArray("endpoints", new JsonArray()); for (int i= 0; i < endpoints.size(); i ++) { process.write(" "); process.write(endpoints.getJsonObject(i).encode()); process.write("\n"); } for (String key : jsonObject.fieldNames()) { if (!"name".equals(key) && !"path".equals(key) && !"method".equals(key) && !"endpoints".equals(key)) { process.write(String.format("%s\n", key)); process.write(" "); process.write(jsonObject.getValue(key).toString()); process.write("\n"); } } process.write("\n"); } }
true
8b883b1ec0bca2c71938ddef73fd8c6512212098
Java
huxiutao/SpringProjects
/02-aop/src/com/bjpowernode/aop05/MyTest.java
ISO-8859-7
697
2.296875
2
[]
no_license
package com.bjpowernode.aop05; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class MyTest { @Test public void test01() throws UserException { // ApplicationContext ac = new ClassPathXmlApplicationContext("com\\bjpowernode\\aop05\\applicationContext.xml"); ISomeService bean = (ISomeService)ac.getBean("someServiceProxy"); bean.doSome(); String doOther = bean.doOther(); System.out.println("---> " + doOther); boolean check = bean.check("admin", "12346"); System.out.println("++++++ > " + check); } }
true
4ff60316f6b802c1039a4681d50216d09bd46d81
Java
1Will/Work1
/EventNoti/src/main/dao/impl/ContactArchivesDaoImpl.java
GB18030
2,102
2.34375
2
[]
no_license
package main.dao.impl; import java.util.List; import main.dao.ContactArchivesDao; import main.pojo.BackVisit; import main.pojo.ContactArchives; import org.hibernate.Session; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; public class ContactArchivesDaoImpl extends HibernateDaoSupport implements ContactArchivesDao { @Override public void saveContactArchives(ContactArchives contactArchives) { try { this.getHibernateTemplate().save(contactArchives); } catch (Exception e) { e.printStackTrace(); } } //idȡʵ @SuppressWarnings("unchecked") @Override public ContactArchives getContactArchivesById(Long id) { ContactArchives contactArchives=null; try { contactArchives=(ContactArchives)getSession().load(ContactArchives.class, id); } catch (Exception e) { e.printStackTrace(); } return contactArchives; } //ʼʱȡʵ @SuppressWarnings("unchecked") public List<ContactArchives> getAllContactArchives() { String hql = "from ContactArchives"; System.out.println("====sql===="+hql); return this.getHibernateTemplate().find(hql); } /*@SuppressWarnings("unchecked") @Override public List<ContactArchives> getAllContactArchivesById(Long[] ids) { String hql="from ContactArchies cont where cont.id in'" + ids + "' "; return this.getHibernateTemplate().find(hql); } */ @Override public Session getSuperSession() { return this.getSession(true); } @SuppressWarnings("unchecked") public List<ContactArchives> getAllContactArchives(Long id) { String hql="from ContactArchives temp where temp.customerId="+id; return this.getHibernateTemplate().find(hql); } //ںContactArchives @SuppressWarnings("unchecked") @Override public List<ContactArchives> getContactArchivesByDate(String date,String name ) { String hql="from ContactArchives c where convert(varchar,c.createdTime,120) like '"+date+"%' and c.creatorName='"+name+"'"; return this.getHibernateTemplate().find(hql); } }
true
dc018d9c0a339466ca36fb47a65e1ffeee9c14a6
Java
meko-deng/ECSE420
/src/ca/mcgill/ecse420/a2/BakeryAlgorithm.java
UTF-8
1,612
3.234375
3
[]
no_license
package ca.mcgill.ecse420.a2; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; public class BakeryAlgorithm { private AtomicBoolean[] flag; private AtomicInteger[] label; private int n; public BakeryAlgorithm(int n) { this.n = n; flag = new AtomicBoolean[n]; label = new AtomicInteger[n]; for (int i = 0; i < n; i++) { flag[i] = new AtomicBoolean(); label[i] = new AtomicInteger(); } } public void lock() { int thread_id = (int) Thread.currentThread().getId() % n; flag[thread_id].set(true); int max = 0; for (int i = 0; i < label.length; i++) { if (label[i].get() > max) { max = label[i].get(); } } label[thread_id].set(max + 1); while (shouldWait(thread_id)) ; } public boolean shouldWait(int currentThreadID) { for (int i = 0; i < n; i++) { if (i == currentThreadID) { continue; } if (flag[i].get() == false) { continue; } else { if (label[i].get() != 0 && (label[currentThreadID].get() > label[i].get() || label[currentThreadID].get() == label[i].get() && currentThreadID > i)) { return true; } } } return false; } public void unlock() { int thread_id = (int) Thread.currentThread().getId() % n; flag[thread_id].set(false); label[thread_id].set(0); } }
true
0d22b9a547eda29e24fb77f2b21054c565dbb3ef
Java
hanytran/StreamClassification
/FileProcessing.java
UTF-8
8,422
2.390625
2
[]
no_license
package source; import java.io.FileNotFoundException; import java.io.PrintWriter; import com.yahoo.labs.samoa.instances.Instance; import moa.classifiers.Classifier; import moa.classifiers.bayes.NaiveBayes; //import moa.classifiers.meta.AccuracyUpdatedEnsemble; import moa.core.InstanceExample; import moa.evaluation.WindowAUCImbalancedPerformanceEvaluator; import moa.streams.ArffFileStream; public class FileProcessing { protected static int saPos = 0, saNeg=0, nSaPos = 0, nSaNeg=0; //number of true values protected static int tpDeprived=0, fpDeprived=0, tpFavored=0, fpFavored=0; protected static int tnDeprived=0, fnDeprived=0, tnFavored=0, fnFavored=0; protected static Classifier learner = new NaiveBayes();//1. // protected static Classifier learner = new HoeffdingTree();//2. // protected static Classifier learner = new kNN();//3. // protected static Classifier learner = new OzaBag();//4. // protected static Classifier learner = new AccuracyUpdatedEnsemble();//5. protected static int saIndex=0; protected static String saVal = "Female"; protected static int desiredClass = 1; protected static int notDesiredClass = 0; protected static String saName = "sex"; protected static int windowSize=0; protected static InstanceExample[] windowList = new InstanceExample[windowSize]; public static void main(String[] args) throws FileNotFoundException { // TODO Auto-generated method stub windowSize=1000; saName = "sex"; saVal = "Female"; // String infile = "new_dataset_for_han_removefnlwgt_stream.arff"; String infile = "small_dataset_remove_fnlwgt.arff"; String outfile = "small_dataset_remove_fnlwgt_SA.arff"; remove_att(infile, outfile, 8); // String infile="small_dataset_remove_fnlwgt_SAClass.arff"; // String out="out/small_dataset_statistics.csv"; // Statistics(infile,out); // String out="out/small_originalData(basedOnSAClass)_AUE.csv"; // Data(infile, out); } public static void Data(String filename, String outfile) throws FileNotFoundException{ ArffFileStream fs = new ArffFileStream(filename, -1); for (int i=0; i<fs.getHeader().numAttributes(); i++){ if (fs.getHeader().attribute(i).name().equals(saName)){ saIndex = i; break; } } fs.prepareForUse(); learner.setModelContext(fs.getHeader()); learner.prepareForUse(); //evaluator definition WindowAUCImbalancedPerformanceEvaluator evaluator =new WindowAUCImbalancedPerformanceEvaluator(); evaluator.widthOption.setValue(windowSize); evaluator.setIndex(saIndex); evaluator.prepareForUse(); PrintWriter writer = new PrintWriter(outfile); writer.println("noSamples, DiscData, D_DeprivedPos, D_FavoredPos, D_DeprivedNeg, D_FavoredNeg, DisClassifier, C_DeprivedPos, C_FavoredPos, C_DeprivedNeg, C_FavoredNeg, Acc, prArea_Original, rocArea_Original, F1"); int numberSamples = 0; while (fs.hasMoreInstances()){ InstanceExample trainInstanceExample = fs.nextInstance(); Instance trainInst = trainInstanceExample.instance; numberSamples++; //evaluator window double[] votes = learner.getVotesForInstance(trainInst); evaluator.addResult(trainInstanceExample, votes); learner.trainOnInstance(trainInst); if (numberSamples>=windowSize) { if (numberSamples==windowSize||(numberSamples-windowSize)%10==0){ //evaluation double precision= evaluator.getAucEstimator().getPrecision(); double acc = evaluator.getAucEstimator().getAccuracy(); double recall=evaluator.getAucEstimator().getRecall(); double f1=0; if (precision!=0||recall!=0) f1=2*precision*recall/(precision+recall); double rocArea= evaluator.getAucEstimator().getAUC(); int[] rankedLabels = evaluator.getAucEstimator().getsortedLabels(); Curve curve = new Curve(rankedLabels); double prArea = curve.prArea(); //for calculation of discrimination score String[] labels = evaluator.getAucEstimator().getSAVal(); double[] predictions = evaluator.getAucEstimator().getPredictions(); int[] trueLabels = evaluator.getAucEstimator().getTrueLabel(); double discClassifier=DiscriminationScore(labels,predictions,trueLabels); double discData = Disc_Data(); int saPos_C=tpDeprived+fpDeprived; int saNeg_C=tnDeprived+fnDeprived; int nSaPos_C=tpFavored+fpFavored; int nSaNeg_C=tnFavored+fnFavored; writer.println(numberSamples+","+discData+","+saPos+","+nSaPos+","+saNeg+","+nSaNeg+","+discClassifier+","+saPos_C+","+nSaPos_C+","+saNeg_C+","+nSaNeg_C+","+acc+","+prArea+","+rocArea+","+f1); } } } writer.close(); System.out.println("Done Data"); } public static double DiscriminationScore(String[] labels, double[] predictions, int[] trueLabels){ tpDeprived=0;tnDeprived=0;fnDeprived=0;fpDeprived=0; tpFavored=0;tnFavored=0;fnFavored=0;fpFavored=0; for (int i=0; i<windowSize; i++){ if (labels[i].equals(saVal)){ //Deprived if (predictions[i]==1.0){//correctly predicted if (trueLabels[i]==desiredClass)//positive tpDeprived++; else tnDeprived++; }else{//incorrectly predicted if (trueLabels[i]==desiredClass)//positive => predict to => negative fnDeprived++; else fpDeprived++; } }else{//Favored if (predictions[i]==1.0){//correctly predicted if (trueLabels[i]==desiredClass)//positive tpFavored++; else tnFavored++; }else{//incorrectly predicted if (trueLabels[i]==desiredClass)//positive => predict to => negative fnFavored++; else fpFavored++; } } } saPos=tpDeprived+fnDeprived; saNeg=tnDeprived+fpDeprived; nSaPos=tpFavored+fnFavored; nSaNeg=tnFavored+fpFavored; if ((saPos+saNeg)==0) return 100*(double)(tpFavored+fpFavored)/(double)(nSaPos+nSaNeg); else{ if ((nSaPos+nSaNeg)==0) return -(double)(tpDeprived+fpDeprived)/(double)(saPos+saNeg); else return 100*((double)(tpFavored+fpFavored)/(double)(nSaPos+nSaNeg) -(double)(tpDeprived+fpDeprived)/(double)(saPos+saNeg)); } } public static double Disc_Data(){//DiscriminationScore should be calculated first saPos=tpDeprived+fnDeprived; saNeg=tnDeprived+fpDeprived; nSaPos=tpFavored+fnFavored; nSaNeg=tnFavored+fpFavored; if ((saPos+saNeg)==0) return 100*(double)nSaPos/(double)(nSaPos+nSaNeg); else{ if ((nSaPos+nSaNeg)==0) return -(double)saPos/(double)(saPos+saNeg); else return 100*((double)(nSaPos)/(double)(nSaPos+nSaNeg) -(double)(saPos)/(double)(saPos+saNeg)); } } public static void Statistics(String input, String output) throws FileNotFoundException{ ArffFileStream fs = new ArffFileStream(input, -1); for (int i=0; i<fs.getHeader().numAttributes(); i++){ if (fs.getHeader().attribute(i).name().equals(saName)){ saIndex = i; break; } } fs.prepareForUse(); int dp=0,dn=0,fp=0,fn=0; while (fs.hasMoreInstances()){ InstanceExample trainInstanceExample = fs.nextInstance(); Instance trainInst = trainInstanceExample.instance; String[] splits=trainInst.toString().split(","); if (splits[saIndex].equals(saVal)){ //deprived if (Integer.parseInt(splits[splits.length-1])==desiredClass){//positive dp++; }else dn++; }else{//favored if (Integer.parseInt(splits[splits.length-1])==desiredClass){//positive fp++; }else fn++; } } PrintWriter w=new PrintWriter(output); w.println("dp,dn,fp,fn"); w.println(dp+","+dn+","+fp+","+fn); w.close(); } public static void remove_att(String infile, String outfile, int num) throws FileNotFoundException{ ArffFileStream fs = new ArffFileStream(infile, -1); // fs.prepareForUse(); PrintWriter writer = new PrintWriter(outfile); writer.write(fs.getHeader().toString()); while (fs.hasMoreInstances()){ Instance inst = fs.nextInstance().instance; String[] splits = inst.toString().split(","); String tmp=""; for (int i=0; i<num; i++){ tmp+=splits[i]+","; } for (int i=num+1; i<splits.length; i++){ tmp+=splits[i]+","; } tmp=tmp.substring(0, tmp.length()-1); writer.println(tmp); } writer.close(); } }
true
d22373f060f074c9b1f660f18585385ee10e7f86
Java
tariqmnasim/java-xsd
/src/main/java/com/travellazy/model/RecurringChargeProposal.java
UTF-8
2,219
2.15625
2
[]
no_license
package com.travellazy.model; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * * Attributes of a recurring charge. * * * <p>Java class for RecurringChargeProposal complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="RecurringChargeProposal"> * &lt;complexContent> * &lt;extension base="{http://www.travellazy.com/product/model}AbstractCharge"> * &lt;sequence> * &lt;element name="paymentFrequencyMonths" type="{http://www.w3.org/2001/XMLSchema}long"/> * &lt;element name="chargeInAdvanceMonths" type="{http://www.w3.org/2001/XMLSchema}long"/> * &lt;/sequence> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "RecurringChargeProposal", namespace = "http://www.travellazy.com/product/model", propOrder = { "paymentFrequencyMonths", "chargeInAdvanceMonths" }) public class RecurringChargeProposal extends AbstractCharge { @XmlElement(namespace = "http://www.travellazy.com/product/model") protected long paymentFrequencyMonths; @XmlElement(namespace = "http://www.travellazy.com/product/model") protected long chargeInAdvanceMonths; /** * Gets the value of the paymentFrequencyMonths property. * */ public long getPaymentFrequencyMonths() { return paymentFrequencyMonths; } /** * Sets the value of the paymentFrequencyMonths property. * */ public void setPaymentFrequencyMonths(long value) { this.paymentFrequencyMonths = value; } /** * Gets the value of the chargeInAdvanceMonths property. * */ public long getChargeInAdvanceMonths() { return chargeInAdvanceMonths; } /** * Sets the value of the chargeInAdvanceMonths property. * */ public void setChargeInAdvanceMonths(long value) { this.chargeInAdvanceMonths = value; } }
true
848347e29509ad69d53a9c3a50170263ed1fda75
Java
topcoder-platform/tcs-cronos
/time_tracker_rates/trunk/src/java/tests/com/topcoder/timetracker/rates/accuracytests/InformixRatePersistenceAccuracyTest.java
UTF-8
9,118
2.671875
3
[]
no_license
package com.topcoder.timetracker.rates.accuracytests; import com.topcoder.timetracker.rates.Rate; import com.topcoder.timetracker.rates.persistence.InformixRatePersistence; /** * Accuracy tests for the class: InformixRatePersistence. * * @author kinfkong * @version 3.2 */ public class InformixRatePersistenceAccuracyTest extends AccuracyBase { /** * Represents the instance of InformixRatePersistence for accuracy tests. */ private InformixRatePersistence irp = null; /** * Sets up the test environment. * * @throws Exception to JUnit */ public void setUp() throws Exception { super.setUp(); irp = new InformixRatePersistence("com.topcoder.timetracker.rates.persistence.InformixRatePersistence"); } /** * Removes all the configuration environments. * * @throws Exception to JUnit */ public void tearDown() throws Exception { super.tearDown(); } /** * Accuracy tests for the constructor: InformixRatePersistence. * * Checks if the instance can be constructed. */ public void testInformixRatePersistence() { assertNotNull("The instance cannot be created.", irp); } /** * Accuracy tests for the method: addRates(). * * @throws Exception to JUnit */ public void testAddRates() throws Exception { // creates the rates Rate[] rates = new Rate[10]; for (int i = 0; i < rates.length; i++) { rates[i] = createDefaultRate(i + 1, i + 1); } irp.addRates(rates, false); // check if they are exists for (int i = 0; i < rates.length; i++) { assertTrue("The method: addRates does not work properly.", existsRate(rates[i])); } } /** * Accuracy tests for the method: updateRates. * * @throws Exception to JUnit * */ public void testUpdateRates() throws Exception { // creates the rates Rate[] rates = new Rate[10]; for (int i = 0; i < rates.length; i++) { rates[i] = createDefaultRate(i + 1, i + 1); } irp.addRates(rates, false); for (int i = 0; i < 5; i++) { rates[i].setModificationUser("User who updated it"); } irp.updateRates(rates, false); // check if they are exists for (int i = 0; i < rates.length; i++) { assertTrue("The method: updateRates does not work properly.", existsRate(rates[i])); } } /** * Accuracy tests for the method: deleteRates(). * * @throws Exception to JUnit * */ public void testDeleteRates() throws Exception { // creates the rates Rate[] rates = new Rate[10]; for (int i = 0; i < rates.length; i++) { rates[i] = createDefaultRate(i + 1, i + 1); } irp.addRates(rates, false); Rate[] deletedRates = new Rate[5]; for (int i = 0; i < 5; i++) { deletedRates[i] = rates[i]; } irp.deleteRates(deletedRates, false); // check if they exist for (int i = 0; i < 10; i++) { if (i < 5) { assertFalse("The method: deleted rates does not work properly.", existsRate(rates[i])); } else { assertTrue("The method: deleted rates does not work properly.", existsRate(rates[i])); } } } /** * Accuracy tests for the method: retrieveRate(long, long). * * @throws Exception to JUnit * */ public void testRetrieveRateLongLong() throws Exception { addToRate(); Rate[] rates = new Rate[10]; for (int i = 0; i < 10; i++) { rates[i] = createDefaultRate(i + 1, i + 1); } irp.addRates(rates, false); // retrieve one Rate rate = irp.retrieveRate(3, 3); // check accuracy assertEquals("The method; retrieveRate does not work properly.", "for accuracy tests of 3 3", rate.getDescription()); } /** * Accuracy tests for the method: retrieveRate(long, long). * * @throws Exception to JUnit * */ public void testRetrieveRateLongLong_NotFound() throws Exception { addToRate(); Rate[] rates = new Rate[10]; for (int i = 0; i < 10; i++) { rates[i] = createDefaultRate(i + 1, i + 1); } irp.addRates(rates, false); // retrieve one Rate rate = irp.retrieveRate(30, 30); assertNull("The method: retrieveRate does not work properly.", rate); } /** * Accuracy tests for the method: retrieveRate(String, Long). * * @throws Exception to JUnit */ public void testRetrieveRateStringLong() throws Exception { addToRate(); Rate[] rates = new Rate[10]; for (int i = 0; i < 10; i++) { rates[i] = createDefaultRate(i + 1, i + 1); } irp.addRates(rates, false); // retrieve one Rate rate = irp.retrieveRate("for accuracy tests of 3 3", 3); // check accuracy assertEquals("The method; retrieveRate does not work properly.", "for accuracy tests of 3 3", rate.getDescription()); } /** * Accuracy tests for the method: retrieveRate(String, Long). * * @throws Exception to JUnit */ public void testRetrieveRateStringLong_NotFound() throws Exception { addToRate(); Rate[] rates = new Rate[10]; for (int i = 0; i < 10; i++) { rates[i] = createDefaultRate(i + 1, i + 1); } irp.addRates(rates, false); // retrieve one Rate rate = irp.retrieveRate("for accuracy tests of 3 3", 2); assertNull("The method: retrieveRate(String, long) does not work properly.", rate); } /** * Accuracy tests for the method: retrieveRates. * * @throws Exception to JUnit */ public void testRetrieveRates_One() throws Exception { addToRate(); Rate[] rates = new Rate[10]; for (int i = 0; i < 10; i++) { rates[i] = createDefaultRate(i + 1, i + 1); } irp.addRates(rates, false); // retrieve one Rate[] retrievedRates = irp.retrieveRates(1); assertEquals("The method: retrieveRates does not work properly.", 1, retrievedRates.length); assertEquals("The method: retrieveRates does not work properly.", "for accuracy tests of 1 1", retrievedRates[0].getDescription()); } /** * Accuracy tests for the method: retrieveRates. * * @throws Exception to JUnit */ public void testRetrieveRates_NotFound() throws Exception { addToRate(); Rate[] rates = new Rate[10]; for (int i = 0; i < 10; i++) { rates[i] = createDefaultRate(i + 1, i + 1); } irp.addRates(rates, false); // retrieve one Rate[] retrievedRates = irp.retrieveRates(100); assertEquals("The method: retrieveRates does not work properly.", 0, retrievedRates.length); } /** * Accuracy tests for the method: retrieveRates. * * @throws Exception to JUnit */ public void testRetrieveRates_MoreThanOne() throws Exception { addToRate(); addToRate(101); Rate[] rates = new Rate[10]; for (int i = 0; i < 10; i++) { rates[i] = createDefaultRate(i + 1, i + 1); } irp.addRates(rates, false); for (int i = 0; i < 10; i++) { rates[i] = createDefaultRate(101 + i, i + 1); } irp.addRates(rates, false); // retrieve one Rate[] retrievedRates = irp.retrieveRates(3); assertEquals("The method: retrieveRates does not work properly.", 2, retrievedRates.length); int c = 0; for (int i = 0; i < retrievedRates.length; i++) { if (retrievedRates[i].getDescription().equals("for accuracy tests of 3 3")) { c++; } else if(retrievedRates[i].getDescription().equals("for accuracy tests of 103 3")) { c++; } } assertEquals("The method: retrieveRates does not work properly.", 2, c); } }
true
0a539efa7e0d996427cfc68847afb7664745300d
Java
Simaski17/AppSoinsa-RamaJimmy
/app/src/main/java/app/nh/com/appsoinsa/MyReceiver.java
UTF-8
10,652
1.90625
2
[]
no_license
package app.nh.com.appsoinsa; import android.app.Application; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.net.ConnectivityManager; import android.net.Network; import android.net.NetworkInfo; import android.os.Build; import android.os.Environment; import android.os.Handler; import android.os.PowerManager; import android.util.Log; import com.android.volley.AuthFailureError; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import org.json.JSONObject; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import app.nh.com.appsoinsa.cls.Functions; import app.nh.com.appsoinsa.cls.OutObject; import app.nh.com.appsoinsa.cls.Preobra; import static android.content.Context.POWER_SERVICE; import static app.nh.com.appsoinsa.Login.json; public class MyReceiver extends BroadcastReceiver { public static String dirHome = "/SourceApp/"; public static String fileNameJson = "Objects.json"; public static String jsonData = ""; final static Handler hh = new Handler(); public static OutObject obj = null; public static int i; ConnectivityManager connMgr; android.net.NetworkInfo wifi; android.net.NetworkInfo mobile; Context context; private Handler h = new Handler(); private Runnable r; public MyReceiver() { } @Override public void onReceive(Context context, Intent intent) { desSerialize(); pruebaHilo(); Log.e("TAG", "HOLA BROADCAST"); this.context = context; connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); wifi = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI); //mobile = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); mobile = connMgr.getActiveNetworkInfo(); } public void desSerialize() { Thread th = new Thread(new Runnable() { public void run() { try { //Metodo que realiza una accion que requiere ser llamada en segundo plano u otro Hilo String path = Environment.getExternalStorageDirectory().getAbsolutePath() + dirHome + fileNameJson; File f = new File(path); if(f.exists()) { File file = new File(path); int length = (int) file.length(); byte[] bytes = new byte[length]; FileInputStream in = new FileInputStream(file); try { in.read(bytes); } finally { in.close(); } jsonData = new String(bytes); Log.i("Json Read:" , jsonData); }else{ makeDirectories(path); desSerialize(false); } } catch (Exception e) { e.printStackTrace(); } //Handler que ejecuta el metodo cuando termina el Hilo hh.postDelayed(toObject,3000); } });//end thread th.start(); } final Runnable toObject = new Runnable() { public void run () { GsonBuilder gsonb = new GsonBuilder(); Gson gson = gsonb.create(); JSONObject j; OutObject gig = null; try { j = new JSONObject(jsonData); gig = gson.fromJson(j.toString(), OutObject.class); } catch (Exception e) { e.printStackTrace(); } obj = gig; if (wifi.isAvailable() || mobile.isAvailable()) { postNewComment(context); } /*Intent i = new Intent(SplashScreen.this, Login.class); startActivity(i); finish();*/ } }; public static boolean makeDirectories(String dirPath) throws IOException { String[] pathElements = dirPath.split("/"); if (pathElements != null && pathElements.length > 0) { for (String singleDir : pathElements) { if (!singleDir.equals("")) { String path = Environment.getExternalStorageDirectory().getAbsolutePath() + dirPath; File dir = new File(path); boolean existed = dir.exists(); boolean created = false; if (!existed) { try { created = dir.mkdir(); } catch (Exception ex) { } if (created) { Log.i("CREATED directory: ", singleDir); } else { Log.i("COULD NOT directory: ", singleDir); //return false; } } } } } return true; } public static void desSerialize(boolean a){ OutObject out = new OutObject(); if (a) { out = obj; }else{ List<Preobra> lp = new ArrayList<Preobra>(); Preobra po = new Preobra(); po.setAlias("Ini"); po.setEstadoId("2"); lp.add(po); out.setListObject(lp); } Gson gson = new GsonBuilder().setPrettyPrinting().create(); String json = gson.toJson(out); Log.i("Json Generated: ", json.toString()); try { String path = Environment.getExternalStorageDirectory().getAbsolutePath() + dirHome + fileNameJson; if(makeDirectories(dirHome)) { FileWriter file = new FileWriter(path); file.write(json); file.flush(); file.close(); } } catch (IOException e) { e.printStackTrace(); } } public void postNewComment(Context context){ //mPostCommentResponse.requestStarted(); Log.e("TAG", "POST"); if(obj.getListObject() != null) { List<Preobra> pl = obj.getListObject(); i = 0; for (final Preobra a : pl) { if (a.getEstadoId().equals("0")) { RequestQueue queue = Volley.newRequestQueue(context); StringRequest sr = new StringRequest(Request.Method.POST, "http://200.111.184.243/api/index.php/insert", new Response.Listener<String>() { @Override public void onResponse(String response) { //mPostCommentResponse.requestCompleted(); String respuesta = response.toString(); Log.e("TAG", "Response:%n %s" + respuesta); if (respuesta != null) { String result = ""; List<Preobra> pl2 = obj.getListObject(); int x = 0; for( Preobra b : pl2) { if(b.getIdApp() != null) { if (b.getIdApp().equals(a.getIdApp())) { String aa = a.getIdApp(); String bb = b.getIdApp(); obj.getListObject().get(x).setEstadoId("1"); obj.getListObject().get(x).setIdPreObra(respuesta); } } x++; } desSerialize(true); // i++; } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { //mPostCommentResponse.requestEndedWithError(error); } }) { @Override protected Map<String, String> getParams() { Map<String, String> params = new HashMap<String, String>(); List<Preobra> pl = obj.getListObject(); List<Preobra> secondList = new ArrayList<Preobra>(); for (Preobra a : pl) { if (a.getEstadoId().equals("0")) { Gson gson = new GsonBuilder().setPrettyPrinting().create(); json = gson.toJson(a); } } Log.e("TAG", "AQUIIII: " + json); params.put("json", json); return params; } @Override public Map<String, String> getHeaders() throws AuthFailureError { Map<String, String> params = new HashMap<String, String>(); params.put("Content-Type", "application/x-www-form-urlencoded"); return params; } }; queue.add(sr); } i++; } } } public interface PostCommentResponseListener { public void requestStarted(); public void requestCompleted(); public void requestEndedWithError(VolleyError error); } public void pruebaHilo(){ new Handler().postDelayed(new Runnable() { @Override public void run() { /* * Creamos un Intent que lanzará nuestra Actividad principal (en * nuestro caso Main.java) */ Log.e("TAG","MENSAJE"); postNewComment(context); pruebaHilo(); } }, 10000); } }
true
c7bc4916afdabe1b84fd8457a8583c2b5fa3f47c
Java
sniktawekim/ORB-P
/src/orb/p/OnScreenObjects/MTextBox.java
UTF-8
1,265
2.484375
2
[]
no_license
/* * Here comes the text of your license * Each line should be prefixed with * */ package orb.p.OnScreenObjects; import java.awt.Graphics; import java.awt.image.ImageObserver; import javax.swing.JPanel; import javax.swing.JTextField; import orb.p.listeners.IClick; import orb.p.panels.HostSetupPanel; /** * * @author Michael Watkins */ public class MTextBox extends HudObject { JTextField text; JPanel toPaint; HostSetupPanel paintTo; public MTextBox(int xPos, int yPos, int xSize, int ySize, String imagePath, String aName, HostSetupPanel paintTo, String startText) { super(xPos, yPos, xSize, ySize, imagePath, aName); text = new JTextField(startText, 6); text.setLocation(xPos,yPos); text.setSize(xSize, ySize); this.paintTo = paintTo; paintTo.add(text); text.setOpaque(false); } @Override public void setVisible(boolean visible){ this.visible = visible; if(visible){ paintTo.add(text); text.setOpaque(true); } else { paintTo.remove(text); text.setOpaque(false); } } @Override public void paint(int xOffset, int yOffset, Graphics g, ImageObserver lulz, IClick mouse) { } }
true
860c92b06b8e1ac05688cd912d5cebf702aa32a8
Java
pattch/PolyFi
/src/edge/SobelFilter.java
UTF-8
3,380
3.140625
3
[]
no_license
package edge; import java.awt.image.*; import java.io.*; import java.lang.Math; import javax.imageio.*; public class SobelFilter { static String fileName, outputName; static final String FILE_TYPE_PNG = "png"; static BufferedImage inputFile, outputFile; static int width, height; static File example, result; /* NPU APPROXIMATION START */ public static double sobel(double[][] window) { double x, y, r = 0; x = (window[0][0] + 2 * window[0][1] + window[0][2]); x -= (window[2][0] + 2 * window[2][1] + window[2][2]); y = (window[0][2] + 2 * window[1][2] + window[2][2]); y -= (window[0][0] + 2 * window[1][1] + window[2][0]); r = Math.sqrt((x * x) + (y * y)); if (r > 255.0) r = 0; return r; } /* NPU APPROXIMATION END */ public static void printRGB(int clr) { int red = (clr & 0x00FF0000) >> 16; int green = (clr & 0x0000FF00) >> 8; int blue = (clr & 0x000000FF); System.out.println("Red: " + red + " Green: " + green + " Blue: " + blue); } public static int getGreyScale(int clr) { int red = (clr & 0x00FF0000) >> 16; int green = (clr & 0x0000FF00) >> 8; int blue = (clr & 0x000000FF); if ((red == blue) && (blue == green)) return red; else return -1; } public static int setGreyScaleValue(int clr) { return (clr) + (clr << 8) + (clr << 16); } public static double[][] buildWindow(int x, int y, BufferedImage srcImg) { double[][] retVal = new double[5][5]; for (int ypos = -2; ypos <= 2; ypos++) { for (int xpos = -2; xpos <= 2; xpos++) { int currX = xpos + x; int currY = ypos + y; if ((currX >= 0 && currX < width) && (currY >= 0 && currY < height)) { int rgbRawValue = srcImg.getRGB(currX, currY); int grayScaleValue = getGreyScale(rgbRawValue); retVal[xpos + 2][ypos + 2] = grayScaleValue; } else retVal[xpos + 2][ypos + 2] = 255; } } return retVal; } public static BufferedImage edgeDetection(BufferedImage srcImg) { BufferedImage retVal = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY); double[][] window = new double[3][3]; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { window = buildWindow(x, y, srcImg); // double newValue = sobel(window); double newValue = srcImg.getRGB(x, y); double sobelValue = sobel(window); int sobelRGBValue = setGreyScaleValue((int) sobelValue); int grayScaleMag = getGreyScale((int) newValue); int greyscaleValue = setGreyScaleValue(grayScaleMag); retVal.setRGB(x, y, sobelRGBValue); } } return retVal; } public static BufferedImage getEdgesOfImage(BufferedImage sourceImage) { height = sourceImage.getHeight(); width = sourceImage.getWidth(); return edgeDetection(sourceImage); } public static void main(String[] args) { fileName = "test.png"; outputName = "result.png"; example = new File(fileName); System.out.println(fileName); try { inputFile = ImageIO.read(example); width = inputFile.getWidth(); height = inputFile.getHeight(); outputFile = edgeDetection(inputFile); System.out.println("Success!! Width: " + width + " Height: " + height); } catch (IOException e) { /* DO NOTHING */ } try { result = new File(outputName); ImageIO.write(outputFile, FILE_TYPE_PNG, result); } catch (IOException e) { /* DO NOTHING */ } } }
true
2aaa05d081a88bb47cfe5113634b5bea4472215c
Java
bellmit/fleet-spring-boot
/spring-boot-async/src/main/java/com/fleet/async/controller/TestController.java
UTF-8
1,054
2.546875
3
[]
no_license
package com.fleet.async.controller; import org.springframework.scheduling.annotation.Async; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.annotation.Resource; @RestController public class TestController { @Resource private AsyncTask asyncTask; @RequestMapping("start") public void start() throws Exception { System.out.println("任务开始"); asyncTask.doAsync(); System.out.println("任务结束"); } @RequestMapping("start1") public void start1() throws Exception { System.out.println("任务开始"); doAsync(); System.out.println("任务结束"); } /** * @Async 异步方法不要和同步调用方法写在同一个类中,否则注解时效 */ @Async public void doAsync() throws InterruptedException { System.out.println("执行任务开始"); Thread.sleep(1000 * 10); System.out.println("执行任务结束"); } }
true
cde73145f580106a632665fbbe1b18038e14b5c0
Java
gufanyi/wdp
/src/ehcache/net/sf/ehcache/GroupElement.java
UTF-8
2,993
2.65625
3
[]
no_license
/** * Copyright 2003-2008 Luck Consulting Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.ehcache; import java.util.Collections; import java.util.HashSet; import java.util.Set; /** A special cache Element that holds references to group elements via * its value which can always relied on being a Set of object keys. * This class is intended for use only by Ehcache internally. * @author Andrew Liles * @since 1.7 * */ class GroupElement extends Element { /** * The default key used to store the Master Group. * This is configurable on a per-cache basis, see {@link Cache#setMasterGroupKey(String)} */ public static final String MASTER_GROUP_KEY = "net.sf.ehcache.groups.master"; private static final long serialVersionUID = 66172327024702L; /** Partial constructor intended to make a GroupElement with * the special Set Value. Intended use only by {@link Cache} * @param key */ GroupElement(Object key) { super(key, /* Object value */ makeMemberKeySet(), /* Boolean eternal */ Boolean.TRUE, /* Integer timeToIdleSeconds */ null, /* Integer timeToLiveSeconds */ null); } /** Use with care, GroupElements should only be created by Ehcache * @param key * @param value * @param version * @param creationTime * @param lastAccessTime * @param nextToLastAccessTime * @param lastUpdateTime * @param hitCount */ public GroupElement(Object key, Object value, long version, long creationTime, long lastAccessTime, long nextToLastAccessTime, long lastUpdateTime, long hitCount) { super(key, value, version, creationTime, lastAccessTime, nextToLastAccessTime, lastUpdateTime, hitCount); } /** Obtains all the keys of the members of the group. * This result may be inaccurate, e.g. an element identified * by the key may not longer exist. The canonical * definition of group membership exist within the Element itself, * see {@link Element#getGroupKeys()} * @return a Set of keys; this Set should never be changed */ public Set getMemberKeys() { return (Set) getObjectValue(); } /** Create the value object for a Group Element * @return */ private static Set makeMemberKeySet() { return Collections.synchronizedSet(new HashSet()); } }
true
0c68bee9d46ac4ad6ded208f87bdab6bed86972a
Java
venkat-thota/java-simulations
/aimxcel-common/src/main/java/com/aimxcel/abclearn/common/aimxcelcommon/view/util/ColorFilter.java
UTF-8
370
1.945313
2
[]
no_license
package com.aimxcel.abclearn.common.aimxcelcommon.view.util; import java.awt.Color; import com.aimxcel.abclearn.common.aimxcelcommon.view.util.ColorFilter; public interface ColorFilter { public static final ColorFilter NULL = new ColorFilter() { public Color filter( Color in ) { return in; } }; Color filter( Color in ); }
true
fc42c75c2bcce4aebfb44d64c1582f87c3e9dcdd
Java
github4n/tx-api
/src/main/java/com/cn/tianxia/api/game/impl/IGGameServiceImpl.java
UTF-8
11,420
1.96875
2
[]
no_license
package com.cn.tianxia.api.game.impl; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.util.HashMap; import java.util.Map; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.lang3.StringUtils; import org.apache.http.HttpStatus; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.cn.tianxia.api.utils.DESEncrypt; import com.cn.tianxia.api.utils.FileLog; import com.cn.tianxia.api.utils.PlatFromConfig; import net.sf.json.JSONObject; /** * * @ClassName IGServiceImpl * @Description IG彩票 * @author Hardy * @Date 2019年2月9日 下午4:32:12 * @version 1.0.0 */ public class IGGameServiceImpl{ /* * private static final String * apiurl="http://igyfsw.iasia99.com/igapiyf/app/api.do"; private static * final String hashcode="ttx_2e823371-a192-40db-b8ad-9904edd8"; */ /* * (1)LOGIN命令 (2)CHANGE_PASSWORD命令 (3)GET_BALANCE 命令 (4)DEPOSIT 命令 * (5)WITHDRAW 命令 (6)CHECK_REF命令 */ DESEncrypt d = new DESEncrypt(""); private static String apiurl;// 命令(3) (4) (5) (6)对接地址为 private static String hashcode; private static String line; private static String lotto_url; // 香港彩 命令(1) (2) 对接地址为 private static String lottery_url; // 时时彩 命令(1) (2) 对接地址为 String lotteryTray=null; private static Logger logger = LoggerFactory.getLogger(IGGameServiceImpl.class); public IGGameServiceImpl(Map<String, String> pmap,String cagent) { PlatFromConfig pf = new PlatFromConfig(); pf.InitData(pmap, "IG"); JSONObject jsonObject = new JSONObject().fromObject(pf.getPlatform_config()); JSONObject jo = null; if(jsonObject.containsKey(cagent)){ jo = JSONObject.fromObject(jsonObject.getString(cagent)); }else if(jsonObject.containsKey("ALL")){ jo = JSONObject.fromObject(jsonObject.getString("ALL")); } apiurl = jo.getString("apiurl").toString(); hashcode = jo.getString("hashcode").toString(); lotto_url = jo.getString("lotto_url").toString(); lottery_url = jo.getString("lottery_url").toString(); try { line = jo.getString("line").toString(); } catch (Exception e) { line = "1"; } try{ //获取盘口 lotteryTray=jo.getString("lotteryTray"); }catch(Exception e){ } } public String LoginGame(String username, String password, String gameType, String gameid, String type,String handicap) { logger.info("用户【"+ username +"】调用IG游戏登录业务开始"); password = d.getMd5(password); String data = "{\"hashCode\":\"" + hashcode + "\",\"command\":\"LOGIN\",\"params\":{\"username\":\"" + username + "\",\"password\":\"" + password + "\","; if ("LOTTERY".equals(gameType)) { data += "\"currency\":\"CNY\",\"language\":\"CN\",\"gameType\":\"" + gameType + "\",\"lotteryTray\":\""+handicap+"\",\"lotteryPage\":\"" + gameid + "\",\"userCode\":\"" + username + "\",\"lotteryType\":\"" + type + "\",\"line\":\"" + line + "\",\"lobby\":\"1\"}}"; } else { data += "\"currency\":\"CNY\",\"language\":\"CN\",\"gameType\":\"" + gameType + "\",\"lottoTray\":\""+handicap+"\",\"userCode\":\"" + username + "\",\"lottoType\":\"" + type + "\",\"line\":\"" + line + "\",\"lobby\":\"1\"}}"; } logger.info("用户【"+ username +"】调用IG游戏登录业务,请求参数:{}",data); // 香港彩票 if ("LOTTO".equals(gameType)) { apiurl = lotto_url; } else if ("LOTTERY".equals(gameType)) {// 时时彩 apiurl = lottery_url; } logger.info("用户【"+ username +"】调用IG游戏登录业务,请求地址:{}",apiurl); String msg = sendPost(apiurl, data); if (StringUtils.isBlank(msg)) { logger.error("用户【"+ username +"】调用IG游戏登录业务,发起HTTP请求响应结果为空"); return null; } logger.info("用户【"+ username +"】调用IG游戏登录业务,发起HTTP请求响应结果:{}",msg); JSONObject json = JSONObject.fromObject(msg); if (!"0".equals(json.getString("errorCode"))) { FileLog f = new FileLog(); Map<String, String> map = new HashMap<>(); map.put("apiurl", apiurl); map.put("data", data); map.put("msg", msg); map.put("Function", "LoginGame"); f.setLog("IG", map); } return msg; } public String getBalance(String username, String password) { logger.info("用户【"+ username +"】调用IG游戏查询余额业务开始"); password = d.getMd5(password); // 登录创建账号 String data = "{\"hashCode\":\"" + hashcode + "\",\"command\":\"GET_BALANCE\",\"params\":"; data += "{\"username\":\"" + username + "\",\"password\":\"" + password + "\"}}"; logger.info("用户【"+ username +"】调用IG游戏查询余额,请求地址:{},请求参数:{}",apiurl,data); String msg = sendPost(apiurl, data); JSONObject json = JSONObject.fromObject(msg); if (StringUtils.isBlank(msg)) { logger.error("用户【"+ username +"】调用IG游戏查询余额,发起HTTP请求响应结果为空"); return "error"; } logger.info("用户【"+ username +"】调用IG游戏查询余额,发起HTTP请求响应结果:{}",msg); if (!"0".equals(json.getString("errorCode"))) { FileLog f = new FileLog(); Map<String, String> map = new HashMap<>(); map.put("apiurl", apiurl); map.put("data", data); map.put("msg", msg); map.put("Function", "getBalance"); f.setLog("IG", map); } return msg; } public String DEPOSIT(String username, String password, String billno, String amount) { logger.info("用户【"+ username +"】调用IG游戏上分业务开始,订单号:{}",billno); try { password = d.getMd5(password); // 登录创建账号 String data = "{\"hashCode\":\"" + hashcode + "\",\"command\":\"DEPOSIT\",\"params\":{\"username\":\"" + username + "\",\"password\":\"" + password + "\","; data += "\"ref\":\"" + billno + "\",\"desc\":\"\",\"amount\":\"" + amount + "\"}}"; logger.info("IG转账转出,post请求url"+apiurl+"参数"+data); String msg = sendPost(apiurl, data); if(msg.equals("error")) return "faild"; if (StringUtils.isBlank(msg)) { logger.error("用户【"+ username +"】调用IG游戏上分,订单号【"+billno+"】发起HTTP请求响应结果为空"); return "process"; } logger.info("用户【"+ username +"】调用IG游戏上分,订单号【"+billno+"】发起HTTP请求响应结果:{}",msg); //解析响应结果 JSONObject json = JSONObject.fromObject(msg); logger.info("[IG] HTTP响应上分报文:{}",json); if ("0".equals(json.getString("errorCode"))) { return "success"; } logger.info("[IG] 转账响应状态为失败!返回process再次确认订单状态! IG响应状态:{}",json.getString("errorCode")); } catch (Exception e) { logger.info("[IG] 业务系统错误!",e); } return "process"; } public String WITHDRAW(String username, String password, String billno, String amount) { logger.info("用户【"+ username +"】调用IG游戏下分业务开始,订单号:{}",billno); try { password = d.getMd5(password); // 登录创建账号 String data = "{\"hashCode\":\"" + hashcode + "\",\"command\":\"WITHDRAW\",\"params\":{\"username\":\"" + username + "\",\"password\":\"" + password + "\","; data += "\"ref\":\"" + billno + "\",\"desc\":\"\",\"amount\":\"" + amount + "\"}}"; logger.info("IG转账游戏下分,post请求url"+apiurl+"参数"+data); String msg = sendPost(apiurl, data); if(msg.equals("error")) return "faild"; if (StringUtils.isBlank(msg)) { logger.error("用户【"+ username +"】调用IG游戏下分,订单号【"+billno+"】发起HTTP请求响应结果为空"); return "process"; } logger.info("用户【"+ username +"】调用IG游戏下分,订单号【"+billno+"】发起HTTP请求响应结果:{}",msg); //解析响应结果 JSONObject json = JSONObject.fromObject(msg); logger.info("[IG] HTTP响应下分报文:{}",json); if ("0".equals(json.getString("errorCode"))) { return "success"; } logger.info("[IG] 转账响应状态为失败!返回process再次确认订单状态! IG响应状态:{}",json.getString("errorCode")); } catch (Exception e) { logger.info("[IG] 游戏下分错误:",e.getMessage()); e.printStackTrace(); } return "process"; } public String CHECK_REF(String billno) { logger.info("查询IG游戏转账订单,订单号:{}",billno); // 登录创建账号 String data = "{\"hashCode\":\"" + hashcode + "\",\"command\":\"CHECK_REF\",\"params\":{\"ref\":\"" + billno + "\"}}"; logger.info("查询IG游戏转账订单,post请求url"+apiurl+"参数"+data); try { String msg = sendPost(apiurl, data); if (StringUtils.isBlank(msg)) { logger.error("查询IG游戏转账订单,订单号【"+billno+"】发起HTTP请求响应结果为空"); return "process"; } logger.info("查询IG游戏转账订单,订单号【"+billno+"】发起HTTP请求响应结果:{}",msg); JSONObject json = JSONObject.fromObject(msg); String errorcode = json.getString("errorCode"); if("0".equals(errorcode) || "6614".equals(errorcode)) return "faild"; if("6601".equals(errorcode)) return "success"; if("6617".equals(errorcode)) return "process"; logger.info("[IG]无法识别订单【"+billno+"】 响应的状态码:{}",errorcode); } catch (Exception e) { logger.info(e.getMessage(),e); } return "process"; } /** * 发送请求到server端 * * @param * * @param * @return null发送失败,否则返回响应内容 */ public static String sendPost(String tagUrl, String Data) { // 创建httpclient工具对象 HttpClient client = new HttpClient(); // 创建post请求方法 PostMethod myPost = new PostMethod(tagUrl); String responseString = null; int statusCode=0; try { // 设置请求头部类型 myPost.setRequestHeader("Content-Type", "application/json"); myPost.setRequestHeader("charset", "utf-8"); myPost.setRequestBody(Data); //这里的超时单位是毫秒。这里的http.socket.timeout相当于SO_TIMEOUT 读取时间设置5秒 client.getHttpConnectionManager().getParams().setConnectionTimeout(5000); client.getHttpConnectionManager().getParams().setSoTimeout(10000); // 设置请求体,即xml文本内容,一种是直接获取xml内容字符串,一种是读取xml文件以流的形式 statusCode = client.executeMethod(myPost); if (statusCode == HttpStatus.SC_OK) { InputStream inputStream = myPost.getResponseBodyAsStream(); BufferedReader br = new BufferedReader(new InputStreamReader(inputStream)); StringBuffer stringBuffer = new StringBuffer(); String str = ""; while ((str = br.readLine()) != null) { stringBuffer.append(str); } responseString = stringBuffer.toString(); logger.info("[IG] HTTP请求响应结果:{}",responseString); } else { logger.info("[IG] 发起HTTP请求无效,响应状态值:{}",statusCode); if(String.valueOf(statusCode).startsWith("2")) return null; return "error"; } } catch (Exception e) { logger.error("[IG] 发起HTTP请求错误!",e.getMessage()); e.printStackTrace(); } finally { myPost.releaseConnection(); client.getHttpConnectionManager().closeIdleConnections(0); } return responseString; } }
true
66353002142adbaa7db53cf97c523836efc48f20
Java
RyanTech/QJYS
/qjys_android_code/src/com/rmtech/qjys/ui/qjactivity/DoctorPickActivity.java
UTF-8
16,236
1.757813
2
[ "Apache-2.0" ]
permissive
package com.rmtech.qjys.ui.qjactivity; import java.util.ArrayList; import java.util.List; import org.greenrobot.eventbus.EventBus; import okhttp3.Call; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.google.gson.Gson; import com.hyphenate.chat.EMClient; import com.hyphenate.easeui.adapter.EaseContactAdapter; import com.hyphenate.easeui.domain.EaseUser; import com.hyphenate.easeui.utils.EaseCommonUtils; import com.hyphenate.easeui.widget.EaseSidebar; import com.rmtech.qjys.QjConstant; import com.rmtech.qjys.QjHttp; import com.rmtech.qjys.R; import com.rmtech.qjys.callback.BaseModelCallback; import com.rmtech.qjys.callback.QjHttpCallback; import com.rmtech.qjys.callback.QjHttpCallbackNoParse; import com.rmtech.qjys.event.CaseEvent; import com.rmtech.qjys.model.CaseInfo; import com.rmtech.qjys.model.DoctorInfo; import com.rmtech.qjys.model.gson.MBase; import com.rmtech.qjys.model.gson.MDoctorList; import com.rmtech.qjys.model.gson.MGroupData; import com.rmtech.qjys.utils.DoctorListManager; import com.rmtech.qjys.utils.DoctorListManager.OnGetDoctorInfoCallback; public class DoctorPickActivity extends CaseWithIdActivity { private ListView listView; /** 是否为一个新建的群组 */ protected boolean isCreatingNewGroup; /** 是否为单选 */ private boolean isSignleChecked; private PickContactAdapter contactAdapter; /** group中一开始就有的成员 */ private List<DoctorInfo> exitingMembers; final List<EaseUser> alluserList = new ArrayList<EaseUser>(); private ArrayList<DoctorInfo> selectedDoctorList; // public static final int TYPE_ADD_MEMBERS = 0; // public static final int TYPE_NEW_CASE = 1; // public static final int TYPE_DELETE_MEMBERS = 2; // public static final int TYPE_CHANGE_DOCTOR = 3; public int type = QjConstant.REQUEST_CODE_ADD_DOCTORS; private void onActionFinish() { if (type == QjConstant.REQUEST_CODE_DELETE_DOCTORS) { Toast.makeText(getApplicationContext(), "删除失败!", 1).show(); } else { Toast.makeText(getApplicationContext(), "添加失败!", 1).show(); } } private void loadData() { DoctorListManager.getInstance().getDoctorList(true, new QjHttpCallbackNoParse<MDoctorList>() { @Override public void onError(Call call, Exception e) { Toast.makeText(getApplicationContext(), "服务器拉取医生列表失败!", 1).show(); } @Override public void onResponseSucces(boolean iscache, MDoctorList response) { if (response.ret == 0 && response.data != null && !response.data.isEmpty()) { if (type == QjConstant.REQUEST_CODE_DELETE_DOCTORS) { ArrayList<DoctorInfo> exitingMembers2 = getIntent() .getParcelableArrayListExtra( "selectedDoctorList"); for (DoctorInfo info : exitingMembers2) { EaseUser user = new EaseUser(info.id); EaseCommonUtils.setUserInitialLetter(user); user.setAvatar(info.head); user.setNick(info.name); alluserList.add(user); } contactAdapter = new PickContactAdapter( DoctorPickActivity.this, R.layout.em_row_contact_with_checkbox, alluserList); listView.setAdapter(contactAdapter); } else if (type == QjConstant.REQUEST_CODE_ADD_DOCTORS) { DoctorListManager.initDoctorList(alluserList, response.data); initAdapter(); } else { DoctorListManager.initDoctorList(alluserList, response.data); initAdapter(); if (selectedDoctorList != null) { contactAdapter .updateCheckedList(selectedDoctorList); contactAdapter.notifyDataSetChanged(); } } } else { Toast.makeText(getApplicationContext(), "没有好友!", 1) .show(); } } }); } public static void show(Activity activity, CaseInfo caseinfo, List<DoctorInfo> selectedDoctorList, int type) { Intent intent = new Intent(activity, DoctorPickActivity.class);// setCaseInfo(intent, caseinfo); setCaseId(intent, caseinfo.id); intent.putExtra("type", type); if (selectedDoctorList != null) { intent.putParcelableArrayListExtra("selectedDoctorList", new ArrayList<DoctorInfo>(selectedDoctorList)); } activity.startActivityForResult(intent, type); } // public static void show(Activity activity, String caseid, // List<DoctorInfo> selectedDoctorList) { // Intent intent = new Intent(activity, DoctorPickActivity.class);// // setCaseId(intent, caseid); // intent.putExtra("type", TYPE_ADD_MEMBERS); // if (selectedDoctorList != null) { // intent.putParcelableArrayListExtra("selectedDoctorList", new // ArrayList<DoctorInfo>(selectedDoctorList)); // } // activity.startActivityForResult(intent, // QjConstant.REQUEST_CODE_ADD_DOCTORS); // } @Override protected boolean showTitleBar() { // TODO Auto-generated method stub return true; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.em_activity_group_pick_contacts); type = getIntent().getIntExtra("type", QjConstant.REQUEST_CODE_ADD_DOCTORS); // if (exitingMembers == null) { // exitingMembers = new ArrayList<DoctorInfo>(); // } setTitle("添加讨论组成员"); listView = (ListView) findViewById(R.id.list); ((EaseSidebar) findViewById(R.id.sidebar)).setListView(listView); listView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { CheckBox checkBox = (CheckBox) view.findViewById(R.id.checkbox); checkBox.toggle(); } }); if (type == QjConstant.REQUEST_CODE_CHANGE_DOCTOR) { isSignleChecked = true; selectedDoctorList = getIntent().getParcelableArrayListExtra( "selectedDoctorList"); setRightTitle("保存", new OnClickListener() { @Override public void onClick(View v) { QjHttp.updateAdmin(caseInfo.id, getMembersString(), new BaseModelCallback() { @Override public void onResponseSucces(MBase response) { EventBus.getDefault() .post(new CaseEvent( CaseEvent.TYPE_GROUP_CHANGED)); Intent intent = new Intent(); intent.putParcelableArrayListExtra( "selectedDoctorList", getToBeAddMembers()); setResult(RESULT_OK, intent); finish(); } @Override public void onError(Call call, Exception e) { // TODO Auto-generated method stub onActionFinish(); } }); } }); } else if (type == QjConstant.REQUEST_CODE_DELETE_DOCTORS) { setRightTitle("删除", new OnClickListener() { @Override public void onClick(View v) { QjHttp.deleteMembers(caseInfo.id, getMembersString(), new BaseModelCallback() { @Override public void onResponseSucces(MBase response) { int length = contactAdapter.isCheckedArray.length; for (int i = 0; i < length; i++) { String username = contactAdapter .getItem(i).getUsername(); if (contactAdapter.isCheckedArray[i]) { try { EMClient.getInstance() .groupManager() .removeUserFromGroup( caseInfo.group_id, username); } catch (Exception e) { e.printStackTrace(); } } } EventBus.getDefault() .post(new CaseEvent( CaseEvent.TYPE_GROUP_CHANGED)); setResult(RESULT_OK, new Intent() .putParcelableArrayListExtra( "deleteDoctorList", getToBeAddMembers()));// ("newmembers", finish(); } @Override public void onError(Call call, Exception e) { // TODO Auto-generated method stub onActionFinish(); } }); } }); } else if (type == QjConstant.REQUEST_CODE_ADD_DOCTORS) { exitingMembers = getIntent().getParcelableArrayListExtra( "selectedDoctorList"); setRightTitle("确定", new OnClickListener() { @Override public void onClick(View v) { Log.d("sssssssssss", "setRightTitle onClick"); QjHttp.addMembers(caseInfo, getMembersString(), new QjHttpCallback<MGroupData>() { @Override public void onResponseSucces(MGroupData response) { // if(TextUtils.isEmpty(caseInfo.group_id)) // { // caseInfo.group_id = caseInfo // } // if (response != null && response.data != // null) { EventBus.getDefault() .post(new CaseEvent( CaseEvent.TYPE_GROUP_CHANGED)); Intent intent = new Intent(); intent.putParcelableArrayListExtra( "selectedDoctorList", getToBeAddMembers());// ("newmembers", intent.putExtra("group_id", response.data == null ? "" : response.data.group_id); setResult(RESULT_OK, intent); finish(); // } else { // onActionFinish(); // } } @Override public void onError(Call call, Exception e) { // TODO Auto-generated method stub onActionFinish(); } @Override public MGroupData parseNetworkResponse( String str) throws Exception { // TODO Auto-generated method stub return new Gson().fromJson(str, MGroupData.class); } }); } }); } else { selectedDoctorList = getIntent().getParcelableArrayListExtra( "selectedDoctorList"); setRightTitle("确定", new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(); intent.putParcelableArrayListExtra("selectedDoctorList", getToBeAddMembers());// ("newmembers", setResult(RESULT_OK, intent); finish(); } }); } loadData(); // String groupName = getIntent().getStringExtra("groupName"); // if (groupId == null) {// 创建群组 // isCreatingNewGroup = true; // } else { // // 获取此群组的成员列表 // EMGroup group = // EMClient.getInstance().groupManager().getGroup(groupId); // exitingMembers = group.getMembers(); // } // if (exitingMembers == null) // exitingMembers = new ArrayList<String>(); // 获取好友列表 // final List<EaseUser> alluserList = new ArrayList<EaseUser>(); // for (EaseUser user : // QjHelper.getInstance().getContactList().values()) { // if (!user.getUsername().equals(QjConstant.NEW_FRIENDS_USERNAME) & // !user.getUsername().equals(QjConstant.GROUP_USERNAME) & // !user.getUsername().equals(QjConstant.CHAT_ROOM) & // !user.getUsername().equals(QjConstant.CHAT_ROBOT)) // alluserList.add(user); // } // // 对list进行排序 // Collections.sort(alluserList, new Comparator<EaseUser>() { // // @Override // public int compare(EaseUser lhs, EaseUser rhs) { // if(lhs.getInitialLetter().equals(rhs.getInitialLetter())){ // return lhs.getNick().compareTo(rhs.getNick()); // }else{ // if("#".equals(lhs.getInitialLetter())){ // return 1; // }else if("#".equals(rhs.getInitialLetter())){ // return -1; // } // return lhs.getInitialLetter().compareTo(rhs.getInitialLetter()); // } // // } // }); } protected void initAdapter() { // TODO Auto-generated method stub contactAdapter = new PickContactAdapter(this, R.layout.em_row_contact_with_checkbox, alluserList); listView.setAdapter(contactAdapter); } // /** // * 确认选择的members // * // * @param v // */ // public void save(View v) { // // setResult(RESULT_OK, new Intent().putExtra("newmembers", // // getToBeAddMembers().toArray(new String[0]))); // // getToBeAddMembers().toArray(new // setResult(RESULT_OK, new // Intent().putParcelableArrayListExtra("selectedDoctorList", // getToBeAddMembers()));// ("newmembers", // // String[0]))); // finish(); // } /** * 获取要被添加的成员 * * @return */ private ArrayList<DoctorInfo> getToBeAddMembers() { final ArrayList<DoctorInfo> members = new ArrayList<DoctorInfo>(); int length = contactAdapter.isCheckedArray.length; for (int i = 0; i < length; i++) { String username = contactAdapter.getItem(i).getUsername(); if (contactAdapter.isCheckedArray[i] && !isContainsInExitingMembers(username)) { DoctorListManager.getInstance().getDoctorInfoByHXid(username, new OnGetDoctorInfoCallback() { @Override public void onGet(DoctorInfo info) { members.add(info); } }); } } return members; } private boolean isContainsInExitingMembers(String username) { if (exitingMembers != null) { for (DoctorInfo info : exitingMembers) { if (TextUtils.equals(info.id, username)) { return true; } } } return false; } private String getMembersString() { ArrayList<DoctorInfo> list = getToBeAddMembers(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < list.size(); i++) { sb.append(list.get(i).id); if (i < list.size() - 1) { sb.append(","); } } return sb.toString(); } /** * adapter */ private class PickContactAdapter extends EaseContactAdapter { private boolean[] isCheckedArray; public PickContactAdapter(Context context, int resource, List<EaseUser> users) { super(context, resource, users); isCheckedArray = new boolean[users.size()]; } public void updateCheckedList(ArrayList<DoctorInfo> selectedDoctorList) { for (int i = 0; i < getCount(); i++) { EaseUser easeUser = getItem(i); for (DoctorInfo info : selectedDoctorList) { if (TextUtils.equals(info.id, easeUser.getUsername())) { isCheckedArray[i] = true; break; } } } } @Override public View getView(final int position, View convertView, ViewGroup parent) { View view = super.getView(position, convertView, parent); // if (position > 0) { final String username = getItem(position).getUsername(); // 选择框checkbox final CheckBox checkBox = (CheckBox) view .findViewById(R.id.checkbox); ImageView avatarView = (ImageView) view.findViewById(R.id.avatar); TextView nameView = (TextView) view.findViewById(R.id.name); if (checkBox != null) { if (isContainsInExitingMembers(username)) { checkBox.setButtonDrawable(R.drawable.em_checkbox_bg_gray_selector); } else { checkBox.setButtonDrawable(R.drawable.em_checkbox_bg_selector); } // checkBox.setOnCheckedChangeListener(null); checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { // 群组中原来的成员一直设为选中状态 if (isContainsInExitingMembers(username)) { isChecked = true; checkBox.setChecked(true); } isCheckedArray[position] = isChecked; // 如果是单选模式 if (isSignleChecked && isChecked) { for (int i = 0; i < isCheckedArray.length; i++) { if (i != position) { isCheckedArray[i] = false; } } contactAdapter.notifyDataSetChanged(); } } }); // 群组中原来的成员一直设为选中状态 if (isContainsInExitingMembers(username)) { checkBox.setChecked(true); isCheckedArray[position] = true; } else { checkBox.setChecked(isCheckedArray[position]); } } // } return view; } } public void back(View view) { finish(); } }
true
8c8102ff19b0440734b346f9486b43622fc2a3ad
Java
radislavB/octane-jira-coverage-plugin
/src/main/java/com/microfocus/octane/plugins/configuration/ConfigurationUtil.java
UTF-8
18,283
2.046875
2
[ "Apache-2.0" ]
permissive
package com.microfocus.octane.plugins.configuration; import com.atlassian.jira.component.ComponentAccessor; import com.atlassian.jira.issue.IssueConstant; import com.microfocus.octane.plugins.admin.KeyValueItem; import com.microfocus.octane.plugins.admin.SpaceConfigurationOutgoing; import com.microfocus.octane.plugins.admin.WorkspaceConfigurationOutgoing; import com.microfocus.octane.plugins.descriptors.OctaneEntityTypeDescriptor; import com.microfocus.octane.plugins.descriptors.OctaneEntityTypeManager; import com.microfocus.octane.plugins.rest.RestStatusException; import com.microfocus.octane.plugins.rest.entities.OctaneEntityCollection; import com.microfocus.octane.plugins.rest.query.LogicalQueryPhrase; import com.microfocus.octane.plugins.rest.query.QueryPhrase; import org.apache.commons.lang.StringUtils; import java.io.UnsupportedEncodingException; import java.net.URL; import java.net.URLDecoder; import java.util.*; import java.util.stream.Collectors; public class ConfigurationUtil { private static final String PARAM_SHARED_SPACE = "p"; // NON-NLS public static LocationParts parseUiLocation(String uiLocation) { String errorMsg = null; try { URL url = new URL(uiLocation); int contextPos = uiLocation.toLowerCase().indexOf("/ui"); if (contextPos < 0) { errorMsg = "Location url is missing '/ui' part "; } else { LocationParts parts = new LocationParts(); parts.setBaseUrl(uiLocation.substring(0, contextPos)); Map<String, List<String>> queries = splitQuery(url); if (queries.containsKey(PARAM_SHARED_SPACE)) { List<String> sharedSpaceParamValue = queries.get(PARAM_SHARED_SPACE); if (sharedSpaceParamValue != null && !sharedSpaceParamValue.isEmpty()) { String[] sharedSpaceAndWorkspace = sharedSpaceParamValue.get(0).split("/"); if (sharedSpaceAndWorkspace.length == 2 /*p=1001/1002*/ || sharedSpaceAndWorkspace.length == 1 /*p=1001*/) { try { long spaceId = Long.parseLong(sharedSpaceAndWorkspace[0].trim()); parts.setSpaceId(spaceId); return parts; } catch (NumberFormatException e) { errorMsg = "Space id must be numeric value"; } } else { errorMsg = "Location url has invalid sharedspace/workspace part"; } } } else { errorMsg = "Location url is missing sharedspace id"; } } } catch (Exception e) { errorMsg = "Location contains invalid URL "; } throw new IllegalArgumentException(errorMsg); } private static Map<String, List<String>> splitQuery(URL url) throws UnsupportedEncodingException { final Map<String, List<String>> query_pairs = new LinkedHashMap<String, List<String>>(); final String[] pairs = url.getQuery().split("&"); for (String pair : pairs) { final int idx = pair.indexOf("="); final String key = idx > 0 ? URLDecoder.decode(pair.substring(0, idx), "UTF-8") : pair; if (!query_pairs.containsKey(key)) { query_pairs.put(key, new LinkedList<String>()); } final String value = idx > 0 && pair.length() > idx + 1 ? URLDecoder.decode(pair.substring(idx + 1), "UTF-8") : null; query_pairs.get(key).add(value); } return query_pairs; } public static void validateName(SpaceConfigurationOutgoing sco) { if (StringUtils.isEmpty(sco.getName().trim())) { throw new IllegalArgumentException("Space configuration name is required"); } if (sco.getName().trim().length() > 40) { throw new IllegalArgumentException("Space configuration name exceeds allowed length (40 characters)"); } } public static SpaceConfiguration validateRequiredAndConvertToInternal(SpaceConfigurationOutgoing sco, boolean isNew) { if (StringUtils.isEmpty(sco.getLocation().trim())) { throw new IllegalArgumentException("Location URL is required"); } if (StringUtils.isEmpty(sco.getClientId().trim())) { throw new IllegalArgumentException("Client ID is required"); } if (StringUtils.isEmpty(sco.getClientSecret())) { throw new IllegalArgumentException("Client secret is required"); } LocationParts locationParts = null; try { locationParts = parseUiLocation(sco.getLocation().trim()); sco.setLocation(locationParts.getKey()); //remove from url what's after sharedspace id } catch (Exception e) { throw new IllegalArgumentException(e.getMessage()); } String clientSecret = sco.getClientSecret(); if (isNew) { //validate id is missing if (StringUtils.isNotEmpty(sco.getId())) { throw new IllegalArgumentException("New space configuration cannot contain configuration id"); } sco.setId(UUID.randomUUID().toString()); } else { //validate id is exist if (StringUtils.isEmpty(sco.getId())) { throw new IllegalArgumentException("Configuration id is missing"); } //replace password if required Optional<SpaceConfiguration> opt = ConfigurationManager.getInstance().getSpaceConfigurationById(sco.getId(), true); if (PluginConstants.PASSWORD_REPLACE.equals(clientSecret) && !isNew) { clientSecret = opt.get().getClientSecret(); } } //convert SpaceConfiguration sc = new SpaceConfiguration() .setId(sco.getId()) .setName(sco.getName().trim()) .setLocation(sco.getLocation().trim()) .setLocationParts(locationParts) .setClientId(sco.getClientId().trim()) .setClientSecret(clientSecret); return sc; } public static SpaceConfigurationOutgoing convertToOutgoing(SpaceConfiguration sc) { SpaceConfigurationOutgoing sco = new SpaceConfigurationOutgoing() .setId(sc.getId()) .setName(sc.getName()) .setLocation(sc.getLocation()) .setClientSecret(PluginConstants.PASSWORD_REPLACE) .setClientId(sc.getClientId()); return sco; } public static void doSpaceConfigurationUniquenessValidation(SpaceConfiguration spaceConfiguration, boolean isConnectionTested) { try { validateSpaceNameIsUnique(spaceConfiguration); validateSpaceUrlIsUnique(spaceConfiguration); } catch (IllegalArgumentException ex) { if (isConnectionTested) { throw new IllegalArgumentException("Connection is successful, but the following problem was found: " + ex.getMessage()); } else { throw ex; } } } private static void validateSpaceNameIsUnique(SpaceConfiguration spaceConfiguration) { Optional<SpaceConfiguration> opt = ConfigurationManager.getInstance().getSpaceConfigurations().stream() .filter((s -> !s.getId().equals(spaceConfiguration.getId()) //don't check the same configuration && s.getName().equals(spaceConfiguration.getName()))) .findFirst(); if (opt.isPresent()) { String msg = String.format("Name '%s' is already in use by another space configuration.", spaceConfiguration.getName()); throw new IllegalArgumentException(msg); } } private static void validateSpaceUrlIsUnique(SpaceConfiguration spaceConfiguration) { Optional<SpaceConfiguration> opt = ConfigurationManager.getInstance().getSpaceConfigurations().stream() .filter((s -> !s.getId().equals(spaceConfiguration.getId()) //don't check the same configuration && s.getLocationParts().getKey().equals(spaceConfiguration.getLocationParts().getKey()))) .findFirst(); if (opt.isPresent()) { String msg = String.format("Space location is already defined in space configuration '%s'", opt.get().getName()); throw new IllegalArgumentException(msg); } } public static void validateSpaceConfigurationConnectivity(SpaceConfiguration spaceConfig) { try { OctaneRestManager.getWorkspaces(spaceConfig); } catch (RestStatusException e) { String msg = parseExceptionMessage(e,spaceConfig); throw new IllegalArgumentException(msg); } catch (Exception e) { throw new IllegalArgumentException("Test connection failed: " + e.getMessage()); } } public static String parseExceptionMessage(RestStatusException e, SpaceConfiguration spaceConfig){ if (e.getStatus() == 404 && e.getMessage().contains("SharedSpaceNotFoundException")) { return String.format("Space id '%d' is not exist", spaceConfig.getLocationParts().getSpaceId()); } else { return "Test connection failed: " + e.getMessage(); } } public static WorkspaceConfigurationOutgoing convertToOutgoing(WorkspaceConfiguration wc, Map<String, String> spaceConfigurationId2Name) { WorkspaceConfigurationOutgoing result = new WorkspaceConfigurationOutgoing() .setId(wc.getId()) .setSpaceConfigId(wc.getSpaceConfigurationId()) .setSpaceConfigName(spaceConfigurationId2Name.get(wc.getSpaceConfigurationId())) .setWorkspaceId(Long.toString(wc.getWorkspaceId())) .setWorkspaceName(wc.getWorkspaceName()) .setOctaneUdf(wc.getOctaneUdf()) .setOctaneEntityTypes(wc.getOctaneEntityTypes().stream() .map(typeName -> { OctaneEntityTypeDescriptor desc = OctaneEntityTypeManager.getByTypeName(typeName); return desc == null ? "" : desc.getLabel(); }) .collect(Collectors.toSet())) .setJiraIssueTypes(wc.getJiraIssueTypes()) .setJiraProjects(wc.getJiraProjects()); return result; } public static WorkspaceConfiguration validateRequiredAndConvertToInternal(WorkspaceConfigurationOutgoing wco, boolean isNew) { //validation if (StringUtils.isEmpty(wco.getSpaceConfigId())) { throw new IllegalArgumentException("Space configuration is missing."); } if (StringUtils.isEmpty(wco.getWorkspaceId())) { throw new IllegalArgumentException("Workspace id is missing."); } if (StringUtils.isEmpty(wco.getWorkspaceName())) { throw new IllegalArgumentException("Workspace name is missing."); } if (wco.getOctaneEntityTypes().size() == 0) { throw new IllegalArgumentException("Octane entity types not found for given workspace and udf"); } if (wco.getJiraProjects().size() == 0) { throw new IllegalArgumentException("Jira projects are missing"); } if (wco.getJiraIssueTypes().size() == 0) { throw new IllegalArgumentException("Jira issue types are missing"); } long workspaceId; try { workspaceId = Long.parseLong(wco.getWorkspaceId()); } catch (NumberFormatException e) { throw new IllegalArgumentException("Workspace Id must be numeric value"); } SpaceConfiguration spaceConfiguration = ConfigurationManager.getInstance().getSpaceConfigurationById(wco.getSpaceConfigId(), true).get(); validateSpaceConfigurationConnectivity(spaceConfiguration); validateWorkspace(wco); validateJiraIssuesList(wco); validateJiraProjectKey(wco); if (isNew) { if (StringUtils.isNotEmpty(wco.getId())) { throw new IllegalArgumentException("New workspace configuration cannot contain configuration id"); } wco.setId(UUID.randomUUID().toString()); } else { if (StringUtils.isEmpty(wco.getId())) { throw new IllegalArgumentException("Configuration id is missing"); } } WorkspaceConfiguration wc = new WorkspaceConfiguration() .setId(wco.getId()) .setSpaceConfigurationId(wco.getSpaceConfigId()) .setWorkspaceId(workspaceId) .setWorkspaceName(wco.getWorkspaceName()) .setOctaneUdf(wco.getOctaneUdf()) .setOctaneEntityTypes(wco.getOctaneEntityTypes().stream() .map(label -> OctaneEntityTypeManager.getByLabel(label).getTypeName()) .collect(Collectors.toSet())) .setJiraIssueTypes(new HashSet<>(wco.getJiraIssueTypes())) .setJiraProjects(new HashSet<>(wco.getJiraProjects())); return wc; } private static void validateWorkspace(WorkspaceConfigurationOutgoing wco) { Collection<KeyValueItem> validWorkspaces = getValidWorkspaces(wco.getSpaceConfigId(), wco.getId()); if (validWorkspaces.stream().noneMatch(e -> e.getText().equals(wco.getWorkspaceName()))) { throw new IllegalArgumentException("Workspace is not valid. Either it doesn't exist, it is not reachable/active or it is already used in another workspace configuration"); } } private static void validateJiraProjectKey(WorkspaceConfigurationOutgoing wco) { Collection<KeyValueItem> validProjects = getValidProjects(wco.getId()); if (!validProjects.stream() .map(KeyValueItem::getId) .collect(Collectors.toList()) .containsAll(wco.getJiraProjects())) { throw new IllegalArgumentException("Jira projects list is not valid. The projects are either already used or don't exist"); } } private static void validateJiraIssuesList(WorkspaceConfigurationOutgoing wco) { if (!ComponentAccessor.getConstantsManager().getAllIssueTypeObjects() .stream() .map(IssueConstant::getName) .collect(Collectors.toList()) .containsAll(wco.getJiraIssueTypes())) { throw new IllegalArgumentException("Jira issue types list is not valid"); } } public static Set<String> getOctaneTypesList(WorkspaceConfigurationOutgoing wco, String workspaceId) { String spaceConfigurationId = wco.getSpaceConfigId(); SpaceConfiguration sc = ConfigurationManager.getInstance().getSpaceConfigurationById(spaceConfigurationId, true).get(); List<String> octaneEntityTypes = OctaneRestManager.getSupportedOctaneTypes(sc, Long.parseLong(workspaceId), wco.getOctaneUdf()); return octaneEntityTypes .stream() .map(t -> OctaneEntityTypeManager.getByTypeName(t).getLabel()) .collect(Collectors.toSet()); } public static Collection<KeyValueItem> getValidWorkspaces(String spaceConfigId, String workspaceConfId) { SpaceConfiguration spConfig = ConfigurationManager.getInstance().getSpaceConfigurationById(spaceConfigId, true).get(); Set<Long> usedWorkspaces = getAlreadyUsedWorkspaces(workspaceConfId, spaceConfigId); List<QueryPhrase> conditions = Arrays.asList(new LogicalQueryPhrase("activity_level", 0));//only active workspaces OctaneEntityCollection workspaces = OctaneRestManager.getEntitiesByCondition(spConfig, PluginConstants.SPACE_CONTEXT, "workspaces", conditions, Arrays.asList("id", "name")); return workspaces.getData() .stream() .filter(e -> !usedWorkspaces.contains(Long.valueOf(e.getId()))) .map(e -> new KeyValueItem(e.getId(), e.getName())) .collect(Collectors.toList()); } private static Set<Long> getAlreadyUsedWorkspaces(String currentWsConfigId, String spaceConfigId) { Set<Long> usedWorkspaces = spaceConfigId == null ? new HashSet<>() : ConfigurationManager.getInstance().getWorkspaceConfigurations() .stream() .filter(w -> w.getSpaceConfigurationId().equals(spaceConfigId)) .map(WorkspaceConfiguration::getWorkspaceId) .collect(Collectors.toSet()); if (currentWsConfigId != null) { WorkspaceConfiguration wc = ConfigurationManager.getInstance().getWorkspaceConfigurationById(currentWsConfigId, true).get(); usedWorkspaces.remove(wc.getWorkspaceId()); } return usedWorkspaces; } public static Collection<KeyValueItem> getValidProjects(String workspaceConfId) { Set<String> usedJiraProjects = ConfigurationUtil.getAlreadyUsedJiraProjects(workspaceConfId); return ComponentAccessor.getProjectManager().getProjectObjects() .stream() .filter(e -> !usedJiraProjects.contains(e.getKey())) .map(e -> new KeyValueItem(e.getKey(), e.getKey())).sorted(Comparator.comparing(KeyValueItem::getId)) .collect(Collectors.toList()); } private static Set<String> getAlreadyUsedJiraProjects(String workspaceConfId) { Set<String> usedJiraProjects = ConfigurationManager.getInstance().getWorkspaceConfigurations() .stream() .flatMap(c -> c.getJiraProjects().stream()) .collect(Collectors.toSet()); if (workspaceConfId != null) { WorkspaceConfiguration wc = ConfigurationManager.getInstance().getWorkspaceConfigurationById(workspaceConfId, true).get(); usedJiraProjects.removeAll(wc.getJiraProjects()); } return usedJiraProjects; } }
true
4286c8c4f9ba9a2e99c625f7e07e97d447cb86ce
Java
vinay25788/datastructure-amazonQuestions
/datastructure-amazonQuestions/datastrucuture/src/com/practise/designPattern/ObserverPatteren.java
UTF-8
2,396
3.515625
4
[]
no_license
package com.practise.designPattern; import java.util.ArrayList; import java.util.List; interface Subject { public void register(Observere ob); public void unregister(Observere ob); public void notifyAllOb(); public Object getUpdate(Observere ob); } class MyTopic implements Subject { String name; List<Observere> list; public boolean isChanged = false; public Object Mutex = new Object(); String msg; MyTopic(String name) { this.name = name; list = new ArrayList<>(); } @Override public void register(Observere ob) { // TODO Auto-generated method stub if(ob == null) throw new NullPointerException(); synchronized(Mutex) { this.list.add(ob); } } @Override public void unregister(Observere ob) { // TODO Auto-generated method stub synchronized(Mutex) { list.remove(ob); } } @Override public void notifyAllOb() { List<Observere> obList = null; synchronized(Mutex) { if(!isChanged) { return; } else { obList = this.list; this.isChanged = false; } } for(Observere ob: obList) { ob.update(); } } @Override public Object getUpdate(Observere ob) { // TODO Auto-generated method stub return this.msg; } public void postMessage(String msg) { System.out.println(" msg posted on topic "+msg); this.msg = msg; this.isChanged = true; notifyAllOb(); } } interface ObserverTest { public void update(); public void setSubject(Subject sub); } class Observere implements ObserverTest { String name; Subject sub; public Observere(String name) { this.name =name; } public void update() { String msg = (String)sub.getUpdate(this); if(msg == null) System.out.println(" no new msg "); else System.out.println(" message consumed by "+this.name +" "+msg); } @Override public void setSubject(Subject sub) { // TODO Auto-generated method stub this.sub = sub; } } public class ObserverPatteren { public static void main(String[] args) { MyTopic myTopic = new MyTopic("Software_Engineer"); Observere ob1 = new Observere("test1"); Observere ob2 = new Observere("test2"); Observere ob3 = new Observere("test3"); myTopic.register(ob1); myTopic.register(ob3); myTopic.register(ob2); ob1.setSubject(myTopic); ob2.setSubject(myTopic); ob3.setSubject(myTopic); ob1.update(); myTopic.postMessage("hello"); } }
true
af92ab059d01bdfa43017df799ffe05128bcc4f8
Java
wj159263/Manager-Cloud-Demo
/manager-consumer-user-9000/src/main/java/com/wj/manager/consumer/user/service/feign/interceptor/FeignClientInterceptor.java
UTF-8
1,494
2.59375
3
[]
no_license
package com.wj.manager.consumer.user.service.feign.interceptor; import feign.RequestInterceptor; import feign.RequestTemplate; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import javax.servlet.http.HttpServletRequest; import java.util.Enumeration; /** * feign间调用并向下传递头信息 * 该拦截器可能会频繁被用,所有最好写到一个公共模块。 * 公共模块中得话暂时不用被加载到spring容器,哪个模块要用该拦截器,就@Bean在new出来 */ public class FeignClientInterceptor implements RequestInterceptor { @Override public void apply(RequestTemplate requestTemplate) { //获取request ServletRequestAttributes attributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes(); if(attributes != null) { HttpServletRequest request = attributes.getRequest(); Enumeration<String> headerNames = request.getHeaderNames(); if(headerNames != null){ //遍历,把所有得header向下传 while (headerNames.hasMoreElements()){ String headerName = headerNames.nextElement(); String headerValue = request.getHeader(headerName); //向下传递头信息 requestTemplate.header(headerName,headerValue); } } } } }
true
f29a64f6c3b0afd8dc90c44cf7c9364d97fce93e
Java
humanfly008/001
/stockmanagement/src/com/stream/it/ss/service/webcustom/setting/RenderMenuServiceImpl.java
UTF-8
4,159
2.03125
2
[]
no_license
package com.stream.it.ss.service.webcustom.setting; import java.util.ArrayList; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; import com.stream.it.ss.base.constant.SQLConstantOperType; import com.stream.it.ss.base.constant.SQLConstantWhereType; import com.stream.it.ss.base.databo.SearchBean; import com.stream.it.ss.base.databo.SearchConditionValuesBean; import com.stream.it.ss.hibernate.dao.InquiryDAO; import com.stream.it.ss.hibernate.inquiry.GroupMenuInquiry; import com.stream.it.ss.hibernate.inquiry.SubMenuInquiry; @Service("renderMenuService") public class RenderMenuServiceImpl implements RenderMenuService { private static final Log logger = LogFactory.getLog(RenderMenuServiceImpl.class); //****** dao ***********// @Autowired @Qualifier("functionRanderMenuInquiry") private InquiryDAO inquiryDAO; @Autowired @Qualifier("functionRanderSubMenuInquiry") private InquiryDAO inquirySubMenuDAO; @Autowired @Qualifier("menuMasterInquiry") private InquiryDAO menuMasterInquiryDAO; @Override public List<GroupMenuInquiry> renderMenuByGroup(String gid) throws Exception { List resultDataList = null; try{ List param = new ArrayList(); String gidTemp[] = gid.trim().split(","); for(int i = 0 ;i< gidTemp.length ; i++){ if(gidTemp[i] != "") param.add(gidTemp[i].trim()); } SearchBean searchBean = new SearchBean(); searchBean.setConditionValuesBean(new SearchConditionValuesBean[]{ new SearchConditionValuesBean(SQLConstantWhereType.AND, "G.G_ID",SQLConstantOperType.EQUALS,param.toArray()) }); resultDataList = inquiryDAO.listAll(searchBean); }catch (Exception e) { e.printStackTrace(); logger.error(e); } return resultDataList; } @Override public List<SubMenuInquiry> renderSubMenuByGroup(String func_id) throws Exception { List resultDataList = null; List param = new ArrayList(); try{ if(func_id.startsWith("[")){ String func = func_id.replace("[", " ").replace("]", " "); param.add(func.trim()); } else{ //System.out.println(func_id); String func_idTemp[] = func_id.trim().split(","); for(int i = 0 ;i< func_idTemp.length ; i++){ if(func_idTemp[i] != "") param.add(func_idTemp[i].trim()); } } //F.FUNC_ID SearchBean searchBean = new SearchBean(); searchBean.setConditionValuesBean(new SearchConditionValuesBean[]{ new SearchConditionValuesBean(SQLConstantWhereType.AND, "F.FUNC_ID",SQLConstantOperType.EQUALS,param.toArray()) }); resultDataList = inquirySubMenuDAO.listAll(searchBean); }catch (Exception e) { e.printStackTrace(); logger.error(e); } return resultDataList; } @Override public List renderMenuByFunction(String[]functionList)throws Exception{ List resultDataList = null; try{ List param = new ArrayList(); for(int i = 0 ;i< functionList.length ; i++){ if(functionList[i] != "") param.add(functionList[i].trim()); } SearchBean searchBean = new SearchBean(); searchBean.setConditionValuesBean(new SearchConditionValuesBean[]{ new SearchConditionValuesBean(SQLConstantWhereType.AND, "MENU_ID",SQLConstantOperType.EQUALS,param.toArray()) }); resultDataList = menuMasterInquiryDAO.listAll(searchBean); }catch (Exception e) { e.printStackTrace(); logger.error(e); } return resultDataList; } @Override public List renderMenuByMenu(String mid) throws Exception { // TODO Auto-generated method stub return null; } public InquiryDAO getInquiryDAO() { return inquiryDAO; } public void setInquiryDAO(InquiryDAO inquiryDAO) { this.inquiryDAO = inquiryDAO; } public static Log getLogger() { return logger; } public InquiryDAO getInquirySubMenuDAO() { return inquirySubMenuDAO; } public void setInquirySubMenuDAO(InquiryDAO inquirySubMenuDAO) { this.inquirySubMenuDAO = inquirySubMenuDAO; } }
true
f5ce6d8dd77792a70abe16aeefdfa177a5f3d2af
Java
MaiconCanedo/financas
/src/br/com/caelum/financas/teste/TeteFuncoesJPQL.java
UTF-8
797
2.3125
2
[]
no_license
package br.com.caelum.financas.teste; import java.util.List; import javax.persistence.EntityManager; import br.com.caelum.financas.dao.MovimentacaoDao; import br.com.caelum.financas.modelo.Conta; import br.com.caelum.financas.modelo.TipoMovimentacao; import br.com.caelum.financas.util.JPAUtil; public class TeteFuncoesJPQL { public static void main(String[] args) { EntityManager entityManager = new JPAUtil().getEntityManager(); entityManager.getTransaction().begin(); Conta conta = new Conta(2); MovimentacaoDao dao = new MovimentacaoDao(entityManager); List<Double> medias = dao.getMediasPorDiaETipo(TipoMovimentacao.SAIDA, conta); System.out.println("Média do dia 22: " + medias); entityManager.getTransaction().commit(); entityManager.close(); } }
true
0d366bcb1a2df59af47ca196626bc0dac344ae83
Java
KhosroPakmanesh/EquityMarketSoftwareEcosystem
/project/src/main/java/emSeco/exchangeUnit/core/modules/orderValidationRules/sharedOrderValidationRules/implementations/SharedOrderRoutingInformationValidation.java
UTF-8
1,021
2.203125
2
[ "BSD-3-Clause" ]
permissive
package emSeco.exchangeUnit.core.modules.orderValidationRules.sharedOrderValidationRules.implementations; //#if ExchangeSharedOrderRoutingInformationValidation import emSeco.exchangeUnit.core.entities.order.Order; import emSeco.exchangeUnit.core.modules.orderValidationRules.sharedOrderValidationRules.interfaces.ISharedOrderValidationRule; import emSeco.shared.architecturalConstructs.BooleanResultMessage; import emSeco.shared.architecturalConstructs.OperationMessage; public class SharedOrderRoutingInformationValidation implements ISharedOrderValidationRule { @Override public BooleanResultMessage checkRule(Order order) { if (order.getRoutingInformation().getBrokerId() == null) { return new BooleanResultMessage (false, OperationMessage. Create("The brokerId field is empty or its value is invalid!")); } return new BooleanResultMessage (true, OperationMessage.emptyOperationMessage()); } } //#endif
true