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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
a75c0aee6ce16681f4b6a3232554f85a4a0e72ae | Java | onap/archive-sdc-dcae-d-dt-be-main | /dcaedt_be/src/main/java/org/onap/sdc/dcae/rule/editor/validators/ConditionValidator.java | UTF-8 | 2,984 | 2.015625 | 2 | [
"Apache-2.0"
] | permissive | /*-
* ============LICENSE_START=======================================================
* SDC
* ================================================================================
* Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ============LICENSE_END=========================================================
*/
package org.onap.sdc.dcae.rule.editor.validators;
import org.apache.commons.lang.StringUtils;
import org.onap.sdc.dcae.composition.restmodels.ruleeditor.Condition;
import org.onap.sdc.dcae.errormng.ActionStatus;
import org.onap.sdc.dcae.errormng.ErrConfMgr;
import org.onap.sdc.dcae.errormng.ResponseFormat;
import org.onap.sdc.dcae.rule.editor.enums.OperatorTypeEnum;
import org.onap.sdc.dcae.rule.editor.utils.ValidationUtils;
import java.util.List;
public class ConditionValidator extends BaseConditionValidator<Condition> {
private static ConditionValidator conditionValidator = new ConditionValidator();
public static ConditionValidator getInstance() {
return conditionValidator;
}
private ConditionValidator(){}
@Override
public boolean validate(Condition condition, List<ResponseFormat> errors) {
return validateConditionalAction(condition, errors) && super.validate(condition, errors);
}
public boolean validateConditionalAction(Condition condition, List<ResponseFormat> errors) {
boolean valid = true;
if(!ValidationUtils.validateNotEmpty(condition.getLeft())) {
valid = false;
errors.add(ErrConfMgr.INSTANCE.getResponseFormat(ActionStatus.MISSING_OPERAND, null, "left"));
}
OperatorTypeEnum operatorTypeEnum = StringUtils.isNotEmpty(condition.getOperator()) ? OperatorTypeEnum.getTypeByName(condition.getOperator()) : null;
if(null == operatorTypeEnum) {
valid = false;
String operatorValue = StringUtils.isNotEmpty(condition.getOperator()) ? condition.getOperator() : "empty";
errors.add(ErrConfMgr.INSTANCE.getResponseFormat(ActionStatus.INVALID_OPERATOR, null, operatorValue));
}
if(OperatorTypeEnum.ASSIGNED != operatorTypeEnum && OperatorTypeEnum.UNASSIGNED != operatorTypeEnum && (condition.getRight().isEmpty() || !condition.getRight().stream().allMatch(ValidationUtils::validateNotEmpty))) {
valid = false;
errors.add(ErrConfMgr.INSTANCE.getResponseFormat(ActionStatus.MISSING_OPERAND, null, "right"));
}
return valid;
}
}
| true |
96748422ae25089d69c3fd6d8b3f9db77f5610fc | Java | allmyson/MonitoringApp | /app/src/main/java/com/ys/monitor/util/DateUtil.java | UTF-8 | 12,549 | 2.71875 | 3 | [] | no_license | package com.ys.monitor.util;
import android.text.TextUtils;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
public class DateUtil {
/**
* @return void
* @author 彭粟
* @version 1.0
* @Description: 传入时间戳
* @time: 2016/12/28
*/
public static String getLongDate(String date) {
String resultDate = "";
if (!TextUtils.isEmpty(date)) {
if (!"0".equals(date)) {
try {
long datel = Long.valueOf(date);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
resultDate = sdf.format(new Date(datel));
} catch (Exception e) {
e.printStackTrace();
}
}
}
//Thu Jan 01 08:00:00 GMT+08:00 1970
return resultDate;
}
/**
* @return void
* @author 彭粟
* @version 1.0
* @Description: 传入时间戳
* @time: 2016/12/28
*/
public static String getDateAndMinute(String date) {
String resultDate = "";
if (!TextUtils.isEmpty(date)) {
if (!"0".equals(date)) {
try {
long datel = Long.valueOf(date);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
resultDate = sdf.format(new Date(datel));
} catch (Exception e) {
e.printStackTrace();
}
}
}
//Thu Jan 01 08:00:00 GMT+08:00 1970
return resultDate;
}
/**
* 根据毫秒时间得到日期
*
* @param time
* @return String
* @创建时间:2017年2月16日 下午7:54:31
* @作者: 董杰科
* @描述: TODO
*/
public static String getLongDate(long time) {
if (time == 0) {
return "";
} else {
Date dat = new Date(time);
GregorianCalendar gc = new GregorianCalendar();
gc.setTime(dat);
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
String sb = format.format(gc.getTime());
return sb;
}
}
public static String getLongHM(long time) {
if (time == 0) {
return "";
} else {
Date dat = new Date(time);
GregorianCalendar gc = new GregorianCalendar();
gc.setTime(dat);
SimpleDateFormat format = new SimpleDateFormat("HH:mm");
String sb = format.format(gc.getTime());
return sb;
}
}
/**
* 获取时间戳
*
* @param
* @return String
* @创建时间:2017年2月27日
* @作者: 李杰
* @描述: TODO
*/
public static long getLongTime() {
return System.currentTimeMillis();
}
public static long getTimeYearMString(String time) {
if (TextUtils.isEmpty(time)) {
return 0;
} else {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
long resultTime = 0;
try {
resultTime = format.parse(time).getTime();
} catch (Exception e) {
e.printStackTrace();
}
return resultTime;
}
}
/**
* 根据毫秒时间得到日期
*
* @param time
* @return String
* @创建时间:2017年2月16日 下午7:54:31
* @作者: 董杰科
* @描述: TODO
*/
public static String getLongDate2(long time) {
if (time == 0) {
return "";
} else {
Date dat = new Date(time);
GregorianCalendar gc = new GregorianCalendar();
gc.setTime(dat);
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String sb = format.format(gc.getTime());
return sb;
}
}
public static String getLongDate3(long time) {
if (time == 0) {
return "";
} else {
Date dat = new Date(time);
GregorianCalendar gc = new GregorianCalendar();
gc.setTime(dat);
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
String sb = format.format(gc.getTime());
return sb;
}
}
public static String changeTimeToYMD(String s) {
long time = StringUtil.StringToLong(s);
if (time == 0) {
return "";
} else {
Date dat = new Date(time);
GregorianCalendar gc = new GregorianCalendar();
gc.setTime(dat);
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
String sb = format.format(gc.getTime());
return sb;
}
}
public static String changeTimeToHMS(String time) {
SimpleDateFormat formatter = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ss.SSSZ");
Date date = null;
try {
date = formatter.parse(time);
} catch (Exception e) {
e.printStackTrace();
date = new Date();
}
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm:ss");
String res = simpleDateFormat.format(date);
return res;
}
public static String changeTimeToYMDHMS(String time) {
return getLongDate2(StringUtil.StringToLong(time));
}
public static long changeTimeToLong(String time) {
SimpleDateFormat formatter = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
Date date = null;
try {
date = formatter.parse(time);
} catch (Exception e) {
e.printStackTrace();
date = new Date();
}
return date.getTime();
}
public static long changeTimeToLong2(String time) {
SimpleDateFormat formatter = new SimpleDateFormat(
"yyyy-MM-dd");
Date date = null;
try {
date = formatter.parse(time);
} catch (Exception e) {
e.printStackTrace();
date = new Date();
}
return date.getTime();
}
public static void isBelong() {
SimpleDateFormat df = new SimpleDateFormat("HH:mm");//设置日期格式
Date now = null;
Date beginTime = null;
Date endTime = null;
try {
now = df.parse(df.format(new Date()));
beginTime = df.parse("06:00");
endTime = df.parse("18:21");
} catch (Exception e) {
e.printStackTrace();
}
Boolean flag = belongCalendar(now, beginTime, endTime);
System.out.println(flag);
}
/**
* 判断时间是否在时间段内
*
* @param nowTime
* @param beginTime
* @param endTime
* @return
*/
public static boolean belongCalendar(Date nowTime, Date beginTime, Date endTime) {
Calendar date = Calendar.getInstance();
date.setTime(nowTime);
Calendar begin = Calendar.getInstance();
begin.setTime(beginTime);
Calendar end = Calendar.getInstance();
end.setTime(endTime);
if (date.after(begin) && date.before(end)) {
return true;
} else {
return false;
}
}
/**
* @param start 10:00
* @param end 22:00
* @return
*/
public static boolean isIn(String start, String end) {
SimpleDateFormat df = new SimpleDateFormat("HH:mm");//设置日期格式
Date now = null;
Date beginTime = null;
Date endTime = null;
try {
now = df.parse(df.format(new Date()));
beginTime = df.parse(start);
endTime = df.parse(end);
} catch (Exception e) {
e.printStackTrace();
}
boolean flag = belongCalendar(now, beginTime, endTime);
return flag;
}
//10:00-22:00
public static boolean isTen() {
return isIn("10:00", "22:00");
}
//22:00-02:00
public static boolean isFive() {
return isIn("00:00", "02:00") || isIn("22:00", "23:59");
}
//凌晨2点-早上10点之间不开奖
public static boolean isOpen() {
return !isIn("02:00", "09:59");
}
public static char[] getRemainTime(long saleTime) {
long nowTime = System.currentTimeMillis();
if (saleTime <= nowTime) {
return new char[]{'0', '0', '0', '0', '0', '0'};
}
long free = saleTime - nowTime;
int hour = (int) (free / 1000 / 60 / 60);
int minute = (int) (free / 1000 / 60);
minute = minute - hour * 60;
int second = (int) (free / 1000);
second = second - hour * 60 * 60 - minute * 60;
String hourStr = hour >= 10 ? String.valueOf(hour) : "0" + hour;
String muniteStr = minute >= 10 ? String.valueOf(minute) : "0" + minute;
String secondStr = second >= 10 ? String.valueOf(second) : "0" + second;
String resultStr = hourStr.concat(muniteStr).concat(secondStr);
char[] resultChar = resultStr.toCharArray();
return resultChar;
}
public static String getRemainTime2(long saleTime) {
char[] c = getRemainTime(saleTime);
StringBuilder sb = new StringBuilder();
sb.append(c[2]);
sb.append(c[3]);
sb.append(":");
sb.append(c[4]);
sb.append(c[5]);
return sb.toString();
}
/*
* 将时间戳转换为时间
*/
public static String longToYMD(long s) {
String res;
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date = new Date(s);
res = simpleDateFormat.format(date);
return res;
}
/*
* 将时间转换为时间戳
*/
public static long dateToStamp(String s) {
String res;
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = null;
try {
date = simpleDateFormat.parse(s);
} catch (ParseException e) {
e.printStackTrace();
}
long ts = date.getTime();
return ts;
}
public static long getCurrentDayStart() {
long current = System.currentTimeMillis();
String str = longToYMD(current);
str = str + " 00:00:00";
return dateToStamp(str);
}
public static long getCurrentDayEnd() {
long current = System.currentTimeMillis();
String str = longToYMD(current);
str = str + " 23:59:59";
return dateToStamp(str);
}
public static String getCurrentDayStartStr() {
long current = System.currentTimeMillis();
String str = longToYMD(current);
str = str + " 00:00:00";
return str;
}
public static String getCurrentDayEndStr() {
long current = System.currentTimeMillis();
String str = longToYMD(current);
str = str + " 23:59:59";
return str;
}
/**
* @param str 2018-12-05
* @return
*/
public static long getWhichDayStart(String str) {
return dateToStamp(str + " 00:00:00");
}
public static long getWhichDayEnd(String str) {
return dateToStamp(str + " 23:59:59");
}
//判断选择的日期是否是本周
public static boolean isThisWeek(long time) {
Calendar calendar = Calendar.getInstance();
int currentWeek = calendar.get(Calendar.WEEK_OF_YEAR);
calendar.setTime(new Date(time));
int paramWeek = calendar.get(Calendar.WEEK_OF_YEAR);
if (paramWeek == currentWeek) {
return true;
}
return false;
}
//判断选择的日期是否是今天
public static boolean isToday(long time) {
return isThisTime(time, "yyyy-MM-dd");
}
//判断选择的日期是否是本月
public static boolean isThisMonth(long time) {
return isThisTime(time, "yyyy-MM");
}
private static boolean isThisTime(long time, String pattern) {
Date date = new Date(time);
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
String param = sdf.format(date);//参数时间
String now = sdf.format(new Date());//当前时间
if (param.equals(now)) {
return true;
}
return false;
}
}
| true |
4b0501b85c57fb919751baf2a58cfd3124d909b4 | Java | Zezus/Android_HW_19_Earthquake | /app/src/main/java/com/example/HW_19_Earthquake/EarthquakesBase.java | UTF-8 | 2,264 | 2.3125 | 2 | [] | no_license |
package com.example.HW_19_Earthquake;
import android.os.Parcel;
import android.os.Parcelable;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.util.List;
public class EarthquakesBase implements Parcelable {
public final static Parcelable.Creator<EarthquakesBase> CREATOR = new Creator<EarthquakesBase>() {
@SuppressWarnings({
"unchecked"
})
public EarthquakesBase createFromParcel(Parcel in) {
return new EarthquakesBase(in);
}
public EarthquakesBase[] newArray(int size) {
return (new EarthquakesBase[size]);
}
};
@SerializedName("type")
@Expose
private String type;
@SerializedName("metadata")
@Expose
private Metadata metadata;
@SerializedName("features")
@Expose
private List<Feature> features = null;
@SerializedName("bbox")
@Expose
private List<Double> bbox = null;
protected EarthquakesBase(Parcel in) {
this.type = ((String) in.readValue((String.class.getClassLoader())));
this.metadata = ((Metadata) in.readValue((Metadata.class.getClassLoader())));
in.readList(this.features, (com.example.HW_19_Earthquake.Feature.class.getClassLoader()));
in.readList(this.bbox, (java.lang.Double.class.getClassLoader()));
}
public EarthquakesBase() {
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Metadata getMetadata() {
return metadata;
}
public void setMetadata(Metadata metadata) {
this.metadata = metadata;
}
public List<Feature> getFeatures() {
return features;
}
public void setFeatures(List<Feature> features) {
this.features = features;
}
public List<Double> getBbox() {
return bbox;
}
public void setBbox(List<Double> bbox) {
this.bbox = bbox;
}
public void writeToParcel(Parcel dest, int flags) {
dest.writeValue(type);
dest.writeValue(metadata);
dest.writeList(features);
dest.writeList(bbox);
}
public int describeContents() {
return 0;
}
}
| true |
8713f9e79d78a90e35410ef31d673fc2b010c6d9 | Java | liuyf8688/demos | /hibernate-demos/src/test/java/Test.java | UTF-8 | 875 | 2.5 | 2 | [
"Apache-2.0"
] | permissive | import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class Test {
public static void main(String[] args) throws SQLException {
String url = "jdbc:mysql://127.0.0.1:3306?user=liu%25200&password=123456";
// String url = "jdbc:mysql://mysqlservices.chinacloudapp.cn/sp2p7_zrjk?user=rilidaidbt%25webuser&password=zrwjsdba";
Connection connection = null;
PreparedStatement ps = null;
try {
connection = DriverManager.getConnection(url);
ps = connection.prepareStatement("show databases;");
ResultSet rs = ps.executeQuery();
while (rs.next()) {
System.out.println(rs.getString(1));
}
} finally {
if (ps != null) {
ps.close();
}
if (connection != null) {
connection.close();
}
}
}
}
| true |
6706e1365311b1b1bf3b69c099c2716912306221 | Java | Nobel1893/AndroidBaseApp | /app/src/main/java/bluecrunch/utils/SocialNetworkUtils.java | UTF-8 | 1,227 | 1.9375 | 2 | [] | no_license | package bluecrunch.utils;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
/**
* Created by amrahmed on 3/7/19.
*/
public class SocialNetworkUtils extends FragmentActivity implements GoogleApiClient.OnConnectionFailedListener {
public GoogleApiClient initGoogleApiClient(Context context,String requestIdToken) {
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.requestIdToken(requestIdToken)
.build();
return new GoogleApiClient.Builder(context)
.enableAutoManage(this, this)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
Log.w("google connection error", connectionResult.getErrorMessage());
}
}
| true |
46b0783a96227fd4bd47b8af62c3742c258e866c | Java | eLBirador/yfaces | /yfaces-demo/src/main/java/de/hybris/yfaces/demo/frame/BasicFrame.java | UTF-8 | 332 | 2.296875 | 2 | [
"Apache-2.0"
] | permissive | package de.hybris.yfaces.demo.frame;
import de.hybris.yfaces.component.AbstractYFrame;
public class BasicFrame extends AbstractYFrame {
private String time = null;
public BasicFrame() {
this.time = String.valueOf(System.currentTimeMillis());
}
public String getCreationTime() {
return this.time;
}
}
| true |
13fcc9970ee08d832bd482ba5765572a9cde102b | Java | moutainhigh/desenmall | /desenmall-product/src/main/java/com/desen/desenmall/product/service/SkuSaleAttrValueService.java | UTF-8 | 682 | 1.726563 | 2 | [] | no_license | package com.desen.desenmall.product.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.desen.common.utils.PageUtils;
import com.desen.desenmall.product.entity.SkuSaleAttrValueEntity;
import com.desen.desenmall.product.vo.ItemSaleAttrVo;
import java.util.List;
import java.util.Map;
/**
* sku销售属性&值
*
* @author yangminglin
* @email 240662308@qq.com
* @date 2021-03-21 17:56:46
*/
public interface SkuSaleAttrValueService extends IService<SkuSaleAttrValueEntity> {
PageUtils queryPage(Map<String, Object> params);
List<ItemSaleAttrVo> getSaleAttrsBuSpuId(Long spuId);
List<String> getSkuSaleAttrValuesAsStringList(Long skuId);
}
| true |
2937a0127363cd4d38f5fa95dc6aeea3877f12ad | Java | AlanJacobdev/ProjetRPOO_GroupeB_Alan_Lucas | /src/fourmiliere/Nymphe.java | UTF-8 | 759 | 2.875 | 3 | [] | no_license | package fourmiliere;
import environnement.InformationsFourmiliere;
public class Nymphe extends Etape {
protected int age;
protected final int joursAvantFourmis = 10;
protected Fourmis fourmis;
/**
* Constructeur d'une nymphe.
*
* @param fourmis La fourmis.
*/
public Nymphe(Fourmis fourmis) {
this.age = 0;
this.fourmis = fourmis;
}
@Override
protected Etape next() {
if (age == joursAvantFourmis) {
return new Adulte(this.fourmis);
}
return this;
}
@Override
protected Role getRole() {
return null;
}
@Override
protected void step() {
age++;
}
@Override
protected void renseignerInformations(InformationsFourmiliere infos) {
infos.incrementerNymphes();
}
}
| true |
ba90872e3bbc7b84f35ea05e0e837ae47446a3d6 | Java | ct8356/TimeTrackerApp | /src/com/ct8356/mysecondapp/CustomDialogFragment.java | UTF-8 | 3,341 | 2.390625 | 2 | [] | no_license | package com.ct8356.mysecondapp;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import com.ct8356.mysecondapp.DbContract.Tags;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
//import android.app.DialogFragment;
import android.support.v4.app.DialogFragment;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
public class CustomDialogFragment extends DialogFragment {
List<String> mAllTags;
SharedPreferences mPrefs;
protected Dialog mDialog;
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
//Note how above method used to be an Activity method. Now it is a Fragment method...
//It is automatically called when DialogFragment is created!!!
//(I.e. it is alot like the constructor!)
//BUT, this way is better, because DialogFragment can be in own class! More reusable!
//It can do this, thanks to...
// Use the Builder class for convenient dialog construction
DbHelper dbHelper = new DbHelper(getActivity());
dbHelper.openDatabase();
mAllTags = dbHelper.getAllEntriesColumn(Tags.TABLE_NAME, Tags.TAG);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setItems(mAllTags.toArray(new String[0]), new MyListener());
//builder.setMessage("fire missiles");
//Create the AlertDialog object and return it.
return builder.create();
}
public class MyListener implements DialogInterface.OnClickListener {
@Override
public void onClick(DialogInterface arg0, int which) {
String selectedTag = mAllTags.get(which);
AbstractManagerActivity activity = (AbstractManagerActivity) getActivity();
activity.onDataPass();
}
}
}
//public class CustomDialogBuilder extends AlertDialog.Builder {
// List<String> mAllTags;
// SharedPreferences mPrefs;
// protected Dialog mDialog;
//
// protected CustomDialogBuilder(Context context) {
// super(context);
// DbHelper dbHelper = new DbHelper(context);
// dbHelper.openDatabase();
// mAllTags = dbHelper.getAllEntriesColumn(Tags.TABLE_NAME, Tags.TAG);
// setItems(mAllTags.toArray(new String[0]), new MyListener());
//// mPrefs = context.
//// getSharedPreferences("com.ct8356.mysecondapp", 0);//0 = Context.MODE_PRIVATE
// //mPrefs.getString(DbContract.TAG_NAMES, "StringNotFound");
// mDialog = create();
// mDialog.show();
// }
//
//// AlertDialog.Builder builder = new AlertDialog.Builder(this);
//// AlertDialog dialog = builder.create();
//// dialog.show();
//
// public class MyListener implements DialogInterface.OnClickListener {
// @SuppressLint("NewApi") //CBTL
// @Override
// public void onClick(DialogInterface arg0, int which) {
// //AbstractManagerActivity.this.mSelectedTags = mTags;
// Activity activity = mDialog.getOwnerActivity();
//// SharedPreferences.Editor editor = mPrefs.edit();
// String selectedTag = mAllTags.get(which);
//// editor.putString(DbContract.TAG_NAMES, selectedTag);
//// editor.commit();
// activity.dismissDialog(10); //HARDCODE
//
// }
// }
//
//}
| true |
79f00a5c4dadfb61da53c1401d20d7e05220993f | Java | XiaoMi/mone | /hera-all/hera-app/app-server/src/test/java/com/xiaomi/mone/test/HeraAppEnvControllerTest.java | UTF-8 | 1,246 | 1.929688 | 2 | [
"Apache-2.0"
] | permissive | package com.xiaomi.mone.test;
import com.xiaomi.mone.app.AppBootstrap;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
/**
* @author wtt
* @version 1.0
* @description
* @date 2023/6/15 10:03
*/
@SpringBootTest(classes = AppBootstrap.class)
public class HeraAppEnvControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
public void queryAppEnvByIdTest() throws Exception {
//模拟发送一个请求访问分页查询品牌列表的接口
mockMvc.perform(MockMvcRequestBuilders.get("/hera/app/env/id") //设置请求地址
.param("id", "1")) //设置请求参数
.andExpect(MockMvcResultMatchers.status().isOk()) //断言返回状态码为200
.andDo(MockMvcResultHandlers.print()) //在控制台打印日志
.andReturn(); //返回请求结果
}
}
| true |
54ddf2913f7218b1a18a4276535ba1550c2a6743 | Java | fangke-ray/RVS-OGZ | /rvs2.0/src/com/osh/rvs/action/equipment/DeviceSpareAction.java | UTF-8 | 10,875 | 1.835938 | 2 | [
"Apache-2.0"
] | permissive | package com.osh.rvs.action.equipment;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionManager;
import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import com.osh.rvs.bean.LoginData;
import com.osh.rvs.common.RvsConsts;
import com.osh.rvs.form.equipment.DeviceSpareAdjustForm;
import com.osh.rvs.form.equipment.DeviceSpareForm;
import com.osh.rvs.service.BrandService;
import com.osh.rvs.service.DevicesTypeService;
import com.osh.rvs.service.equipment.DeviceSpareAdjustService;
import com.osh.rvs.service.equipment.DeviceSpareService;
import framework.huiqing.action.BaseAction;
import framework.huiqing.bean.message.MsgInfo;
import framework.huiqing.common.util.CodeListUtils;
import framework.huiqing.common.util.copy.BeanUtil;
import framework.huiqing.common.util.copy.DateUtil;
import framework.huiqing.common.util.validator.Validators;
/**
* 设备工具备品
*
* @author liuxb
*
*/
public class DeviceSpareAction extends BaseAction {
private Logger log = Logger.getLogger(getClass());
private DevicesTypeService devicesTypeService = new DevicesTypeService();
private BrandService brandService = new BrandService();
/**
* 初始化
*
* @param mapping
* @param form
* @param req
* @param res
* @param conn
* @throws Exception
*/
public void init(ActionMapping mapping, ActionForm form, HttpServletRequest req, HttpServletResponse res, SqlSession conn) throws Exception {
log.info("DeviceSpareAction.init start");
DeviceSpareService service = new DeviceSpareService();
// 品名
String nReferChooser = devicesTypeService.getDevicesTypeReferChooser(conn);
req.setAttribute("nReferChooser", nReferChooser);
// 备品种类
req.setAttribute("goDeviceSpareType", CodeListUtils.getSelectOptions("device_spare_type", null, ""));
// 品牌
String brandNameReferChooser = brandService.getOptions(conn);
req.setAttribute("brandNameReferChooser", brandNameReferChooser);
// 计算开始时期,“起”的默认值为当前日期一个月前
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_MONTH, -30);
req.setAttribute("startDate", DateUtil.toString(cal.getTime(), DateUtil.DATE_PATTERN));
// 管理理由
req.setAttribute("goManageReasonType", CodeListUtils.getSelectOptions("device_spare_adjust_manage_reason_type", null, ""));
// 设备工具备品总价
req.setAttribute("totalPrice", service.calculatePrice(conn));
LoginData user = (LoginData) req.getSession().getAttribute(RvsConsts.SESSION_USER);
String privacy = "";
// 设备管理员
if(user.getPrivacies().contains(RvsConsts.PRIVACY_TECHNOLOGY)){
privacy = "technology";
}
req.setAttribute("privacy", privacy);
// 迁移到页面
actionForward = mapping.findForward(FW_INIT);
log.info("DeviceSpareAction.init end");
}
/**
* 检索
*
* @param mapping
* @param form
* @param req
* @param res
* @param conn
* @throws Exception
*/
public void search(ActionMapping mapping, ActionForm form, HttpServletRequest req, HttpServletResponse res, SqlSession conn) throws Exception {
log.info("DeviceSpareAction.search start");
// Ajax回馈对象
Map<String, Object> listResponse = new HashMap<String, Object>();
List<MsgInfo> errors = new ArrayList<MsgInfo>();
DeviceSpareService service = new DeviceSpareService();
List<DeviceSpareForm> list = service.search(form, conn);
// 设备工具备品总价
Map<String, Integer> map = service.calculatePrice(conn);
listResponse.put("totalPrice", map);
listResponse.put("spareList", list);
listResponse.put("errors", errors);
// 返回Json格式响应信息
returnJsonResponse(res, listResponse);
log.info("DeviceSpareAction.search end");
}
/**
* 新建设备工具备品
*
* @param mapping
* @param form
* @param req
* @param res
* @param conn
* @throws Exception
*/
public void doInsert(ActionMapping mapping, ActionForm form, HttpServletRequest req, HttpServletResponse res, SqlSessionManager conn) throws Exception {
log.info("DeviceSpareAction.doInsert start");
// Ajax回馈对象
Map<String, Object> listResponse = new HashMap<String, Object>();
DeviceSpareForm dviceSpareForm = (DeviceSpareForm) form;
// 备品种类
String deviceSpareType = dviceSpareForm.getDevice_spare_type();
Validators v = BeanUtil.createBeanValidators(dviceSpareForm, BeanUtil.CHECK_TYPE_ALL);
if ("1".equals(deviceSpareType)) {// 消耗备品
v.delete("location");
} else if ("2".equals(deviceSpareType)) {// 备件
v.delete("order_cycle");
}
List<MsgInfo> errors = v != null ? v.validate() : new ArrayList<MsgInfo>();
if (errors.size() == 0) {
DeviceSpareService service = new DeviceSpareService();
// 新建设备工具备品
service.insert(dviceSpareForm, conn, req, errors);
}
listResponse.put("errors", errors);
// 返回Json格式响应信息
returnJsonResponse(res, listResponse);
log.info("DeviceSpareAction.doInsert end");
}
/**
* 取消管理
*
* @param mapping
* @param form
* @param req
* @param res
* @param conn
* @throws Exception
*/
public void doCancelManage(ActionMapping mapping, ActionForm form, HttpServletRequest req, HttpServletResponse res, SqlSessionManager conn) throws Exception {
log.info("DeviceSpareAction.doCancel start");
// Ajax回馈对象
Map<String, Object> listResponse = new HashMap<String, Object>();
Validators v = BeanUtil.createBeanValidators(form, BeanUtil.CHECK_TYPE_PASSEMPTY);
List<MsgInfo> errors = v != null ? v.validate() : new ArrayList<MsgInfo>();
if (errors.size() == 0) {
DeviceSpareService service = new DeviceSpareService();
service.canceManage(form, req, conn);
}
listResponse.put("errors", errors);
// 返回Json格式响应信息
returnJsonResponse(res, listResponse);
log.info("DeviceSpareAction.doCancel end");
}
/**
* 盘点
*
* @param mapping
* @param form
* @param req
* @param res
* @param conn
* @throws Exception stock
*/
public void doStock(ActionMapping mapping, ActionForm form, HttpServletRequest req, HttpServletResponse res, SqlSessionManager conn) throws Exception {
log.info("DeviceSpareAction.doStock start");
// Ajax回馈对象
Map<String, Object> listResponse = new HashMap<String, Object>();
Validators v = BeanUtil.createBeanValidators(form, BeanUtil.CHECK_TYPE_PASSEMPTY);
v.add("adjust_inventory", v.required("修正有效库存"));
v.add("comment", v.required("调整备注"));
List<MsgInfo> errors = v != null ? v.validate() : new ArrayList<MsgInfo>();
if (errors.size() == 0) {
DeviceSpareService service = new DeviceSpareService();
service.stock(form, req, conn);
}
listResponse.put("errors", errors);
// 返回Json格式响应信息
returnJsonResponse(res, listResponse);
log.info("DeviceSpareAction.doStock end");
}
/**
* 详细
*
* @param mapping
* @param form
* @param req
* @param res
* @param conn
* @throws Exception
*/
public void detail(ActionMapping mapping, ActionForm form, HttpServletRequest req, HttpServletResponse res, SqlSession conn) throws Exception {
log.info("DeviceSpareAction.detail start");
// Ajax回馈对象
Map<String, Object> listResponse = new HashMap<String, Object>();
Validators v = BeanUtil.createBeanValidators(form, BeanUtil.CHECK_TYPE_PASSEMPTY);
List<MsgInfo> errors = v != null ? v.validate() : new ArrayList<MsgInfo>();
if (errors.size() == 0) {
DeviceSpareService service = new DeviceSpareService();
DeviceSpareForm deviceSpareForm = service.getDeviceSpare(form, conn);
DeviceSpareAdjustService deviceSpareAdjustService = new DeviceSpareAdjustService();
// 调整记录
List<DeviceSpareAdjustForm> adjustList = deviceSpareAdjustService.searchAdjustRecord(form, conn);
listResponse.put("deviceSpareForm", deviceSpareForm);
listResponse.put("adjustList", adjustList);
}
listResponse.put("errors", errors);
// 返回Json格式响应信息
returnJsonResponse(res, listResponse);
log.info("DeviceSpareAction.detail end");
}
/**
* 更新
*
* @param mapping
* @param form
* @param req
* @param res
* @param conn
* @throws Exception
*/
public void doUpdate(ActionMapping mapping, ActionForm form, HttpServletRequest req, HttpServletResponse res, SqlSessionManager conn) throws Exception {
log.info("DeviceSpareAction.doUpdate start");
// Ajax回馈对象
Map<String, Object> listResponse = new HashMap<String, Object>();
DeviceSpareForm dviceSpareForm = (DeviceSpareForm) form;
// 备品种类
String deviceSpareType = dviceSpareForm.getDevice_spare_type();
Validators v = BeanUtil.createBeanValidators(form, BeanUtil.CHECK_TYPE_ALL);
v.delete("available_inventory");
if ("1".equals(deviceSpareType)) {// 消耗备品
v.delete("location");
} else if ("2".equals(deviceSpareType)) {// 备件
v.delete("order_cycle");
}
List<MsgInfo> errors = v != null ? v.validate() : new ArrayList<MsgInfo>();
if (errors.size() == 0) {
DeviceSpareService service = new DeviceSpareService();
service.update(form, conn);
}
listResponse.put("errors", errors);
// 返回Json格式响应信息
returnJsonResponse(res, listResponse);
log.info("DeviceSpareAction.doUpdate end");
}
/**
* 管理
*
* @param mapping
* @param form
* @param req
* @param res
* @param conn
* @throws Exception
*/
public void doManage(ActionMapping mapping, ActionForm form, HttpServletRequest req, HttpServletResponse res, SqlSessionManager conn) throws Exception {
log.info("DeviceSpareAction.doUpdate start");
// Ajax回馈对象
Map<String, Object> listResponse = new HashMap<String, Object>();
DeviceSpareForm dviceSpareForm = (DeviceSpareForm) form;
// 理由
String reasonType = dviceSpareForm.getReason_type();
Validators v = BeanUtil.createBeanValidators(form, BeanUtil.CHECK_TYPE_PASSEMPTY);
v.add("reason_type", v.required("理由"));
v.add("adjust_inventory", v.required("数量"));
if (!"11".equals(reasonType)) {// 除“入库”外,必须填写“调整备注”
v.add("comment", v.required("调整备注"));
}
List<MsgInfo> errors = v != null ? v.validate() : new ArrayList<MsgInfo>();
if (errors.size() == 0) {
DeviceSpareService service = new DeviceSpareService();
service.manage(form, req, conn, errors);
}
listResponse.put("errors", errors);
// 返回Json格式响应信息
returnJsonResponse(res, listResponse);
log.info("DeviceSpareAction.doUpdate end");
}
}
| true |
0c24ef62c5617f5ed4aea4bc18b6a94f6ddc5259 | Java | Tatsinnit/P | /Src/PRuntimes/PSymbolicRuntime/src/main/java/psymbolic/commandline/Program.java | UTF-8 | 413 | 2.015625 | 2 | [
"MIT"
] | permissive | package psymbolic.commandline;
import psymbolic.runtime.Event;
import psymbolic.runtime.machine.Monitor;
import psymbolic.runtime.scheduler.Scheduler;
import psymbolic.runtime.machine.Machine;
import java.util.List;
import java.util.Map;
public interface Program {
Machine getStart();
void setScheduler(Scheduler s);
Map<Event, List<Monitor>> getMonitorMap();
List<Monitor> getMonitorList();
}
| true |
fb535424a3abb952e4b912c919403116d4059f2f | Java | tombenko/CrossWordMaker | /sources/old/Square.java | UTF-8 | 1,940 | 4 | 4 | [] | no_license | import java.lang.Character;
class Square{
/**
* This class describes a square in a crossword. It has a letter
* written in, possibly a number (with any meaning) and maybe lines
* round of it. Because there can be only one letter in a square,
* it's enough to declare it as char. The numbers are usually under
* 100, but in special cases, eg. giant crosswords can have more, so
* it is good to be int. The border lines are just a true/false in-
* formation, therefore they are stored in a boolean array.
* **/
public static final short RIGHT = 0; //These two values are for
public static final short BOTTOM = 1; //seting the bold sidelines.
private char letter;
private int number;
private boolean[] sideLine = {false, false};
Square(){
/**
* The normal constructor. The letter written into is a simple
* emptiness.
* */
letter = ' ';
number = 0;
}
Square(char letter){
this.letter = letter;
this.number = 0;
}
public void setLetter(char letter){
/**
* Sets the letter written into the square. Capital letters are
* more readable, so all the letters changed to this shape.
* */
this.letter = Character.toUpperCase(letter);
}
public char getLetter(){
/**
* Returns the letter written into.
* */
return letter;
}
public void setNumber(int number){
/**
* Sets the number of the square.
* */
this.number = number;
}
public int getNumber(){
/**
* Returns the sqares number.
* */
return number;
}
public void toggleSideLine(short which){
/**
* The which parameter is described above. For sure we take the
* modulo 2 remains of the given parameter for not slipping out
* of the array bounds.
* */
which %= 2;
this.sideLine[which] ^= true;
}
public boolean[] getSideLine(){
/**
* Returns the border lines existence.
* */
return sideLine;
}
}
| true |
a56eef1457a7542296737fb6fa37c1fc6bbd7f0b | Java | rquintao/RPG-Java-CommandLine | /src/main/java/com/throwner/engine/character/CharacterFactory.java | UTF-8 | 139 | 2 | 2 | [] | no_license | package com.throwner.engine.character;
public interface CharacterFactory {
public GenericCharacter createCharacter(CharacterType c);
}
| true |
9f52a10c4a61e1ed46b743cefb33f20810a0815a | Java | thock321/CombatScript | /src/org/scripts/combat/util/AutomaticPathMaker.java | UTF-8 | 1,936 | 3.1875 | 3 | [
"LicenseRef-scancode-other-permissive"
] | permissive | package org.scripts.combat.util;
import java.util.LinkedList;
import java.util.List;
import org.powerbot.core.script.job.Container;
import org.powerbot.core.script.job.LoopTask;
import org.powerbot.game.api.methods.Calculations;
import org.powerbot.game.api.methods.interactive.Players;
import org.powerbot.game.api.wrappers.Tile;
/**
* An automatic path maker.
* @author Thock321
*
*/
public class AutomaticPathMaker {
private static final int DISTANCE_INTERVAL = 5;
private List<Tile> tilePath = new LinkedList<Tile>();
private static abstract class PathMakerLoopTask extends LoopTask {
protected boolean stop = false;
}
private PathMakerLoopTask loopTask;
/**
* Starts creating a path and adding a loop task for it using the specified container.
* @param container The container.
*/
public void startMakingPath(Container container) {
tilePath.add(Players.getLocal().getLocation());
loopTask = new PathMakerLoopTask() {
@Override
public int loop() {
if (!stop) {
if (Calculations.distance(tilePath.get(tilePath.size() - 1), Players.getLocal().getLocation()) >= DISTANCE_INTERVAL) {
tilePath.add(Players.getLocal().getLocation());
}
} else {
interrupt();
}
return 50;
}
};
container.submit(loopTask);
}
/**
* Gets the path generated.
* @return The path.
*/
public Tile[] getPath() {
Tile[] path = new Tile[tilePath.size()];
return tilePath.toArray(path);
}
/**
* Sets whether or not for the path maker to stop.
* @param stop Whether or not the path maker stops.
*/
public void setStop(boolean stop) {
loopTask.stop = stop;
}
/**
* Checks whether or not the path maker is running.
* @return <code>true</code> if running, otherwise <code>false</code>.
*/
public boolean isRunning() {
return !loopTask.stop;
}
/**
* Resets the tile path.
*/
public void reset() {
tilePath.clear();
}
}
| true |
6b6ce8f985df0bae54cfb2a5cd5c9dc3a42215ce | Java | jason9075/Android-Ttd-Playground | /app/src/test/java/com/jason9075/androidttdplayground/bank/MoneyTest.java | UTF-8 | 488 | 2.6875 | 3 | [] | no_license | package com.jason9075.androidttdplayground.bank;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
/**
* Created by jason9075 on 2016/3/14.
*/
public class MoneyTest {
@Test
public void MoneyAddTest() throws Exception {
Money money = new Money(10, "TWD");
assertEquals(new Money(20, "TWD"), money.addMoney(money));
assertNotEquals(new Money(21, "TWD"), money.addMoney(money));
}
}
| true |
07b730a27de687f1dd8717f3c74e2fd88e0c255b | Java | numberone0001/mp3player | /app/src/main/java/com/example/app/ui/main/SongTab.java | UTF-8 | 2,595 | 2.03125 | 2 | [] | no_license | package com.example.app.ui.main;
import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import com.example.app.R;
import com.google.android.material.snackbar.Snackbar;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
public class SongTab extends Fragment {
private ArrayList<Song> songList;
public SongTab(ArrayList<Song> songs) {
super();
// Song song = new Song();
// song.setDuration("3:06");
// song.setName("Numb");
// song.setArtist("Linkin Park");
// songList = new ArrayList<Song>();
// songList.add(song);
songList = songs;
}
public void setSongList(ArrayList<Song> songs) {
songList = songs;
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View view = inflater.inflate(R.layout.songpage_layout, container, false);
ListView songListView = view.findViewById(R.id.songListView); //Objects.requireNonNull(getView()).findViewById(R.id.songListView);
SongListviewAdapter adapter = new SongListviewAdapter(this.getActivity(), R.layout.songlistview_item_layout, songList);
songListView.setAdapter(adapter);
Button refreshButton = view.findViewById(R.id.refreshButton);
refreshButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (Objects.requireNonNull(getActivity()).checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1001);
}
if (Objects.requireNonNull(getActivity()).checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1234);
}
setSongList((new SongRetriever()).getSongList());
}
});
return view;
}
}
| true |
a6a323d954429ff6d01de08e3c3d10b3a057c452 | Java | IupyterAaron/SGCC_WHS_V-1.0.0 | /src/Out.java | UTF-8 | 1,078 | 1.914063 | 2 | [] | no_license | package com.sgcc.entity;
public class Out {
private long outid;
private long projectid;
private java.sql.Date outdate;
private String starter;
private String picker;
private String outprice;
public long getOutid() {
return outid;
}
public void setOutid(long outid) {
this.outid = outid;
}
public long getProjectid() {
return projectid;
}
public void setProjectid(long projectid) {
this.projectid = projectid;
}
public java.sql.Date getOutdate() {
return outdate;
}
public void setOutdate(java.sql.Date outdate) {
this.outdate = outdate;
}
public String getStarter() {
return starter;
}
public void setStarter(String starter) {
this.starter = starter;
}
public String getPicker() {
return picker;
}
public void setPicker(String picker) {
this.picker = picker;
}
public String getOutprice() {
return outprice;
}
public void setOutprice(String outprice) {
this.outprice = outprice;
}
}
| true |
7c6461a8cdf909a111399efddabca0899d3662db | Java | theG8/rummikuboberflaeche | /app/src/main/java/de/g8keeper/rummikuboberflaeche/GamesAdapter.java | UTF-8 | 3,216 | 2.453125 | 2 | [] | no_license | package de.g8keeper.rummikuboberflaeche;
import android.app.Activity;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;
import de.g8keeper.rummikub.Game;
public class GamesAdapter extends ArrayAdapter<Game> {
private static final String TAG = GamesAdapter.class.getSimpleName();
private int resourceView;
private Context context;
private List<Game> mGames;
private boolean[] mCheckedStates;
private boolean mCheckable;
@Override
public void notifyDataSetChanged() {
if (mCheckedStates.length != mGames.size()){
mCheckedStates = new boolean[mGames.size()];
}
super.notifyDataSetChanged();
}
public void setCheckable(boolean flag){
mCheckable = flag;
}
public void setItemChecked(int itemID, boolean checked){
mCheckedStates[itemID] = checked;
}
public GamesAdapter(@NonNull Context context, int resource, @NonNull List<Game> objects) {
super(context, resource, objects);
this.resourceView = resource;
this.context = context;
this.mGames = objects;
mCheckedStates = new boolean[mGames.size()];
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
convertView = ((Activity) context).getLayoutInflater().inflate(resourceView,parent,false);
Log.d(TAG, "getView: ");
TextView tvStatus = convertView.findViewById(R.id.li_games_tv_status);
TextView tvTitle = convertView.findViewById(R.id.li_games_tv_title);
TextView tvId = convertView.findViewById(R.id.li_games_tv_id);
ImageView ivCheck = convertView.findViewById(R.id.li_games_iv_check);
if(mCheckable) {
ivCheck.setVisibility(View.VISIBLE);
if (mCheckedStates[position]) {
// erst ab level 23
// ivCheck.setImageDrawable(getContext().getDrawable(android.R.drawable.checkbox_on_background));
// für tablet
ivCheck.setImageDrawable(ContextCompat.getDrawable(getContext(),android.R.drawable.checkbox_on_background));
} else {
// ivCheck.setImageDrawable(getContext().getDrawable(android.R.drawable.checkbox_off_background));
ivCheck.setImageDrawable(ContextCompat.getDrawable(getContext(),android.R.drawable.checkbox_off_background));
}
} else {
ivCheck.setVisibility(View.INVISIBLE);
}
Game game = mGames.get(position);
tvTitle.setText(game.getTitle());
tvId.setText("ID: " + game.getId() + " players: " + game.getPlayers());
String[] state = context.getResources().getStringArray(R.array.game_status);
tvStatus.setText(state[game.state()]);
return convertView;
}
}
| true |
253fdb843eedb638bda7a4a0d40ae0f4b892e658 | Java | HoorayLee/BookGuidance | /src/com/example/book1/MainActivity.java | UTF-8 | 2,601 | 2.140625 | 2 | [] | no_license | package com.example.book1;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketTimeoutException;
import android.os.Bundle;
import android.os.StrictMode;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.Intent;
import android.telephony.TelephonyManager;
import android.util.AttributeSet;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button Btn1 = (Button)findViewById(R.id.button1);//��ȡ��ť��Դ
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads()
.detectDiskWrites()
.detectNetwork() // or .detectAll() for all detectable problems
.penaltyLog()
.build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
.detectLeakedSqlLiteObjects()
.detectLeakedClosableObjects()
.penaltyLog()
.penaltyDeath()
.build());
Btn1.setOnClickListener(new Button.OnClickListener(){//��������
@Override
public void onClick(View arg0) {
String account=((EditText) findViewById(R.id.editText1)).getText().toString();
String password=((EditText) findViewById(R.id.editText2)).getText().toString();
login(account, password);
User.account=account;
}
});
}
public void login(String account, String password)
{
User user=new User();
user.setAccount(account);
user.setPassword(password);
user.setOperation(3);
String b;
//int a=1;
thread.run(user);
b=thread.ret();
//��½�ɹ�
if(b.equals("yeah")){
Intent intent = new Intent();
intent.setClass(MainActivity.this, act1.class);
startActivity(intent); // TODO Auto-generated method stub
}else {
setTitle(b);
Toast.makeText(this, "wrong password/acount!", Toast.LENGTH_SHORT).show();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
| true |
0b34aa26eb292e428c265d9f14356ec2b9005ff9 | Java | guneetnagia/CoreJava | /src/online/UniqueProduct.java | UTF-8 | 1,217 | 3.734375 | 4 | [] | no_license | package online;
import java.util.LinkedHashMap;
import java.util.Map;
public class UniqueProduct {
public static String firstUniqueProduct(String[] products) {
/*
* return Stream.of(products)
* .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
* .entrySet() .stream() .filter(entry->entry.getValue() ==1) .findFirst()
* .map(Map.Entry::getKey) .orElse(null);
*/
Integer ZERO = 0; // to avoid repeated autoboxing below
final LinkedHashMap<String, Integer> map = new LinkedHashMap<>(products.length);
// build the map
for (String s : products) {
Integer count = map.getOrDefault(s, ZERO);
map.put(s, count + 1);
}
// find the first unique entry. Note that set order is deterministic here.
for (Map.Entry<String, Integer> entry : map.entrySet()) {
if (entry.getValue() == 1) {
return entry.getKey();
}
}
return null;
}
public static void main(String[] args) {
System.out.println(firstUniqueProduct(new String[] { "Apple", "Computer", "Apple", "Bag" }));
}
}
| true |
9bd84a41036968dbe68ae06ac6753d5721d2283d | Java | visastah/AESmS | /app/src/main/java/com/example/visas/genielogiciel2/ManageGroupActivity.java | UTF-8 | 8,515 | 2.015625 | 2 | [] | no_license | package com.example.visas.genielogiciel2;
import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.ArrayList;
public class ManageGroupActivity extends AppCompatActivity {
View view;
ActionBar actionBar;
RecyclerView recyclerView, dialogRecyclerView;
RecyclerView.Adapter adapter, dialogAdapter;
RecyclerView.LayoutManager layoutManager, dialogLayoutManager;
ArrayList<ContactsDataProvider> arrayList, addContactsList;
CircularTextView groupInitials;
TextView groupName;
AlertDialog.Builder deleteGroupConfirmationDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_manage_group);
view = LayoutInflater.from(this).inflate(R.layout.manage_group_action_bar, null);
groupInitials = view.findViewById(R.id.manage_group_initials);
groupName = view.findViewById(R.id.manage_group_name);
actionBar = getSupportActionBar();
actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
actionBar.setDisplayShowCustomEnabled(true);
actionBar.setCustomView(view);
getGroupMembers();
Intent intent = getIntent();
String groupInitials = intent.getStringExtra(GroupsRecyclerAdapter.GROUP_INITIALS);
String groupName = intent.getStringExtra(GroupsRecyclerAdapter.GROUP_NAME);
this.groupInitials.setText(groupInitials);
this.groupName.setText(groupName);
recyclerView = (RecyclerView) findViewById(R.id.manage_group_recycler_view);
adapter = new ManageGroupRecyclerAdapter(arrayList, false);
layoutManager = new LinearLayoutManager(this);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(layoutManager);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.manage_group_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.add_contacts) {
displayAddContactsDialog();
return true;
}
else if(id == R.id.edit_group){
displayEditGroupDialog();
return true;
}
else if(id == R.id.delete_group){
displayDeleteGroupDialog();
return true;
}
return super.onOptionsItemSelected(item);
}
//method to fill list of available contacts to add
private void fillAddContactsList(){
addContactsList = new ArrayList<>();
addContactsList.add(new ContactsDataProvider("Tsebo Mike", 677898232));
addContactsList.add(new ContactsDataProvider("Tsebo Mike", 677898232));
addContactsList.add(new ContactsDataProvider("Tsebo Mike", 677898232));
addContactsList.add(new ContactsDataProvider("Tsebo Mike", 677898232));
addContactsList.add(new ContactsDataProvider("Tsebo Mike", 677898232));
addContactsList.add(new ContactsDataProvider("Tsebo Mike", 677898232));
addContactsList.add(new ContactsDataProvider("Tsebo Mike", 677898232));
addContactsList.add(new ContactsDataProvider("Tsebo Mike", 677898232));
addContactsList.add(new ContactsDataProvider("Tsebo Mike", 677898232));
addContactsList.add(new ContactsDataProvider("Tsebo Mike", 677898232));
addContactsList.add(new ContactsDataProvider("Tsebo Mike", 677898232));
}
//code to get group members
private void getGroupMembers(){
arrayList = new ArrayList<>();
arrayList.add(new ContactsDataProvider("Tsebo Mike", 677898232));
arrayList.add(new ContactsDataProvider("Tsebo Mike", 677898232));
arrayList.add(new ContactsDataProvider("Tsebo Mike", 677898232));
arrayList.add(new ContactsDataProvider("Tsebo Mike", 677898232));
arrayList.add(new ContactsDataProvider("Tsebo Mike", 677898232));
arrayList.add(new ContactsDataProvider("Tsebo Mike", 677898232));
arrayList.add(new ContactsDataProvider("Tsebo Mike", 677898232));
arrayList.add(new ContactsDataProvider("Tsebo Mike", 677898232));
arrayList.add(new ContactsDataProvider("Tsebo Mike", 677898232));
arrayList.add(new ContactsDataProvider("Tsebo Mike", 677898232));
arrayList.add(new ContactsDataProvider("Tsebo Mike", 677898232));
}
private void displayAddContactsDialog(){
fillAddContactsList();
final Dialog dialog = new Dialog(this);
dialog.setContentView(R.layout.add_contacts_dialog);
dialogRecyclerView = dialog.findViewById(R.id.add_contacts_dialog_recycler_view);
dialogAdapter = new ManageGroupRecyclerAdapter(addContactsList, true);
dialogLayoutManager = new LinearLayoutManager(this);
dialogLayoutManager.setAutoMeasureEnabled(false);
dialogRecyclerView.setHasFixedSize(true);
dialogRecyclerView.setLayoutManager(dialogLayoutManager);
dialogRecyclerView.setAdapter(dialogAdapter);
Button cancelButton = dialog.findViewById(R.id.add_contacts_cancel_btn);
Button saveButton = dialog.findViewById(R.id.add_contacts_save_btn);
cancelButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
}
});
saveButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Code to add contacts
}
});
dialog.show();
}
private void displayEditGroupDialog(){
final Dialog dialog = new Dialog(this);
dialog.setContentView(R.layout.modify_group_dialog);
Button cancelButton = dialog.findViewById(R.id.modify_group_cancel_btn);
Button saveButton = dialog.findViewById(R.id.modify_group_save_btn);
EditText groupName = dialog.findViewById(R.id.modify_group_name);
EditText groupInitials = dialog.findViewById(R.id.modify_group_initials);
groupName.setText(this.groupName.getText());
groupInitials.setText(this.groupInitials.getText());
cancelButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
}
});
saveButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Code to add contacts
}
});
dialog.show();
}
private void displayDeleteGroupDialog(){
deleteGroupConfirmationDialog = new AlertDialog.Builder(this,
R.style.ThemeOverlay_AppCompat_Dialog_Alert);
deleteGroupConfirmationDialog.setMessage("Voulez vous vraiement suppremer le group "
+groupName.getText()+"?")
.setPositiveButton("OUI", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//Code to delete contact from group
finish();
}
})
.setNegativeButton("NON", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.show();
}
}
| true |
a529fb6332364bdfec0279282e356c355d2c9af6 | Java | kushal55/CSC543_AssignRepo | /src/Assignment1/SumArray.java | UTF-8 | 647 | 3.640625 | 4 | [] | no_license | package Assignment1;
import java.util.*;
public class SumArray {
public static void main(String[] args) {
@SuppressWarnings("resource")
Scanner sc=new Scanner(System.in);
int size=sc.nextInt();
int givenNumber[]= new int[size];
System.out.print("Given number:");
for(int i=0;i<size;i++) {
givenNumber[i]=sc.nextInt();
}
System.out.print("target:");
int target=sc.nextInt();
int sum=0;
for(int k=0;k<givenNumber.length;k++)
{
for(int j=givenNumber.length-1;j>0;j--)
{
sum =givenNumber[k]+givenNumber[j];
if(sum == target)
{
System.out.println(k+","+j);
System.exit(0);
}
}
}
}
}
| true |
028dd9c11bc70dd6b5e2e8fad4c8fc8d03c93b3a | Java | LevPhilippov/JavaDeep | /src/lev/philippov/Lesson1Generics/Orange.java | UTF-8 | 205 | 3 | 3 | [] | no_license | package lev.philippov.Lesson1Generics;
public class Orange extends Fruit{
private final double orangeWeight = 1.5d;
@Override
public double getWeight() {
return orangeWeight;
}
}
| true |
e95febd5eafd05681f8baf09b10f9434a3863b1d | Java | MD-Shibli-Mollah/Project-with-NetBeans | /InheritanceClassSEU/src/PolymorphismSEU/SockerPlayer.java | UTF-8 | 238 | 2.890625 | 3 | [] | no_license | package PolymorphismSEU;
public class SockerPlayer {
void Striker() {
System.out.println("Good Stiker");
}
void Striker(String name) {
System.out.println("The name of the Striker is " + name);
}
}
| true |
7ecf76a892ee8de5895ea4227efa43bf9815da3e | Java | arturaskuzminas/SeleniumPractice | /test/Test_Cases/ProductReviewTest.java | UTF-8 | 4,278 | 2.1875 | 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 Test_Cases;
import Base.TestBase;
import POM.AccountPage;
import POM.HomePage;
import POM.LoginPage;
import POM.ProductPage;
import java.util.List;
import java.util.ResourceBundle;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.AfterClass;
import org.testng.annotations.Test;
/**
*
* @author Artūras
*/
public class ProductReviewTest {
protected WebDriver driver;
private TestBase base;
private LoginPage loginPage;
private AccountPage accPage;
private HomePage homePage;
private ProductPage productPage;
ResourceBundle resources;
//--------------------------------------------------------------------------
/*
Actions performed (navigation, object initialization) before tests.
*/
@BeforeClass
public void setUp() throws Exception {
resources = ResourceBundle.getBundle("Properties.GlobalVariables");
base = new TestBase();
base.openChrome(resources.getString("loginPageURL"));
driver = base.getDriver();
accPage = new AccountPage(driver);
productPage = new ProductPage(driver);
loginPage = new LoginPage(driver);
loginPage.signInWith("kaunaskaunietis2@gmail.com", "Testas123");
accPage.getMyStoreLogo().click();
Actions action = new Actions(driver);
List<WebElement> list = driver.findElements(By.className("product-container"));
// Needed for hovering item card
action.moveToElement(list.get(0)).perform();
// Click first item card in 'MyStore'(default) page
list.get(0).click();
productPage.getWriteReviewButton().click();
}
//--------------------------------------------------------------------------
/*
Checks whether 'Product' page review pop up window locators are visible and
enabled before executing tests.
*/
@Test (priority = 1)
public void assertReviewWindowLocators() {
Assert.assertTrue(productPage.getCommentTitleField().isDisplayed());
Assert.assertTrue(productPage.getCommentContentField().isDisplayed());
Assert.assertTrue(productPage.getSubmitMessageButton().isEnabled());
}
//--------------------------------------------------------------------------
/*
1) Check error behaviour with no title & no content.
2) Check error behaviour with no content.
3) Check error behaviour with no title.
*/
@Test (priority = 2)
public void invalidReview() {
productPage.setReviewTitleText("");
productPage.setReviewContentText("");
productPage.getSubmitMessageButton().click();
Assert.assertTrue(productPage.getTitleMissingError().isDisplayed());
productPage.setReviewTitleText("ProductReview");
productPage.setReviewContentText("");
productPage.getSubmitMessageButton().click();
Assert.assertTrue(productPage.getContentMissingError().isDisplayed());
productPage.setReviewTitleText("");
productPage.setReviewContentText("LorumIpsum");
productPage.getSubmitMessageButton().click();
Assert.assertTrue(productPage.getTitleMissingError().isDisplayed());
}
//--------------------------------------------------------------------------
/*
1) Check behaviour with valid review form details.
*/
@Test (priority = 3)
public void validReview() {
productPage.setReviewTitleText("Review title");
productPage.setReviewContentText("Review content");
productPage.getSubmitMessageButton().click();
Assert.assertTrue(productPage.getReviewSuccesMessage().isDisplayed());
}
//--------------------------------------------------------------------------
/*
Tests end.
*/
@AfterClass
public void closeAll() throws Exception {
base.quitChrome();
}
}
| true |
44c1f50813f49c924e888ed609ce32ef705e317c | Java | dima-online/frsi | /frsi-portlet/src/main/java/mb/SuInfoBean.java | UTF-8 | 24,836 | 1.84375 | 2 | [] | no_license | package mb;
import entities.*;
import org.apache.log4j.Logger;
import org.primefaces.context.RequestContext;
import org.primefaces.event.SelectEvent;
import org.primefaces.event.ToggleSelectEvent;
import org.primefaces.event.UnselectEvent;
import util.Convert;
import util.Util;
import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.portlet.PortletContext;
import java.io.File;
import java.io.FileOutputStream;
import java.io.Serializable;
import java.text.MessageFormat;
import java.util.*;
@ManagedBean
@SessionScoped
public class SuInfoBean implements Serializable {
private static final long serialVersionUID = 1L;
private static final Logger logger = Logger.getLogger("fileLogger");
@ManagedProperty(value = "#{applicationBean}")
private ApplicationBean applicationBean;
@ManagedProperty(value = "#{sessionBean}")
private SessionBean sessionBean;
@ManagedProperty(value = "#{userBean}")
private UserBean userBean;
private Date reportDate;
private List<RefSubjectTypeItem> subjectTypes;
private RefSubjectTypeItem selectedSubjectType;
private Map<Long, Boolean> subjectTypeCheckBoxes = new HashMap<Long, Boolean>();
private List<RefRespondentItem> respondents;
private List<RefRespondentItem> selectedRespondents;
private Set<RefRespondentItem> selectedResp = new HashSet<RefRespondentItem>();
private Map<Long, Set<Long>> unselectedRespondentRecIds = new HashMap<Long, Set<Long>>();
private List<Form> forms;
private List<Form> selectedForm;
private boolean btnReportsClicked;
private boolean btnRespondentsClicked;
private boolean btnSummaryClicked;
private boolean btnMatrixClicked;
private Boolean stateSender;
private String infoName;
private String pdfFilePath;
private String typeInfo;
private List<ReportListItem> reportListItems;
private List<ReportValueNameListItem> reportValueNameListItems;
private List<ColumnModel> columns;
@PostConstruct
public void init() {
Date dateStart = new Date();
try {
if (sessionBean.isEjbNull()) sessionBean.init();
} catch (Exception e) { applicationBean.redirectToErrorPage(e); }
Date dateEnd = new Date();
long duration = dateEnd.getTime() - dateStart.getTime();
logger.debug(MessageFormat.format("t: {0}, d: {1} ms", dateStart, duration));
if(reportDate == null){
reportDate = Util.getFirstDayOfCurrentMonth();
}
refreshData();
}
// At least dummy preRender event listener required to properly redirect to error pages when exceptions occur in PostConstruct methods.
public void preRender() {
boolean isPostBack = FacesContext.getCurrentInstance().isPostback();
boolean isAjax = FacesContext.getCurrentInstance().getPartialViewContext().isAjaxRequest();
if (isPostBack || isAjax) return;
try {
} catch (Exception e) {
applicationBean.redirectToErrorPage(e);
}
RequestContext context = RequestContext.getCurrentInstance();
context.execute("PF('statusDialog').show()");
}
private void updateBtns(){
btnReportsClicked = false;
btnRespondentsClicked = false;
btnSummaryClicked = false;
}
public String getReports(String kindGroup, boolean summary){
updateBtns();
Boolean vStateSender = stateSender;
if (kindGroup.equals("BY_RESPONDENT")) {
btnMatrixClicked = false;
if (summary) {
vStateSender = null;
btnSummaryClicked = true;
typeInfo = "SUMMARY";
infoName = "Состояние отчетов респондентов - ";
} else {
btnReportsClicked = true;
typeInfo = "REPORTS";
infoName = "Список отчетов в разрезе респондентов - ";
}
} else if (kindGroup.equals("BY_FORM_NAME")) {
btnMatrixClicked = false;
if (summary) {
vStateSender = null;
btnSummaryClicked = true;
typeInfo = "SUMMARY";
infoName = "Состояние отчетов касательно респондентов - ";
} else {
btnRespondentsClicked = true;
typeInfo = "RESPONDENTS";
infoName = "Список респондентов в разрезе отчетов - ";
}
} else if (kindGroup.equals("BY_RESPONDENT_FORMS")) {
infoName = "Справка в разрезе респондентов и отчетов - ";
btnMatrixClicked = true;
typeInfo = "RESPONDENT_FORMS";
}
infoName = infoName + " на " + Convert.getDateStringFromDate(reportDate);
List<Long> subjTypeRecIdList = new ArrayList<Long>();
for (Map.Entry<Long, Boolean> e : subjectTypeCheckBoxes.entrySet()) {
if (e.getValue())
subjTypeRecIdList.add(e.getKey());
}
List<Long> respRecIdList = new ArrayList<Long>();
for (RefRespondentItem respItem : selectedResp) {
respRecIdList.add(respItem.getRecId());
}
List<String> formCodes = new ArrayList<String>();
for (Form form : selectedForm) {
formCodes.add(form.getCode());
}
AuditEvent auditEvent = new AuditEvent();
auditEvent.setCodeObject(typeInfo);
auditEvent.setNameObject(infoName);
auditEvent.setIdKindEvent(40L);
auditEvent.setDateEvent(sessionBean.getIntegration().getNewDateFromBackEndServer());
auditEvent.setIdRefRespondent(sessionBean.respondent.getId());
auditEvent.setDateIn(sessionBean.getIntegration().getNewDateFromBackEndServer());
auditEvent.setRecId(null);
auditEvent.setUserId((long) sessionBean.user.getUserId());
auditEvent.setUserLocation(sessionBean.user.getLoginIP());
reportListItems = sessionBean.getPersistence().getAllReportsForInfo(sessionBean.user.getUserId(), subjTypeRecIdList, respRecIdList, formCodes, reportDate, sessionBean.languageCode, vStateSender, auditEvent);
reportValueNameListItems = new ArrayList<ReportValueNameListItem>();
SortedSet<String> valueNames = new TreeSet<String>();
columns = new ArrayList<ColumnModel>();
for (ReportListItem repItem : reportListItems) {
if (kindGroup.equals("BY_RESPONDENT")) {
valueNames.add(repItem.getRespondentNameRu());
} else if (kindGroup.equals("BY_FORM_NAME")) {
valueNames.add(repItem.getFormName());
} else if(kindGroup.equals("BY_RESPONDENT_FORMS")){
valueNames.add(repItem.getRespondentNameRu());
ColumnModel column = new ColumnModel(repItem.getFormName(), repItem.getFormCode());
if (!columns.contains(column)) {
columns.add(column);
}
}
}
if (columns.size() > 0) {
Collections.sort(columns);
}
int sumRownNum = 1;
for (String valueName : valueNames) {
ReportValueNameListItem reportValueNameListItem = new ReportValueNameListItem();
reportValueNameListItem.setValueName(valueName);
List<ReportListItem> reportsList = new ArrayList<ReportListItem>();
long cnt = 0;
long submitCnt = 0;
int rowNum = 1;
int overdueReportsCount = 0;
for (ReportListItem repItem : reportListItems) {
if (kindGroup.equals("BY_RESPONDENT")) {
if (valueName.equals(repItem.getRespondentNameRu())) {
if(summary){
cnt ++;
if(repItem.isSubmitReport()){
submitCnt ++;
}
if (repItem.getOverdueDays() != null && repItem.getOverdueDays() > 0) {
overdueReportsCount++;
}
}else {
repItem.setRowNum(rowNum++);
reportsList.add(repItem);
}
}
} else if (kindGroup.equals("BY_FORM_NAME")) {
if (valueName.equals(repItem.getFormName())) {
if(summary){
cnt ++;
if(repItem.isSubmitReport()){
submitCnt ++;
}
if (repItem.getOverdueDays() != null && repItem.getOverdueDays() > 0) {
overdueReportsCount++;
}
} else {
repItem.setRowNum(rowNum++);
reportsList.add(repItem);
}
}
} else if (kindGroup.equals("BY_RESPONDENT_FORMS")) {
if (valueName.equals(repItem.getRespondentNameRu())) {
reportValueNameListItem.addReportListItem(repItem);
}
}
}
if(summary){
reportValueNameListItem.setCnt(cnt);
reportValueNameListItem.setSubmitCnt(submitCnt);
reportValueNameListItem.setNotSubmitCnt(cnt - submitCnt);
reportValueNameListItem.setRowNum(sumRownNum++);
reportValueNameListItem.setOverdueReportsCount(overdueReportsCount);
}else{
reportValueNameListItem.setReportListItems(reportsList);
}
reportValueNameListItems.add(reportValueNameListItem);
}
return "/views/su/info/infoView?faces-redirect=true";
}
public void downloadExcel(){
byte[] bytes = null;
String fileName = "";
try {
FileWrapper fileWrapper = sessionBean.getPersistence().suInfoToExcelFile(typeInfo, infoName, reportValueNameListItems, columns);
bytes = fileWrapper.getBytes();
ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
fileName = Convert.getContentDespositionFilename(infoName + "." + fileWrapper.getFileFormat(), externalContext.getRequestHeaderMap());
} catch (Exception e) {
bytes = null;
fileName = "";
} finally {
applicationBean.putFileContentToResponseOutputStream(bytes, "application/vnd.ms-excel", fileName);
}
try {
AuditEvent auditEvent = new AuditEvent();
auditEvent.setCodeObject(typeInfo);
auditEvent.setNameObject(infoName);
auditEvent.setIdKindEvent(41L);
auditEvent.setDateEvent(sessionBean.getIntegration().getNewDateFromBackEndServer());
auditEvent.setIdRefRespondent(sessionBean.respondent.getId());
auditEvent.setDateIn(sessionBean.getIntegration().getNewDateFromBackEndServer());
auditEvent.setRecId(null);
auditEvent.setUserId((long) sessionBean.user.getUserId());
auditEvent.setUserLocation(sessionBean.user.getLoginIP());
sessionBean.getPersistence().insertAuditEvent(auditEvent);
} catch (Exception e) {
RequestContext.getCurrentInstance().addCallbackParam("hasErrors", true);
RequestContext.getCurrentInstance().showMessageInDialog(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Ошибка", e.getMessage()));
}
}
public void prepareSuInfoPdfFile() {
try {
FileWrapper fileWrapper = sessionBean.getPersistence().generateSuInfoPdfFile(typeInfo, infoName, reportValueNameListItems, columns);
ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
PortletContext portletContext = (PortletContext) externalContext.getContext();
String dir = portletContext.getRealPath("/resources/reports/");
File file = File.createTempFile("suInfo_" + typeInfo + "_", ".pdf", new File(dir));
if(!file.exists()) {
boolean created = file.createNewFile();
if(!created)
throw new Exception("Ошибка при создании pdf-файла");
}
FileOutputStream outputStream = new FileOutputStream(file);
outputStream.write(fileWrapper.getBytes());
outputStream.flush();
outputStream.close();
pdfFilePath = "/frsi-portlet/resources/reports/" + file.getName();
} catch (Exception e) {
pdfFilePath = "";
RequestContext.getCurrentInstance().addCallbackParam("hasErrors", true);
RequestContext.getCurrentInstance().showMessageInDialog(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Ошибка", e.getMessage()));
}
try {
AuditEvent auditEvent = new AuditEvent();
auditEvent.setCodeObject(typeInfo);
auditEvent.setNameObject(infoName);
auditEvent.setIdKindEvent(42L);
auditEvent.setDateEvent(sessionBean.getIntegration().getNewDateFromBackEndServer());
auditEvent.setIdRefRespondent(sessionBean.respondent.getId());
auditEvent.setDateIn(sessionBean.getIntegration().getNewDateFromBackEndServer());
auditEvent.setRecId(null);
auditEvent.setUserId((long) sessionBean.user.getUserId());
auditEvent.setUserLocation(sessionBean.user.getLoginIP());
sessionBean.getPersistence().insertAuditEvent(auditEvent);
} catch (Exception e) {
RequestContext.getCurrentInstance().addCallbackParam("hasErrors", true);
RequestContext.getCurrentInstance().showMessageInDialog(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Ошибка", e.getMessage()));
}
}
public String getSubmitRowStyle(boolean submitReport) {
return submitReport ? "color: green;" : "color: red;";
}
public String getRowStyleForSts(String statusIn) {
String result = null;
ReportStatus.Status status = ReportStatus.Status.ERROR;
try { status = ReportStatus.Status.valueOf(statusIn); } catch (IllegalArgumentException e) {};
switch (status) {
case SIGNED:
result = "color:blue";
break;
case ERROR:
result = "color:red;";
break;
case COMPLETED:
case DISAPPROVED:
result = "color:#008080;";
break;
case APPROVED:
result = "color:green";
break;
}
return result;
}
public String getControlRowStyle(String controlResult) {
Long controlResultType = 3L;
try {
ControlResult.ResultType rt = ControlResult.ResultType.valueOf(controlResult);
controlResultType = rt.getId();
} catch (IllegalArgumentException e) {
}
if (controlResultType == null) return "";
String result = "";
switch (controlResultType.intValue()) {
case 1:
result = "color: green;";
break;
case 2:
case 3:
result = "color: red;";
break;
}
return result;
}
public void refreshData() {
subjectTypeCheckBoxes.clear();
selectedSubjectType = null;
selectedRespondents = null;
selectedResp.clear();
unselectedRespondentRecIds.clear();
selectedForm = null;
updateSubjectTypes();
respondents = null;
forms = null;
}
private void updateSubjectTypes() {
if (reportDate != null) {
subjectTypes = sessionBean.getReference().getRefSubjectTypeListAdvanced(reportDate, false);
} else {
subjectTypes = null;
}
}
public void updateRespondents() {
if (reportDate != null && selectedSubjectType != null && subjectTypeCheckBoxes.get(selectedSubjectType.getRecId()))
respondents = sessionBean.getReference().getUserRespondentsBySubjectType(sessionBean.user.getUserId(), selectedSubjectType.getRecId(), reportDate, null);
else
respondents = new ArrayList<RefRespondentItem>();
if(selectedRespondents != null)
selectedResp.addAll(selectedRespondents);
selectedRespondents = new ArrayList<RefRespondentItem>();
for (RefRespondentItem respondent : respondents) {
if (!unselected(respondent.getRecId()))
selectedRespondents.add(respondent);
}
selectedResp.addAll(selectedRespondents);
}
private boolean unselected(Long subjectTypeRecId, Long respondentRecId) {
if (!unselectedRespondentRecIds.containsKey(subjectTypeRecId))
return false;
return unselectedRespondentRecIds.get(subjectTypeRecId).contains(respondentRecId);
}
private boolean unselected(Long respondentRecId) {
if (selectedSubjectType == null)
return false;
return unselected(selectedSubjectType.getRecId(), respondentRecId);
}
public void onSubjectTypeChange(RefSubjectTypeItem subjectType) {
boolean checked = subjectTypeCheckBoxes.get(subjectType.getRecId());
List<RefRespondentItem> respList = sessionBean.getReference().getUserRespondentsBySubjectType(sessionBean.user.getUserId(), subjectType.getRecId(), reportDate, null);
if (!checked) {
if (unselectedRespondentRecIds.containsKey(subjectType.getRecId()))
unselectedRespondentRecIds.remove(subjectType.getRecId());
selectedResp.removeAll(respList);
}else{
selectedResp.addAll(respList);
}
updateForms();
if(selectedForm == null)
selectedForm = new ArrayList<Form>();
else
selectedForm.clear();
selectedForm.addAll(forms);
}
private void updateForms() {
if (reportDate != null) {
List<Long> subjectTypeRecIds = new ArrayList<Long>();
for (Map.Entry<Long, Boolean> e : subjectTypeCheckBoxes.entrySet()) {
if (e.getValue())
subjectTypeRecIds.add(e.getKey());
}
if (subjectTypeRecIds.size() > 0)
forms = sessionBean.getPersistence().getFormsByUserIdDateSTList(sessionBean.user.getUserId(), reportDate, subjectTypeRecIds);
else {
forms = new ArrayList<Form>();
}
} else {
forms = new ArrayList<Form>();
}
selectedForm = null;
}
public void onRespondentRowSelect(SelectEvent event) {
Long respondentId = ((RefRespondentItem) event.getObject()).getRecId();
removeFromUnselected(respondentId);
selectedResp.add((RefRespondentItem) event.getObject());
}
private void removeFromUnselected(Long respondentId) {
if (selectedSubjectType != null) {
if (unselectedRespondentRecIds.containsKey(selectedSubjectType.getRecId())) {
Set<Long> ids = unselectedRespondentRecIds.get(selectedSubjectType.getRecId());
if (ids.contains(respondentId))
ids.remove(respondentId);
}
}
}
public void onRespondentRowUnselect(UnselectEvent event) {
Long respondentId = ((RefRespondentItem) event.getObject()).getRecId();
addToUnselected(respondentId);
selectedResp.remove((RefRespondentItem) event.getObject());
}
public void onRespondentToggleSelect(ToggleSelectEvent event) {
if (event.isSelected()) {
for (RefRespondentItem respondent : respondents)
removeFromUnselected(respondent.getRecId());
selectedResp.addAll(respondents);
} else {
for (RefRespondentItem respondent : respondents)
addToUnselected(respondent.getRecId());
selectedResp.removeAll(respondents);
}
}
private void addToUnselected(Long respondentId) {
if (selectedSubjectType != null) {
if (!unselectedRespondentRecIds.containsKey(selectedSubjectType.getRecId()))
unselectedRespondentRecIds.put(selectedSubjectType.getRecId(), new HashSet<Long>());
unselectedRespondentRecIds.get(selectedSubjectType.getRecId()).add(respondentId);
}
}
public void onSelectFormAll(ToggleSelectEvent event) {
selectedForm.clear();
if (event.isSelected()) {
selectedForm.addAll(forms);
}
}
public int getOverdueDaysForSort(ReportListItem item) {
if (item == null) {
return 0;
} else if (item.getPeriodAlgError() == null) {
return -1;
} else {
return item.getOverdueDays() != null ? item.getOverdueDays() : 0;
}
}
public String getOverdueDays(ReportListItem item) {
if (item == null) {
return "";
} else if (item.getPeriodAlgError() != null) {
return "Ошибка";
} else {
return item.getOverdueDays() != null ? item.getOverdueDays().toString() : "";
}
}
// Getters & Setters
public void setApplicationBean(ApplicationBean applicationBean) {
this.applicationBean = applicationBean;
}
public void setSessionBean(SessionBean sessionBean) {
this.sessionBean = sessionBean;
}
public void setUserBean(UserBean userBean) {
this.userBean = userBean;
}
public Date getReportDate() {
return reportDate;
}
public void setReportDate(Date reportDate) {
this.reportDate = reportDate;
}
public boolean isBtnReportsClicked() {
return btnReportsClicked;
}
public void setBtnReportsClicked(boolean btnReportsClicked) {
this.btnReportsClicked = btnReportsClicked;
}
public String getInfoName() {
return infoName;
}
public List<ReportValueNameListItem> getReportValueNameListItems() {
return reportValueNameListItems;
}
public boolean isBtnRespondentsClicked() {
return btnRespondentsClicked;
}
public boolean isBtnSummaryClicked() {
return btnSummaryClicked;
}
public String getPdfFilePath() {
return pdfFilePath;
}
public List<RefSubjectTypeItem> getSubjectTypes() {
return subjectTypes;
}
public void setSubjectTypes(List<RefSubjectTypeItem> subjectTypes) {
this.subjectTypes = subjectTypes;
}
public Map<Long, Boolean> getSubjectTypeCheckBoxes() {
return subjectTypeCheckBoxes;
}
public void setSubjectTypeCheckBoxes(Map<Long, Boolean> subjectTypeCheckBoxes) {
this.subjectTypeCheckBoxes = subjectTypeCheckBoxes;
}
public RefSubjectTypeItem getSelectedSubjectType() {
return selectedSubjectType;
}
public void setSelectedSubjectType(RefSubjectTypeItem selectedSubjectType) {
this.selectedSubjectType = selectedSubjectType;
}
public List<RefRespondentItem> getRespondents() {
return respondents;
}
public void setRespondents(List<RefRespondentItem> respondents) {
this.respondents = respondents;
}
public List<RefRespondentItem> getSelectedRespondents() {
return selectedRespondents;
}
public void setSelectedRespondents(List<RefRespondentItem> selectedRespondents) {
this.selectedRespondents = selectedRespondents;
}
public List<Form> getForms() {
return forms;
}
public void setForms(List<Form> forms) {
this.forms = forms;
}
public List<Form> getSelectedForm() {
return selectedForm;
}
public void setSelectedForm(List<Form> selectedForm) {
this.selectedForm = selectedForm;
}
public Boolean getStateSender() {
return stateSender;
}
public void setStateSender(Boolean stateSender) {
this.stateSender = stateSender;
}
public List<ColumnModel> getColumns() {
return columns;
}
public boolean isBtnMatrixClicked() {
return btnMatrixClicked;
}
}
| true |
cd1b3641469b2ad68af164149d86e08c264a4d96 | Java | jenkinsci/clearcase-plugin | /src/test/java/hudson/plugins/clearcase/action/AbstractCheckoutActionTest.java | UTF-8 | 7,885 | 1.789063 | 2 | [] | no_license | /**
* The MIT License
*
* Copyright (c) 2013 Vincent Latombe
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package hudson.plugins.clearcase.action;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import hudson.FilePath;
import hudson.Launcher;
import hudson.model.TaskListener;
import hudson.plugins.clearcase.AbstractWorkspaceTest;
import hudson.plugins.clearcase.ClearTool;
import hudson.plugins.clearcase.ClearToolLauncher;
import hudson.plugins.clearcase.MkViewParameters;
import java.io.IOException;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
public class AbstractCheckoutActionTest extends AbstractWorkspaceTest {
private static class DummyCheckoutAction extends SnapshotCheckoutAction {
public DummyCheckoutAction(ClearTool cleartool, String[] loadRules, boolean useUpdate, String viewPath) {
super(cleartool, loadRules, useUpdate, viewPath, null);
}
@Override
public boolean checkout(Launcher launcher, FilePath workspace, String viewName) throws IOException, InterruptedException {
return false;
}
@Override
public boolean cleanAndCreateViewIfNeeded(FilePath workspace, String viewTag, String viewPath, String streamSelector) throws IOException,
InterruptedException {
return super.cleanAndCreateViewIfNeeded(workspace, viewTag, viewPath, streamSelector);
}
}
@Mock
private ClearTool clearTool;
@Mock
private ClearToolLauncher ctLauncher;
@Mock
private TaskListener taskListener;
@Test
public void firstTimeShouldCreate() throws Exception {
when(clearTool.doesViewExist("aViewTag")).thenReturn(Boolean.FALSE);
DummyCheckoutAction action = new DummyCheckoutAction(clearTool, new String[] { "aLoadRule" }, true, "");
action.cleanAndCreateViewIfNeeded(workspace, "aViewTag", "path", "stream@\\pvob");
verify(clearTool).doesViewExist("aViewTag");
ArgumentCaptor<MkViewParameters> argument = ArgumentCaptor.forClass(MkViewParameters.class);
verify(clearTool).mkview(argument.capture());
assertEquals("path", argument.getValue().getViewPath());
assertEquals("aViewTag", argument.getValue().getViewTag());
assertEquals("stream@\\pvob", argument.getValue().getStreamSelector());
}
@Test
public void ifRmViewTagIsNotSupportedCallRmTag() throws Exception {
workspace.child("path").mkdirs();
when(clearTool.doesViewExist("aViewTag")).thenReturn(Boolean.TRUE);
when(clearTool.lscurrentview("path")).thenReturn("anotherViewTag");
doThrow(new IOException()).when(clearTool).rmviewtag("aViewTag");
DummyCheckoutAction action = new DummyCheckoutAction(clearTool, new String[] { "aLoadRule" }, false, "");
action.cleanAndCreateViewIfNeeded(workspace, "aViewTag", "path", "stream@\\pvob");
verify(clearTool).doesViewExist("aViewTag");
verify(clearTool).lscurrentview("path");
verify(clearTool).rmviewtag("aViewTag");
verify(clearTool).rmtag("aViewTag");
ArgumentCaptor<MkViewParameters> argument = ArgumentCaptor.forClass(MkViewParameters.class);
verify(clearTool).mkview(argument.capture());
assertEquals("path", argument.getValue().getViewPath());
assertEquals("aViewTag", argument.getValue().getViewTag());
assertEquals("stream@\\pvob", argument.getValue().getStreamSelector());
}
@Test
public void secondTimeWithInvalidViewShouldRmviewTagMoveFolderThenCreateView() throws Exception {
workspace.child("path").mkdirs();
when(clearTool.doesViewExist("aViewTag")).thenReturn(Boolean.TRUE);
when(clearTool.lscurrentview("path")).thenReturn("anotherViewTag");
DummyCheckoutAction action = new DummyCheckoutAction(clearTool, new String[] { "aLoadRule" }, false, "");
action.cleanAndCreateViewIfNeeded(workspace, "aViewTag", "path", "stream@\\pvob");
verify(clearTool).doesViewExist("aViewTag");
verify(clearTool).lscurrentview("path");
verify(clearTool).rmviewtag("aViewTag");
ArgumentCaptor<MkViewParameters> argument = ArgumentCaptor.forClass(MkViewParameters.class);
verify(clearTool).mkview(argument.capture());
assertEquals("path", argument.getValue().getViewPath());
assertEquals("aViewTag", argument.getValue().getViewTag());
assertEquals("stream@\\pvob", argument.getValue().getStreamSelector());
}
@Test
public void secondTimeWithoutUseUpdateRemoveThenCreateView() throws Exception {
workspace.child("path").mkdirs();
when(clearTool.doesViewExist("aViewTag")).thenReturn(Boolean.TRUE);
when(clearTool.lscurrentview("path")).thenReturn("aViewTag");
DummyCheckoutAction action = new DummyCheckoutAction(clearTool, new String[] { "aLoadRule" }, false, "");
action.cleanAndCreateViewIfNeeded(workspace, "aViewTag", "path", "stream@\\pvob");
verify(clearTool).rmview("path");
ArgumentCaptor<MkViewParameters> argument = ArgumentCaptor.forClass(MkViewParameters.class);
verify(clearTool).mkview(argument.capture());
assertEquals("path", argument.getValue().getViewPath());
assertEquals("aViewTag", argument.getValue().getViewTag());
assertEquals("stream@\\pvob", argument.getValue().getStreamSelector());
verify(clearTool).doesViewExist("aViewTag");
verify(clearTool).lscurrentview("path");
}
@Test
public void secondTimeWithUseUpdateShouldDoNothing() throws Exception {
workspace.child("path").mkdirs();
when(clearTool.doesViewExist("aViewTag")).thenReturn(Boolean.TRUE);
when(clearTool.lscurrentview("path")).thenReturn("aViewTag");
DummyCheckoutAction action = new DummyCheckoutAction(clearTool, new String[] { "aLoadRule" }, true, "");
action.cleanAndCreateViewIfNeeded(workspace, "aViewTag", "path", "stream@\\pvob");
verify(clearTool).doesViewExist("aViewTag");
verify(clearTool).lscurrentview("path");
}
@Before
public void setUp() throws Exception {
when(clearTool.getLauncher()).thenReturn(ctLauncher);
when(ctLauncher.getListener()).thenReturn(taskListener);
when(taskListener.getLogger()).thenReturn(System.out);
createWorkspace();
}
@After
public void teardown() throws Exception {
deleteWorkspace();
}
}
| true |
357e29f08d1d97fa8a4096fbec820aff9f089391 | Java | voglrobe/FtInterface | /ftinterface-core/src/main/java/de/voglrobe/ftinterface/async/MccExecutorThread.java | UTF-8 | 2,618 | 2.8125 | 3 | [] | no_license | package de.voglrobe.ftinterface.async;
import de.voglrobe.ftinterface.exceptions.ComException;
import de.voglrobe.ftinterface.io.FtOutput;
import de.voglrobe.ftinterface.io.FtSerialPortSenderReceiver;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* This class implements a Thread that executes the given MCC until it's termination.
* This Thread is not reusable. Once terminated it cannot be restarted.
*
* @author vlr
*/
public class MccExecutorThread extends Thread
{
private static final Logger LOGGER = Logger.getLogger(MccExecutorThread.class.getName());
private final FtSerialPortSenderReceiver ftSenderReceiver;
private volatile FtOutput mcc;
private volatile boolean stopped;
private volatile boolean paused;
/**
* Constructor.
*
* @param ftSenderReceiver An object to access of the serial interface.
*/
public MccExecutorThread(final FtSerialPortSenderReceiver ftSenderReceiver)
{
this.ftSenderReceiver = ftSenderReceiver;
this.paused = true;
this.mcc = null;
this.stopped = false;
}
/**
* Pauses the Executor from sending MCCs.
*/
public synchronized void pause()
{
this.paused = true;
}
/**
* Proceeds sending the given MCC. Does nothing if mcc argument is NULL.
*
* @param mcc The MCC to send recurrently.
*/
public synchronized void activate(final FtOutput mcc)
{
this.mcc = mcc;
this.paused = false;
}
/**
* Asks the Thread to terminate and returns immediately.
* The caller should sync with the Thread and await it's termination.
*/
public synchronized void terminate()
{
LOGGER.log(Level.INFO, "Stopping MccExecutorThread...");
this.mcc = null;
this.stopped = true;
}
@Override
public void run()
{
if (ftSenderReceiver == null || stopped)
{
return;
}
do
{
try
{
if (!paused && mcc != null)
{
ftSenderReceiver.send(mcc.bytes());
}
Thread.sleep(200);
}
catch(InterruptedException dontcare)
{
}
catch(ComException e)
{
LOGGER.log(Level.SEVERE, "The MccExecutorThread dies unexpectedly.", e);
break;
}
} while(!stopped);
LOGGER.log(Level.INFO, "MccExecutorThread stopped.");
}
}
| true |
3e6a418a8c64a9df952ff58869f30530a7cfdb89 | Java | ElegantDancer/AndroidStudioProject | /MyApplication/viewswitcherdemo/src/main/java/com/example/zhenzhen/myapplication/ViewSwitcherTest.java | UTF-8 | 6,677 | 2.015625 | 2 | [] | no_license | package com.example.zhenzhen.myapplication;
import java.util.ArrayList;
import android.os.Bundle;
import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.ViewSwitcher;
import android.widget.ViewSwitcher.ViewFactory;
public class ViewSwitcherTest extends Activity
{
// ¶¨ÒåÒ»¸ö³£Á¿£¬ÓÃÓÚÏÔʾÿÆÁÏÔʾµÄÓ¦ÓóÌÐòÊý
public static final int NUMBER_PER_SCREEN = 12;
// ´ú±íÓ¦ÓóÌÐòµÄÄÚ²¿À࣬
public static class DataItem
{
// Ó¦ÓóÌÐòÃû³Æ
public String dataName;
// Ó¦ÓóÌÐòͼ±ê
public Drawable drawable;
}
// ±£´æÏµÍ³ËùÓÐÓ¦ÓóÌÐòµÄList¼¯ºÏ
private ArrayList<DataItem> items = new ArrayList<DataItem>();
// ¼Ç¼µ±Ç°ÕýÔÚÏÔʾµÚ¼¸ÆÁµÄ³ÌÐò
private int screenNo = -1;
// ±£´æ³ÌÐòËùÕ¼µÄ×ÜÆÁÊý
private int screenCount;
ViewSwitcher switcher;
// ´´½¨LayoutInflater¶ÔÏó
LayoutInflater inflater;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
inflater = LayoutInflater.from(ViewSwitcherTest.this);
// ´´½¨Ò»¸ö°üº¬40¸öÔªËØµÄList¼¯ºÏ£¬ÓÃÓÚÄ£Äâ°üº¬40¸öÓ¦ÓóÌÐò
for (int i = 0; i < 40; i++)
{
String label = "" + i;
Drawable drawable = getResources().getDrawable(
R.mipmap.ic_launcher);
DataItem item = new DataItem();
item.dataName = label;
item.drawable = drawable;
items.add(item);
}
// ¼ÆËãÓ¦ÓóÌÐòËùÕ¼µÄ×ÜÆÁÊý¡£
// Èç¹ûÓ¦ÓóÌÐòµÄÊýÁ¿ÄÜÕû³ýNUMBER_PER_SCREEN£¬³ý·¨µÄ½á¹û¾ÍÊÇ×ÜÆÁÊý¡£
// Èç¹û²»ÄÜÕû³ý£¬×ÜÆÁÊýÓ¦¸ÃÊdzý·¨µÄ½á¹ûÔÙ¼Ó1¡£
screenCount = items.size() % NUMBER_PER_SCREEN == 0 ?
items.size()/ NUMBER_PER_SCREEN :
items.size() / NUMBER_PER_SCREEN + 1;
switcher = (ViewSwitcher) findViewById(R.id.viewSwitcher);
switcher.setFactory(new ViewFactory()
{
// ʵ¼ÊÉϾÍÊÇ·µ»ØÒ»¸öGridView×é¼þ
@Override
public View makeView()
{
// ¼ÓÔØR.layout.slidelistview×é¼þ£¬Êµ¼ÊÉϾÍÊÇÒ»¸öGridView×é¼þ¡£
return inflater.inflate(R.layout.slidelistview, null);
}
});
// Ò³Ãæ¼ÓÔØÊ±ÏÈÏÔʾµÚÒ»ÆÁ¡£
next(null);
}
public void next(View v)
{
if (screenNo < screenCount - 1)
{
screenNo++;
// ΪViewSwitcherµÄ×é¼þÏÔʾ¹ý³ÌÉèÖö¯»
switcher.setInAnimation(this, android.R.anim.slide_out_right);
// ΪViewSwitcherµÄ×é¼þÒþ²Ø¹ý³ÌÉèÖö¯»
switcher.setOutAnimation(this, android.R.anim.slide_in_left);
// ¿ØÖÆÏÂÒ»ÆÁ½«ÒªÏÔʾµÄGridView¶ÔÓ¦µÄ Adapter
((GridView) switcher.getNextView()).setAdapter(adapter);
// µã»÷Óұ߰´Å¥£¬ÏÔʾÏÂÒ»ÆÁ£¬
// ѧϰÊÖÊÆ¼ì²âºó£¬Ò²¿Éͨ¹ýÊÖÊÆ¼ì²âʵÏÖÏÔʾÏÂÒ»ÆÁ.
switcher.showNext(); // ¢Ù
}
}
public void prev(View v)
{
if (screenNo > 0)
{
screenNo--;
// ΪViewSwitcherµÄ×é¼þÏÔʾ¹ý³ÌÉèÖö¯»
switcher.setInAnimation(this, android.R.anim.slide_in_left);
// ΪViewSwitcherµÄ×é¼þÒþ²Ø¹ý³ÌÉèÖö¯»
switcher.setOutAnimation(this, android.R.anim.slide_out_right);
// ¿ØÖÆÏÂÒ»ÆÁ½«ÒªÏÔʾµÄGridView¶ÔÓ¦µÄ Adapter
((GridView) switcher.getNextView()).setAdapter(adapter);
// µã»÷×ó±ß°´Å¥£¬ÏÔʾÉÏÒ»ÆÁ£¬µ±È»¿ÉÒÔ²ÉÓÃÊÖÊÆ
// ѧϰÊÖÊÆ¼ì²âºó£¬Ò²¿Éͨ¹ýÊÖÊÆ¼ì²âʵÏÖÏÔʾÉÏÒ»ÆÁ.
switcher.showPrevious(); // ¢Ú
}
}
// ¸ÃBaseAdapter¸ºÔðΪÿÆÁÏÔʾµÄGridViewÌṩÁбíÏî
private BaseAdapter adapter = new BaseAdapter()
{
@Override
public int getCount()
{
// Èç¹ûÒѾµ½ÁË×îºóÒ»ÆÁ£¬ÇÒÓ¦ÓóÌÐòµÄÊýÁ¿²»ÄÜÕû³ýNUMBER_PER_SCREEN
if (screenNo == screenCount - 1
&& items.size() % NUMBER_PER_SCREEN != 0)
{
// ×îºóÒ»ÆÁÏÔʾµÄ³ÌÐòÊýΪӦÓóÌÐòµÄÊýÁ¿¶ÔNUMBER_PER_SCREENÇóÓà
return items.size() % NUMBER_PER_SCREEN;
}
// ·ñÔòÿÆÁÏÔʾµÄ³ÌÐòÊýÁ¿ÎªNUMBER_PER_SCREEN
return NUMBER_PER_SCREEN;
}
@Override
public DataItem getItem(int position)
{
// ¸ù¾ÝscreenNo¼ÆËãµÚposition¸öÁбíÏîµÄÊý¾Ý
return items.get(screenNo * NUMBER_PER_SCREEN + position);
}
@Override
public long getItemId(int position)
{
return position;
}
@Override
public View getView(int position
, View convertView, ViewGroup parent)
{
View view = convertView;
if (convertView == null)
{
// ¼ÓÔØR.layout.labelicon²¼¾ÖÎļþ
view = inflater.inflate(R.layout.labelicon, null);
}
// »ñÈ¡R.layout.labelicon²¼¾ÖÎļþÖеÄImageView×é¼þ£¬²¢ÎªÖ®ÉèÖÃͼ±ê
ImageView imageView = (ImageView)
view.findViewById(R.id.imageview);
imageView.setImageDrawable(getItem(position).drawable);
// »ñÈ¡R.layout.labelicon²¼¾ÖÎļþÖеÄTextView×é¼þ£¬²¢ÎªÖ®ÉèÖÃÎı¾
TextView textView = (TextView)
view.findViewById(R.id.textview);
textView.setText(getItem(position).dataName);
return view;
}
};
} | true |
90e4c4352a3bf3b33ec7e14c957bd6eaf2fe6327 | Java | snoylee/koudaibao | /code/v1.0.0/src/com/kdkj/koudailicai/view/more/AboutKoudaiActivity.java | UTF-8 | 4,340 | 1.710938 | 2 | [] | no_license | package com.kdkj.koudailicai.view.more;
import org.json.JSONObject;
import android.content.Intent;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.TextView;
import com.android.volley.Response.Listener;
import com.kdkj.koudailicai.R;
import com.kdkj.koudailicai.lib.ui.TitleView;
import com.kdkj.koudailicai.util.global.G;
import com.kdkj.koudailicai.view.BaseActivity;
import com.kdkj.koudailicai.view.WebViewActivity;
public class AboutKoudaiActivity extends BaseActivity {
private TitleView abouttitle;
private String tele;
private String address;
private String site;
// private String email;
private String name;
private String appAbout;
private TextView title;
private TextView aboutcontent;
private TextView abouttele;
private TextView aboutaddress;
private TextView aboutsite;
// private TextView aboutcite;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_about_koudai);
parseUrl();
findView();
inittitle();
contents();
}
private void parseUrl() {
// TODO Auto-generated method stub
if (this.getApplicationContext().isGlobalConfCompleted()) {
tele = getApplicationContext().getConfVal(G.GCK_VAL_APP_TELE);
address = getApplicationContext().getConfVal(
G.GCK_VAL_COMPANY_ADDRESS);
site = getApplicationContext().getConfVal(G.GCK_VAL_SITE_URL);
// email = getApplicationContext().getConfVal(G.GCK_VAL_COMPANY_EMAIL);
name = getApplicationContext().getConfVal(G.GCK_VAL_APP_NAME);
appAbout = getApplicationContext().getConfVal(
G.GCK_VAL_COMPANY_ABOUT);
} else {
tele = G.VAL_APP_TELE;
address = G.VAL_COMPANY_ADDRESS;
site = G.VAL_SITE_URL;
// email = G.VAL_COMPANY_EMAIL;
name = G.VAL_APP_NAME;
appAbout = G.VAL_COMPANY_ABOUT;
}
}
private void findView() {
abouttitle = (TitleView) findViewById(R.id.abouttitle);
title = (TextView) findViewById(R.id.title);
aboutcontent = (TextView) findViewById(R.id.aboutcontent);
abouttele = (TextView) findViewById(R.id.abouttele_num);
aboutaddress = (TextView) findViewById(R.id.aboutaddress);
aboutsite = (TextView) findViewById(R.id.aboutsite);
// aboutcite = (TextView) findViewById(R.id.aboutcite);
}
private void contents(){
title.setText(name);
aboutcontent.setText(appAbout);
abouttele.setText(tele);
abouttele.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
abouttele.getPaint().setAntiAlias(true);
aboutaddress.setText("公司地址:"+address);
aboutsite.setText(site);
aboutsite.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
aboutsite.getPaint().setAntiAlias(true);
abouttele.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
tele = tele.replaceAll("-", "").trim().toString();
Intent intent = new Intent(Intent.ACTION_CALL,Uri.parse("tel:"+tele));
startActivity(intent);
}
});
aboutsite.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
// Intent intent=new Intent(AboutKoudaiActivity.this,WebViewActivity.class);
// intent.putExtra("url", "http://"+site+"/");
// intent.putExtra("title","口袋理财");
// AboutKoudaiActivity.this.startActivity(intent);
Intent intent = new Intent(Intent.ACTION_VIEW,Uri.parse("http://"+site+"/"));
AboutKoudaiActivity.this.startActivity(intent);
}
});
// aboutcite.setText(email);
// aboutcite.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
}
private void inittitle() {
abouttitle.setTitle(R.string.more_about_koudai);
abouttitle.showLeftButton(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
AboutKoudaiActivity.this.finish();
}
});
abouttitle.setLeftImageButton(R.drawable.back);
abouttitle.setLeftTextButton("返回");
}
}
| true |
a8cbca5c533a7d0dda07d1efc6b50ff863985596 | Java | HarmonyCloud-zz/DevOps | /common/src/main/java/com/harmony/devops/common/vo/NetVO.java | UTF-8 | 977 | 2.375 | 2 | [] | no_license | package com.harmony.devops.common.vo;
import com.harmony.devops.common.enums.ReturnMsgEnum;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.Serializable;
/**
* 网络通信层vo
* @author 葛文镇
*/
@ApiModel(discriminator = "谐云-网络层返回vo")
public abstract class NetVO implements Serializable {
@ApiModelProperty(value="网络层返回码",name="code")
private String code;
@ApiModelProperty(value="异常返回信息",name="message")
private String message;
public NetVO(ReturnMsgEnum returnMsgEnum) {
this.code = returnMsgEnum.getCode();
this.message = returnMsgEnum.getMsg();
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
| true |
088884aa60f0e3fe98bd8170b617a189c920ebde | Java | Gauravd70/ExampleArchitecture | /app/src/main/java/com/gd70/android/examplearchitecture/uis/presenter_listeners/BasePresenterListener.java | UTF-8 | 329 | 1.984375 | 2 | [] | no_license | package com.gd70.android.examplearchitecture.uis.presenter_listeners;
import android.app.Activity;
import android.content.Context;
public interface BasePresenterListener {
Activity getActivity();
Context getContext();
void showToast(String toast);
void showToast(String toast,int duration);
void close();
}
| true |
005f6ac07b2234237b79999d902f71c5dba5e686 | Java | hilledor/FastenYourSeatbelt | /fasten your seatbelt/src/controller/ClientController.java | UTF-8 | 10,895 | 2 | 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 controller;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableRow;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
import model.Client;
import model.DataEntity;
import model.User;
import model.User.Rol;
import utils.Utils;
/**
* FXML Controller class
*
* @author jandorresteijn
*/
public class ClientController extends SearchMaintenanceController implements Initializable {
// Moet apart naar SearchMaintenanceController
@FXML
public Pane searchPane;
@FXML
Pane maintenancePane;
@FXML
Button searchBut;
@FXML
TextField searchField;
@FXML
Button newBut;
@FXML
Button saveBut;
@FXML
Button deleteBut;
@FXML
Button logBut;
@FXML
TableView<Client> grid;
@FXML
TableColumn<Client, Integer> idCol;
@FXML
TableColumn<Client, String> firstnameCol;
@FXML
TableColumn<Client, String> middlenameCol;
@FXML
TableColumn<Client, String> lastnameCol;
@FXML
TableColumn<Client, String> emailCol;
@FXML
TableColumn<Client, String> phonenumberCol;
@FXML
TableColumn<Client, String> streetCol;
@FXML
TableColumn<Client, String> streetnumberCol;
@FXML
TableColumn<Client, String> zipcodeCol;
@FXML
TableColumn<Client, String> cityCol;
@FXML
TableColumn<Client, String> countryCol;
@FXML
TextField idField;
@FXML
TextField firstnameField;
@FXML
TextField middlenameField;
@FXML
TextField lastnameField;
@FXML
TextField emailField;
@FXML
TextField phonenumberField;
@FXML
TextField streetField;
@FXML
TextField streetnumberField;
@FXML
TextField zipcodeField;
@FXML
TextField cityField;
@FXML
TextField countryField;
Client activeClient;
@FXML
ComboBox rolSearch;
@Override
public void start(Stage primaryStage) throws Exception {
try {
AnchorPane page = (AnchorPane) FXMLLoader.load(MainView.class.getResource("Client.fxml"));
Scene scene = new Scene(page);
primaryStage.setScene(scene);
primaryStage.setTitle("Hille's oplossing");
primaryStage.show();
} catch (Exception e) {
}
}
public static void main(String[] args) {
Application.launch(ClientController.class, (java.lang.String[]) null);
}
/**
* Initializes the controller class.
*/
@Override
public void initialize(URL url, ResourceBundle rb) {
//idCol.setCellValueFactory(new PropertyValueFactory<Client, Integer>("id"));
firstnameCol.setCellValueFactory(new PropertyValueFactory<Client, String>("firstname"));
middlenameCol.setCellValueFactory(new PropertyValueFactory<Client, String>("middlename"));
lastnameCol.setCellValueFactory(new PropertyValueFactory<Client, String>("lastname"));
emailCol.setCellValueFactory(new PropertyValueFactory<Client, String>("email"));
phonenumberCol.setCellValueFactory(new PropertyValueFactory<Client, String>("phonenumber"));
streetCol.setCellValueFactory(new PropertyValueFactory<Client, String>("phonenumber"));
streetnumberCol.setCellValueFactory(new PropertyValueFactory<Client, String>("phonenumber"));
zipcodeCol.setCellValueFactory(new PropertyValueFactory<Client, String>("phonenumber"));
cityCol.setCellValueFactory(new PropertyValueFactory<Client, String>("phonenumber"));
countryCol.setCellValueFactory(new PropertyValueFactory<Client, String>("phonenumber"));
try {
grid.setItems(getClients());
} catch (ClassNotFoundException ex) {
Logger.getLogger(ClientController.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(ClientController.class.getName()).log(Level.SEVERE, null, ex);
}
saveBut.setOnMousePressed(
new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
System.out.println("in save");
activeClient.setFirstname(firstnameField.getText());
activeClient.setMiddlename(middlenameField.getText());
activeClient.setLastname(lastnameField.getText());
activeClient.setEmail(emailField.getText());
activeClient.setPhonenumber(phonenumberField.getText());
activeClient.setStreet(streetField.getText());
activeClient.setStreetnumber(streetnumberField.getText());
activeClient.setZipcode(zipcodeField.getText());
activeClient.setCity(cityField.getText());
activeClient.setCountry(countryField.getText());
activeClient.save();
newItem(null);
fillGrid(null);
}
}
);
defaultSearchMaintenanceInit();
}
private ObservableList<Client> getClients() throws ClassNotFoundException, SQLException {
ObservableList<Client> list = FXCollections.observableArrayList();
Connection conn = DataEntity.getConnection();
// Definer paramsList
List<Object> params = new ArrayList<Object>();
// Maak SQL string
String sqlString = "SELECT * FROM Client ";
sqlString += getWhereClause(params);
sqlString += " ORDER BY lastname ";
System.out.println("sqlString = "+ sqlString);
PreparedStatement pstmt = conn.prepareStatement(sqlString);
DataEntity.addParamsToStatement(pstmt, params);
System.out.println("sql query " + pstmt.toString());
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
Client client = new Client(rs.getInt("id"),
rs.getString("firstname"),
rs.getString("middlename"),
rs.getString("lastname"),
rs.getString("email"),
rs.getString("phonenumber"),
rs.getString("street"),
rs.getString("streetnumber"),
rs.getString("zipcode"),
rs.getString("city"),
rs.getString("country"));
list.add(client);
}
return list;
}
public void doGridSelect(TableRow row) {
Client client = (Client) row.getItem();
client.load(); // Extra laden inactive veld is niet in het grid
fillFields(client);
// delete.setDisable(false);
}
public void newItem(ActionEvent event) {
Client client = new Client();
client.getNew();
fillFields(client);
// Deactivate buttons
deleteBut.setDisable(true);
logBut.setDisable(true);
}
public void delete(ActionEvent event) {
activeClient.delete();
// Set new client
newItem(event);
// Refresh grid
fillGrid(event);
}
public void fillFields(Client client) {
activeClient = client;
if (client.getId() < 0) {
idField.setText("New");
} else {
idField.setText(String.valueOf(client.getId()));
// Activate buttons
deleteBut.setDisable(false);
logBut.setDisable(false);
}
firstnameField.setText(client.getFirstname());
middlenameField.setText(client.getMiddlename());
lastnameField.setText(client.getLastname());
emailField.setText(client.getEmail());
phonenumberField.setText(client.getPhonenumber());
streetField.setText(client.getStreet());
}
public String getWhereClause( List<Object> params) {
String whereString = "";
// Beetje fulltext
String[] searchStrs = getSearchStrings();
String whereLikes = "";
for (int i = 0 ; i < searchStrs.length ; i++){
whereLikes = Utils.glue(whereLikes, "firstname like ?" , " OR ");
params.add("%"+searchStrs[i]+"%");
whereLikes = Utils.glue(whereLikes, "lastname like ?" , " OR ");
params.add("%"+searchStrs[i]+"%");
whereLikes = Utils.glue(whereLikes, "email like ?" , " OR ");
params.add("%"+searchStrs[i]+"%");
}
// Check ook ints
int[] searchInts = getSearchInts();
for (int i = 0 ; i < searchInts.length ; i++){
whereLikes = Utils.glue(whereLikes, "id like ?" , " OR ");
params.add(searchInts[i]);
}
if (!Utils.isEmpty(whereLikes)){
whereLikes = " ( "+ whereLikes+" ) ";
}
whereString = Utils.glue(whereString, whereLikes, " AND ");
if (!Utils.isEmpty(whereString)) {
whereString = " WHERE " +whereString;
}
return whereString;
}
public void fillGrid(ActionEvent event) {
try {
grid.setItems(getClients());
} catch (ClassNotFoundException ex) {
Logger.getLogger(ClientController.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(ClientController.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void showLog(ActionEvent event) {
showLog(activeClient.getTable(), activeClient.getId());
}
}
| true |
da798241b353f6a2084fa08b317eae2d49230714 | Java | 1319280657/testBlob | /src/main/java/GteConnection.java | UTF-8 | 5,962 | 2.28125 | 2 | [] | no_license | import java.io.*;
import java.sql.*;
/**
* @program: testBlob
* @description: ${description}
* @author: RenChao
* @create: 2019-09-29 11:00
**/
public class GteConnection {
public static Connection getConnection() {
Connection conn = null;
System.out.println("开始进行加载驱动类");
// 加载类
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
// 获取连接
conn = DriverManager.getConnection("jdbc:oracle:thin:@r1227.erptest.com:1521:test",
"apps",
"apps");
} catch (Exception e) {
e.printStackTrace();
System.out.println("出现了错误!!!");
}
return conn;
}
public static BlobFiles getBlobFiles() {
// 一步一步来,先进行获取连接的测试
Connection connection;
PreparedStatement preparedStatement;
String sql;
ResultSet resultSet;
Blob blob;
String fileName;
String fileType;
BlobFiles blobFiles = null;
connection = getConnection();
if (connection == null) {
System.out.println("获取链接失败!");
return null;
}
System.out.println("进行SQL语句的查看!");
sql = "SELECT t.file_name, t.file_type ,t.file_byte FROM cux_test_21101 t where t.file_name = '平台管理员证明上传(admin_prove).pdf'";
try {
preparedStatement = connection.prepareStatement(sql);
resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
fileName = resultSet.getString("file_name");
fileType = resultSet.getString("file_type");
blob = resultSet.getBlob("file_byte");
System.out.println("文件名称为:" + fileName + '.' + fileType);
System.out.println("文件内容为:" + blob.toString());
blobFiles = new BlobFiles(blob, fileName, fileType);
}
} catch (SQLException e) {
e.printStackTrace();
}
return blobFiles;
}
public static void setNewBlobFiles(BlobFiles blobFiles) {
/// 进行写入文件的测试
File file;
byte[] bytes = new byte[1000];
// blobFiles = getBlobFiles();
Blob blob = blobFiles.getBlob();
String fileName = blobFiles.fileName;//blobFiles.fileName + '.' + blobFiles.fileType;
Long leng = null;
Integer length;
try {
leng = blob.length();
} catch (SQLException e) {
e.printStackTrace();
System.out.println("获取文件长度出错!");
}
System.out.println("文件长度为" + leng);
file = new File("C:\\Users\\13192\\Desktop\\HAP进行供应商许可证测试\\生成文件路径\\" + fileName);
if (file.exists()) {
System.out.println("文件存在!继续执行下一步骤!");
} else {
System.out.println("文件不存在!执行文件创建步骤!");
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
// 读取源文件的内容,复制进新文件内
try {
InputStream inputStream = blob.getBinaryStream();
FileOutputStream fileOutputStream = new FileOutputStream(file);
while ((length = inputStream.read(bytes)) !=-1) {
fileOutputStream.write(bytes, 0, length);
}
fileOutputStream.close();
System.out.println("文件创建成功!");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
public static BlobFiles getBlobFiles(Integer p_oid ) {
// 一步一步来,先进行获取连接的测试
Connection connection;
PreparedStatement preparedStatement;
String sql;
ResultSet resultSet;
Blob blob = null;
String fileName= null;
String fileType= null;
BlobFiles blobFiles = null;
boolean executeFlag;
connection = getConnection();
if (connection == null) {
System.out.println("获取链接失败!");
return null;
}
System.out.println("进行SQL语句的查看!");
sql = "begin cux_srm_get_vendor_blob_files ( "+ p_oid + "); end ;";
try {
preparedStatement = connection.prepareStatement(sql);
executeFlag = preparedStatement.execute();
/*if (executeFlag){
System.out.println("调用存储过程成功!");
}else{
System.out.println("调用存储过程失败!,结束!");
return null;
}*/
sql = "SELECT t.oid,t.lefal_represent_id_b from cux_srm_support_blob_files_all t where t.oid = " + p_oid;
preparedStatement = connection.prepareStatement(sql);
resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
blob = resultSet.getBlob("lefal_represent_id_b");
}
if (blob != null){
blobFiles = new BlobFiles(blob, fileName, fileType);
}else{
System.out.println("没有获取到BLOB字段");
}
} catch (SQLException e) {
e.printStackTrace();
}
return blobFiles;
}
public static void main(String[] args) {
// 获取文件的的Blob字段
BlobFiles blobFiles = getBlobFiles(1);
//Blob blob = blobFiles.getBlob();
if(blobFiles!= null){
setNewBlobFiles(blobFiles);
}
}
}
| true |
dafe4f6946a83ca6aded1d0e965c01c990019c62 | Java | MartaZab/Twitter | /src/main/java/com/example/twitter/Twitter/controller/CommentController.java | UTF-8 | 1,778 | 2.296875 | 2 | [] | no_license | package com.example.twitter.Twitter.controller;
import com.example.twitter.Twitter.model.dto.CommentDto;
import com.example.twitter.Twitter.model.dto.PostDto;
import com.example.twitter.Twitter.model.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class CommentController {
@Autowired
private CommentService service;
@RequestMapping("/comments")
public ModelAndView commentView(){
return new ModelAndView("comments", "allComments", service.getAllComments());
}
@GetMapping("/addcomment")
public String createNewCommentView(@ModelAttribute CommentDto comment){
return "redirect:addcommentform?postId=" + comment.getPostId();
}
@GetMapping("/addcommentform")
public String createNewComment(@ModelAttribute CommentDto comment, Model model){
model.addAttribute("commentToInsert", comment);
model.addAttribute("postId", comment.getPostId());
return "addcommentform";
}
@PostMapping("/addcommentform")
public String addNewComment(@ModelAttribute CommentDto comment) throws Exception {
System.out.println("Dodajemy nowy komentarz " + comment.getMessage());
service.addComment(comment);
return "index";
}
@PostMapping("/deletecomment")
public String deleteComment(@ModelAttribute("comment") CommentDto comment) throws IllegalAccessException {
System.out.println(comment.getId() + " " + comment.getMessage());
service.deleteComment(comment);
return "redirect:comments";
}
}
| true |
04c552b9f7096f077fe8d1e3fcb1509ad080d4c8 | Java | LIJIEJIE519/algorithm | /ToOffer/src/com/topic2/T_06_buildTree.java | UTF-8 | 1,041 | 3.125 | 3 | [] | no_license | package com.topic2;
import java.util.HashMap;
import java.util.Map;
/**
* @Author LJ
* @Date 2020/12/10
* msg
*/
public class T_06_buildTree {
int[] preorder;
Map<Integer, Integer> map = new HashMap<>();
public TreeNode buildTree(int[] preorder, int[] inorder) {
if (preorder == null || preorder.length == 0)
return null;
this.preorder = preorder;
for(int i = 0; i < inorder.length; i++) {
map.put(inorder[i], i);
}
return help(0, 0, preorder.length - 1);
}
public TreeNode help(int root, int left, int right) {
if (left > right)
return null;
TreeNode node = new TreeNode(this.preorder[root]);
int index = map.get(preorder[root]);
node.left = help(root+1, left, index-1);
//前序[根,左子树,右子树] root+index-left+1 : 下一个根=前序中取出上一个根+左子树个数(index-left) + 1
node.right = help(root+index-left+1, index+1, right);
return node;
}
}
| true |
b5788764419f983b50ef5055ca9e516058ba0af5 | Java | bipulmanjhi001/Inventory | /app/src/main/java/com/broadwaybazar/model/Company_Product_List.java | UTF-8 | 756 | 2.25 | 2 | [] | no_license | package com.broadwaybazar.model;
public class Company_Product_List {
private String ids = "";
private String types = "";
private boolean checkeds = false;
public Company_Product_List(String ids, String types, boolean checkeds) {
this.ids = ids;
this.types = types;
this.checkeds = checkeds;
}
public String getIds() {
return ids;
}
public void setIds(String ids) {
this.ids = ids;
}
public String getTypes() {
return types;
}
public void setTypes(String types) {
this.types = types;
}
public boolean isCheckeds() {
return checkeds;
}
public void setCheckeds(boolean checkeds) {
this.checkeds = checkeds;
}
}
| true |
888275fbd91d3ba865a0d81e63f341a7c5ae7f3b | Java | 784134748/platform | /src/main/java/com/yalonglee/platform/service/example/EnversServiceI.java | UTF-8 | 476 | 1.648438 | 2 | [] | no_license | package com.yalonglee.platform.service.example;
import com.yalonglee.common.service.BaseServiceI;
import com.yalonglee.platform.entity.example.envers.Customer;
/**
* <p>《一句话功能简述》
* <p><功能详细描述>
* <p>
* <p>Copyright (c) 2017, listener@iflytek.com All Rights Reserve</p>
* <p>Company : 科大讯飞</p>
*
* @author listener
* @version [V1.0, 2017/12/10]
* @see [相关类/方法]
*/
public interface EnversServiceI extends BaseServiceI<Customer>{
}
| true |
fd062575f6deb4720b7e8ac7980ae0f9c0b069c0 | Java | exylaci/training-solutions | /src/main/java/erettsegi2019/PassangerData.java | UTF-8 | 2,272 | 2.84375 | 3 | [] | no_license | package erettsegi2019;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Objects;
public class PassangerData {
private int stop;
private LocalDateTime time;
private String ID;
private Type type;
private LocalDate expires;
private int remainedTravels;
public PassangerData(int stop, LocalDateTime time, String ID, Type type, LocalDate expires) {
this.stop = stop;
this.time = time;
this.ID = ID;
this.type = type;
this.expires = expires;
}
public PassangerData(int stop, LocalDateTime time, String ID, Type type, int remainedTravels) {
this.stop = stop;
this.time = time;
this.ID = ID;
this.type = type;
this.remainedTravels = remainedTravels;
}
public int getStop() {
return stop;
}
public LocalDateTime getTime() {
return time;
}
public String getID() {
return ID;
}
public Type getType() {
return type;
}
public LocalDate getExpires() {
return expires;
}
public int getRemainedTravels() {
return remainedTravels;
}
@Override
public String toString() {
return "PassangerData{" +
"stop=" + stop +
", time=" + time +
", ID='" + ID + '\'' +
", type=" + type +
", expires=" + expires +
", remainedTravels=" + remainedTravels +
'}';
// return String.format(new Locale("hu","HU"),"%2d. %tc %s %s %tc %d",
// stop, time , ID, type.toString() , expires ,remainedTravels );
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
PassangerData that = (PassangerData) o;
return stop == that.stop &&
remainedTravels == that.remainedTravels
&& time.equals(that.time) &&
ID.equals(that.ID) &&
type == that.type &&
expires.equals(that.expires);
}
@Override
public int hashCode() {
return Objects.hash(stop, time, ID, type, expires, remainedTravels);
}
}
| true |
d6c83117e4c15d9b0e6d7ab25d4f52f5007c044b | Java | 99Nistha/Java-Programming | /Recursion/allIndex.java | UTF-8 | 1,009 | 3.578125 | 4 | [] | no_license | import java.util.Scanner;
public class allIndex {
public static void main(String[] args) {
Scanner scn= new Scanner(System.in);
System.out.print("Enter the sie=ze of array: ");
int n= scn.nextInt();
System.out.print("Enter all the values: ");
int[] arr= new int[n];
for(int i=0;i<n;i++) arr[i]= scn.nextInt();
System.out.print("Enter the value you want to search all index: ");
int val= scn.nextInt();
int[] d= index(arr,0 , val,0);
display(d);
}
public static int[] index(int[] a, int si, int val, int count) {
if(si==a.length) {
int[] base = new int[count];
return base;
}
int[] in=null;
if(a[si]==val) in= index(a,si+1, val, count+1);
else in= index(a,si+1, val, count);
if(a[si]==val) in[count]=si;
return in;
}
public static void display(int[] a) {
for(int i=0;i<a.length;i++) System.out.print(a[i]+ " ");
}
}
| true |
de2778af9fb3ba3bc925c62ff3fc4b97db479c45 | Java | tiagods/sisrh-desktop | /src/main/java/com/plkrhone/sisrh/config/init/VersaoSistema.java | UTF-8 | 1,571 | 2.359375 | 2 | [] | no_license | package com.plkrhone.sisrh.config.init;
import com.plkrhone.sisrh.config.PropsConfig;
import com.plkrhone.sisrh.config.enums.PropsEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static com.plkrhone.sisrh.config.PropsConfig.getValue;
public class VersaoSistema extends PropsConfig {
private static String nome="";
private static String versao="";
private static String data="";
private static String versaoBanco="";
private static String detalhes="";
Logger log = LoggerFactory.getLogger(VersaoSistema.class);
private static VersaoSistema instance;
public static VersaoSistema getInstance() {
if(instance == null)
instance = new VersaoSistema(PropsEnum.CONFIG);
return instance;
}
public VersaoSistema(PropsEnum propsEnum) {
super(propsEnum);
this.nome=getValue("sis.nome");
this.versao=getValue("sis.versao");
this.data=getValue("sis.data");
this.versaoBanco=getValue("sis.banco");
this.detalhes=getValue("sis.detalhes");
}/**
* @return the nome
*/
public String getNome() {
return nome;
}
/**
* @return the versao
*/
public String getVersao() {
return versao;
}
public String getDate(){
return data;
}
/**
* @return the versaoBanco
*/
public String getVersaoBanco() {
return versaoBanco;
}
public String getDetalhes(){
return this.detalhes;
}
}
| true |
e672552ef7c58592b62a2d0a1a02827c2445d396 | Java | 0xera/rAndroidDev | /app/src/test/java/ru/aydarov/randroid/data/util/RedditUtilsNetTest.java | UTF-8 | 1,400 | 1.90625 | 2 | [] | no_license | package ru.aydarov.randroid.data.util;
import org.junit.Assert;
import org.junit.Test;
import java.util.Map;
public class RedditUtilsNetTest {
@Test
public void getHttpBasicAuthHeader() {
Map<String, String> httpBasicAuthHeader = RedditUtilsNet.getHttpBasicAuthHeader();
Assert.assertEquals(1, httpBasicAuthHeader.size());
Assert.assertNotNull(httpBasicAuthHeader.get(RedditUtilsNet.AUTHORIZATION_KEY));
}
@Test
public void getOAuthHeader() {
Map<String, String> oAuthHeader = RedditUtilsNet.getOAuthHeader("1234");
Assert.assertEquals(2, oAuthHeader.size());
Assert.assertTrue(oAuthHeader.get(RedditUtilsNet.USER_AGENT_KEY).contains(RedditUtilsNet.USER_AGENT));
Assert.assertTrue(oAuthHeader.get(RedditUtilsNet.AUTHORIZATION_KEY).contains("1234"));
}
@Test
public void getParamsAuth() {
Map<String, String> paramsAuth = RedditUtilsNet.getParamsAuth("1234");
Assert.assertEquals(3, paramsAuth.size());
Assert.assertTrue(paramsAuth.get(RedditUtilsNet.RESPONSE_TYPE).contains("1234"));
}
@Test
public void getParamsRefresh() {
Map<String, String> paramsRefresh = RedditUtilsNet.getParamsRefresh("1234");
Assert.assertEquals(2, paramsRefresh.size());
Assert.assertTrue(paramsRefresh.get(RedditUtilsNet.REFRESH_TOKEN_KEY).contains("1234"));
}
} | true |
a428688cf5ea852e437da03021f6bbf91b7d76c5 | Java | Andreas237/AndroidPolicyAutomation | /ExtractedJars/RT_News_com.rt.mobile.english/javafiles/com/google/android/gms/analytics/zzk$zza.java | UTF-8 | 2,163 | 2.125 | 2 | [
"MIT"
] | permissive | // Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) annotate safe
package com.google.android.gms.analytics;
import java.util.concurrent.*;
// Referenced classes of package com.google.android.gms.analytics:
// zzk, zzm
final class zzk$zza extends ThreadPoolExecutor
{
protected final RunnableFuture newTaskFor(Runnable runnable, Object obj)
{
return ((RunnableFuture) (new zzm(this, runnable, obj)));
// 0 0:new #45 <Class zzm>
// 1 3:dup
// 2 4:aload_0
// 3 5:aload_1
// 4 6:aload_2
// 5 7:invokespecial #48 <Method void zzm(zzk$zza, Runnable, Object)>
// 6 10:areturn
}
final zzk zzsi;
public zzk$zza(zzk zzk1)
{
zzsi = zzk1;
// 0 0:aload_0
// 1 1:aload_1
// 2 2:putfield #13 <Field zzk zzsi>
super(1, 1, 1L, TimeUnit.MINUTES, ((java.util.concurrent.BlockingQueue) (new LinkedBlockingQueue())));
// 3 5:aload_0
// 4 6:iconst_1
// 5 7:iconst_1
// 6 8:lconst_1
// 7 9:getstatic #19 <Field TimeUnit TimeUnit.MINUTES>
// 8 12:new #21 <Class LinkedBlockingQueue>
// 9 15:dup
// 10 16:invokespecial #24 <Method void LinkedBlockingQueue()>
// 11 19:invokespecial #27 <Method void ThreadPoolExecutor(int, int, long, TimeUnit, java.util.concurrent.BlockingQueue)>
setThreadFactory(((java.util.concurrent.ThreadFactory) (new zzk$zzb(((zzl) (null))))));
// 12 22:aload_0
// 13 23:new #29 <Class zzk$zzb>
// 14 26:dup
// 15 27:aconst_null
// 16 28:invokespecial #32 <Method void zzk$zzb(zzl)>
// 17 31:invokevirtual #36 <Method void setThreadFactory(java.util.concurrent.ThreadFactory)>
allowCoreThreadTimeOut(true);
// 18 34:aload_0
// 19 35:iconst_1
// 20 36:invokevirtual #40 <Method void allowCoreThreadTimeOut(boolean)>
// 21 39:return
}
}
| true |
b143f1779b9fbdb0c9729c0311df15f3ab501683 | Java | sureshdraco/RedditShow | /app/src/main/java/redit/com/redditshow/network/SuccessListener.java | UTF-8 | 362 | 2.0625 | 2 | [] | no_license | package redit.com.redditshow.network;
import com.android.volley.Response;
import redit.com.redditshow.network.reply.ReplyBase;
public abstract class SuccessListener<T extends ReplyBase> implements Response.Listener<T> {
public abstract void onSuccessResponse(T response);
@Override
public void onResponse(T response) {
onSuccessResponse(response);
}
}
| true |
02853a1a14c91facb7158c1db7494060519bda98 | Java | fanghuabing/happylifeplat-transaction | /happylifeplat-transaction-common/src/main/java/com/happylifeplat/transaction/common/netty/serizlize/MessageEncoder.java | UTF-8 | 1,342 | 1.804688 | 2 | [
"Apache-2.0"
] | permissive | /*
*
* Copyright 2017-2018 549477611@qq.com(xiaoyu)
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, see <http://www.gnu.org/licenses/>.
*
*/
package com.happylifeplat.transaction.common.netty.serizlize;
import com.happylifeplat.transaction.common.netty.MessageCodecService;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
public abstract class MessageEncoder extends MessageToByteEncoder<Object> {
private MessageCodecService util = null;
public MessageEncoder(final MessageCodecService util) {
this.util = util;
}
protected void encode(final ChannelHandlerContext ctx, final Object msg, final ByteBuf out) throws Exception {
util.encode(out, msg);
}
}
| true |
6b4820ea5b708d938c0273315105cd9a97de5f93 | Java | OGNet/Commons | /src/main/java/com/caved_in/commons/command/commands/ClearInventoryCommand.java | UTF-8 | 1,450 | 3.0625 | 3 | [] | no_license | package com.caved_in.commons.command.commands;
import com.caved_in.commons.Messages;
import com.caved_in.commons.command.Command;
import com.caved_in.commons.player.Players;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class ClearInventoryCommand {
@Command(name = "ci", usage = "/ci [player]", permission = "tunnels.common.clearinventory", aliases = {"clearinventory", "clearinv"})
public void onClearInventoryCommand(CommandSender commandSender, String[] args) {
//Check if we've got a player using this command
Player player = null;
if (args.length > 0) {
String playerName = args[0];
//Check if there's a player online with the name in our argument
if (Players.isOnline(playerName)) {
//Assign the player to clear the inventory of
player = Players.getPlayer(playerName);
} else {
Players.sendMessage(commandSender, Messages.playerOffline(playerName));
return;
}
} else {
//Check if the commandsender is a player
if (commandSender instanceof Player) {
//Assign the player variable to the player sending the command
player = (Player) commandSender;
} else {
Players.sendMessage(commandSender, Messages.invalidCommandUsage("name"));
return;
}
}
//Clear the players inventory
Players.clearInventory(player, true);
//Send them a message saying their inventory was cleared
Players.sendMessage(player, Messages.INVENTORY_CLEARED);
}
}
| true |
8ab231fb099ca551767d6d6c7dd1fae284f340fe | Java | puneetnegi1986/PDF-AND-Mail-PARSER | /TextExtractor.java | UTF-8 | 9,535 | 2.515625 | 3 | [] | no_license | package com.pro;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import org.apache.pdfbox.text.PDFTextStripperByArea;
public class TextExtractor {
public static final String EMAIL_FILE_PATH = "F:\\cvbqn19bu51s5ptqiddk1e2p9qnvf8qucoird201";
public static final String ATTACHMENT_PATH = "F:\\emailparserpoc";
public static void main(String[] args) {
try {
String path = extractEML(EMAIL_FILE_PATH);
generateTxtFromPDF(path);
} catch (Exception ex) {
ex.printStackTrace();
}
}
/**
*
* @param filename
*/
private static void generateTxtFromPDF(String filename) {
Scanner file = null;
try (PDDocument document = PDDocument.load(new File(filename))) {
document.getClass();
if (!document.isEncrypted()) {
PDFTextStripperByArea stripper = new PDFTextStripperByArea();
stripper.setSortByPosition(true);
PDFTextStripper tStripper = new PDFTextStripper();
String pdfFileInText = tStripper.getText(document);
pdfFileInText = removeBlankLine(pdfFileInText);
pdfFileInText = cleanTextContent(pdfFileInText);
System.out.println(pdfFileInText);
file = new Scanner(new StringReader(pdfFileInText));
getTotalDue(file);
getcustomerID(file);
getBalanceDue(file);
String[] tableHeaderKeys = new String[] {"INVOICE #", "DATE", "TOTAL DUE", "DUE DATE", "TERMS"};
String[] tableDataRegex = new String[] {"\\d{5}-\\d{4}", "\\d{2}/\\d{2}/\\d{4}",
"\\${1}[0-9,]+\\.\\d{2}", "\\d{2}/\\d{2}/\\d{4}", "[A-Za-z]+[\\s]+\\d+"};
readTableContent(tableHeaderKeys, "\\s+", pdfFileInText, "\\s+",
tableDataRegex);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != file) {
file.close();
}
}
}
/**
*
* @param file
* @return
* @throws Exception
*/
private static String getcustomerID(Scanner file) throws Exception {
String lineData = null;
while (file.hasNext()) {
lineData = file.nextLine().trim();
if (lineData.contains("CUSTOMER ID") || lineData.contains("CUSTOMERID")) {
lineData = file.nextLine().trim();
break;
}
}
System.out.println("Customer ID: " + lineData);
return lineData;
}
/**
*
* @param file
* @return
* @throws Exception
*/
private static String getTotalDue(Scanner file) throws Exception {
String lineData = null;
String totalDue = null;
while (file.hasNext()) {
lineData = file.nextLine().trim();
if (lineData.contains("TOTAL DUE") || lineData.contains("TOTALDUE")) {
lineData = file.nextLine().trim();
totalDue = parseCurrancy(lineData, " ");
break;
}
}
System.out.println("TOTAL DUE: " + totalDue);
return lineData;
}
/**
*
* @param file
* @return
* @throws Exception
*/
private static String getBalanceDue(Scanner file) throws Exception {
String lineData = null;
String totalDue = null;
while (file.hasNext()) {
lineData = file.nextLine().trim();
if (lineData.contains("BALANCE DUE") || lineData.contains("BALANCEDUE")) {
totalDue = parseCurrancy(lineData, " ");
break;
}
}
System.out.println("BALANCE DUE: " + totalDue);
return lineData;
}
/**
*
* @param lineData
* @param dataDelimiter
* @return
*/
private static String parseCurrancy(String lineData, String dataDelimiter) {
List<String> dataList = Arrays.asList(lineData.split(dataDelimiter));
String totalDue = null;
for (String data : dataList) {
if (data.contains("$")) {
totalDue = data.replaceAll("[^\\d.]+", "");
}
}
return totalDue;
}
/**
*
* @param pdfFileInText
* @return
*/
private static String removeBlankLine(String pdfFileInText) {
return pdfFileInText.replaceAll("(?m)^[ \t]*\r?\n", "");
}
/**
*
* @param rawData
* @return
*/
private static String cleanTextContent(String rawData) {
rawData = rawData.replaceAll("[^\\x00-\\x7F]", "");
rawData = rawData.replaceAll("[\\p{Cntrl}&&[^\r\n\t]]", "");
return rawData;
}
/**
*
* @param path
* @return
* @throws Exception
*/
public static String extractEML(String path) throws Exception {
try {
String downloadedFilePath = null;
Properties props = new Properties();
Session mailSession = Session.getDefaultInstance(props, null);
InputStream source = new FileInputStream(path);
MimeMessage message = new MimeMessage(mailSession, source);
System.out.println("Subject : " + message.getSubject());
System.out.println("From : " + message.getFrom()[0]);
System.out.println("--------------");
System.out.println("Body : " + message.getContent());
String contentType = message.getContentType();
if (contentType.contains("multipart")) {
System.out.println("Multipart EMail File");
Multipart multiPart = (Multipart) message.getContent();
int numberOfParts = multiPart.getCount();
System.out.println("Parts:::" + numberOfParts);
for (int partCount = 0; partCount < numberOfParts; partCount++) {
MimeBodyPart part = (MimeBodyPart) multiPart.getBodyPart(partCount);
if (Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) {
String fileName = part.getFileName();
String extension = "";
downloadedFilePath = ATTACHMENT_PATH + File.separator + fileName;
int i = fileName.lastIndexOf(".");
if (i > 0) {
extension = fileName.substring(i + 1);
}
if (extension.equalsIgnoreCase("pdf")) {
new File(downloadedFilePath);
part.saveFile(downloadedFilePath);
}
}
}
}
return downloadedFilePath;
} catch (Exception e) {
return null;
}
}
/**
*
* @param tableHeaderKeys
* @param keyDelimiter
* @param pdfFileInText
* @param dataDelimiter
* @param tableValueRegex
* @return
* @throws Exception
*/
public static Map<String, List<String>> readTableContent(String[] tableHeaderKeys, String keyDelimiter, String pdfFileInText,
String dataDelimiter, String[] tableValueRegex)throws Exception {
Map<String, List<String>> tableDataMap = new LinkedHashMap<>();
String regex = regexCreator(keyDelimiter, tableHeaderKeys);
Pattern pattern = Pattern.compile(regex);
try(Scanner file = new Scanner(new StringReader(pdfFileInText))){
while (file.hasNextLine()) {
String line = file.nextLine();
Matcher matcher = pattern.matcher(line);
if (matcher.find()) {
for (int i = 1; i <= tableHeaderKeys.length; i++) {
tableDataMap.put(matcher.group(i), new ArrayList<String>());
}
readTable(tableDataMap, dataDelimiter, file, tableValueRegex);
}
}
}
System.out.println("----------------- Table Data ------------------------");
tableDataMap.entrySet()
.forEach(entry -> System.out.println(entry.getKey() + " : " + entry.getValue().toString()));
return tableDataMap;
}
/**
*
* @param tableDataMap
* @param dataDelimiter
* @param file
* @param tableValueRegex
* @throws Exception
*/
public static void readTable(Map<String, List<String>> tableDataMap, String dataDelimiter, Scanner file,
String[]tableValueRegex)throws Exception {
String line = file.nextLine();
String regex = regexCreator(dataDelimiter, tableValueRegex);
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(line);
if (matcher.find()) {
int index = 1;
for (Entry<String, List<String>> entry : tableDataMap.entrySet()) {
entry.getValue().add(matcher.group(index));
index++;
}
}
}
/**
*
* @param delimiter
* @param regexList
* @return
* @throws Exception
*/
public static String regexCreator(String delimiter, String... regexList)throws Exception {
StringBuilder regex = new StringBuilder();
delimiter = "[" + delimiter + "]";
for (String tableHeaderKey : regexList) {
regex.append("(" + tableHeaderKey + ")").append(delimiter);
}
regex.delete(regex.lastIndexOf(delimiter), regex.length());
return regex.toString();
}
/**
*
* @param delimiter
* @param regexOfkey
* @param regexOfValue
* @param file
* @return
* @throws Exception
*/
public static Record lineRecordReader(String delimiter,String regexOfkey, String regexOfValue,Scanner file)throws Exception {
Record record=null;
String line = file.nextLine();
String regex =regexCreator(delimiter,regexOfkey,regexOfValue);
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(line);
if (matcher.find()) {
record= new Record();
record.setKey(matcher.group(1));
record.setValue(matcher.group(2));
}
return record;
}
public static class Record{
String key;
String value;
/**
* @return the key
*/
public String getKey() {
return key;
}
/**
* @param key the key to set
*/
public void setKey(String key) {
this.key = key;
}
/**
* @return the value
*/
public String getValue() {
return value;
}
/**
* @param value the value to set
*/
public void setValue(String value) {
this.value = value;
}
}
}
| true |
20720986dbf3c928a16e2d25fd2aaea325a6d5db | Java | CoderIntuition/api | /src/main/java/com/coderintuition/CoderIntuition/pojos/request/cms/ProblemDto.java | UTF-8 | 1,265 | 1.96875 | 2 | [] | no_license | package com.coderintuition.CoderIntuition.pojos.request.cms;
import com.coderintuition.CoderIntuition.enums.Difficulty;
import com.coderintuition.CoderIntuition.enums.ProblemCategory;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.util.List;
@Getter
@Setter
@NoArgsConstructor
public class ProblemDto {
@NotBlank
@Size(max = 300)
private String name;
@NotBlank
@Size(max = 300)
private String urlName;
@NotNull
private Boolean plusOnly;
@NotNull
private ProblemCategory category;
@NotNull
private Difficulty difficulty;
@NotBlank
private String description;
@NotBlank
private String pythonCode;
@NotNull
private String javaCode;
@NotNull
private String javascriptCode;
@NotEmpty
private List<ProblemStepDto> problemSteps;
@NotEmpty
private List<TestCaseDto> testCases;
@NotEmpty
private List<SolutionDto> solutions;
@NotEmpty
private List<ArgumentDto> arguments;
@NotNull
private ReturnTypeDto returnType;
}
| true |
f20b119724d8955356a95ebbebdf42d54be9cd8e | Java | raphagmoreira/Biblioteca | /src/main/java/br/biblioteca/livros/repository/UsuarioRepository.java | UTF-8 | 1,612 | 2.53125 | 3 | [] | no_license | package br.biblioteca.livros.repository;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import br.biblioteca.livros.beans.Role;
import br.biblioteca.livros.beans.Usuario;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Repository;
@Repository
public class UsuarioRepository {
@Autowired
private UsuarioDao usuarioDao;
@Autowired
private RoleDao roleDao;
PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
UsuarioRepository() {
/*Usuario basic = new Usuario("teste",passwordEncoder.encode("123456"));
basic.getRoles().add(new Role("ROLE_BASIC"));
usuarios.add(basic);
Usuario admin = new Usuario("admin", passwordEncoder.encode("123456"));
admin.getRoles().add(new Role("ROLE_BASIC"));
admin.getRoles().add(new Role("ROLE_ADMIN"));
usuarios.add(admin);*/
//usuarios = usuarioDao.findAll();
}
public Usuario findByUsername(String username) {
Usuario usuario = null;
for (Usuario u : this.findAll()) {
if (u.getUsername().equals(username)) {
usuario = u;
}
}
//System.out.println("usuário encontrado: " + usuario.getUsername());
return usuario;
}
public Usuario findById(Long id) {
return usuarioDao.findOne(id);
}
public void save(Usuario usuario, Role role) {
usuarioDao.save(usuario);
roleDao.save(role);
}
public List<Usuario> findAll(){
return usuarioDao.findAll();
}
}
| true |
b6fe4a07c2c805f88079cc04290325e1deb14c4d | Java | PlayerNguyen/Weaponist | /src/main/java/com/playernguyen/weaponist/runnable/ScopeRunnable.java | UTF-8 | 2,101 | 2.390625 | 2 | [] | no_license | package com.playernguyen.weaponist.runnable;
import com.playernguyen.weaponist.Weaponist;
import com.playernguyen.weaponist.entity.Shooter;
import com.playernguyen.weaponist.util.ActionBar;
import com.playernguyen.weaponist.util.LocationUtil;
import net.md_5.bungee.api.ChatColor;
import org.bukkit.scheduler.BukkitRunnable;
public class ScopeRunnable extends BukkitRunnable {
private final Shooter shooter;
private BreatheChargerRunnable currentRunnable = null;
public ScopeRunnable(Shooter shooter) {
this.shooter = shooter;
}
@Override
public void run() {
if (!shooter.isScoping()) {
// Charge
shooter.setBreathing(false);
new BreatheChargerRunnable(shooter, this)
.runTaskTimerAsynchronously(Weaponist.getWeaponist(), 0, 0);
// Cancel the task
cancel();
return;
}
// If sneaking
if (shooter.asPlayer().isSneaking()) {
shooter.setBreathing(true);
shooter.setBreathLevel(shooter.getBreathLevel() - 0.1d);
} else {
shooter.setBreathing(false);
if (shooter.getBreathLevel() < shooter.getMaxBreathLevel())
new BreatheChargerRunnable(shooter, this)
.runTaskTimerAsynchronously(Weaponist.getWeaponist(), 20, 20);
}
if (shooter.isBreathing() && shooter.getBreathLevel() <= 0) {
shooter.setBreathing(false);
}
// Always display breath level
new ActionBar.Percentage(shooter.getMaxBreathLevel(), shooter.getBreathLevel())
.activeColor(ChatColor.AQUA)
.backgroundColor(ChatColor.GRAY)
.prefix(ChatColor.AQUA + ": [-]")
.suffix("[-] :")
.sendActionBar(shooter.asPlayer());
if (!shooter.isBreathing())
LocationUtil.createScopeNoise(shooter.asPlayer(), 3);
}
public void setCurrentRunnable(BreatheChargerRunnable currentRunnable) {
this.currentRunnable = currentRunnable;
}
}
| true |
b409ca8b35edc45dc64440a5fbca8c3e8f4422f4 | Java | jmansiya/GestionTurnosDeTrabajo | /GestionTurnosDeTrabajo/GestionTurnosPersistencia/src/main/java/org/sun/resorts/holidays/persistence/service/impl/PuestoDeTrabajoServiceImpl.java | UTF-8 | 3,826 | 2.078125 | 2 | [] | no_license | /*
* Created on 31 oct 2015 ( Time 10:51:35 )
* Generated by Telosys Tools Generator ( version 2.1.0 )
*/
package org.sun.resorts.holidays.persistence.service.impl;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;
import org.sun.resorts.holidays.model.PuestoDeTrabajo;
import org.sun.resorts.holidays.model.jpa.PuestoDeTrabajoEntity;
import java.util.List;
import org.sun.resorts.holidays.persistence.service.PuestoDeTrabajoService;
import org.sun.resorts.holidays.persistence.service.mapping.PuestoDeTrabajoServiceMapper;
import org.sun.resorts.holidays.data.repository.jpa.PuestoDeTrabajoJpaRepository;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
/**
* Implementation of PuestoDeTrabajoService
*/
@Component
@Transactional
public class PuestoDeTrabajoServiceImpl implements PuestoDeTrabajoService {
@Resource
private PuestoDeTrabajoJpaRepository puestoDeTrabajoJpaRepository;
@Resource
private PuestoDeTrabajoServiceMapper puestoDeTrabajoServiceMapper;
@Override
public PuestoDeTrabajo findById(Integer idpuestoDeTrabajo) {
PuestoDeTrabajoEntity puestoDeTrabajoEntity = puestoDeTrabajoJpaRepository.findOne(idpuestoDeTrabajo);
return puestoDeTrabajoServiceMapper.mapPuestoDeTrabajoEntityToPuestoDeTrabajo(puestoDeTrabajoEntity);
}
@Override
public List<PuestoDeTrabajo> findAll() {
Iterable<PuestoDeTrabajoEntity> entities = puestoDeTrabajoJpaRepository.findAll();
List<PuestoDeTrabajo> beans = new ArrayList<PuestoDeTrabajo>();
for(PuestoDeTrabajoEntity puestoDeTrabajoEntity : entities) {
beans.add(puestoDeTrabajoServiceMapper.mapPuestoDeTrabajoEntityToPuestoDeTrabajo(puestoDeTrabajoEntity));
}
return beans;
}
@Override
public PuestoDeTrabajo save(PuestoDeTrabajo puestoDeTrabajo) {
return update(puestoDeTrabajo) ;
}
@Override
public PuestoDeTrabajo create(PuestoDeTrabajo puestoDeTrabajo) {
PuestoDeTrabajoEntity puestoDeTrabajoEntity = puestoDeTrabajoJpaRepository.findOne(puestoDeTrabajo.getIdpuestoDeTrabajo());
if( puestoDeTrabajoEntity != null ) {
throw new IllegalStateException("already.exists");
}
puestoDeTrabajoEntity = new PuestoDeTrabajoEntity();
puestoDeTrabajoServiceMapper.mapPuestoDeTrabajoToPuestoDeTrabajoEntity(puestoDeTrabajo, puestoDeTrabajoEntity);
PuestoDeTrabajoEntity puestoDeTrabajoEntitySaved = puestoDeTrabajoJpaRepository.save(puestoDeTrabajoEntity);
return puestoDeTrabajoServiceMapper.mapPuestoDeTrabajoEntityToPuestoDeTrabajo(puestoDeTrabajoEntitySaved);
}
@Override
public PuestoDeTrabajo update(PuestoDeTrabajo puestoDeTrabajo) {
PuestoDeTrabajoEntity puestoDeTrabajoEntity = puestoDeTrabajoJpaRepository.findOne(puestoDeTrabajo.getIdpuestoDeTrabajo());
puestoDeTrabajoServiceMapper.mapPuestoDeTrabajoToPuestoDeTrabajoEntity(puestoDeTrabajo, puestoDeTrabajoEntity);
PuestoDeTrabajoEntity puestoDeTrabajoEntitySaved = puestoDeTrabajoJpaRepository.save(puestoDeTrabajoEntity);
return puestoDeTrabajoServiceMapper.mapPuestoDeTrabajoEntityToPuestoDeTrabajo(puestoDeTrabajoEntitySaved);
}
@Override
public void delete(Integer idpuestoDeTrabajo) {
puestoDeTrabajoJpaRepository.delete(idpuestoDeTrabajo);
}
public PuestoDeTrabajoJpaRepository getPuestoDeTrabajoJpaRepository() {
return puestoDeTrabajoJpaRepository;
}
public void setPuestoDeTrabajoJpaRepository(PuestoDeTrabajoJpaRepository puestoDeTrabajoJpaRepository) {
this.puestoDeTrabajoJpaRepository = puestoDeTrabajoJpaRepository;
}
public PuestoDeTrabajoServiceMapper getPuestoDeTrabajoServiceMapper() {
return puestoDeTrabajoServiceMapper;
}
public void setPuestoDeTrabajoServiceMapper(PuestoDeTrabajoServiceMapper puestoDeTrabajoServiceMapper) {
this.puestoDeTrabajoServiceMapper = puestoDeTrabajoServiceMapper;
}
}
| true |
0d9d3530b4edeb0dfe22d05e4535f324eb98bffb | Java | mariapoilao/MaterialFinal | /app/src/main/java/com/example/mariapoilao/materialfinal/DetalleLabiales.java | UTF-8 | 1,403 | 1.90625 | 2 | [] | no_license | package com.example.mariapoilao.materialfinal;
import android.content.Intent;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.widget.ImageView;
import com.squareup.picasso.Picasso;
public class DetalleLabiales extends AppCompatActivity {
private CollapsingToolbarLayout collapsingToolbarLayout;
private Labial p;
private String marca,precio,urlfoto;
private Bundle b;
private Intent i;
private ImageView foto;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detalle_labiales);
Toolbar toolbar= (Toolbar)findViewById(R.id.toolbar2);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
i = getIntent();
b=i.getBundleExtra("datos");
marca = b.getString("marca");
precio = b.getString("precio");
urlfoto = b.getString("urlfoto");
collapsingToolbarLayout = (CollapsingToolbarLayout)findViewById(R.id.collapsing_toolbar);
foto = (ImageView)findViewById(R.id.fotoLabial);
Picasso.with(getApplicationContext()).load(urlfoto).into(foto);
collapsingToolbarLayout.setTitle(marca+" "+precio);
}
} | true |
59798a5cbf22530be1e272fd543cd298f6ee3c5b | Java | BryanFriestad/CyCap | /src/main/java/com/cycapservers/game/AnimatedEntity.java | UTF-8 | 1,303 | 3.25 | 3 | [] | no_license | package com.cycapservers.game;
public class AnimatedEntity extends Entity {
protected int num_of_frames;
protected int time_length;
protected boolean looping;
protected long startTime;
/**
* the amount of time in ms for each frame in the animation
*/
protected double frame_time;
public AnimatedEntity(int id, int sprIdx, double x, double y, double w, double h, double r, double a, String entity_id, int frames, int time, boolean looping) {
super(id, sprIdx, x, y, w, h, r, a, entity_id);
this.num_of_frames = frames;
this.time_length = time;
this.looping = looping;
this.startTime = System.currentTimeMillis();
this.frame_time = (double) this.time_length / (double) this.num_of_frames;
}
/**
* Updates the current frame(sprite index)
* @return if the entity is finished with it's animation, this will return true, signaling it is to be deleted
*/
protected boolean updateFrame() {
long run_time = (System.currentTimeMillis() - this.startTime);
if(run_time > this.time_length) {
if(!this.looping) return true;
}
this.spriteIndex = (int) ((run_time % this.time_length) / (this.frame_time));
if(this.spriteIndex == this.num_of_frames) {
this.spriteIndex = this.num_of_frames - 1; //we don't want to go too many frames
}
return false;
}
}
| true |
3656541990505328d32e67a8bc73b259439d0b2c | Java | ca814495571/javawork | /fucai/jweb_appmanagement/src/main/java/com/cqfc/management/model/LotterySaleDetail.java | UTF-8 | 981 | 2.15625 | 2 | [] | no_license | package com.cqfc.management.model;
import java.io.Serializable;
/**
* 站点各种彩票的某年某月的销售量
*
* @author Administrator
*
*/
public class LotterySaleDetail implements Serializable {
/**
*
*/
private static final long serialVersionUID = 6845725451355426686L;
private int day;
private int saleNum;
private String lotteryType;
public LotterySaleDetail() {
super();
// TODO Auto-generated constructor stub
}
public LotterySaleDetail(int day, int saleNum, String lotteryType) {
super();
this.day = day;
this.saleNum = saleNum;
this.lotteryType = lotteryType;
}
public int getDay() {
return day;
}
public void setDay(int day) {
this.day = day;
}
public int getSaleNum() {
return saleNum;
}
public void setSaleNum(int saleNum) {
this.saleNum = saleNum;
}
public String getLotteryType() {
return lotteryType;
}
public void setLotteryType(String lotteryType) {
this.lotteryType = lotteryType;
}
}
| true |
c069b48024c0694e7310fc6588fcaab3c5a72d0c | Java | enzoteles/DataBindingRoom | /app/src/main/java/com/example/enzoteles/databinding/view/ContentFragment.java | UTF-8 | 2,120 | 2.09375 | 2 | [] | no_license | package com.example.enzoteles.databinding.view;
import android.app.Fragment;
import android.arch.lifecycle.LifecycleOwner;
import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.example.enzoteles.databinding.R;
import com.example.enzoteles.databinding.databinding.ContentBinding;
import com.example.enzoteles.databinding.model.po.EnzoPO;
import com.example.enzoteles.databinding.util.ManagerFragment;
import com.example.enzoteles.databinding.viewmodel.ContentViewModel;
import java.util.List;
/**
* Created by enzoteles on 28/01/18.
*/
public class ContentFragment extends Fragment{
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
final ContentBinding binding = DataBindingUtil.inflate(inflater, R.layout.content, container, false);
final View view = binding.getRoot();
final ManagerFragment managerFragment = new ManagerFragment();
final ListFragment listFragment = new ListFragment();
final ContentViewModel viewModel = ViewModelProviders.of((FragmentActivity) getActivity()).get(ContentViewModel.class);
binding.setEnzo(viewModel.getEnzo());
binding.btnAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getActivity(), "onClick " + binding.getEnzo().getName(), Toast.LENGTH_SHORT).show();
//insert university
EnzoPO enzoPO = new EnzoPO(binding.getEnzo().getName(), binding.getEnzo().getEmail());
viewModel.insertEnzo(enzoPO);
managerFragment.replaceFragment(listFragment, "list", true);
}
});
return view;
}
}
| true |
563c2f91cb1f0e3bef0872c31084733af865d7e8 | Java | sakura1379/boot_bookManagement | /src/main/java/boot_bookmanage/java/mapper/AdminMapper.java | UTF-8 | 487 | 1.921875 | 2 | [] | no_license | //package boot_bookmanage.java.mapper;
import boot_bookmanage.java.entities.Admin;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Component;
import java.util.List;
/**
* @author Zenglr
* @ClassName AdminMapper
* @Description
* @create 2020-09-11-7:20 下午
*/
//@Mapper
//@Component
//public interface AdminMapper {
//
// public Admin getAdminByAccoutAndPw(String account, String password);
//
// public List<Admin> selectAdmins();
//}
| true |
060af7b3582f04806b2c3421a27eacaff3cf728b | Java | tree33333/Hrm | /de.hswt.hrm.place.ui/src/de/hswt/hrm/place/ui/wizard/PlaceWizardPageOne.java | UTF-8 | 7,884 | 2.15625 | 2 | [] | no_license | package de.hswt.hrm.place.ui.wizard;
import java.net.URL;
import java.util.HashMap;
import org.apache.commons.validator.routines.RegexValidator;
import org.eclipse.e4.xwt.IConstants;
import org.eclipse.e4.xwt.XWT;
import org.eclipse.e4.xwt.forms.XWTForms;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.Label;
import org.eclipse.ui.forms.widgets.Section;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Optional;
import de.hswt.hrm.common.ui.swt.forms.FormUtil;
import de.hswt.hrm.common.ui.swt.layouts.PageContainerFillLayout;
import de.hswt.hrm.i18n.I18n;
import de.hswt.hrm.i18n.I18nFactory;
import de.hswt.hrm.place.model.Place;
public class PlaceWizardPageOne extends WizardPage {
private static final Logger LOG = LoggerFactory.getLogger(PlaceWizardPageOne.class);
private static final I18n I18N = I18nFactory.getI18n(PlaceWizardPageOne.class);
private Composite container;
private HashMap<String, Text> widgets;
private Optional<Place> place;
private RegexValidator plzVal = new RegexValidator("[0-9]{5}");
private RegexValidator cityVal = new RegexValidator("([A-ZÄÖÜ]{1}[a-zäöü]+[\\s]?[\\-]?)*");
private RegexValidator streetNoVal = new RegexValidator("[1-9]+[a-zA-Z0-9-]*");
protected PlaceWizardPageOne(String pageName, Optional<Place> place) {
super(pageName);
this.place = place;
setDescription(createDiscription());
setTitle(I18N.tr("Place Wizard"));
}
private String createDiscription() {
if (place.isPresent()) {
return I18N.tr("Edit the location.");
}
return I18N.tr("Add a new location.");
}
public Place getPlace() {
// We have to return a valid place here!
return updatePlace(place);
}
@Override
public void createControl(Composite parent) {
parent.setLayout(new PageContainerFillLayout());
URL url = PlaceWizardPageOne.class.getClassLoader().getResource(
"de/hswt/hrm/place/ui/xwt/PlaceWizardPageOne" + IConstants.XWT_EXTENSION_SUFFIX);
try {
container = (Composite) XWTForms.load(parent, url);
}
catch (Exception e) {
LOG.error("Could not load PlaceWizardPageOne XWT file.", e);
return;
}
translate(container);
if (place.isPresent()) {
updateFields(place.get());
}
FormUtil.initSectionColors((Section) XWT.findElementByName(container, "Mandatory"));
setKeyListener();
setControl(container);
setPageComplete(false);
}
private void updateFields(Place place) {
HashMap<String, Text> widgets = getWidgets();
widgets.get(Fields.NAME).setText(place.getPlaceName());
widgets.get(Fields.STREET).setText(place.getStreet());
widgets.get(Fields.STREET_NO).setText(place.getStreetNo());
widgets.get(Fields.ZIP_CODE).setText(place.getPostCode());
widgets.get(Fields.CITY).setText(place.getCity());
}
private Place updatePlace(Optional<Place> place) {
HashMap<String, Text> widgets = getWidgets();
String name = widgets.get(Fields.NAME).getText();
String street = widgets.get(Fields.STREET).getText();
String streetNo = widgets.get(Fields.STREET_NO).getText();
String zipCode = widgets.get(Fields.ZIP_CODE).getText();
String city = widgets.get(Fields.CITY).getText();
if (place.isPresent()) {
Place p = place.get();
p.setPlaceName(name);
p.setStreet(street);
p.setStreetNo(streetNo);
p.setPostCode(zipCode);
p.setCity(city);
return p;
}
Place p = new Place(name, zipCode, city, street, streetNo);
return p;
}
public HashMap<String,Text> getWidgets() {
// We cache the widgets for later calls
if (widgets == null) {
widgets = new HashMap<String, Text>();
widgets.put(Fields.NAME, (Text) XWT.findElementByName(container, Fields.NAME));
widgets.put(Fields.STREET, (Text) XWT.findElementByName(container, Fields.STREET));
widgets.put(Fields.STREET_NO, (Text) XWT.findElementByName(container, Fields.STREET_NO));
widgets.put(Fields.ZIP_CODE, (Text) XWT.findElementByName(container, Fields.ZIP_CODE));
widgets.put(Fields.CITY, (Text) XWT.findElementByName(container, Fields.CITY));
}
return widgets;
}
@Override
public boolean isPageComplete(){
HashMap<String, Text> widgets = getWidgets();
// Sorted arry
Text[] widArray = { widgets.get(Fields.NAME), widgets.get(Fields.STREET),
widgets.get(Fields.STREET_NO), widgets.get(Fields.ZIP_CODE),
widgets.get(Fields.CITY) };
boolean isValid;
for (int i = 0; i < widArray.length; i++) {
isValid = checkValidity(widArray[i]);
if (widArray[i].getText().length() == 0) {
setErrorMessage(I18N.tr("Field is mandatory")+ ": " + I18N.tr(XWT.getElementName((Object) widArray[i])));
return false;
}
if (!isValid) {
setErrorMessage(I18N.tr("Invalid input for field")+ " " + I18N.tr(XWT.getElementName((Object) widArray[i])));
return false;
}
}
setErrorMessage(null);
return true;
}
private boolean checkValidity(Text textField) {
String textFieldName = XWT.getElementName((Object) textField);
boolean isInvalidStreetNo = textFieldName.equals(Fields.STREET_NO) && !streetNoVal.isValid(textField.getText());
boolean isInvalidZipCode = textFieldName.equals(Fields.ZIP_CODE) && !plzVal.isValid(textField.getText());
boolean isInvalidCity = textFieldName.equals(Fields.CITY) && !cityVal.isValid(textField.getText());
if (isInvalidStreetNo || isInvalidZipCode || isInvalidCity) {
return false;
}
return true;
}
public void setKeyListener() {
HashMap<String,Text> widgets = getWidgets();
for (Text text : widgets.values()) {
text.addKeyListener(new KeyListener() {
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
getWizard().getContainer().updateButtons();
}
});
}
}
private void translate(Composite container) {
// Labels
setLabelText(container, "lblName", I18N.tr("Name")+":");
setLabelText(container, "lblStreet", I18N.tr("Street / No.")+":");
setLabelText(container, "lblZipCode", I18N.tr("Zipcode / City")+":");
}
private void setLabelText(Composite container, String labelName, String text) {
Label l = (Label) XWT.findElementByName(container, labelName);
if (l==null) {
LOG.error("Label '"+labelName+"' not found.");
return;
}
l.setText(text);
}
private static final class Fields {
public static final String NAME = "name";
public static final String STREET = "street";
public static final String STREET_NO = "streetNumber";
public static final String ZIP_CODE = "zipCode";
public static final String CITY = "city";
}
} | true |
94ebe95d01aa957f8e3f7430433705f8ff7fd22d | Java | Kaellah/SwipableRecyclerView | /app/src/main/java/com/rollncode/swipablerecyclerview/swipablerecyclerview/activity/MainActivity.java | UTF-8 | 7,267 | 2.421875 | 2 | [] | no_license | package com.rollncode.swipablerecyclerview.swipablerecyclerview.activity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import com.rollncode.swipablerecyclerview.swipablerecyclerview.R;
import com.rollncode.swipablerecyclerview.swipablerecyclerview.adapter.DataAdapter;
import com.rollncode.swipablerecyclerview.swipablerecyclerview.utility.carousellayoutmanager.CarouselLayoutManager;
import com.rollncode.swipablerecyclerview.swipablerecyclerview.utility.carousellayoutmanager.CarouselZoomPostLayoutListener;
import com.rollncode.swipablerecyclerview.swipablerecyclerview.utility.carousellayoutmanager.CenterScrollListener;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
final DataAdapter adapter = new DataAdapter();
// final RecyclerLayoutManager manager = new RecyclerLayoutManager();
// final CarouselLayoutManager layoutManager = new CarouselLayoutManager(CarouselLayoutManager.VERTICAL);
// recyclerView.setLayoutManager(layoutManager);
// recyclerView.setHasFixedSize(true);
//
//// recyclerView.setLayoutManager(manager);
// recyclerView.setAdapter(adapter);
//
//// recyclerView.setChildDrawingOrderCallback(new RecyclerView.ChildDrawingOrderCallback() {
//// @Override
//// public int onGetChildDrawingOrder(int childCount, int i) {
//// return childCount - i - 1;
//// }
//// });
//
// // vertical and cycle layout
// layoutManager.setPostLayoutListener(new CarouselZoomPostLayoutListener());
// recyclerView.addOnScrollListener(new CenterScrollListener());
initRecyclerView(recyclerView, new CarouselLayoutManager(CarouselLayoutManager.VERTICAL, false), adapter);
// Extend the Callback class
// ItemTouchHelper.Callback ithCallback = new ItemTouchHelper.Callback() {
// //and in your imlpementaion of
// public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
// // get the viewHolder's and target's positions in your adapter data, swap them
// Collections.swap(adapter.getData(), viewHolder.getAdapterPosition(), target.getAdapterPosition());
// // and notify the adapter that its dataset has changed
// adapter.notifyItemMoved(viewHolder.getAdapterPosition(), target.getAdapterPosition());
// return true;
// }
//
// @Override
// public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
// viewHolder.getItemId();
// }
//
// //defines the enabled move directions in each state (idle, swiping, dragging).
// @Override
// public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
// return makeFlag(ItemTouchHelper.ACTION_STATE_DRAG, ItemTouchHelper.DOWN | ItemTouchHelper.UP | ItemTouchHelper.START | ItemTouchHelper.END);
// }
//
// @Override
// public void onMoved(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, int fromPos, RecyclerView.ViewHolder target, int toPos, int x, int y) {
// super.onMoved(recyclerView, viewHolder, fromPos, target, toPos, x, y);
// }
//
// @Override
// public void clearView(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
// super.clearView(recyclerView, viewHolder);
//
//// ((DataAdapter.ViewHolder) viewHolder).getView().setAlpha();
// ((DataAdapter.ViewHolder) viewHolder).getView().animate()
// .setDuration(250)
// .alpha(0F)
// .start();
// adapter.remove(viewHolder.getAdapterPosition());
// }
//
// @Override
// public void onSelectedChanged(RecyclerView.ViewHolder viewHolder, int actionState) {
// super.onSelectedChanged(viewHolder, actionState);
// }
//
// @Override
// public boolean canDropOver(RecyclerView recyclerView, RecyclerView.ViewHolder current, RecyclerView.ViewHolder target) {
// return false;//super.canDropOver(recyclerView, current, target);
// }
//
// @Override
// public RecyclerView.ViewHolder chooseDropTarget(RecyclerView.ViewHolder selected, List<RecyclerView.ViewHolder> dropTargets, int curX, int curY) {
// return super.chooseDropTarget(selected, dropTargets, curX, curY);
// }
// };
//
// ItemTouchHelper ith = new ItemTouchHelper(ithCallback);
// ith.attachToRecyclerView(recyclerView);
//
//
//
// recyclerView.setOnDragListener(new View.OnDragListener() {
// @Override
// public boolean onDrag(View view, DragEvent dragEvent) {
// return false;
// }
//
//
// });
}
private void initRecyclerView(final RecyclerView recyclerView, final CarouselLayoutManager layoutManager, final DataAdapter adapter) {
// enable zoom effect. this line can be customized
layoutManager.setPostLayoutListener(new CarouselZoomPostLayoutListener());
recyclerView.setLayoutManager(layoutManager);
// we expect only fixed sized item for now
recyclerView.setHasFixedSize(true);
// sample adapter with random data
recyclerView.setAdapter(adapter);
// enable center post scrolling
recyclerView.addOnScrollListener(new CenterScrollListener());
// enable center post touching on item and item click listener
// DefaultChildSelectionListener.initCenterItemListener(new DefaultChildSelectionListener.OnCenterItemClickListener() {
// @Override
// public void onCenterItemClicked(@NonNull RecyclerView recyclerView, @NonNull CarouselLayoutManager carouselLayoutManager, @NonNull View v) {
// final int position = recyclerView.getChildLayoutPosition(v);
// final String msg = String.format(Locale.US, "Item %1$d was clicked", position);
// Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
// }
// }, recyclerView, layoutManager);
layoutManager.addOnItemSelectionListener(new CarouselLayoutManager.OnCenterItemSelectionListener() {
@Override
public void onCenterItemChanged(final int adapterPosition) {
if (CarouselLayoutManager.INVALID_POSITION != adapterPosition) {
// final int value = adapter.mPosition[adapterPosition];
/*
adapter.mPosition[adapterPosition] = (value % 10) + (value / 10 + 1) * 10;
adapter.notifyItemChanged(adapterPosition);
*/
}
}
});
}
}
| true |
9765e687fdb6c9a2c5e14e504fb11141ee5ae774 | Java | catastro/SIGEV | /src/java/SIGEV/DAO/VentaDAO.java | UTF-8 | 4,982 | 2.359375 | 2 | [] | no_license | package SIGEV.DAO;
import SIGEV.BE.*;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.Query;
public class VentaDAO {
private Session session;
private Transaction tx;
public VentaDAO() {
HibernateFactory.buildIfNeeded();
}
/*char*/
public ArrayList<TVenta> listarVentarXfecha(String fecha, String estado ) throws DataAccessLayerException{
ArrayList<TVenta> listVentas= new ArrayList<>() ;
try {
startOperation();
Query query = session.createQuery("from TVenta TV left join fetch TV.TCliente TC left join fetch TC.TPersona TP where TV.fechacreac = '" + fecha + "'" +
" and TV.idcventa = " + estado +
" and TV.estado = '1'" );
listVentas = (ArrayList<TVenta>)query.list();
tx.commit();
} catch (HibernateException e) {
handleException(e);
} finally {
//HibernateFactory.close(session);
}
return listVentas;
}
/*char*/
public ArrayList<TVenta> listarVentarXComprobante(String numComprobante ) throws DataAccessLayerException{
ArrayList<TVenta> listVentas= new ArrayList<>() ;
try {
startOperation();
Query query = session.createQuery("from TVenta TV left join fetch TV.TCliente TC left join fetch TC.TPersona TP where TV.numcomprovante = '" + numComprobante + "'" +
" and TV.estado = '1'" );
listVentas = (ArrayList<TVenta>)query.list();
tx.commit();
} catch (HibernateException e) {
handleException(e);
} finally {
//HibernateFactory.close(session);
}
return listVentas;
}
/*char*/
public ArrayList<TVenta> listarVentarXPersonal(String fechaDe, String fechaHasta, String personal) throws DataAccessLayerException{
ArrayList<TVenta> listVentas= new ArrayList<>() ;
try {
startOperation();
Query query = session.createQuery("from TVenta TV left join fetch TV.TCliente TC left join fetch TC.TPersona TP where TV.idpersonal =" + personal +
" and TV.fechacreac between '" + fechaDe + "' and '" + fechaHasta + "'" +
" and TV.estado = '1'" );
listVentas = (ArrayList<TVenta>)query.list();
tx.commit();
} catch (HibernateException e) {
handleException(e);
} finally {
//HibernateFactory.close(session);
}
return listVentas;
}
/*char*/
public ArrayList<TVenta> listarVentarXCliente(String fechaDe, String fechaHasta, String cliente) throws DataAccessLayerException{
ArrayList<TVenta> listVentas= new ArrayList<>() ;
try {
startOperation();
Query query = session.createQuery("from TVenta TV left join fetch TV.TCliente TC left join fetch TC.TPersona TP where " +
"concat(TP.apppat, TP.appmat, TP.nombres) like '%" +cliente + "%'"
+ " and TV.fechacreac between '" + fechaDe + "' and '" + fechaHasta + "'" +
" and TV.estado = '1'" );
listVentas = (ArrayList<TVenta>)query.list();
tx.commit();
} catch (HibernateException e) {
handleException(e);
} finally {
//HibernateFactory.close(session);
}
return listVentas;
}
public static void main(String[] args) {
VentaDAO oVentaDAO = new VentaDAO();
//System.out.println(oVentaDAO.listarVentar("05/06/2015"));
//System.out.println(oVentaDAO.listarVentarXfecha("2015/05/06","1"));
//System.out.println(oVentaDAO.listarVentarXComprobante("123"));
//System.out.println(oVentaDAO.listarVentarXPersonal("2015/05/06","2015/05/06","1"));
//System.out.println(oVentaDAO.listarVentarXCliente("2015/05/06","2015/05/06","mendozaprado"));
}
private void handleException(HibernateException e) throws DataAccessLayerException {
HibernateFactory.rollback(tx);
throw new DataAccessLayerException(e);
}
private void startOperation() throws HibernateException {
session = HibernateFactory.openSession();
tx = session.beginTransaction();
}
}
| true |
3af5cf8dd121fe693fcb58a87a5fc2f1ad6f478d | Java | UsStore/usStore | /src/main/java/com/example/usStore/dao/mybatis/MybatisUniversityDao.java | UTF-8 | 1,025 | 2.234375 | 2 | [] | no_license | package com.example.usStore.dao.mybatis;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Repository;
import com.example.usStore.dao.UniversityDao;
import com.example.usStore.dao.mybatis.mapper.UniversityMapper;
import com.example.usStore.domain.University;
@Repository
public class MybatisUniversityDao implements UniversityDao{
@Autowired
UniversityMapper univMapper;
@Override
public University getUnivByName(String univName) throws DataAccessException {
return univMapper.getUnivByName(univName);
}
@Override
public void insertUniv(University university) throws DataAccessException {
univMapper.insertUniv(university);
}
@Override
public String getUnivAddrByName(String univName) throws DataAccessException {
return univMapper.getUnivAddrByName(univName);
}
@Override
public int isExistUniv(String univName) throws DataAccessException {
return univMapper.isExistUniv(univName);
}
}
| true |
a07db0e4091aa41be84f7393b5fe25fb2fc210bb | Java | droidsde/eclip_app | /BatteryMaster/src/com/nvn/log/BroadcastListener.java | UTF-8 | 87 | 1.953125 | 2 | [] | no_license | package com.nvn.log;
public interface BroadcastListener {
public void onReceive();
}
| true |
6a43ff54b995019c565c285aa61cf70c4504ba1b | Java | atahalybe/ujaseno | /Android/app/src/main/java/com/privysol/smartlock/BaseUrl.java | UTF-8 | 351 | 2 | 2 | [] | no_license | package com.privysol.smartlock;
public class BaseUrl {
public static String url;
public static String LOCALHOST = "http://192.168.10.5/smartlock/api/api.php?action=";
private BaseUrl() {
}
public static String getInstance(){
if (url == null){
url = LOCALHOST;
}
return url;
}
}
| true |
cd6a21596e8370ee0fcf1cf1f79e6cf019b414cf | Java | koteswaradk/BikeTracker | /app/src/main/java/com/stratvave/biketracker/settings/GetCallerInfoActivity.java | UTF-8 | 4,103 | 1.960938 | 2 | [] | no_license | package com.stratvave.biketracker.settings;
import com.stratvave.biketracker.main.R;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.telephony.PhoneStateListener;
import android.telephony.SmsManager;
import android.telephony.TelephonyManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.RadioGroup;
import android.widget.Toast;
public class GetCallerInfoActivity extends Activity implements OnClickListener {
String number;
RadioGroup rg;
String text="I Am Busy call you Later";
SharedPreferences prefs;
SharedPreferences.Editor edit;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
findViewById(R.id.ok_button_ok).setOnClickListener(this);
prefs = PreferenceManager.getDefaultSharedPreferences(GetCallerInfoActivity.this);
TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
rg = (RadioGroup) findViewById(R.id.radioGroup1);
PhoneStateListener callStateListener = new PhoneStateListener() {
public void onCallStateChanged(int state, String incomingNumber) {
// TODO React to incoming call.
number = incomingNumber;
if (state == TelephonyManager.CALL_STATE_RINGING) {
Toast.makeText(getApplicationContext(),"Phone Is Riging" + number, Toast.LENGTH_LONG).show();
sendSMS(number,text);
/* Intent smsIntent = new Intent(GetCallerInfoActivity.this,
MyEventService.class); Bundle bundle = new Bundle();
bundle.putCharSequence("extraSmsNumber",number);
bundle.putCharSequence("extraSmsText", "");
smsIntent.putExtras(bundle);
PendingIntent Sender =
PendingIntent.getService(GetCallerInfoActivity.this, 0
,smsIntent , 0); startActivity(Sender);*/
}
if (state == TelephonyManager.CALL_STATE_OFFHOOK) {
Toast.makeText(getApplicationContext(),
"Phone is Currently in A call", Toast.LENGTH_LONG)
.show();
}
if (state == TelephonyManager.CALL_STATE_IDLE) {
Toast.makeText(getApplicationContext(),
"phone is neither ringing nor in a call",
Toast.LENGTH_LONG).show();
}
}
/*private void startActivity(PendingIntent sender) {
// TODO Auto-generated method stub
}*/
};
telephonyManager.listen(callStateListener,
PhoneStateListener.LISTEN_CALL_STATE);
}
public void sendSMS(String phoneNumber, String message) { PendingIntent
pi = PendingIntent.getActivity(this, 0, new Intent(this,
PhoneCallReceiver.class), 0); SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, pi, null); }
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.ok_button:
rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// TODO Auto-generated method stub
switch (checkedId) {
case R.id.radio0:
Toast.makeText(GetCallerInfoActivity.this, "Milage r1", Toast.LENGTH_SHORT).show();
text="I Am Busy call you Later";
edit=prefs.edit();
edit.putString("key", text);
break;
case R.id.radio1:
Toast.makeText(GetCallerInfoActivity.this, "Fuel r2", Toast.LENGTH_SHORT).show();
text="I Am Driving CAll Me Later";
edit=prefs.edit();
edit.putString("key", text);
break;
case R.id.radio2:
Toast.makeText(GetCallerInfoActivity.this, "Expences r3", Toast.LENGTH_SHORT).show();
text="I Am Driving CAll You Later";
edit=prefs.edit();
edit.putString("key", text);
break;
}
}
});
break;
}
}
}
| true |
d77117426f2ad62ac9705833593491b6e36d52de | Java | yunze-github/cms_jd1908 | /src/main/java/com/briup/apps/cms/bean/extend/CommentExtend.java | UTF-8 | 883 | 1.914063 | 2 | [] | no_license | package com.briup.apps.cms.bean.extend;
import com.briup.apps.cms.bean.Article;
import com.briup.apps.cms.bean.Comment;
import com.briup.apps.cms.bean.User;
import java.util.List;
public class CommentExtend extends Comment {
private UserExtend userExtend;
private Article article;
private List<CommentExtend> commentExtends;
public UserExtend getUserExtend() {
return userExtend;
}
public void setUserExtend(UserExtend userExtend) {
this.userExtend = userExtend;
}
public Article getArticle() {
return article;
}
public void setArticle(Article article) {
this.article = article;
}
public List<CommentExtend> getCommentExtends() {
return commentExtends;
}
public void setCommentExtends(List<CommentExtend> commentExtends) {
this.commentExtends = commentExtends;
}
}
| true |
545e1ba0f45a83350de50d9b602a7ba9ca085959 | Java | wemecan/talentmov-master-alice | /app/src/main/java/com/movtalent/app/adapter/SubjectEntity.java | UTF-8 | 800 | 2.171875 | 2 | [
"MIT"
] | permissive | package com.movtalent.app.adapter;
/**
* @author huangyong
* createTime 2019-09-15
*/
public class SubjectEntity {
private final String subJectName;
private final String subJectNameSub;
private final String posterUrl;
private final int topId;
public SubjectEntity(String subJectName, String posterUrl, int topId, String subJectNameSub) {
this.subJectName = subJectName;
this.posterUrl = posterUrl;
this.topId = topId;
this.subJectNameSub = subJectNameSub;
}
public String getSubJectName() {
return subJectName;
}
public String getPosterUrl() {
return posterUrl;
}
public int getTopId() {
return topId;
}
public String getSubJectNameSub() {
return subJectNameSub;
}
} | true |
5ccd7cdceb2334c529738b9de8e00011b85acfb0 | Java | grandburge/TestAutomation | /src/truview/page/AdministrationSitesPage.java | UTF-8 | 1,293 | 2.484375 | 2 | [] | no_license | package truview.page;
import org.openqa.selenium.WebDriver;
public class AdministrationSitesPage extends AdministrationPage {
public AdministrationSitesPage(WebDriver driver)
{
super(driver);
}
public AdministrationSitesPage(WebDriver driver,String elementLocatorFile)
{
super(driver,elementLocatorFile);
}
public AdministrationSitesPage(WebDriver driver,String elementLocatorPath,String elementLocatorFile)
{
super(driver,elementLocatorPath,elementLocatorFile);
}
// addSite("autosite1","1.1.1.1/32 1.1.1.2/32")
public void addSite(String siteName,String subnet)
{
String ipAddress;
String mask;
this.getElement("AddSiteBtn").click();
this.getElement("SitePropertiesTab").click();
this.getElement("SiteNameInput").sendKeys(siteName);
this.getElement("SubNetTab").click();
this.wait(500);
String[] subnetList = subnet.split(" ");
for(String ipMask : subnetList)
{ String[] ipMaskPair = ipMask.split("/");
ipAddress = ipMaskPair[0];
mask = ipMaskPair[1];
this.getElement("AddSubnetBtn").click();
this.getElement("IPAddressInput").sendKeys(ipAddress);
this.getElement("SubnetMaskInput").sendKeys(mask);
this.getElement("SaveSubnetBtn").click();
}
this.getElement("SaveSiteBtn").click();
this.wait(1000);
}
}
| true |
01028f032f3b1556cc1a5b6f31bb31ff915723cb | Java | gabrielbran/osgi.ee | /osgi.ee.extender.cdi/src/osgi/extender/cdi/scopes/ExtenderContext.java | UTF-8 | 2,492 | 2.0625 | 2 | [
"Apache-2.0"
] | permissive | /*
* Copyright 2015, Imtech Traffic & Infra
* Copyright 2015, aVineas IT Consulting
*
* 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 osgi.extender.cdi.scopes;
import java.lang.annotation.Annotation;
import java.util.Collection;
/**
* The interface to a CDI context within the CDI extender that should be used by bundles to manipulate
* the setting of the current thread scope context as is defined by the CDI specification (one thread can
* only have one scope). Normally, this would be used by servlet listeners to set the session scopes
* and request scopes into the container before anything useful is done within the container using these
* scopes.<br></br>
* In the extender context, the current context is identified by an object. Therefore as long as the object
* passed is the same, contexts are handled as such.
*
* @author Arie van Wijngaarden
*/
public interface ExtenderContext {
/**
* Set the thread current context to the specified identifier. Note that this method assumes that
* the context for this identifier already exists or at least will be added before any action is
* done for the related scope.
*
* @param identifier The identifier to set as active context for this thread or null to remove it
*/
public void setCurrent(Object identifier);
/**
* Add a context for the specific identifier.
*
* @param identifier The identifier
*/
public void add(Object identifier);
/**
* Remove the context for the specific identifier, since it will not be used after this
*
* @param identifier The identifier
*/
public void remove(Object identifier);
/**
* Get the scope of this context.
*
* @return The scope of the context
*/
public Class<? extends Annotation> getScope();
/**
* Get the identifiers for this context.
*
* @return The identifiers for this context
*/
public Collection<Object> getIdentifiers();
} | true |
494ecfbc2926846f4d14d15e373c78ee13a5b5ce | Java | apoorva2406/AsyncRequest | /src/main/java/com/request/get/MultipleAssynRequests.java | UTF-8 | 3,442 | 2.5 | 2 | [] | no_license | package com.request.get;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import kafka.javaapi.producer.Producer;
import com.ning.http.client.AsyncHttpClient;
import com.ning.http.client.Realm;
import com.ning.http.client.Response;
public class MultipleAssynRequests {
/*This code uses asysnchronous HTTP client on each studies existed in Rave web service
* and sending request simultaneously and after getting the response we are calling a class(webHdfs.DataIngest(finalResponse,j);)
* that sends data directly to the hdfs and if the data cant be pulled in 6000 ms from any webservice
* it will start pulling the data from the same url next time and so we dont have any loss of
* information*/
public NextUrl AssynchronousRequest(List<String>studyUrl,String username,String password){
NextUrl nextUrlInfo = new NextUrl();
WebServiceToHDFS webHdfs = new WebServiceToHDFS();
AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
Realm realm = new Realm.RealmBuilder()
.setPrincipal(username)
.setPassword(password)
.build();
List<Future<Response>> multipleFuture = new ArrayList<Future<Response>>();
Future<Response> singleFuture;
Response finalResponse = null;
Future<Response> r;
String []linkArray = new String [10];
int flag=0;
try {
for(int i=0;i<studyUrl.size();i++){
System.out.println(studyUrl.get(i));
singleFuture=asyncHttpClient.prepareGet(studyUrl.get(i)).setRealm(realm).execute();
multipleFuture.add(i, singleFuture);
//System.out.println("");
}
for(int j=0;j<multipleFuture.size();j++){
System.out.println(multipleFuture.size());
flag=0;
r=multipleFuture.get(j);
try {
finalResponse=r.get();
} catch (InterruptedException | ExecutionException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
//System.out.println(".............");
System.out.println("cannot fetch the data from study at index"+j+" will fetch the data in next iteration");
nextUrlInfo.nextUrl.add(j, studyUrl.get(j));
//System.out.println(nextUrlInfo.nextUrl.get(j));
flag=1;
}
try {
String link=finalResponse.getHeader("Link");
linkArray = link.split(";");
String finalLink = linkArray[0].substring(1,linkArray[0].length()-1);
//System.out.println(finalLink);
if(flag==0){
nextUrlInfo.nextUrl.add(j, finalLink);
//webHdfs.DataIngest(finalResponse,j);
System.out.println(finalResponse.getStatusCode());
ProducerSpeedLayer pl = new ProducerSpeedLayer();
Producer<String,String>p;
p=pl.SetProducerProperties();
String newLineRemoveResponse = finalResponse.getResponseBody().replaceAll("\\n", "");
pl.AddData(p, newLineRemoveResponse);
}
} catch (NullPointerException npe) {
if(flag==0){
nextUrlInfo.nextUrl.add(j, studyUrl.get(j));
//System.out.println(studyUrl.get(j));
nextUrlInfo.reachedend.add(j, 1);
}
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
asyncHttpClient.closeAsynchronously();
return nextUrlInfo;
}
}
| true |
e80200f2226306ee6f61b406a2b31e4904c1111e | Java | BaiWenchao/HISProject2.0 | /src/userInterface/PatientSignUp.java | UTF-8 | 2,024 | 2.453125 | 2 | [] | no_license | package userInterface;
import com.alibaba.fastjson.JSON;
import dataAccess.WriteFile;
import entity.Hospital;
import entity.Patient;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.Parent;
import javafx.scene.control.*;
import logic.PatientSignUpClass;
import logic.ReturnNum;
import logic.Util;
public class PatientSignUp {
//创建医院单例
Hospital hospital = Hospital.getInstance();
//创建返回病案号方法的单例
ReturnNum returnNum = ReturnNum.getInstance();
//创建Util单例
Util util = Util.getInstance();
//创建患者注册方法的单例
PatientSignUpClass patientSignUpClass = PatientSignUpClass.getInstance();
@FXML
private DatePicker birthday;
@FXML
private ChoiceBox<String> gender;
@FXML
private TextField hosRecordNum;
@FXML
private TextField name;
@FXML
private TextField phoneNum;
@FXML
private Button regist;
@FXML
private TextField homeAddress;
@FXML
private TextField IDNum;
@FXML
private void regist(){
//数据缺失处理
if(hosRecordNum.getText() == null || name.getText() == null || gender.getValue() == null || birthday.getValue() == null){
util.errorInformationAlert("相关信息未完善!");
return;
}
//将患者信息添加至医院的患者列表
patientSignUpClass.patientSignUp(hosRecordNum.getText(), name.getText(), gender.getValue(), birthday.getValue().toString(), homeAddress.getText(), phoneNum.getText(), IDNum.getText());
//注册成功提示
util.completeInformationAlert("注册成功!");
}
@FXML
private void initGender(){
ObservableList<String> choices = FXCollections.observableArrayList("男","女");
gender.setItems(choices);
}
@FXML
private void initialize(){
hosRecordNum.setText(returnNum.returnHosRecordNum());
}
}
| true |
a59638447edb8d1d0db5db0fd055739d95056fb7 | Java | Jgarciagithub/co.com.choucair.certifation.test | /src/test/java/stepdefinitions/ChoucairTestStepDefintions.java | UTF-8 | 1,759 | 2.09375 | 2 | [] | no_license | package stepdefinitions;
import cucumber.api.java.Before;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
import model.TestData;
import net.serenitybdd.screenplay.GivenWhenThen;
import net.serenitybdd.screenplay.actors.OnStage;
import net.serenitybdd.screenplay.actors.OnlineCast;
import questions.Answer;
import tasks.Enterdata;
import tasks.JoinToday;
import tasks.OpenUp;
import java.util.List;
public class ChoucairTestStepDefintions {
@Before
public void setStage(){
OnStage.setTheStage(new OnlineCast());
}
@Given("^than brandon wants register in page web Utes$")
public void thanBrandonWantsRegisterInPpageWebUtes(List<TestData> testData) throws Exception {
OnStage.theActorCalled( "Brandon").wasAbleTo(OpenUp.thePage(),(JoinToday.clicbuttonjointoday()));
}
@When("^he complete the text boxs in the platform$")
public void heCompletetheTextboxsinThePlatform(List<TestData>testData) throws Exception{
OnStage.theActorInTheSpotlight().attemptsTo(Enterdata.the(testData.get(0).getName(),testData.get(0).getLastname(),
testData.get(0).getEmailaddress(),testData.get(0).getMonth(),testData.get(0).getDay(), testData.get(0).getYear(),testData.get(0).getCreatedPassword()));
}
@Then("^he finds the button complete setup$")
public void heFindstheButtonCompleteSetup(List<TestData>testData) throws Exception{
OnStage.theActorInTheSpotlight().should(GivenWhenThen.seeThat(Answer.tothe(testData.get(0).getName(), testData.get(0).getLastname()
,testData.get(0).getEmailaddress(),testData.get(0).getMonth(),testData.get(0).getDay(), testData.get(0).getYear(),testData.get(0).getCreatedPassword())));
}
}
| true |
f4d1b6eeadd5cff1bd7a2afe8939cab95d076b79 | Java | xingcici/xc-design-pattern | /src/main/java/com/elvin/pattern/pattern/iouchain/BaseHandler.java | UTF-8 | 475 | 2.1875 | 2 | [
"Apache-2.0"
] | permissive | package com.elvin.pattern.pattern.iouchain;
import com.elvin.pattern.pattern.chain.Handler;
/**
* @author : Haifeng Pang.
* @version 0.1 : Handler v0.1 2018/5/24 10:30 By Haifeng Pang.
* @description :
*/
public abstract class BaseHandler {
/**
*
*/
protected BaseHandler successor;
/**
*
*/
public void setSuccessor(BaseHandler successor) {
this.successor = successor;
}
public abstract void handlerRequest(Object object);
}
| true |
b0da8f17fadc35eb9ab919944e38125839709599 | Java | pitoszud/Java-Study | /src/main/java/Enums/Main.java | UTF-8 | 984 | 3.21875 | 3 | [] | 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 Enums;
/**
*
* @author upatryk
*/
public class Main {
public static void main(String[] args) {
PrimitiveEnum grade = PrimitiveEnum.A;
System.out.println(grade); // A
System.out.println(PrimitiveEnum.A); // A
System.out.println(PrimitiveEnum.A.value()); // 4.0
System.out.println(grade.value()); // 4.0
//---------------------------------------------------
ObjectEnum q = ObjectEnum.software;
System.out.println(q.value().getQualificationName()); // BSc in Software Enginering
System.out.println(ObjectEnum.software.value().getQualificationName()); //BSc in Software Enginering
// ---------------------------------------------------
}
}
| true |
68f72b8d0b53fbcd2d8096bde0c04490d96c5135 | Java | snada/BitmapFontLoader | /app/src/main/java/it/snada/bitmapfontloaderapp/MainActivity.java | UTF-8 | 7,272 | 1.992188 | 2 | [
"MIT"
] | permissive | package it.snada.bitmapfontloaderapp;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.opengl.GLES20;
import android.opengl.GLSurfaceView;
import android.opengl.Matrix;
import android.os.Bundle;
import android.util.ArrayMap;
import android.util.Log;
import org.xmlpull.v1.XmlPullParserException;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Map;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
import it.snada.bitmap3dstring.Bitmap3DChar;
import it.snada.bitmap3dstring.Bitmap3DColor;
import it.snada.bitmap3dstring.Bitmap3DGeometry;
import it.snada.bitmap3dstring.Bitmap3DString;
import it.snada.bitmapfontloader.AngelCodeBinLoader;
import it.snada.bitmapfontloader.AngelCodeTxtLoader;
import it.snada.bitmapfontloader.AngelCodeXmlLoader;
import it.snada.bitmapfontloader.BitmapFont;
public class MainActivity extends Activity implements GLSurfaceView.Renderer {
private GLSurfaceView mGLView;
protected String TAG = "MainActivity";
private float[] view;
private float[] projection;
private float time = 0.0f;
BitmapFont targetFont;
BitmapFont txtFont;
BitmapFont xmlFont;
BitmapFont binFont;
Bitmap3DString string;
Bitmap3DGeometry geometry;
Bitmap3DColor color;
Map<String, Texture> textures;
Texture texture;
ShaderProgram program;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mGLView = new MyGLSurfaceView(this);
setContentView(mGLView);
}
public void onSurfaceCreated(GL10 unused, EGLConfig config) {
try {
txtFont = new BitmapFont();
xmlFont = new BitmapFont();
binFont = new BitmapFont();
AngelCodeXmlLoader.load(xmlFont, getResources().openRawResource(R.raw.arial_xml));
AngelCodeTxtLoader.load(txtFont, getResources().openRawResource(R.raw.arial_txt));
AngelCodeBinLoader.load(binFont, getResources().openRawResource(R.raw.arial_bin));
//Change font here to switch rendered loader
targetFont = binFont;
string = new Bitmap3DString(targetFont, "Hello!");
string.setXScaleByPreferredWidth(1.0f);
string.setScaleY(string.getScaleX());
string.setScaleZ(string.getScaleX());
string.setCentered(true);
} catch(XmlPullParserException e) {
Log.e(TAG, "Your xml file has an error: " + e);
} catch(IOException e) {
Log.e(TAG, "There's an error with your file: " + e);
}
color = new Bitmap3DColor(
1.0f, 0.0f, 0.0f, 1.0f,
0.0f, 1.0f, 0.0f, 1.0f,
0.0f, 0.0f, 1.0f, 1.0f,
1.0f, 1.0f, 0.0f, 1.0f
);
geometry = Bitmap3DGeometry.getInstance();
GLES20.glClearColor(0.5f, 0.5f, 0.5f, 1.0f);
view = new float[16];
Matrix.setLookAtM(view, 0,
0.0f, 0.0f, 1.5f,
0.0f, 0.0f, 0.0f,
0.0f, 1.0f, 0.0f
);
projection = new float[16];
Matrix.setIdentityM(projection, 0);
textures = new ArrayMap<>();
BitmapFactory.Options options = new BitmapFactory.Options();
options.inScaled = false;
for(int counter = 0; counter < targetFont.getPagesNumber(); counter++) {
String pageName = targetFont.getPage(counter);
Bitmap bitmap = BitmapFactory.decodeResource(
this.getResources(),
this.getResources().getIdentifier(pageName.split("\\.")[0], "drawable", this.getPackageName()),
options
);
textures.put(targetFont.getPage(counter), new Texture(bitmap));
}
program = new ShaderProgram(readRawTextFile(R.raw.vertex_shader), readRawTextFile(R.raw.fragment_shader));
}
public void onDrawFrame(GL10 unused) {
GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);
GLES20.glUseProgram(program.getId());
time += 0.01f;
for (Bitmap3DChar chr : string.get3dChars()) {
string.setRotationY(time * 500);
int positionHandle = GLES20.glGetAttribLocation(program.getId(), "vPosition");
GLES20.glEnableVertexAttribArray(positionHandle);
GLES20.glVertexAttribPointer(positionHandle, 3, GLES20.GL_FLOAT, false, 3 * 4, geometry.getVertexBuffer());
int colorHandle = GLES20.glGetAttribLocation(program.getId(), "vColor");
GLES20.glEnableVertexAttribArray(colorHandle);
GLES20.glVertexAttribPointer(colorHandle, 4, GLES20.GL_FLOAT, false, 4 * 4, color.getColorBuffer());
int uvHandle = GLES20.glGetAttribLocation(program.getId(), "vUv");
GLES20.glEnableVertexAttribArray(uvHandle);
GLES20.glVertexAttribPointer(uvHandle, 2, GLES20.GL_FLOAT, false, 2 * 4, chr.getUvBuffer());
int modelMatrixHandle = GLES20.glGetUniformLocation(program.getId(), "model");
GLES20.glUniformMatrix4fv(modelMatrixHandle, 1, false, chr.getModelMatrix(), 0);
int viewMatrixHandle = GLES20.glGetUniformLocation(program.getId(), "view");
GLES20.glUniformMatrix4fv(viewMatrixHandle, 1, false, view, 0);
int projectionMatrixHandle = GLES20.glGetUniformLocation(program.getId(), "projection");
GLES20.glUniformMatrix4fv(projectionMatrixHandle, 1, false, projection, 0);
int textureUniformHandle = GLES20.glGetUniformLocation(program.getId(), "texture");
GLES20.glActiveTexture(GLES20.GL_TEXTURE0);
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textures.get(targetFont.getPage(chr.getBitmapChar().getPage())).getId());
GLES20.glUniform1i(textureUniformHandle, 0);
GLES20.glDrawElements(GLES20.GL_TRIANGLE_STRIP, 6, GLES20.GL_UNSIGNED_SHORT, geometry.getIndexBuffer());
GLES20.glDisableVertexAttribArray(positionHandle);
}
}
public void onSurfaceChanged(GL10 unused, int width, int height) {
GLES20.glViewport(0, 0, width, height);
float ratio = (float)width/(float)height;
Matrix.perspectiveM(projection, 0, 45.0f, ratio, 0.1f, 10.0f);
}
/**
* Converts a raw text file into a string: useful to load shaders from text files
*
* @param resId The resource ID of the raw text file about to be turned into a shader.
* @return The context of the text file, or null in case of error.
*/
private String readRawTextFile(int resId) {
InputStream inputStream = getResources().openRawResource(resId);
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
reader.close();
return sb.toString();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
| true |
587639bb4a9bc19f3dba138bfddfa824def155d8 | Java | darkestpriest/fermat | /CHT/android/sub_app/fermat-cht-android-sub-app-chat-bitdubai/src/main/java/com/bitbudai/fermat_cht_android_sub_app_chat_bitdubai/adapters/ChatAdapter.java | UTF-8 | 9,165 | 1.929688 | 2 | [
"LicenseRef-scancode-warranty-disclaimer",
"MIT"
] | permissive | package com.bitbudai.fermat_cht_android_sub_app_chat_bitdubai.adapters;
import android.content.ClipData;
import android.content.Context;
import android.os.Build;
import android.view.ContextMenu;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.bitbudai.fermat_cht_android_sub_app_chat_bitdubai.filters.ChatFilter;
import com.bitbudai.fermat_cht_android_sub_app_chat_bitdubai.filters.ChatListFilter;
import com.bitbudai.fermat_cht_android_sub_app_chat_bitdubai.holders.ChatHolder;
import com.bitbudai.fermat_cht_android_sub_app_chat_bitdubai.models.ChatMessage;
import com.bitdubai.fermat_android_api.ui.adapters.FermatAdapter;
import com.bitdubai.fermat_api.layer.all_definition.navigation_structure.MenuItem;
import com.bitdubai.fermat_cht_android_sub_app_chat_bitdubai.R;
import com.bitdubai.fermat_cht_api.all_definition.enums.MessageStatus;
import java.util.ArrayList;
import java.util.List;
//import android.support.v4.content.ContextCompat;
//import android.support.v7.widget.RecyclerView;
//import com.bitdubai.fermat_cht_api.layer.cht_middleware.cht_chat_factory.interfaces.ChatFactory; //data del middleware
/**
* ChatAdapter
*
* @author Jose Cardozo josejcb (josejcb89@gmail.com) on 05/01/15.
* @version 1.0
*/
public class ChatAdapter extends FermatAdapter<ChatMessage, ChatHolder>
/*implements Filterable*/ {
List<ChatMessage> chatMessages = new ArrayList<>();
ArrayList<String> messagesData = new ArrayList<>();
ArrayList<ChatMessage> filteredData;
ArrayList<String> originalData;
private String filterString;
public ChatAdapter(Context context) {
super(context);
}
public ChatAdapter(Context context, List<ChatMessage> chatMessages) {//ChatFactory
super(context, chatMessages);
}
@Override
protected ChatHolder createHolder(View itemView, int type) {
return new ChatHolder(itemView);
}
@Override
protected int getCardViewResource() {return R.layout.chat_list_item; }
@Override
protected void bindHolder(ChatHolder holder, ChatMessage data, int position) {
if (data != null) {
boolean myMsg = data.getIsme();
setAlignment(holder, myMsg, data);
// final String copiedMessage = holder.txtMessage.getText().toString();
// holder.txtMessage.setOnLongClickListener(new View.OnLongClickListener() {
// @Override
// public boolean onLongClick(View v) {
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
// android.content.ClipboardManager clipboard = (android.content.ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
// ClipData clip = ClipData.newPlainText("simple text",copiedMessage);
// clipboard.setPrimaryClip(clip);}
// else{
// android.text.ClipboardManager clipboard = (android.text.ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
// clipboard.setText(copiedMessage);
// }
// Toast.makeText(context, "Copied: "+copiedMessage, Toast.LENGTH_SHORT).show();
// return true;
// }
// });
}
}
public View getView() {
LayoutInflater vi = LayoutInflater.from(context) ;
View convertView = vi.inflate(R.layout.chat_list_item, null);
return convertView;
}
public void refreshEvents(ArrayList<ChatMessage> chatHistory) {
for (int i = 0; i < chatHistory.size(); i++) {
ChatMessage message = chatHistory.get(i);
add(message);
changeDataSet(chatHistory);
notifyDataSetChanged();
}
}
public void add(ChatMessage message) {
chatMessages.add(message);
}
private void setAlignment(ChatHolder holder, boolean isMe, ChatMessage data) {
holder.tickstatusimage.setImageResource(0);
holder.txtMessage.setText(data.getMessage());
holder.txtInfo.setText(data.getDate());
if (isMe) {
holder.contentWithBG.setBackgroundResource(R.drawable.burble_green_shadow);
LinearLayout.LayoutParams layoutParams =
(LinearLayout.LayoutParams) holder.contentWithBG.getLayoutParams();
layoutParams.gravity = Gravity.RIGHT;
holder.contentWithBG.setLayoutParams(layoutParams);
RelativeLayout.LayoutParams lp =
(RelativeLayout.LayoutParams) holder.content.getLayoutParams();
lp.addRule(RelativeLayout.ALIGN_PARENT_LEFT, 0);
lp.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
holder.content.setLayoutParams(lp);
layoutParams = (LinearLayout.LayoutParams) holder.txtMessage.getLayoutParams();
layoutParams.gravity = Gravity.RIGHT;
holder.txtMessage.setLayoutParams(layoutParams);
layoutParams = (LinearLayout.LayoutParams) holder.txtInfo.getLayoutParams();
layoutParams.gravity = Gravity.RIGHT;
holder.txtInfo.setLayoutParams(layoutParams);
if(data.getStatus() != null) {
if (data.getStatus().equals(MessageStatus.SEND.toString()) /*|| data.getStatus().equals(MessageStatus.CREATED.toString())*/)
holder.tickstatusimage.setImageResource(R.drawable.cht_ticksent);
else if (data.getStatus().equals(MessageStatus.DELIVERED.toString()) || data.getStatus().equals(MessageStatus.RECEIVE.toString()))
holder.tickstatusimage.setImageResource(R.drawable.cht_tickdelivered);
else if (data.getStatus().equals(MessageStatus.READ.toString()))
holder.tickstatusimage.setImageResource(R.drawable.cht_tickread);
}
} else {
holder.contentWithBG.setBackgroundResource(R.drawable.burble_white_shadow);
LinearLayout.LayoutParams layoutParams =
(LinearLayout.LayoutParams) holder.contentWithBG.getLayoutParams();
layoutParams.gravity = Gravity.LEFT;
holder.contentWithBG.setLayoutParams(layoutParams);
RelativeLayout.LayoutParams lp =
(RelativeLayout.LayoutParams) holder.content.getLayoutParams();
lp.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, 0);
lp.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
holder.content.setLayoutParams(lp);
layoutParams = (LinearLayout.LayoutParams) holder.txtMessage.getLayoutParams();
layoutParams.gravity = Gravity.LEFT;
holder.txtMessage.setLayoutParams(layoutParams);
layoutParams = (LinearLayout.LayoutParams) holder.txtInfo.getLayoutParams();
layoutParams.gravity = Gravity.LEFT;
holder.txtInfo.setLayoutParams(layoutParams);
}
}
// public int getCount() {
// if (chatMessages != null) {
// if (filteredData != null) {
// if (filteredData.size() <= chatMessages.size()) {
// return filteredData.size();
// } else {
// return chatMessages.size();
// }
// }else return chatMessages.size();
// } else {
// return 0;
// }
// }
//
// @Override
// public ChatMessage getItem(int position) {
// ChatMessage dataM;
// if (chatMessages != null) {
// if (filteredData != null) {
// if (filteredData.size() <= chatMessages.size()) {
// dataM= filteredData.get(position);
// } else {
// dataM= chatMessages.get(position);
// }
// }else dataM=chatMessages.get(position);
// } else {
// dataM=chatMessages.get(position);
// }
// return dataM;
// }
//
// @Override
// public long getItemId(int position) {
// return position;
// }
//
// public void setData(ArrayList<ChatMessage> data) {
// this.filteredData = data;
// }
//
// public Filter getFilter() {
// messagesData=null;
// for(ChatMessage data:chatMessages){
// messagesData.add(data.getMessage());
// }
// return new ChatFilter(messagesData, this);
// }
//
// public void setFilterString(String filterString) {
// this.filterString = filterString;
// }
//
// public String getFilterString() {
// return filterString;
// }
//
// @Override
// public ChatMessage getItem(int position) {
// if (chatMessages != null) {
// return chatMessages.get(position);
// } else {
// return null;
// }
// }
//
//
// public long getItemId(int position) {
// return position;
// }
} | true |
09a5d22d8071171e19cdc7782aba6aa5128b5cd4 | Java | Lextokil/BluPark | /app/src/main/java/com/android/blupark/adapter/VeiculoRow.java | UTF-8 | 503 | 2.484375 | 2 | [] | no_license | package com.android.blupark.adapter;
public class VeiculoRow {
private String rowText;
private int icon;
public VeiculoRow(String rowText, int icon) {
this.rowText = rowText;
this.icon = icon;
}
public String getRowText() {
return rowText;
}
public void setRowText(String rowText) {
this.rowText = rowText;
}
public int getIcon() {
return icon;
}
public void setIcon(int icon) {
this.icon = icon;
}
}
| true |
0c5baab20e9e2e59901c96a60d0e3090e82c8eea | Java | nightwolf93/Wakxy-Core-Decompiled | /1_39_120042/com/ankamagames/framework/kernel/core/common/Validable.java | UTF-8 | 134 | 1.609375 | 2 | [] | no_license | package com.ankamagames.framework.kernel.core.common;
public interface Validable
{
long getId();
void setId(long p0);
}
| true |
13198987e370137ca2a9b819784d33743c183954 | Java | LyricsRH/java- | /src/五/E6.java | WINDOWS-1252 | 396 | 2.65625 | 3 | [] | no_license | package ;
import .b16;
import .b6;
public class E6 {
public static void main(String[] args) {
// TODO Auto-generated method stub
int []perfect=new b6().perfectNums();
for (int i = 0; i < perfect.length; i++) {
String string=new E5().intToString(perfect[i], 2);
System.out.printf("perfectnum: %4d form of 2: %20s%n", perfect[i],string);
}
}
}
| true |
99bdaf387906b9b8e5a42ebe22cdfe4981e1bb05 | Java | groupon/monsoon | /expr/src/main/java/com/groupon/lex/metrics/timeseries/ExpressionLookBack.java | UTF-8 | 8,652 | 2.5 | 2 | [
"BSD-3-Clause"
] | permissive | package com.groupon.lex.metrics.timeseries;
import com.groupon.lex.metrics.lib.ForwardIterator;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NonNull;
import lombok.Value;
import org.joda.time.DateTime;
import org.joda.time.Duration;
public interface ExpressionLookBack {
public static ChainableExpressionLookBack EMPTY = new ChainableExpressionLookBack() {
@Override
public <TSC extends TimeSeriesCollection> Stream<TSC> filter(@NonNull ForwardIterator<TSC> tsc) { return Stream.empty(); }
@Override
public Duration hintDuration() { return Duration.ZERO; }
@Override
public ExpressionLookBack andThen(@NonNull ExpressionLookBack next) { return next; }
@Override
public ExpressionLookBack andThen(@NonNull Stream<ExpressionLookBack> children) {
final List<ExpressionLookBack> chain = children.collect(Collectors.toList());
if (chain.isEmpty()) return this;
if (chain.size() == 1) return andThen(chain.get(0));
return new ExpressionLookBack() {
@Override
public <TSC extends TimeSeriesCollection> Stream<TSC> filter(@NonNull ForwardIterator<TSC> tsc) {
return chain.stream().flatMap(elb -> elb.filter(tsc.clone()));
}
@Override
public Duration hintDuration() {
return chain.stream().map(ExpressionLookBack::hintDuration).max(Comparator.naturalOrder()).orElse(Duration.ZERO);
}
};
}
};
/**
* Filter the TimeSeriesCollections we want to keep active.
*
* @param tsc A list of TimeSeriesCollection currently being kept.
* @return A stream with the TimeSeriesCollections we want to keep active.
* The returned stream may contain duplicate entries.
*/
public <TSC extends TimeSeriesCollection> Stream<TSC> filter(@NonNull ForwardIterator<TSC> tsc);
/**
* Give an estimate of how much history has to be maintained, as a time interval.
* This is mainly an indication of how far in the past a history update would be needed.
*/
public Duration hintDuration();
@Value
public static class ScrapeCount implements ChainableExpressionLookBack {
private final int count;
public ScrapeCount(int count) {
if (count < 0) throw new IllegalArgumentException("cannot look back negative amounts");
this.count = count;
}
private <TSC extends TimeSeriesCollection> Stream<TSC> filter_(@NonNull ForwardIterator<TSC> tsc) {
final List<TSC> local_result = new ArrayList<>(count);
for (int n = 0; n < count; ++n) {
if (!tsc.hasNext()) return local_result.stream();
local_result.add(tsc.next());
}
return local_result.stream();
}
@Override
public <TSC extends TimeSeriesCollection> Stream<TSC> filter(@NonNull ForwardIterator<TSC> tsc) {
return filter_(tsc);
}
@Override
public Duration hintDuration() { return Duration.ZERO; }
@Override
public ExpressionLookBack andThen(@NonNull ExpressionLookBack next) {
return new ExpressionLookBack() {
@Override
public <TSC extends TimeSeriesCollection> Stream<TSC> filter(@NonNull ForwardIterator<TSC> tsc) {
final Stream<TSC> local_result = filter_(tsc);
if (!tsc.hasNext()) return local_result;
return Stream.concat(local_result, next.filter(tsc));
}
@Override
public Duration hintDuration() {
return next.hintDuration();
}
};
}
@Override
public ExpressionLookBack andThen(@NonNull Stream<ExpressionLookBack> children) {
final List<ExpressionLookBack> chain = children.collect(Collectors.toList());
if (chain.isEmpty()) return this;
if (chain.size() == 1) return andThen(chain.get(0));
return new ExpressionLookBack() {
@Override
public <TSC extends TimeSeriesCollection> Stream<TSC> filter(@NonNull ForwardIterator<TSC> tsc) {
final Stream<TSC> local_result = filter_(tsc);
if (!tsc.hasNext()) return local_result;
return Stream.concat(local_result, chain.stream().flatMap(elb -> elb.filter(tsc.clone())));
}
@Override
public Duration hintDuration() {
return chain.stream().map(ExpressionLookBack::hintDuration).max(Comparator.naturalOrder()).orElse(Duration.ZERO);
}
};
}
}
@Value
public static class Interval implements ChainableExpressionLookBack {
private final Duration duration;
@AllArgsConstructor
@Getter
private static class FilterResult<TSC extends TimeSeriesCollection> {
private final Stream<TSC> used;
private final ForwardIterator<TSC> unused;
}
public Interval(@NonNull Duration duration) {
if (duration.isShorterThan(Duration.ZERO)) throw new IllegalArgumentException("negative duration not supported");
this.duration = duration;
}
private <TSC extends TimeSeriesCollection> FilterResult<TSC> filter_(@NonNull ForwardIterator<TSC> tsc) {
if (!tsc.hasNext()) return new FilterResult(Stream.empty(), tsc);
final List<TSC> local_result = new ArrayList<>();
final TSC head = tsc.next();
local_result.add(head);
final DateTime oldest_preserve = head.getTimestamp().minus(duration);
while (tsc.hasNext()) {
final TSC next = tsc.next();
local_result.add(next);
if (!next.getTimestamp().isAfter(oldest_preserve)) break;
}
return new FilterResult(local_result.stream(), tsc);
}
@Override
public <TSC extends TimeSeriesCollection> Stream<TSC> filter(@NonNull ForwardIterator<TSC> tsc) {
return filter_(tsc).getUsed();
}
@Override
public Duration hintDuration() { return duration; }
@Override
public ExpressionLookBack andThen(@NonNull ExpressionLookBack elb) {
return new ExpressionLookBack() {
@Override
public <TSC extends TimeSeriesCollection> Stream<TSC> filter(@NonNull ForwardIterator<TSC> tsc) {
final FilterResult<TSC> fr = filter_(tsc);
Stream<TSC> result = fr.getUsed();
if (fr.getUnused().hasNext())
result = Stream.concat(result, elb.filter(fr.getUnused()));
return result;
}
@Override
public Duration hintDuration() {
return duration.plus(elb.hintDuration());
}
};
}
@Override
public ExpressionLookBack andThen(@NonNull Stream<ExpressionLookBack> children) {
final List<ExpressionLookBack> chain = children.collect(Collectors.toList());
if (chain.isEmpty()) return this;
if (chain.size() == 1) return andThen(chain.get(0));
return new ExpressionLookBack() {
@Override
public <TSC extends TimeSeriesCollection> Stream<TSC> filter(@NonNull ForwardIterator<TSC> tsc) {
final FilterResult<TSC> fr = filter_(tsc);
Stream<TSC> result = fr.getUsed();
if (fr.getUnused().hasNext())
result = Stream.concat(result, chain.stream().flatMap(elb -> elb.filter(fr.getUnused().clone())));
return result;
}
@Override
public Duration hintDuration() {
return duration.plus(chain.stream().map(ExpressionLookBack::hintDuration).max(Comparator.naturalOrder()).orElse(Duration.ZERO));
}
};
}
}
public static ChainableExpressionLookBack fromInterval(Duration interval) { return new Interval(interval); }
public static ChainableExpressionLookBack fromScrapeCount(int count) { return new ScrapeCount(count); }
}
| true |
8802ded45a54e2b20a4af5787facf60005be7b65 | Java | kowalikm/MoxaController | /app/src/main/java/pl/appcoders/moxacontroller/di/RestModule.java | UTF-8 | 3,056 | 2.328125 | 2 | [] | no_license | package pl.appcoders.moxacontroller.di;
import android.app.Application;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.util.Log;
import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides;
import pl.appcoders.moxacontroller.inputs.service.DigitalInputService;
import pl.appcoders.moxacontroller.relays.service.RelaysService;
import pl.appcoders.moxacontroller.systeminfo.service.SystemInfoService;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
@Module
class RestModule {
private Retrofit retrofit;
@Provides
@Singleton
SharedPreferences providesSharedPreferences(Application application) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(application);
sharedPreferences.registerOnSharedPreferenceChangeListener(new SharedPreferences.OnSharedPreferenceChangeListener() {
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if(key.contentEquals("deviceAddress") || key.contentEquals("restfulApiEndpoint")) {
createRetrofitInstance(sharedPreferences);
Log.i("Shared prefferences", "Setting shared preferences");
}
}
});
return sharedPreferences;
}
@Provides
@Singleton
Retrofit providesRetrofit(SharedPreferences sharedPreferences) {
if(retrofit == null) {
createRetrofitInstance(sharedPreferences);
}
return retrofit;
}
@Provides
SystemInfoService systemInfoService(Retrofit retrofit) {
return retrofit.create(SystemInfoService.class);
}
@Provides
DigitalInputService digitalInputService(Retrofit retrofit) {
return retrofit.create(DigitalInputService.class);
}
@Provides
RelaysService relaysService(Retrofit retrofit) {
return retrofit.create(RelaysService.class);
}
private void createRetrofitInstance(SharedPreferences sharedPreferences) {
try {
createRetrofit(sharedPreferences);
} catch (IllegalArgumentException ex) { //If wrong address provided
Log.w("Retrofit", ex.getMessage());
sharedPreferences.edit().remove("deviceAddress").apply();
createRetrofit(sharedPreferences);
}
}
private void createRetrofit(SharedPreferences sharedPreferences) {
retrofit = new Retrofit.Builder().addConverterFactory(GsonConverterFactory.create())
.baseUrl(getApiBaseUrl(sharedPreferences)).build();
}
private String getApiBaseUrl(SharedPreferences sharedPreferences) {
String apiAddress = sharedPreferences.getString("deviceAddress", "http://127.0.0.1");
String apiEndpoint = sharedPreferences.getString("restfulApiEndpoint", "/api/slot/0/");
Log.i("URL", "Finished url: " + apiAddress + apiEndpoint);
return apiAddress + apiEndpoint;
}
}
| true |
f618131d5757b16ba11c17bf3a57c36fb62a1473 | Java | rajatgupta2018/store-keeper | /app/src/main/java/com/example/store_keeper/store_keeper/ui/suppliers/product/SupplierProductPickerNavigator.java | UTF-8 | 1,398 | 2.171875 | 2 | [
"Apache-2.0",
"CC-BY-3.0"
] | permissive | /*
* Created By Rajat Gupta And Harshita Joshi
*
* 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.example.store_keeper.store_keeper.ui.suppliers.product;
import com.example.store_keeper.store_keeper.data.local.models.ProductLite;
import java.util.ArrayList;
/**
* Defines Navigation Actions that can be invoked from {@link SupplierProductPickerActivity}.
*
* @author Rajat Gupta And Harshita Joshi
*/
public interface SupplierProductPickerNavigator {
/**
* Method that updates the result {@code productsToSell} to be sent back to the Calling activity.
*
* @param productsToSell List of Products {@link ProductLite} selected by the Supplier
* for selling.
*/
void doSetResult(ArrayList<ProductLite> productsToSell);
/**
* Method that updates the Calling Activity that the operation was aborted.
*/
void doCancel();
}
| true |
bac4184cf456cd5b65245fb9d122a20d4a477023 | Java | pageseeder/flint | /src/main/java/org/pageseeder/flint/catalog/Catalog.java | UTF-8 | 6,682 | 2.34375 | 2 | [
"Apache-2.0"
] | permissive | package org.pageseeder.flint.catalog;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import org.pageseeder.flint.indexing.FlintField;
import org.pageseeder.flint.indexing.FlintField.DocValuesType;
import org.pageseeder.flint.indexing.FlintField.IndexOptions;
import org.pageseeder.flint.indexing.FlintField.NumericType;
import org.pageseeder.flint.indexing.FlintField.Resolution;
import org.pageseeder.xmlwriter.XMLWritable;
import org.pageseeder.xmlwriter.XMLWriter;
public class Catalog implements XMLWritable {
private final HashMap<String, CatalogEntry> _fields = new HashMap<>();
private final String _name;
public Catalog(String name) {
this._name = name;
}
public String name() {
return this._name;
}
public void addFieldType(FlintField builder) {
// ignore non-indexed fields
if (builder.index() == IndexOptions.NONE) return;
synchronized (this._fields) {
CatalogEntry existing = this._fields.get(builder.name());
if (existing == null || !existing.equals(new CatalogEntry(builder, false)))
this._fields.put(builder.name(), new CatalogEntry(builder, existing != null));
}
}
/**
* @deprecated use addFieldType
*/
public void addFieldType(boolean stored, String name, boolean tokenized, DocValuesType dt, NumericType num, float boost) {
addFieldType(stored, name, tokenized, dt, num, null, null, boost);
}
public void addFieldType(boolean stored, String name, boolean tokenized, DocValuesType dt, NumericType num,
SimpleDateFormat df, Resolution r, float boost) {
synchronized (this._fields) {
CatalogEntry newone = new CatalogEntry(stored, dt, tokenized, boost, num, df, r, false);
CatalogEntry existing = this._fields.get(name);
if (existing == null || !existing.equals(newone))
this._fields.put(name, new CatalogEntry(stored, dt, tokenized, boost, num, df, r, existing != null));
}
}
public NumericType getNumericType(String fieldname) {
CatalogEntry entry = this._fields.get(fieldname);
return entry == null ? null : entry.num;
}
public boolean isTokenized(String fieldname) {
CatalogEntry entry = this._fields.get(fieldname);
return entry != null && entry.tokenized;
}
public DocValuesType getDocValuesType(String fieldname) {
CatalogEntry entry = this._fields.get(fieldname);
return entry == null ? null : entry.docValues;
}
public Collection<String> getFieldsByPrefix(String prefix) {
List<String> matching = new ArrayList<>();
synchronized (this._fields) {
for (String field : this._fields.keySet()) {
if (field.startsWith(prefix)) {
matching.add(field);
}
}
}
return matching;
}
public Resolution getResolution(String field) {
CatalogEntry entry = this._fields.get(field);
return entry != null ? entry.resolution : null;
}
public SimpleDateFormat getDateFormat(String field) {
CatalogEntry entry = this._fields.get(field);
return entry != null ? entry.dateFormat : null;
}
public void clear() {
synchronized (this._fields) {
this._fields.clear();
}
}
@Override
public void toXML(XMLWriter xml) throws IOException {
xml.openElement("catalog");
xml.attribute("name", this._name);
for (String fname : this._fields.keySet()) {
xml.openElement("field");
xml.attribute("name", fname);
CatalogEntry entry = this._fields.get(fname);
xml.attribute("stored", String.valueOf(entry.stored));
xml.attribute("tokenized", String.valueOf(entry.tokenized));
if (entry.num != null)
xml.attribute("numeric-type", entry.num.name().toLowerCase());
if (entry.docValues != null)
xml.attribute("doc-values", entry.docValues == DocValuesType.SORTED_SET ? "sorted-set" :
entry.docValues == DocValuesType.SORTED ||
entry.docValues == DocValuesType.SORTED_NUMERIC ? "sorted" : "none");
if (entry.boost != 1.0)
xml.attribute("boost", String.valueOf(entry.boost));
if (entry.error) xml.attribute("error", "true");
if (entry.dateFormat != null &&
entry.dateFormat instanceof SimpleDateFormat)
xml.attribute("date-format", ((SimpleDateFormat) entry.dateFormat).toPattern());
if (entry.resolution != null)
xml.attribute("date-resolution", entry.resolution.toString().toLowerCase());
xml.closeElement();
}
xml.closeElement();
}
public static class CatalogEntry {
private final boolean tokenized;
private final boolean error;
private final boolean stored;
private final DocValuesType docValues;
private final NumericType num;
private final SimpleDateFormat dateFormat;
private final Resolution resolution;
private final float boost;
public CatalogEntry(boolean s, DocValuesType dv, boolean t, float b, NumericType n, SimpleDateFormat df, Resolution r, boolean e) {
this.stored = s;
this.docValues = dv;
this.tokenized = t;
this.boost = b;
this.num = n;
this.resolution = r;
this.dateFormat = df;
this.error = e;
}
public CatalogEntry(FlintField builder, boolean err) {
this.stored = builder.store();
this.tokenized = builder.tokenize();
this.boost = builder.boost();
this.num = builder.numericType();
this.dateFormat = builder.dateformat();
this.resolution = builder.resolution();
this.error = err;
this.docValues = builder.docValues();
}
@Override
public boolean equals(Object obj) {
if (obj instanceof CatalogEntry) {
CatalogEntry entry = (CatalogEntry) obj;
return this.tokenized == entry.tokenized &&
this.stored == entry.stored &&
this.boost == entry.boost &&
this.num == entry.num &&
this.docValues == entry.docValues &&
((this.dateFormat == null && entry.dateFormat == null) ||
(this.dateFormat != null && this.dateFormat.equals(entry.dateFormat)));
}
return false;
}
@Override
public int hashCode() {
return (int) (this.boost * 10000) * 37 +
(this.num == null ? 13 : this.num.hashCode() * 17) +
(this.stored ? 19 : 2) +
(this.docValues == null ? 23 : this.docValues.hashCode() * 7) +
(this.tokenized ? 5 : 11) +
(this.dateFormat == null ? 31 : this.dateFormat.hashCode() * 31);
}
}
}
| true |
b8edb90f96647d46eebb68b268cb1c37e0cf3d52 | Java | glorygaz/NumericalAnalysis | /src/org/neu/dataStructure/Matrix.java | UTF-8 | 8,691 | 3.546875 | 4 | [] | no_license | package org.neu.dataStructure;
public class Matrix {
private double [][] matrix;
private int row;
private int col;
public Matrix(int row, int col) {
this.row = row;
this.col = col;
matrix = new double[row][col];
}
public Matrix(double[][] matrix) {
this.setMatrix(matrix);
}
public int getRow() {
return row;
}
public int getCol() {
return col;
}
public double[][] getMatrix() {
return matrix;
}
public void setMatrix(double[][] matrix) {
this.matrix = matrix;
this.row = matrix.length;
this.col = matrix[0].length;
}
/**
* Function:Matrix Add
* @param a:Matrix
* @param b:Matrix
* @return :Matrix
*/
public static Matrix add(Matrix a, Matrix b) throws Exception {
int row = a.getRow();
int col = a.getCol();
if (row != b.getRow() || col != b.getCol()) {
throw new Exception("AddFailed,Can't Add");
}
Matrix result = new Matrix(row, col);
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
result.getMatrix()[i][j] = a.getMatrix()[i][j] + b.getMatrix()[i][j];
}
}
return result;
}
/**
* Function:Matrix Sub
* @param a:Matrix
* @param b:Matrix
* @return :Matrix
*/
public static Matrix sub(Matrix a, Matrix b) throws Exception {
int row = a.getRow();
int col = a.getCol();
if (row != b.getRow() || col != b.getCol()) {
throw new Exception("SubtractFailed,Can't Subtract");
}
Matrix result = new Matrix(row, col);
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
result.getMatrix()[i][j]= a.getMatrix()[i][j] - b.getMatrix()[i][j];
}
}
return result;
}
/**
* Function:Matrix Multiple Matrix
* @param a:Matrix
* @param b:Matrix
* @return :Matrix
*/
public static Matrix mul(Matrix a, Matrix b) throws Exception {
int row = a.getRow();
int col = b.getCol();
if (a.getCol() != b.getRow()) {
throw new Exception("MultipleFailed,Can't Multiple");
}
Matrix result = new Matrix(row, col);
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
for (int k = 0; k < a.getCol(); k++) {
result.getMatrix()[i][j] += a.getMatrix()[i][k]*b.getMatrix()[k][j];
}
}
}
return result;
}
/**
* Function:Matrix Multiple Number
* @param a Matrix
* @param b double
* @return :Matrix
*/
public static Matrix mul(Matrix a, double b) {
int row = a.getRow();
int col = a.getCol();
Matrix result = new Matrix(row, col);
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
result.getMatrix()[i][j] = a.getMatrix()[i][j] * b;
}
}
return result;
}
/**
* Function:Square Matrix Inversion
* @param a :Matrix
* @return :Matrix
*/
public static Matrix inver(Matrix a) throws Exception {
int row = a.getRow();
if(a.getCol() != a.getRow()){ //方阵才能使用初等行变换求逆
throw new Exception("InversionFailed,Not Square");
}
double[][] copy = copyMatrix(a);
Matrix result = new Matrix(row, row);
double[][] resultM = result.getMatrix();
for(int i = 0; i < row; i++){ //将result矩阵置为单位矩阵
resultM[i][i] = 1;
}
for(int i = 0; i < row; i++){ //遍历每一列,从左到右
double aii = copy[i][i];
for(int j = 0; j < row; j++){ //遍历行中每个元素,除以aii
resultM[i][j] /= aii;
copy[i][j] /= aii;
}
for(int j = i+1; j < row; j++){ //遍历本行以下的每一行
elementaryRowTrans(row, copy, resultM, i, j);
}
}
for(int i = row-1; i >= 0 ; i--){ //遍历每一列,从右到左
for(int j = i-1; j >= 0; j--){ //遍历本行以上的每一行
elementaryRowTrans(row, copy, resultM, i, j);
}
}
return result;
}
/**
* Function:CopyMatrix
* @param a:Matrix
* @return :double[][]
*/
public static double[][] copyMatrix(Matrix a) {
double[][] copy = new double[a.getMatrix().length][]; //复制矩阵
for (int i = 0; i < copy.length; i++) {
copy[i] = a.getMatrix()[i].clone();
}
return copy;
}
/**
*Function:初等行变换
*/
private static void elementaryRowTrans(int row, double[][] copy, double[][] resultM, int i, int j) {
double coef = -copy[j][i]; //每行系数
for (int k = 0; k < row; k++) { //遍历行中每个元素
resultM[j][k] += coef * resultM[i][k];
copy[j][k] += coef * copy[i][k];
}
}
/**
* Function:Print Matrix
* @param matrix :Matrix
*/
public static void print(Matrix matrix) {
double [][] mat = matrix.getMatrix();
for (int i = 0; i < mat.length; i++) {
System.out.print("[");
for (int j = 0; j < mat[0].length; j++) {
System.out.print(mat[i][j]);
if (j != mat[0].length - 1) {
System.out.print(", ");
}
}
System.out.print("]\n");
}
}
/**
* Function:生成全一矩阵
*/
public static Matrix ones(int row, int col){
Matrix a = new Matrix(row, col);
double[][] matrix = a.getMatrix();
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
matrix[i][j] = 1;
}
}
return a;
}
/**
* Function:生成全0矩阵
*/
public static Matrix zeros(int row, int col){
Matrix a = new Matrix(row, col);
double[][] matrix = a.getMatrix();
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
matrix[i][j] = 0;
}
}
return a;
}
/**
* Function:生成无对角线的上三角矩阵
*/
public static Matrix upperTriangularMatrix(Matrix a){
Matrix result = new Matrix(a.getRow(), a.getCol());
for (int i = 0; i < a.getRow(); i++) {
for (int j = i+1; j < a.getCol(); j++) {
result.getMatrix()[i][j] = a.getMatrix()[i][j];
}
}
return result;
}
/**
* Function:生成无对角线的下三角矩阵
*/
public static Matrix lowerTriangularMatrix(Matrix a){
Matrix result = new Matrix(a.getRow(), a.getCol());
for (int i = 0; i < a.getCol(); i++) {
for (int j = i+1; j < a.getRow(); j++) {
result.getMatrix()[j][i] = a.getMatrix()[j][i];
}
}
return result;
}
/**
* Function:生成对角矩阵
*/
public static Matrix diagonalMatrix(Matrix a) throws Exception {
if(a.getCol() != a.getRow()){
throw new Exception("DiagonalMatrixFailed,Not Square");
}
Matrix result = new Matrix(a.getRow(), a.getCol());
for (int i = 0; i < a.getRow(); i++) {
result.getMatrix()[i][i] = a.getMatrix()[i][i];
}
return result;
}
/**
* Function:求解矩阵1-条件数
*/
public static double cond1(Matrix A) throws Exception {
return norm1(A)*norm1(Matrix.inver(A));
}
/**
* Function:求解矩阵1-范数
*/
public static double norm1(Matrix A){
double max = 0;
for (int i = 0; i < A.getCol(); i++) {
double temp = 0;
for (int j = 0; j < A.getRow(); j++) {
temp += A.getMatrix()[j][i];
}
if(max < temp){
max = temp;
}
}
return max;
}
/**
* Function:对对称正定矩阵进行预处理
*/
public static Matrix preTreatment(Matrix A) throws Exception {
Matrix C = Matrix.diagonalMatrix(A);
for (int i = 0; i < C.getRow(); i++) {
C.getMatrix()[i][i] = Math.sqrt(C.getMatrix()[i][i]);
}
return Matrix.mul(Matrix.mul(Matrix.inver(C),A),Matrix.inver(C));
}
}
| true |
479d47d5290f7a1c5c66a09877d684be36d94934 | Java | jennyferhubac/MPPAssign | /src/designworkshop/ordertrackingsystem/Order.java | UTF-8 | 3,342 | 2.859375 | 3 | [] | no_license | package designworkshop.ordertrackingsystem;
import java.text.SimpleDateFormat;
import java.util.*;
public class Order {
private String orderNumber;
private boolean isPrepaid;
private double orderPrice;
private Date orderDate;
private String status;
private double points;
private double custPoints;
private ACustomer customer;
ArrayList<Orderline> arrOrderline;
Order()
{
arrOrderline = new ArrayList<Orderline>();
}
Order(String orderNumber, Date orderDate)
{
this.orderNumber = orderNumber;
this.orderDate = orderDate;
arrOrderline = new ArrayList<Orderline>();
}
public String getOrderNumber() {
return orderNumber;
}
public void setOrderNumber(String orderNumber) {
this.orderNumber = orderNumber;
}
public boolean isPrepaid() {
return isPrepaid;
}
public void setPrepaid(boolean isPrepaid) {
this.isPrepaid = isPrepaid;
}
public double getOrderPrice() {
for(Orderline ordline : arrOrderline)
{
orderPrice = orderPrice + ordline.computePrice();
}
orderPrice = addDiscount(orderPrice);
return orderPrice;
}
public void setOrderPrice(double orderPrice) {
this.orderPrice = orderPrice;
}
public Date getOrderDate() {
return orderDate;
}
public void setOrderDate(Date orderDate) {
this.orderDate = orderDate;
}
public String getStatus() {
status = "SHIPPED";
for(Orderline ordline : arrOrderline)
{
if(!ordline.getStatus().equals("SHIPPED"))
{
status = "PENDING DELIVERY";
}
}
return status;
}
public void setStatus(String status) {
this.status = status;
}
public ArrayList<Orderline> getArrOrderline() {
return arrOrderline;
}
public void addOrderline(Orderline orderline)
{
arrOrderline.add(orderline);
}
public void print()
{
SimpleDateFormat dtFmt = new SimpleDateFormat("yyyy-mm-dd");
System.out.println("\n\n");
System.out.println("=====================================================\n");
System.out.println("Order Number: " + orderNumber + "\tOrder Date: " + dtFmt.format(orderDate));
System.out.printf("Total Order Price:\t $%,.2f \n", getOrderPrice());
System.out.println("Order Points:\t" + getOrderPoints());
System.out.println("Order Status:\t" + getStatus());
System.out.println("=====================================================\n");
System.out.println("Item\t\tQty\tPrice\tShipping Status");
for(Orderline ordline : arrOrderline)
{
ordline.print();
}
}
public ACustomer getCustomer() {
return customer;
}
public void setCustomer(ACustomer customer) {
this.customer = customer;
}
public double getOrderPoints()
{
points = 0;
for(Orderline ordline : arrOrderline)
{
points = points + ordline.getPoints();
}
return points;
}
public void setOrderPoints(double points)
{
this.points = points;
}
public double getCustomerPoints()
{
return customer.getAccumulatedPoints() + getOrderPoints();
}
public void setCustomerPoints(double points)
{
this.points = points;
}
private double addDiscount(double ordPrice)
{
if(getCustomerPoints() >= 25)
{
ordPrice = ordPrice - (ordPrice * 0.4);
customer.setPoints(0);
}
return ordPrice;
}
}
| true |
ed0969edc4f00c53319f81c0b3f2850315e13d6e | Java | ceugster/colibrits2 | /ch.eugster.colibri.client.ui/src/ch/eugster/colibri/client/ui/actions/PrintReceiptAction.java | UTF-8 | 4,829 | 1.820313 | 2 | [] | no_license | /*
* Created on 27.03.2009
*
* To change the template for this generated file go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
package ch.eugster.colibri.client.ui.actions;
import java.awt.event.ActionEvent;
import java.util.Dictionary;
import java.util.GregorianCalendar;
import java.util.Hashtable;
import java.util.Locale;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import org.osgi.service.event.Event;
import org.osgi.service.event.EventAdmin;
import org.osgi.service.event.EventConstants;
import org.osgi.util.tracker.ServiceTracker;
import ch.eugster.colibri.client.ui.Activator;
import ch.eugster.colibri.client.ui.panels.user.UserPanel;
import ch.eugster.colibri.client.ui.panels.user.receipts.CurrentReceiptListModel;
import ch.eugster.colibri.client.ui.panels.user.receipts.CurrentReceiptListSelectionModel;
import ch.eugster.colibri.persistence.events.Topic;
import ch.eugster.colibri.persistence.model.Profile;
import ch.eugster.colibri.persistence.model.Receipt;
import ch.eugster.colibri.persistence.model.SalespointReceiptPrinterSettings;
import ch.eugster.colibri.persistence.model.print.IPrintable;
import ch.eugster.colibri.provider.service.ProviderQuery;
public class PrintReceiptAction extends UserPanelProfileAction implements ListSelectionListener, TableModelListener
{
private static final long serialVersionUID = 0l;
public static final String TEXT = "Drucken";
public static final String ACTION_COMMAND = "print.action";
private final CurrentReceiptListModel tableModel;
private final CurrentReceiptListSelectionModel selectionModel;
public PrintReceiptAction(final UserPanel userPanel, final Profile profile,
final CurrentReceiptListModel tableModel, final CurrentReceiptListSelectionModel selectionModel)
{
super(PrintReceiptAction.TEXT, PrintReceiptAction.ACTION_COMMAND, userPanel, profile);
this.tableModel = tableModel;
this.selectionModel = selectionModel;
}
@Override
public void actionPerformed(final ActionEvent e)
{
final Receipt receipt = this.tableModel.getReceipt(this.selectionModel.getMinSelectionIndex());
final SalespointReceiptPrinterSettings settings = receipt.getSettlement().getSalespoint()
.getReceiptPrinterSettings();
if (settings != null)
{
final ServiceTracker<ProviderQuery, ProviderQuery> ProviderQueryTracker = new ServiceTracker<ProviderQuery, ProviderQuery>(Activator.getDefault().getBundle().getBundleContext(),
ProviderQuery.class, null);
ProviderQueryTracker.open();
try
{
final ProviderQuery providerQuery = (ProviderQuery) ProviderQueryTracker.getService();
if (providerQuery != null)
{
if (receipt.getCustomer() == null && receipt.getCustomerCode() != null && !receipt.getCustomerCode().isEmpty())
{
providerQuery.updateCustomer(receipt);
}
}
}
finally
{
ProviderQueryTracker.close();
}
final ServiceTracker<EventAdmin, EventAdmin> eventAdminTracker = new ServiceTracker<EventAdmin, EventAdmin>(Activator.getDefault().getBundle()
.getBundleContext(), EventAdmin.class, null);
eventAdminTracker.open();
try
{
final EventAdmin eventAdmin = (EventAdmin) eventAdminTracker.getService();
if (eventAdmin != null)
{
eventAdmin.sendEvent(this.getEvent(receipt));
}
}
finally
{
eventAdminTracker.close();
}
}
}
@Override
public void tableChanged(final TableModelEvent event)
{
if (this.isEnabled())
{
this.setEnabled(this.shouldEnable());
}
}
@Override
public void valueChanged(final ListSelectionEvent event)
{
this.setEnabled(this.shouldEnable());
}
private Event getEvent(final Receipt receipt)
{
final Dictionary<String, Object> eventProps = new Hashtable<String, Object>();
eventProps.put(EventConstants.BUNDLE, Activator.getDefault().getBundle());
eventProps.put(EventConstants.BUNDLE_ID, Long.valueOf(Activator.getDefault().getBundle().getBundleId()));
eventProps.put(EventConstants.BUNDLE_SYMBOLICNAME, Activator.getDefault().getBundle().getSymbolicName());
eventProps.put(EventConstants.SERVICE_OBJECTCLASS, this.getClass().getName());
eventProps.put(EventConstants.TIMESTAMP, Long.valueOf(GregorianCalendar.getInstance(Locale.getDefault()).getTimeInMillis()));
eventProps.put(IPrintable.class.getName(), receipt);
eventProps.put("force", true);
return new Event(Topic.PRINT_RECEIPT.topic(), eventProps);
}
private boolean shouldEnable()
{
return (this.tableModel.getRowCount() > 0) && (this.selectionModel.getMinSelectionIndex() > -1);
}
}
| true |
82117c8db1b90cf3ee97562fd023bb86d94be459 | Java | nemerosa/http-client | /http-client-core/src/test/java/net/nemerosa/httpclient/ClientImplTest.java | UTF-8 | 1,478 | 2.40625 | 2 | [] | no_license | package net.nemerosa.httpclient;
import org.apache.http.HttpHost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.client.CloseableHttpClient;
import org.junit.Test;
import java.net.MalformedURLException;
import java.net.URL;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
public class ClientImplTest {
@Test
public void encoding_for_spaces() throws MalformedURLException {
URL url = new URL("http://host:443/context");
ClientImpl client = new ClientImpl(
url,
new HttpHost("host", 443),
() -> mock(CloseableHttpClient.class),
mock(HttpClientContext.class),
System.out::println
);
assertEquals(
"http://host:443/context/Path/%20with%20spaces",
client.getUrl("/Path/ with spaces")
);
}
@Test
public void encoding_no_spaces() throws MalformedURLException {
URL url = new URL("http://host:443/context");
ClientImpl client = new ClientImpl(
url,
new HttpHost("host", 443),
() -> mock(CloseableHttpClient.class),
mock(HttpClientContext.class),
System.out::println
);
assertEquals(
"http://host:443/context/Path/With/No/Spaces",
client.getUrl("/Path/With/No/Spaces")
);
}
}
| true |
58b5ed656dd8969f0fbc409934fd39c47e9fa4f3 | Java | fengwuze/aggregate-framework | /aggregate-framework-core/src/main/java/org/aggregateframework/eventhandling/EventHandlerInvoker.java | UTF-8 | 1,165 | 2.328125 | 2 | [
"Apache-2.0"
] | permissive | package org.aggregateframework.eventhandling;
import org.aggregateframework.SystemException;
import org.aggregateframework.context.ReflectionUtils;
import org.aggregateframework.eventhandling.async.AsyncMethodInvoker;
import org.aggregateframework.session.EventInvokerEntry;
import java.lang.reflect.InvocationTargetException;
/**
* Created by changmingxie on 12/2/15.
*/
public class EventHandlerInvoker {
public static void invoke(EventInvokerEntry eventInvokerEntry) {
EventHandler eventHandler = ReflectionUtils.getAnnotation(eventInvokerEntry.getMethod(), EventHandler.class);
if (eventHandler.asynchronous()) {
AsyncMethodInvoker.getInstance().invoke(eventInvokerEntry.getMethod(), eventInvokerEntry.getTarget(), eventInvokerEntry.getParams());
} else {
try {
eventInvokerEntry.getMethod().invoke(eventInvokerEntry.getTarget(), eventInvokerEntry.getParams());
} catch (IllegalAccessException e) {
throw new SystemException(e);
} catch (InvocationTargetException e) {
throw new SystemException(e);
}
}
}
}
| true |
663430b3cefd141a6ff1599dc5e28fb35fc8addc | Java | brooklynphotos/codingexercises | /test/java/photos/brooklyn/practice/codingexercises/java/leetcode/OverlappingSquareMatricesTest.java | UTF-8 | 627 | 2.71875 | 3 | [] | no_license | package photos.brooklyn.practice.codingexercises.java.leetcode;
import org.junit.Test;
import static org.junit.Assert.*;
public class OverlappingSquareMatricesTest {
@Test
public void largestOverlap() {
final int[][] A = {{1,1,0}, {0,1,0},{0,1,0}};
final int[][] B = {{0,0,0}, {0,1,1},{0,0,1}};
assertEquals(3, new OverlappingSquareMatrices().largestOverlap(A, B));
}
@Test
public void largestOverlap2x2() {
final int[][] A = {{0,1}, {1,1}};
final int[][] B = {{1,1}, {1,0}};
assertEquals(3, new OverlappingSquareMatrices().largestOverlap(A, B));
}
} | true |
f7614cad55c6ce284fef085150a956adfb4d3b51 | Java | zleonardo/lab-comp-2019 | /src/ast/ParamDec.java | UTF-8 | 526 | 2.84375 | 3 | [] | no_license | /*
Nome: Vitor Pratali Camillo RA: 620181
Nome: Leonardo Zaccarias RA: 620491
*/
package ast;
public class ParamDec {
private String id;
private Type type;
public ParamDec(String id, Type type){
this.id = id;
this.type = type;
}
public Type getType() {
return this.type;
}
public void genJava(PW pw){
if(this.type == Type.intType) {
pw.print("int ");
}
else if(this.type == Type.stringType) {
pw.print("String ");
}
else if(this.type == Type.booleanType) {
pw.print("boolean ");
}
pw.print(this.id);
}
}
| true |
ba0af526d396371d82205bbe53b799168f661fcf | Java | RebirthDAN/201725050227-zhengdinghao | /201725050227郑丁豪/src/cn/edu/scau/cmi/zhengdinghao/factory/ChickenFactory.java | UTF-8 | 168 | 2.21875 | 2 | [] | no_license | package cn.edu.scau.cmi.zhengdinghao.factory;
public class ChickenFactory implements Factory{
@Override
public Meat getMeat() {
return new Chicken();
}
}
| true |
aaeed099c746ca981ee147b3ddbca7acb0d60cf8 | Java | HPI-Information-Systems/metanome-algorithms | /dfd/dfdAlgorithm/src/fdiscovery/general/CLIParserMiner.java | UTF-8 | 1,605 | 2.53125 | 3 | [
"Apache-2.0"
] | permissive | package fdiscovery.general;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.GnuParser;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
public class CLIParserMiner extends GnuParser {
@SuppressWarnings("static-access")
public CLIParserMiner() {
Options options = new Options();
Option inputFileName = OptionBuilder.withArgName("file")
.hasArg()
.withDescription("Input file name.")
.create("file");
Option inputDirectory = OptionBuilder.withArgName("input")
.hasArg()
.withDescription("Column files directory.")
.create("input");
Option resultFile = OptionBuilder.withArgName("result")
.hasArg()
.withDescription("Result file.")
.create("result");
Option numberOfColumns = OptionBuilder.withArgName("columns")
.hasArg()
.withDescription("Number of columns.")
.create("columns");
Option numberOfRows = OptionBuilder.withArgName("rows")
.hasArg()
.withDescription("Number of rows.")
.create("rows");
options.addOption(inputFileName);
options.addOption(inputDirectory);
options.addOption(resultFile);
options.addOption(numberOfColumns);
options.addOption(numberOfRows);
this.setOptions(options);
}
public CommandLine parse(String[] cli) {
CommandLine result = null;
try {
result = this.parse(this.getOptions(), cli);
} catch (ParseException e) {
e.printStackTrace();
}
return result;
}
}
| true |
8c55054e85d6b084f47189b418a1e7e8e0f048db | Java | rainbowsky911/springcloud_Hoxton | /springcloud-stream-rabbitmq-provider8801/src/main/java/com/wsh/springcloud/service/impl/MessageProviderImpl.java | UTF-8 | 1,185 | 2.328125 | 2 | [] | no_license | package com.wsh.springcloud.service.impl;
import com.wsh.springcloud.service.IMessageProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.cloud.stream.messaging.Source;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.messaging.MessageChannel;
import javax.annotation.Resource;
import java.util.UUID;
/**
* @Description 消息发送实现类
* @Date 2020/8/27 21:38
* @Author weishihuai
* 说明: @EnableBinding表示信道channel和exchange绑定在一起.
*/
@EnableBinding(Source.class)
public class MessageProviderImpl implements IMessageProvider {
private static final Logger logger = LoggerFactory.getLogger(MessageProviderImpl.class);
/**
* 消息发送管道
*/
@Resource
private MessageChannel output;
@Override
public String sendMessage() {
String uuid = UUID.randomUUID().toString();
output.send(MessageBuilder.withPayload(uuid).build());
logger.info("消息发送者发送消息: {}", uuid);
return "消息发送者发送消息: " + uuid;
}
}
| true |
aacd2f9c726feb1ba3ec0356d6085e77dd468e7f | Java | KovalevuchMykhaylo/Freemarker | /src/main/java/com/library/entity/Author.java | UTF-8 | 1,102 | 2.71875 | 3 | [] | no_license | package com.library.entity;
import com.library.entity.abstractClasses.AbstractNameWithId;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
@Entity
@Table(name = "author")
public class Author extends AbstractNameWithId {
@Column(name = "last_name")
private String lastName;
@ManyToMany(fetch = FetchType.LAZY, cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH})
@JoinTable(
name = "author_book",
joinColumns = {@JoinColumn(name = "author_id")},
inverseJoinColumns = {@JoinColumn(name = "book_id")}
)
private List<Book> books = new ArrayList<>();
public Author() {
}
public Author(String name, String lastName) {
super(name);
this.lastName = lastName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public List<Book> getBooks() {
return books;
}
public void setBooks(List<Book> books) {
this.books = books;
}
}
| true |
2c7afc83a74cc3269b625944da91144e991c87aa | Java | millionvoid/GameofLife_Java | /GUI.java | UTF-8 | 6,845 | 2.578125 | 3 | [] | no_license | import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.*;
public class GUI extends JFrame{
private int windowHeight=850;
private int windowWidth=800;
private int windowStartH;
private int windowStartW;
private int screenHeight;
private int screenWidth;
private int cellHeight=70;
private int cellWidth=70;
private int cellrow;
private int cellcolumn;
private int graphicStartH;
private int graphicStartW;
private int graphicEndH;
private int graphicEndW;
private int graphicH;
private int graphicW;
private int borderHeight=40;
private int borderWidth=30;
private int cellPadding=1;
private boolean [][] alive;
private int [][]cellStartW;
private int [][]cellStartH;
private Color aliveCellColor=Color.black;
private Color deadCellColor=Color.white;
private int buttonStartW;
private int buttonStartH;
private int buttonW=100;
private int buttonH=50;
private int labelStartW;
private int labelStartH;
private int labelW=100;
private int labelH=50;
private int updatetimes=0;
private JButton button;
private String buttonText_normal="暂停";
private String buttonText_paused="开始";
private JLabel label;
private String labelPrefix="演化次数:";
private Container container;
// private LYDClock clock;
private JMenuBar menuBar;
private JPanel uiPanel;
private JPanel buttonPanel;
private PulseEmiter pulseEmiter;
private Graphics uiGraphics;
Cells cells;
public GUI(int row,int column,int interval_ms) {
super("Game of Life");
cells=new Cells(row, column);
pulseEmiter=new PulseEmiter(interval_ms);
setVisible(true);
Dimension dimension=Toolkit.getDefaultToolkit().getScreenSize();
screenHeight=dimension.height;
screenWidth=dimension.width;
setSize(windowWidth, windowHeight);
windowStartW=(screenWidth-windowWidth)/2;
windowStartH=(screenHeight-windowHeight)/2;
setLocation(windowStartW,windowStartH);
cellrow=row;
cellcolumn=column;
graphicStartW=borderWidth;
graphicStartH=borderHeight;
cellHeight=(windowHeight-graphicStartH-borderHeight-cellPadding*(cellrow-1))/cellrow;
cellWidth=(windowWidth-graphicStartW-borderWidth-cellPadding*(cellcolumn-1))/cellcolumn;
if(cellHeight>cellWidth)
cellHeight=cellWidth;
else
cellWidth=cellHeight;
graphicH=cellHeight*cellrow+cellPadding*(cellrow-1);
graphicW=cellWidth*cellcolumn+cellPadding*(cellcolumn-1);
graphicEndW=graphicStartW+graphicW;
graphicEndH=graphicStartH+graphicH;
alive=new boolean[cellrow][cellcolumn];
cellStartH=new int[cellrow][cellcolumn];
cellStartW=new int[cellrow][cellcolumn];
for(int i=0;i<cellrow;i++)
{
for(int j=0;j<cellcolumn;j++)
{
cellStartH[i][j]=graphicStartH+i*(cellHeight+cellPadding);
cellStartW[i][j]=graphicStartW+j*(cellWidth+cellPadding);
}
}
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
);
buttonStartH=graphicEndH+20;
buttonStartW=graphicEndW-20-buttonW;
labelStartH=graphicEndH+20;
labelStartW=graphicStartW+20;
button=new JButton(buttonText_paused);
button.setVisible(true);
button.setPreferredSize(new Dimension(buttonW,buttonH));
label=new JLabel(labelPrefix+updatetimes);
label.setVisible(true);
buttonPanel=new JPanel(new BorderLayout());
uiPanel=new JPanel(new BorderLayout());
buttonPanel.setPreferredSize(new Dimension(windowWidth, 30));
buttonPanel.add(button,BorderLayout.EAST);
buttonPanel.add(label,BorderLayout.WEST);
this.getContentPane().add(uiPanel,BorderLayout.CENTER);
this.getContentPane().add(buttonPanel,BorderLayout.AFTER_LAST_LINE);
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if(button.getText().equals(buttonText_normal))
{
pulseEmiter.pause();
button.setText(buttonText_paused);
}
else
{
pulseEmiter.start();
button.setText(buttonText_normal);
}
}
});
Thread updateThread=new Thread(new Runnable() {
@Override
public void run() {
boolean on=false;
while(true)
{
try {
Thread.sleep(1);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(on!=pulseEmiter.on)
{
on=pulseEmiter.on;
cells.evaluate();
update();
}
}
}
});
updateThread.setDaemon(true);
updateThread.start();
repaint();
}
public void update() {
Graphics graphics=uiPanel.getGraphics();
graphics.setColor(aliveCellColor);
for(int i=0;i<cellrow;i++)
{
for(int j=0;j<cellcolumn;j++)
{
if(cells.getAt(i, j)&&(alive[i][j]!=cells.getAt(i, j)))
{
graphics.fillRect(cellStartW[i][j],cellStartH[i][j],cellWidth,cellHeight);
}
}
}
graphics.setColor(deadCellColor);
for(int i=0;i<cellrow;i++)
{
for(int j=0;j<cellcolumn;j++)
{
if(!cells.getAt(i, j)&&(alive[i][j]!=cells.getAt(i, j)))
{
graphics.fillRect(cellStartW[i][j],cellStartH[i][j],cellWidth,cellHeight);
}
alive[i][j]=cells.getAt(i, j);
}
}
label.setText(labelPrefix+(++updatetimes));
}
public void paint(Graphics graphics) {
super.paint(graphics);
new Thread(new Runnable() {
@Override
public void run() {
while(uiPanel==null);
Graphics panelGraphics=uiPanel.getGraphics();
windowHeight=getSize().height;
windowWidth=getSize().width;
graphicStartW=borderWidth;
graphicStartH=borderHeight;
cellHeight=(windowHeight-graphicStartH-borderHeight-cellPadding*(cellrow-1))/cellrow;
cellWidth=(windowWidth-graphicStartW-borderWidth-cellPadding*(cellcolumn-1))/cellcolumn;
if(cellHeight>cellWidth)
cellHeight=cellWidth;
else
cellWidth=cellHeight;
graphicH=cellHeight*cellrow+cellPadding*(cellrow-1);
graphicW=cellWidth*cellcolumn+cellPadding*(cellcolumn-1);
graphicEndW=graphicStartW+graphicW;
graphicEndH=graphicStartH+graphicH;
for(int i=0;i<cellrow;i++)
{
for(int j=0;j<cellcolumn;j++)
{
cellStartH[i][j]=graphicStartH+i*(cellHeight+cellPadding);
cellStartW[i][j]=graphicStartW+j*(cellWidth+cellPadding);
}
}
for(int i=0;i<cellrow;i++)
{
for(int j=0;j<cellcolumn;j++)
{
if(alive[i][j])
{
panelGraphics.setColor(aliveCellColor);
panelGraphics.fillRect(cellStartW[i][j],cellStartH[i][j],cellWidth,cellHeight);
}
else
{
panelGraphics.setColor(deadCellColor);
panelGraphics.fillRect(cellStartW[i][j],cellStartH[i][j],cellWidth,cellHeight);
}
}
}
}
}).start();
}
}
| true |
5d5e710137416509c908998b023e37509938baa0 | Java | coolprocess/Groccessory_ACE_PROJECT_2019_july | /grocessoryshop/src/main/java/com/niit/groccessory/dao/CategoryDaoImpl.java | UTF-8 | 1,571 | 2.40625 | 2 | [] | no_license | package com.niit.groccessory.dao;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.niit.groccessory.model.Category;
@Transactional
@Repository("categoryDao")
class CategoryDaoImpl implements CategoryDao {
@Autowired
SessionFactory sessionFactory;
public boolean addCategory(Category category) {
try {
sessionFactory.getCurrentSession().save(category);
return true;
} catch (Exception ae) {
return false;
}
}
public boolean deleteCategory(Category category) {
try {
sessionFactory.getCurrentSession().remove(category);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public boolean updateCategory(Category category) {
try {
sessionFactory.getCurrentSession().update(category);
return true;
} catch (Exception ae) {
ae.printStackTrace();
return true;
}
}
public Category getCategory(Integer id) {
try {
return sessionFactory.getCurrentSession().get(Category.class, id);
} catch (Exception ae) {
ae.printStackTrace();
return null;
}
}
@Override
public List<Category> retreiveAllCategories() {
try
{
return sessionFactory.getCurrentSession().createQuery("from Category", Category.class).getResultList();
}
catch(HibernateException ae)
{
ae.printStackTrace();
return null;
}
}
}
| true |
584e702b297906ef63bc16f5c69ac5fcc7afda85 | Java | LinXin04/-Offer | /20.java | UTF-8 | 621 | 3.203125 | 3 | [] | no_license | import java.util.Stack;
public class Solution {
Stack<Integer> stack1=new Stack<Integer>();
Stack<Integer> stack2=new Stack<Integer>();
public void push(int node) {
stack1.push(node);
if(stack2.empty())
stack2.push(node);
else
{
if(stack2.peek()>node)
stack2.push(node);
}
}
public void pop() {
int num=stack1.pop();
if(num==stack2.peek())
stack2.pop();
}
public int top() {
return stack1.peek();
}
public int min() {
return stack2.peek();
}
} | true |
ecb46dd139ab97fe723e3003710f342c1159905a | Java | Amani-sbai/Dari-tn | /src/main/java/tn/esprit/spring/repository/CreditRepository.java | UTF-8 | 382 | 1.8125 | 2 | [] | no_license | package tn.esprit.spring.repository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import tn.esprit.spring.entity.Credit;
@Repository
public interface CreditRepository extends CrudRepository<Credit, Integer>
{
@Query
int countByBankname(String name);
} | true |
863fc51183cc48453bb9cd21fb5a59feb589a047 | Java | cleitondantas/portal | /src/main/java/com/montreal/portal/repository/StatusAnaliseRepository.java | UTF-8 | 249 | 1.515625 | 2 | [] | no_license | package com.montreal.portal.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.montreal.portal.entity.StatusAnalise;
public interface StatusAnaliseRepository extends JpaRepository <StatusAnalise,Integer>{
}
| true |
54881667701ebec7d175fd35a5db1fcd784a3ebe | Java | roger-n/umn-spring-2018-csci-1913 | /UMN_CSCI_1133_LABS/Deque.java | UTF-8 | 1,381 | 3.65625 | 4 | [] | no_license | public class Deque <Base> {
private class Node{
private Base object;
private Node left;
private Node right;
public Node(Base object, Node left, Node right) {
this.object = object;
this.left = left;
this.right = right;
}
}
private Node head;
public Deque(){
head = new Node(null, null, null);
head.left = head;
head.right = head;
}
public void enqueueFront(Base object){
head.right = new Node(object, head, head.right);
head.right.right.left = head.right;
}
public void enqueueRear (Base object){
head.left = new Node(object, head.left, head);
head.left.left.right = head.left;
}
public Base dequeueFront(){
if(isEmpty()) {
throw new IllegalStateException("Empty Deque");
}
Base returnObject = head.right.object;
head.right = head.right.right;
head.right.left = head;
return returnObject;
}
public Base dequeueRear(){
if(isEmpty()){
throw new IllegalStateException("Empty Deque");
}
Base returnObject = head.left.object;
head.left = head.left.left;
head.left.right = head;
return returnObject;
}
public boolean isEmpty(){
return head.right == head;
}
}
| true |
b3a0e810d8b11a9f4bd4ff3a30b2ab283cc37ae7 | Java | Ramis-Bilalov/JAVA_2_Homeworks_MAVEN | /src/main/java/Lesson1/classwork2/Writable.java | UTF-8 | 104 | 2.140625 | 2 | [] | no_license | package Lesson1.classwork2;
public interface Writable<T> {
void write(T value) throws Exception;
}
| true |