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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
4f0e90a11fd7aad46af31fbd755f85c1a66a647b | Java | jitendra-bisht/Java9Demo | /ttnd.jobs/com/ttnd/jobs/BirthdayWishJob.java | UTF-8 | 264 | 1.804688 | 2 | [] | no_license | package com.ttnd.jobs;
import com.ttnd.logger.api.Logger;
import com.ttnd.logger.api.LoggerBuilder;
public class BirthdayWishJob {
public static void main(String []args) {
Logger logger = LoggerBuilder.getLogger();
logger.log("Happy Birthday Java 9");
}
}
| true |
145a929633d332e78b00af67e4a89f5140905320 | Java | tomaszwrobel/representatives-domain-kata | /src/test/java/rdk/e2e/OrganisationE2ETest.java | UTF-8 | 7,154 | 2.171875 | 2 | [] | no_license | package rdk.e2e;
import static org.assertj.core.api.Assertions.assertThat;
import static rdk.assertions.UserAssert.assertThat;
import static rdk.model.User.UserBuilder.user;
import java.util.ArrayList;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import rdk.IntegrationTestBase;
import rdk.exception.UnauthorizedAccessException;
import rdk.model.Organization;
import rdk.model.User;
import rdk.model.UserRole;
import rdk.service.OrganizationService;
public class OrganisationE2ETest extends IntegrationTestBase {
private static final String REGULAR_TEST_USER = "regular user";
private static final int DEFAULT_NUM_OF_ACKNOWLEDGMENTS = 3;
private static final String ADMIN_USER = "Admin user";
private static final int DEFAULT_NUM_OF_DOCUMENT_CONFIRMATIONS = 3;
@Autowired
OrganizationService organizationService;
User owner;
User admin;
Organization testOrganization;
@Before
public void init() {
owner = user(REGULAR_TEST_USER).withRole(UserRole.REGULAR).build();
admin = user(ADMIN_USER).withRole(UserRole.ADMIN).build();
testOrganization = organizationService.createNewOrganisation("nazwa", owner);
}
@Test
public void newOrganisationIsInActive() {
assertThat(testOrganization.isActive()).isFalse();
}
@Test
public void userBecomeOwnerOfNewCreatedOrganisation() {
assertThat(owner).hasRole(UserRole.OWNER);
assertThat(owner).isOwnerOf(testOrganization);
}
@Test
public void ownerRequestsForActivation() throws UnauthorizedAccessException {
organizationService.requestForActivation(testOrganization, owner);
assertThat(testOrganization.isActivationAwaiting()).isTrue();
}
@Test
public void addsMemberToNewInActiveOrganisation() throws UnauthorizedAccessException {
User newMember = user("newMember").withRole(UserRole.REGULAR).build();
assertThat(testOrganization.isActive()).isFalse();
organizationService.addMember(testOrganization, owner, newMember);
assertThat(newMember).isInOrganisationMembers(testOrganization);
}
@Test
public void ownerPromoteNewMemberToBeRepresentative() throws UnauthorizedAccessException {
User newMember = user("newMember").withRole(UserRole.REGULAR).build();
assertThat(testOrganization.isActive()).isFalse();
organizationService.addMember(testOrganization, owner, newMember);
assertThat(newMember).isInOrganisationMembers(testOrganization);
organizationService.promoteMemberBy(testOrganization, newMember, owner);
assertThat(newMember).isRepresentative();
}
@Test
public void ownerSetsRequiredNumberOfAcknowledgmentsForRepresentativeUser() throws UnauthorizedAccessException {
organizationService.setNumOfRequiredAcknowledgments(testOrganization, DEFAULT_NUM_OF_ACKNOWLEDGMENTS, owner);
// assertThat(testOrganisation.getNumOfAcknowledgments()).isEqualTo(DEFAULT_NUM_OF_ACKNOWLEDGMENTS);
}
@Test
public void organisationIsActivatedByAdmin() throws UnauthorizedAccessException {
organizationService.activateOrganisation(testOrganization, admin);
assertThat(testOrganization.isActive()).isTrue();
}
@Test
public void userGetsProperNumOfAcknowledgmentsAndBecomeRepresentative() throws UnauthorizedAccessException {
List<User> someRepresentativeMembers = prepareRepresentativeMembers(3);
User newUser = user("new User").withRole(UserRole.REGULAR).build();
organizationService.addMember(testOrganization, owner, someRepresentativeMembers.get(0));
organizationService.addMember(testOrganization, owner, someRepresentativeMembers.get(1));
organizationService.addMember(testOrganization, owner, someRepresentativeMembers.get(2));
organizationService.activateOrganisation(testOrganization, admin);
organizationService.setNumOfRequiredAcknowledgments(testOrganization, DEFAULT_NUM_OF_ACKNOWLEDGMENTS, owner);
organizationService.addMember(testOrganization, owner, newUser);
organizationService.promoteMemberBy(testOrganization, newUser, someRepresentativeMembers.get(0));
organizationService.promoteMemberBy(testOrganization, newUser, someRepresentativeMembers.get(1));
organizationService.promoteMemberBy(testOrganization, newUser, someRepresentativeMembers.get(2));
assertThat(newUser).isInOrganisationMembers(testOrganization);
assertThat(newUser).hasRole(UserRole.REPRESENTATIVE);
assertThat(newUser).hasNumberOfAcknowledgments(DEFAULT_NUM_OF_ACKNOWLEDGMENTS);
}
@Test
public void userLessNumOfAcknowledgmentsAndNotBecomesRepresentative() throws UnauthorizedAccessException {
List<User> someRepresentativeMembers = prepareRepresentativeMembers(3);
User newUser = user("new User").withRole(UserRole.REGULAR).build();
organizationService.addMember(testOrganization, owner, someRepresentativeMembers.get(0));
organizationService.addMember(testOrganization, owner, someRepresentativeMembers.get(1));
organizationService.addMember(testOrganization, owner, someRepresentativeMembers.get(2));
organizationService.activateOrganisation(testOrganization, admin);
organizationService.setNumOfRequiredAcknowledgments(testOrganization, DEFAULT_NUM_OF_ACKNOWLEDGMENTS, owner);
organizationService.addMember(testOrganization, owner, newUser);
organizationService.promoteMemberBy(testOrganization, newUser, someRepresentativeMembers.get(0));
organizationService.promoteMemberBy(testOrganization, newUser, someRepresentativeMembers.get(1));
assertThat(newUser).isInOrganisationMembers(testOrganization);
assertThat(newUser).hasRole(UserRole.REGULAR);
assertThat(newUser).hasNumberOfAcknowledgments(DEFAULT_NUM_OF_ACKNOWLEDGMENTS - 1);
}
@Test
public void ownerCancelsMemberRepresentativeRole() throws UnauthorizedAccessException {
User representativeUser = user("some representative user").withRole(UserRole.REPRESENTATIVE).build();
organizationService.addMember(testOrganization, owner, representativeUser);
organizationService.cancelMemberRepresentativeRole(testOrganization, representativeUser, owner);
assertThat(representativeUser).isInOrganisationMembers(testOrganization);
assertThat(representativeUser).hasRole(UserRole.REGULAR);
}
private List<User> prepareRepresentativeMembers(int num) {
List<User> users = new ArrayList<User>();
for (int i = 0; i < num; i++) {
users.add(user("user " + (i + 1)).withRole(UserRole.REPRESENTATIVE).build());
}
return users;
}
}
| true |
c44a3e995742d5cdb037e0a04964a289101eabcd | Java | gfis/joeis-lite | /internal/fischer/mangf/A257606.java | UTF-8 | 720 | 3.03125 | 3 | [
"Apache-2.0"
] | permissive | package irvine.oeis.a257;
import irvine.math.z.Z;
import irvine.oeis.triangle.Triangle;
/**
* A257606 Triangle read by rows: T(n,k) = t(n-k, k); t(n,m) = f(m)*t(n-1,m) + f(n)*t(n,m-1), where f(x) = x + 4.
* @author Georg Fischer
*/
public class A257606 extends Triangle {
/**
* Function for the multiplicands of the two previous triangle elements.
* Usually overwritten by sublcasses.
* @param x function parameter: <code>n-k</code> or <code>k</code>
*/
protected long function(final long x) {
return x + 4;
}
@Override
public Z compute(final int n, final int k) {
return n == 0 ? Z.ONE : get(n - 1, k - 1).multiply(function(n - k))
.add(get(n - 1, k).multiply(function(k)));
}
}
| true |
2d28580c9ae4e4cd34adc3a48a79893ba5315736 | Java | blwsw/BLWSERVER | /core-server-interfaces/src/main/java/com/hopedove/coreserver/vo/jcsjgl/SysUser.java | UTF-8 | 3,752 | 1.914063 | 2 | [] | no_license | package com.hopedove.coreserver.vo.jcsjgl;
import java.io.Serializable;
import java.time.LocalDateTime;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.annotations.ApiModelProperty;
/**
* 系统人员
*
*/
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility = JsonAutoDetect.Visibility.NONE)
@Deprecated
public class SysUser implements Serializable {
private static final long serialVersionUID = -2869376274676465708L;
@ApiModelProperty("主键id")
private Integer userId;
@ApiModelProperty("登录账号")
private String loginAccount;
@ApiModelProperty("登录人名称")
private String userName;
@ApiModelProperty("登录密码")
private String password;
@ApiModelProperty("角色id")
private Long roleId;
@ApiModelProperty("删除标记")
private String disabled;
@ApiModelProperty("创建人")
private String createUserId;
@ApiModelProperty("创建人姓名")
private String createUserName;
@ApiModelProperty("创建时间")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime createDatetime;
@ApiModelProperty("创建IP")
private String createIp;
@ApiModelProperty("修改人ID")
private String updateUserId;
@ApiModelProperty("修改人姓名")
private String updateUserName;
@ApiModelProperty("修改时间")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime updateDatetime;
@ApiModelProperty("修改IP")
private String updateIp;
private String newPassword;
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public String getLoginAccount() {
return loginAccount;
}
public void setLoginAccount(String loginAccount) {
this.loginAccount = loginAccount;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Long getRoleId() {
return roleId;
}
public void setRoleId(Long roleId) {
this.roleId = roleId;
}
public String getDisabled() {
return disabled;
}
public void setDisabled(String disabled) {
this.disabled = disabled;
}
public String getCreateUserId() {
return createUserId;
}
public void setCreateUserId(String createUserId) {
this.createUserId = createUserId;
}
public String getCreateUserName() {
return createUserName;
}
public void setCreateUserName(String createUserName) {
this.createUserName = createUserName;
}
public LocalDateTime getCreateDatetime() {
return createDatetime;
}
public void setCreateDatetime(LocalDateTime createDatetime) {
this.createDatetime = createDatetime;
}
public String getCreateIp() {
return createIp;
}
public void setCreateIp(String createIp) {
this.createIp = createIp;
}
public String getUpdateUserId() {
return updateUserId;
}
public void setUpdateUserId(String updateUserId) {
this.updateUserId = updateUserId;
}
public String getUpdateUserName() {
return updateUserName;
}
public void setUpdateUserName(String updateUserName) {
this.updateUserName = updateUserName;
}
public LocalDateTime getUpdateDatetime() {
return updateDatetime;
}
public void setUpdateDatetime(LocalDateTime updateDatetime) {
this.updateDatetime = updateDatetime;
}
public String getUpdateIp() {
return updateIp;
}
public void setUpdateIp(String updateIp) {
this.updateIp = updateIp;
}
public String getNewPassword() {
return newPassword;
}
public void setNewPassword(String newPassword) {
this.newPassword = newPassword;
}
}
| true |
2c1d6d6939e6fa5e1f8b61dcc6fe5846ee327c16 | Java | 0xRar/Problems114 | /warmup/Employee2/Employee.java | UTF-8 | 987 | 3.640625 | 4 | [] | no_license | public class Employee {
// Variable Declaration
private String FirstName;
private String LastName;
private double MonthlySalary;
// Constructor
public Employee2() {
FirstName = "";
LastName = "";
MonthlySalary = 0;
}
// Setters
public void setFirstName(String firstName) {
FirstName = firstName;
}
public void setLastName(String lastName) {
LastName = lastName;
}
public void setMonthlySalary(double monthlySalary) {
MonthlySalary = monthlySalary;
//If the monthly salary is not positive, set it to 0.0.
if (MonthlySalary < 0) {
MonthlySalary = 0.0;
} else
this.MonthlySalary = MonthlySalary;
}
public String getFirstName() {
return FirstName;
}
public String getLastName() {
return LastName;
}
public double getMonthlySalary() {
return MonthlySalary;
}
// Isa Ebrahim (0xRar)
}
| true |
42903fd057a92d6482983d3044398bca22a458fd | Java | AshutoshSundresh/OnePlusSettings-Java | /sources/com/android/settings/fuelgauge/batterytip/AppInfo.java | UTF-8 | 3,019 | 2.421875 | 2 | [] | no_license | package com.android.settings.fuelgauge.batterytip;
import android.os.Parcel;
import android.os.Parcelable;
import android.text.TextUtils;
import android.util.ArraySet;
import java.util.Objects;
public class AppInfo implements Comparable<AppInfo>, Parcelable {
public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
/* class com.android.settings.fuelgauge.batterytip.AppInfo.AnonymousClass1 */
@Override // android.os.Parcelable.Creator
public AppInfo createFromParcel(Parcel parcel) {
return new AppInfo(parcel);
}
@Override // android.os.Parcelable.Creator
public AppInfo[] newArray(int i) {
return new AppInfo[i];
}
};
public final ArraySet<Integer> anomalyTypes;
public final String packageName;
public final long screenOnTimeMs;
public final int uid;
public int describeContents() {
return 0;
}
private AppInfo(Builder builder) {
this.packageName = builder.mPackageName;
this.anomalyTypes = builder.mAnomalyTypes;
this.screenOnTimeMs = builder.mScreenOnTimeMs;
this.uid = builder.mUid;
}
AppInfo(Parcel parcel) {
this.packageName = parcel.readString();
this.anomalyTypes = parcel.readArraySet(null);
this.screenOnTimeMs = parcel.readLong();
this.uid = parcel.readInt();
}
public int compareTo(AppInfo appInfo) {
return Long.compare(this.screenOnTimeMs, appInfo.screenOnTimeMs);
}
public void writeToParcel(Parcel parcel, int i) {
parcel.writeString(this.packageName);
parcel.writeArraySet(this.anomalyTypes);
parcel.writeLong(this.screenOnTimeMs);
parcel.writeInt(this.uid);
}
public String toString() {
return "packageName=" + this.packageName + ",anomalyTypes=" + this.anomalyTypes + ",screenTime=" + this.screenOnTimeMs;
}
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof AppInfo)) {
return false;
}
AppInfo appInfo = (AppInfo) obj;
return Objects.equals(this.anomalyTypes, appInfo.anomalyTypes) && this.uid == appInfo.uid && this.screenOnTimeMs == appInfo.screenOnTimeMs && TextUtils.equals(this.packageName, appInfo.packageName);
}
public static final class Builder {
private ArraySet<Integer> mAnomalyTypes = new ArraySet<>();
private String mPackageName;
private long mScreenOnTimeMs;
private int mUid;
public Builder setPackageName(String str) {
this.mPackageName = str;
return this;
}
public Builder setScreenOnTimeMs(long j) {
this.mScreenOnTimeMs = j;
return this;
}
public Builder setUid(int i) {
this.mUid = i;
return this;
}
public AppInfo build() {
return new AppInfo(this);
}
}
}
| true |
08128558f334455be06bc865447ba996fe446253 | Java | leizhiheng/BaoGang | /src/com/baosteel/qcsh/ui/activity/store/LicencseQueryResultActivity.java | UTF-8 | 3,587 | 2.140625 | 2 | [] | no_license | package com.baosteel.qcsh.ui.activity.store;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import com.baosteel.qcsh.R;
import com.baosteel.qcsh.model.store.StoreDetailData;
import com.common.base.BaseActivity;
import com.common.view.topbar.HeadView;
/**
* 执照查询结果 Created by kuangyong on 15/9/22.
*/
public class LicencseQueryResultActivity extends BaseActivity{
private HeadView headview;// 标题栏
private TextView tvcompanyname;// 公司名称
private TextView tvlicensenum;// 营业执照号码
private TextView tvlegalperson;// 法人代表
private TextView tvadress;// 营业执照所在地
private TextView tvregisteredmoney;// 注册资金
private TextView tvlicensevalidity;// 执照期限
private TextView tvbusinessrange;// 经营范围
private TextView tvcompanyadress;// 公司地址
private TextView tvstorename;// 店铺名称
private TextView tvstoreweb;// 店铺网址
private TextView tvtip;//提示
private StoreDetailData mStoreDetailData;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_license_query_result);
mStoreDetailData = (StoreDetailData) getIntent().getSerializableExtra(StoreDetailsActivity.EXTRA_STORE_DETAIL);
findView();
setListener();
initView();
}
private void findView() {
this.tvtip = (TextView) findViewById(R.id.tv_tip);
this.headview = (HeadView) findViewById(R.id.headview);
this.tvstoreweb = (TextView) findViewById(R.id.tv_store_web);
this.tvstorename = (TextView) findViewById(R.id.tv_store_name);
this.tvcompanyadress = (TextView) findViewById(R.id.tv_company_adress);
this.tvbusinessrange = (TextView) findViewById(R.id.tv_business_range);
this.tvlicensevalidity = (TextView) findViewById(R.id.tv_license_validity);
this.tvregisteredmoney = (TextView) findViewById(R.id.tv_registered_money);
this.tvadress = (TextView) findViewById(R.id.tv_adress);
this.tvlegalperson = (TextView) findViewById(R.id.tv_legal_person);
this.tvlicensenum = (TextView) findViewById(R.id.tv_license_num);
this.tvcompanyname = (TextView) findViewById(R.id.tv_company_name);
}
private void setListener() {
}
private void initView() {
headview.setTitle("查询执照");
headview.setRightImageBtnBackGround(R.drawable.icon_3point);
headview.showRightImageBtn(View.VISIBLE, new View.OnClickListener() {
@Override
public void onClick(View v) {
showToast("菜单");
}
});
headview.setHeadViewBackGroundColor(getResources().getColor(
R.color.red_baosteel));
tvlicensenum.setText("营业执照号:"+mStoreDetailData.getBusinessLicenceCode());
tvcompanyname.setText("企业名称:"+mStoreDetailData.getCompanyName());
tvlegalperson.setText("公司法人:"+mStoreDetailData.getLegalPeople());
tvadress.setText("营业执照所在地:"+mStoreDetailData.getBusinessLicenceAddress());
tvregisteredmoney.setText("企业注册资金:"+mStoreDetailData.getRegisiterMoney());
tvlicensevalidity.setText("营业执照有效期:"+mStoreDetailData.getLicenceTime());
tvbusinessrange.setText("营业执照经营范围:"+mStoreDetailData.getBusinessRange());
tvcompanyadress.setText("公司地址:"+mStoreDetailData.getAddress());
tvstorename.setText("店铺名称:"+mStoreDetailData.getMerchantName());
tvstoreweb.setText("店铺网址:"+mStoreDetailData.getWebsite());
}
/**
*
* @Description 获取执照信息
* @Author blue
* @Time 2015-9-30
*/
private void loadData() {
}
}
| true |
6d8124a6a6f05870e936591b44ba7a4731330dd7 | Java | masumba/ReminderDemo | /app/src/main/java/com/afrifuturae/reminderdemo/MainActivity.java | UTF-8 | 2,613 | 2.421875 | 2 | [] | no_license | package com.afrifuturae.reminderdemo;
import androidx.appcompat.app.AppCompatActivity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TimePicker;
import android.widget.Toast;
import java.util.Calendar;
import java.util.Objects;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/*Set Onclick Listener*/
findViewById(R.id.btnSet).setOnClickListener(this);
findViewById(R.id.btnCancel).setOnClickListener(this);
findViewById(R.id.btnOther).setOnClickListener(this);
}
@Override
public void onClick(View v) {
EditText editText = findViewById(R.id.editTextTask);
TimePicker timePicker = findViewById(R.id.timePicker);
/*Set NotificationId & Text*/
Intent intent = new Intent(MainActivity.this,AlarmReceiver.class);
int notificationId = 1;
intent.putExtra("notificationId", notificationId);
intent.putExtra("todo",editText.getText().toString());
/*Get Broadcast*/
PendingIntent alarmIntent = PendingIntent.getBroadcast(MainActivity.this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
int i = v.getId();
if (i == R.id.btnSet) {
int hour = timePicker.getCurrentHour();
int minute = timePicker.getCurrentMinute();
/*Create Time*/
Calendar startTime = Calendar.getInstance();
startTime.set(Calendar.HOUR_OF_DAY, hour);
startTime.set(Calendar.MINUTE, minute);
startTime.set(Calendar.SECOND, 0);
long alarmStartTime = startTime.getTimeInMillis();
/*Set Alarm*/
Objects.requireNonNull(alarmManager).set(AlarmManager.RTC_WAKEUP, alarmStartTime, alarmIntent);
Toast.makeText(this, "Done!", Toast.LENGTH_SHORT).show();
} else if (i == R.id.btnCancel) {
Objects.requireNonNull(alarmManager).cancel(alarmIntent);
Toast.makeText(this, "Canceled", Toast.LENGTH_SHORT).show();
} else if (i == R.id.btnOther){
Intent intent1 = new Intent(MainActivity.this,Main2Activity.class);
startActivity(intent1);
}
}
}
| true |
54904094990b05eb8c1141d7032853ac9b2f78bf | Java | w407477841/zhlk | /src/com/zyiot/entity/FoodStorageAirColdFormMap.java | UTF-8 | 353 | 1.703125 | 2 | [] | no_license | package com.zyiot.entity;
import com.zyiot.annotation.TableSeg;
import com.zyiot.util.FormMap;
/**
*存储管理-作业记录-空调降温记录
*/
@TableSeg(id = "id", tableName = "t_storage_record_aircold")
public class FoodStorageAirColdFormMap extends FormMap<String, Object>{
/**
*
*/
private static final long serialVersionUID = 1L;
}
| true |
65639fcfcc9ea478cd6da6a2e881613b5888e0ec | Java | SimonGadgeteer/PROG1 | /10_Praktikum-1_Kaffee/src/aufgabe4/Kaffee.java | UTF-8 | 251 | 2.171875 | 2 | [] | no_license | package aufgabe4;
/**
* Diese Klasse bietet die Funktionalitaet, um einen Kaffee
* zu kochen.
*
* @author Dave Kramer, Simon Schwarz
* @Version 1.0
*/
public class Kaffee extends KoffeinGetraenk{
public Kaffee(String type)
{
super(type);
}
}
| true |
46d1b6b1dbd5a43e1718dc2950c38ca78a08f4ff | Java | gorillaz18010589/Fst_41_bluetooth | /app/src/main/java/tw/brad/apps/brad41/MainActivity.java | UTF-8 | 13,499 | 1.960938 | 2 | [] | no_license | package tw.brad.apps.brad41;
//目的:傳統藍芽2:https://developer.android.com/guide/topics/connectivity/bluetooth#ConnectAsAClient
//藍芽用在短距離大約70公尺,還有更短的式NFC公車刷悠遊卡
//RFID:NFC延伸出來用於工廠上面,東西一拿出倉庫馬上被顯示出貨
//Beacon:近距離路過某個店家,突然收到他的訊息,針策擬以靠近的範圍去發送訊息,屬於室內定位,空間的三點可以偵測你的位置
//iphone也有IBeacon可以偵測室內定位
//bluetooth藍芽:1.配對行為向耳機配對2.配玩隊在手機放資料
//3.藍芽二代有一個簡單的安全配對(ssp)比較舊,距離50~70公尺左右,主要是資訊溝通
//4.藍芽三代:速度有加快,增強電源控制,實際空間供耗較低了,大部分用在車載系統
//5.藍芽四代:節能省電,要賣歐洲要通過檢驗,主要式交換資料,雙方交換,其中一個連網把資料傳上網路
//6.藍芽五代:距離可以到300公尺,傳輸速率提供8倍,但目前一般手機都沒到
//手機要4.3以前才有支援BLE,再來手機也要看有沒有BLE才能支援,不然只有傳統藍芽
//<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>存取位置
//<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>存取精確位置
//<uses-permission android:name="android.permission.BLUETOOTH"/>藍芽權限
//<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
//藍芽4觀念:你的腳色是固定,一般手機式控制中心(Centra) 周邊工具(peripheral)
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Set;
import java.util.UUID;
public class MainActivity extends AppCompatActivity {
private BluetoothAdapter bluetoothAdapter;
private LinkedList<HashMap<String,Object>> devices = new LinkedList<>();
private ListView listDevices;
private SimpleAdapter adapter;
private String[] from = {"name", "mac","device"};
private int[] to = {R.id.item_name, R.id.item_mac};
private final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
//3.準備接收廣播訊息
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
try {
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
String deviceName = device.getName(); //取得藍芽名字
String deviceHardwareAddress = device.getAddress(); // 取得藍芽位置
Log.v("brad", deviceName);
HashMap<String,Object> deviceData = new HashMap<>();
deviceData.put("name", deviceName);//掛上name參數
deviceData.put("mac", deviceHardwareAddress);
deviceData.put("device", device);
//尋訪devices
boolean isRepeat = false;
for (HashMap<String,Object> dd : devices){
if (dd.get("device") == device){//如果挖到地址一樣的
Log.v("brad", "device dup");
isRepeat = true; //給他true
break;
}
}
if (!isRepeat) {
Log.v("brad", "new device add");
devices.add(deviceData);//新增資料
adapter.notifyDataSetChanged();//調變器啟動
}
}
}catch (Exception e){
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//設定藍芽權限設定
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) //詢問藍芽位置存取權限
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},//要藍雅位置權限
123);
}else{
init();
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
init();
}
//1.初始化設定
private void init(){
listDevices = findViewById(R.id.listDevices); //抓到listview的畫面
adapter = new SimpleAdapter(this,devices, R.layout.item_device,from,to);//1.創一個簡單調變器從這頁面 2.物件 3.指定畫面,4.從mac的資料 等 5.to灌到頁面
listDevices.setAdapter(adapter); //設置調變器
listDevices.setOnItemClickListener(new AdapterView.OnItemClickListener() { //當按下list view的item
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
doPair(i);
}
});
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); //取得我們這方的藍芽
if (!bluetoothAdapter.isEnabled()) {//如果藍芽馬達,沒有啟動
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); //連接(蘭雅啟動)
startActivityForResult(enableBtIntent, 123); //啟動藍芽
}else{
regReceiver(); //連接廣播
}
}
//4.如果有允許權限才會做以下的式
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 123 && resultCode == RESULT_OK){ //如果你的123詢係依值跑來這,而且權限ok
regReceiver(); //連接廣播
}
}
//5.註冊廣播
private void regReceiver(){
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(broadcastReceiver, filter);//連接廣播
}
//6.關掉時取消藍芽
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(broadcastReceiver);//關掉廣播
}
//2.按下按鈕查詢以配對過的藍芽
public void test1(View view) {
Set<BluetoothDevice> pairedDevices = //BluetoothDevice 代表別人的藍芽
bluetoothAdapter.getBondedDevices();//bluetoothAdapter我的藍芽紀錄
if (pairedDevices.size() > 0) {//如果藍芽記錄的長度大於0
// There are paired devices. Get the name and address of each paired device.
for (BluetoothDevice device : pairedDevices) {
String deviceName = device.getName(); //尋訪別人手機的資訊,取得連過的手機名
String deviceHardwareAddress = device.getAddress();//尋訪別人手機的資訊,取得連過的藍芽位置
Log.v("brad", deviceName + ":" + deviceHardwareAddress);
}
}
}
// 7.藍芽搜尋
public void test2(View view){
if (!bluetoothAdapter.isDiscovering()) {
devices.clear();
bluetoothAdapter.startDiscovery();
Log.v("brad","搜尋中...");
}
}
//藍芽被人搜尋300秒
public void test4(View view){
Intent discoverableIntent =
new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); //被搜尋回應
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);//啟動被搜尋藍雅的intent
Log.v("brad","藍芽被搜尋中啟動");
}
//8.如果藍芽正在搜尋,藍芽關閉搜尋
public void test3(View view){
if (bluetoothAdapter.isDiscovering()){ //如果藍雅正在搜尋的話
Log.v("brad", "關閉搜尋中...");
bluetoothAdapter.cancelDiscovery();//關掉藍芽
}
}
//10.啟動藍雅配對
private void doPair(int i){
// i => MAC device
//new AcceptThread().start();
BluetoothDevice device = (BluetoothDevice) devices.get(i).get("device");//取得所按的item(i)跟取得device,轉型成藍雅
new ConnectThread(device).start(); //開始主動配對的執行緒(此藍芽)
}
//9.藍芽主動配對
private class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
public ConnectThread(BluetoothDevice device) {
// Use a temporary object that is later assigned to mmSocket
// because mmSocket is final.
BluetoothSocket tmp = null;
mmDevice = device;
try {
// Get a BluetoothSocket to connect with the given BluetoothDevice.
// MY_UUID is the app's UUID string, also used in the server code.
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {
Log.v("brad", "Socket's create() method failed", e);
}
mmSocket = tmp;
}
public void run() {
// Cancel discovery because it otherwise slows down the connection.
bluetoothAdapter.cancelDiscovery();
try {
// Connect to the remote device through the socket. This call blocks
// until it succeeds or throws an exception.
mmSocket.connect(); //藍雅連線成功
Log.v("brad", "connect OK");
} catch (IOException connectException) {
// Unable to connect; close the socket and return.
try {
mmSocket.close();//藍芽關閉
} catch (IOException closeException) {
Log.v("brad", "Could not close the client socket", closeException);
}
return;
}
// The connection attempt succeeded. Perform work associated with
// the connection in a separate thread.
//manageMyConnectedSocket(mmSocket);
}
// Closes the client socket and causes the thread to finish.
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {
Log.v("brad", "Could not close the client socket", e);
}
}
}
//藍雅接收被配對
private class AcceptThread extends Thread {
private final BluetoothServerSocket mmServerSocket;
public AcceptThread() {
// Use a temporary object that is later assigned to mmServerSocket
// because mmServerSocket is final.
BluetoothServerSocket tmp = null;
try {
// MY_UUID is the app's UUID string, also used by the client code.
tmp = bluetoothAdapter.listenUsingRfcommWithServiceRecord("brad", MY_UUID);
} catch (IOException e) {
Log.v("brad", "Socket's listen() method failed", e);
}
mmServerSocket = tmp;
}
public void run() {
BluetoothSocket socket = null;
// Keep listening until exception occurs or a socket is returned.
while (true) {
try {
socket = mmServerSocket.accept(); //藍芽被接收中
} catch (IOException e) {
Log.v("brad", "Socket's accept() method failed", e);
break;
}
if (socket != null) {
// A connection was accepted. Perform work associated with
// the connection in a separate thread.
//manageMyConnectedSocket(socket);
try {
mmServerSocket.close();
}catch (Exception e){
}finally {
break;
}
}
}
}
// Closes the connect socket and causes the thread to finish.
public void cancel() {
try {
mmServerSocket.close();
} catch (IOException e) {
Log.v("brad", "Could not close the connect socket", e);
}
}
}
} | true |
3c7e1de298ba2e3ee1a4f5bfc0950237f22b9641 | Java | Luciekimotho/VMS | /app/src/main/java/com/stallar/vms/RestAPI/LoginService.java | UTF-8 | 251 | 1.789063 | 2 | [] | no_license | package com.stallar.vms.RestAPI;
import com.stallar.vms.model.User;
import retrofit2.Call;
import retrofit2.http.POST;
/**
* Created by lucie on 3/2/2018.
*/
public interface LoginService {
@POST("api/visits")
Call<User> basicLogin();
}
| true |
f1ff5b00938a23c52ef6f90a3b735912c435de8b | Java | yomero2030/SpringBoot | /spring-petclinic-master/src/main/java/org/springframework/samples/petclinic/receta/Receta.java | UTF-8 | 1,622 | 2.046875 | 2 | [
"LicenseRef-scancode-generic-cla",
"Apache-2.0"
] | permissive | /*
* 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 org.springframework.samples.petclinic.receta;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.springframework.core.style.ToStringCreator;
import org.springframework.samples.petclinic.citas.Frecuencia;
import org.springframework.samples.petclinic.model.BaseEntity;
import org.springframework.samples.petclinic.owner.Owner;
/**
*
* @author Faabian
*/
@Entity
@Table(name = "recetas")
public class Receta extends BaseEntity {
@Column(name = "id")
@Id
public int id;
@Column(name= "nombre")
public String nombre;
@OneToMany(cascade = CascadeType.ALL, mappedBy ="receta")
private Set<MedicamentoRecetado> medicamentosRecetados;
@Override
public Integer getId() {
return id;
}
@Override
public void setId(Integer id) {
this.id = id;
}
public Set<MedicamentoRecetado> getMedicamentosRecetados() {
return medicamentosRecetados;
}
public void setMedicamentosRecetados(Set<MedicamentoRecetado> medicamentosRecetados) {
this.medicamentosRecetados = medicamentosRecetados;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
}
| true |
a6b962f8c0ec7ca036638f2e84ecf965a12b044c | Java | PrashantJava-tech/products-service | /src/main/java/com/products/productsservice/entity/Product.java | UTF-8 | 1,146 | 2.15625 | 2 | [] | no_license | package com.products.productsservice.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long productId;
private String productName;
private String productCode;
private String productCompany;
public Long getProductId() {
return productId;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public String getProductCode() {
return productCode;
}
public void setProductCode(String productCode) {
this.productCode = productCode;
}
public String getProductCompany() {
return productCompany;
}
public void setProductCompany(String productCompany) {
this.productCompany = productCompany;
}
}
| true |
6cdb970c631be4a096eb62a9529660561337f638 | Java | YanceTimor/IT-Power | /power-common/src/main/java/com/yance520/itpower/model/sys/SysCompterEntity.java | UTF-8 | 2,323 | 2.3125 | 2 | [] | no_license | package com.yance520.itpower.model.sys;
/**
* Author : 杨杨
* Date : 2017/08/20
* Description : 系统配置信息
*/
public class SysCompterEntity {
// jvm最大内存
private long maxControl;
// jvm已占用内存
private long currentUse;
// jvm已占用且已使用内存
private long jvmUse;
// jvm已占用剩余可用内存
private long freeMemory;
// jvm实际可用内存
private long jvmFreeMemory;
// 系统内存
private long sysTotalPhysicalMemorySize;
// 系统可用内存
private long sysFreePhysicalMemorySize;
// jvm可用处理器数量
private long availableProcessors;
public long getAvailableProcessors() {
return availableProcessors;
}
public void setAvailableProcessors(long availableProcessors) {
this.availableProcessors = availableProcessors;
}
public long getSysTotalPhysicalMemorySize() {
return sysTotalPhysicalMemorySize;
}
public void setSysTotalPhysicalMemorySize(long sysTotalPhysicalMemorySize) {
this.sysTotalPhysicalMemorySize = sysTotalPhysicalMemorySize;
}
public long getSysFreePhysicalMemorySize() {
return sysFreePhysicalMemorySize;
}
public void setSysFreePhysicalMemorySize(long sysFreePhysicalMemorySize) {
this.sysFreePhysicalMemorySize = sysFreePhysicalMemorySize;
}
public long getJvmFreeMemory() {
return maxControl - currentUse + freeMemory;
}
public void setJvmFreeMemory(long jvmFreeMemory) {
this.jvmFreeMemory = jvmFreeMemory;
}
public long getJvmUse() {
return currentUse - freeMemory;
}
public void setJvmUse(long jvmUse) {
this.jvmUse = jvmUse;
}
public long getMaxControl() {
return maxControl;
}
public void setMaxControl(long maxControl) {
this.maxControl = maxControl;
}
public long getCurrentUse() {
return currentUse;
}
public void setCurrentUse(long currentUse) {
this.currentUse = currentUse;
}
public long getFreeMemory() {
return freeMemory;
}
public void setFreeMemory(long freeMemory) {
this.freeMemory = freeMemory;
}
}
| true |
0f85e7cae642c41d9b9a0852108d00710688ee4c | Java | declanmcgee01/account-project | /src/main/java/com/qa/accountApplication/Repo.java | UTF-8 | 179 | 1.546875 | 2 | [] | no_license | package com.qa.accountApplication;
import java.util.HashMap;
import java.util.Map;
public class Repo {
Map<Integer, Account> accountMap = new HashMap<Integer, Account>();
}
| true |
8d7167a9b5680f5709747e8696f544f6159c74c4 | Java | doorbrl/test_20210805 | /test/src/lambda/lambda.java | UTF-8 | 1,121 | 4 | 4 | [] | no_license | package lambda;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
public class lambda {
public static void main(String[] args) {
// TODO 自動生成されたメソッド・スタブ
Local local = new Local();
local.sayHello();
Runnable runner = () -> { System.out.println("Hello Lambda!"); };//ラムダ式の一つ
runner.run();
/*Function<T, R>のTはメソッドの引数の型、Rは戻り値の型を指定
*メソッドは R apply(T) */
Function<Integer, String> asterisker = (i) -> { return "*"+ i; };
String result = asterisker.apply(10);
System.out.println(result);
/* 2つの引数を受け付けるBiFunctionというインターフェース*/
BiFunction<Integer, Integer, Integer> adder = (a, b) -> { return a + b; };
int result1 = adder.apply(1, 2);
System.out.println(result1);
/*Consumer<T>のTはメソッドの引数の型を指定
*メソッドは void accept(T) */
Consumer<String> buyer = (goods) -> { System.out.println(goods + "を購入しました"); };
buyer.accept("おにぎり");
}
}
| true |
59fb88eefa200f9af6da2471e19ac43887d72c74 | Java | aashita1998/NUHomeStudio | /app/src/main/java/com/example/njudesigns/Dashboard.java | UTF-8 | 8,459 | 1.742188 | 2 | [] | no_license | package com.example.njudesigns;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.recyclerview.widget.GridLayoutManager;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
import com.example.njudesigns.adapter.ProductsAdapter;
import com.example.njudesigns.model.Products;
import com.google.android.gms.auth.api.identity.SignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.navigation.NavigationView;
import com.google.android.material.snackbar.Snackbar;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
public class Dashboard extends AppCompatActivity {
NavigationView nav;
ActionBarDrawerToggle toggle;
DrawerLayout drawerLayout;
Toolbar toolbar;
StateRec prodItems;
RequestQueue requestQueue;
GoogleSignInClient mGoogleSignInClient;
FloatingActionButton fabship;
@Override
public void onBackPressed()
{
super.onBackPressed();
startActivity(new Intent(Dashboard.this, Login.class));
finish();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
ActionBar actionBar = getSupportActionBar();
assert actionBar != null;
actionBar.hide();
getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE,
WindowManager.LayoutParams.FLAG_SECURE);
setContentView(R.layout.activity_dashboard);
toolbar = findViewById(R.id.toolbar);
nav = findViewById(R.id.navmenu);
drawerLayout = findViewById(R.id.drawer);
toggle = new ActionBarDrawerToggle(this,drawerLayout,toolbar,R.string.open,R.string.close);
drawerLayout.addDrawerListener(toggle);
toggle.syncState();
prodItems = findViewById(R.id.dash_rec);
if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
prodItems.setLayoutManager(new GridLayoutManager(this, 1));
} else {
prodItems.setLayoutManager(new GridLayoutManager(this, 2));
}
requestQueue = Volley.newRequestQueue(this);
List<Products> productsList = new ArrayList<>();
productsList.add(new Products("1", "Living", R.drawable.living10));
productsList.add(new Products("2", "Living", R.drawable.tv1));
productsList.add(new Products("3", "Living", R.drawable.kitchen1));
productsList.add(new Products("4", "Living", R.drawable.bed4));
productsList.add(new Products("5", "Living", R.drawable.living5));
productsList.add(new Products("6", "Living", R.drawable.tv4));
productsList.add(new Products("7", "Living", R.drawable.living7));
productsList.add(new Products("8", "Living", R.drawable.living8));
productsList.add(new Products("9", "Living", R.drawable.kitchen8));
productsList.add(new Products("10", "Living", R.drawable.tv3));
setProdItems(productsList);
ConnectivityManager connectivityManager = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
setProdItems(productsList);
} else {
if (this.getApplication().getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT || this.getApplication().getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setMessage("No Internet Connection...Please Check Your Network");
dialog.setNeutralButton("Ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
dialog.setCancelable(false);
dialog.show();
}
}
nav.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.menu_living:
// Toast.makeText(Dashboard.this, "Living", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Dashboard.this,Living.class);
startActivity(intent);
drawerLayout.closeDrawer(GravityCompat.START);
break;
case R.id.menu_tv:
//Toast.makeText(Dashboard.this, "Tv", Toast.LENGTH_SHORT).show();
Intent Tvintent = new Intent(Dashboard.this,Tvunit.class);
startActivity(Tvintent);
drawerLayout.closeDrawer(GravityCompat.START);
break;
case R.id.menu_kitchen:
//Toast.makeText(Dashboard.this, "Kitchen", Toast.LENGTH_SHORT).show();
Intent kitchenintent = new Intent(Dashboard.this,Kitchen.class);
startActivity(kitchenintent);
drawerLayout.closeDrawer(GravityCompat.START);
break;
case R.id.menu_bedroom:
//Toast.makeText(Dashboard.this, "Bedroom", Toast.LENGTH_SHORT).show();
Intent bedintent = new Intent(Dashboard.this,Bedroom.class);
startActivity(bedintent);
drawerLayout.closeDrawer(GravityCompat.START);
break;
case R.id.contact:
Intent contact_intent = new Intent(Dashboard.this, Contact.class);
startActivity(contact_intent);
drawerLayout.closeDrawer(GravityCompat.START);
break;
case R.id.logout:
Intent logintent = new Intent(Dashboard.this,Login.class);
startActivity(logintent);
drawerLayout.closeDrawer(GravityCompat.START);
finish();
break;
}
return true;
}
});
updateNavHeader();
}
private void setProdItems(List<Products> productsList) {
ProductsAdapter adapter = new ProductsAdapter(this, productsList);
prodItems.setAdapter(adapter);
}
public void updateNavHeader() {
NavigationView navigationView = findViewById(R.id.navmenu);
View headerview = navigationView.getHeaderView(0);
TextView navuser = headerview.findViewById(R.id.menu_username);
Intent intent = getIntent();
String str = intent.getStringExtra("username");
navuser.setText(str);
}
} | true |
8a8d7f8f914ceb6f4f77a08e5f3fdd0aec143543 | Java | china-zhangmy/java-core | /collection/src/main/java/com/demo/javacore/collection/Test.java | UTF-8 | 1,077 | 3.3125 | 3 | [] | no_license | package com.demo.javacore.collection;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
public class Test {
public static void main(String[] args) {
Set<String> set = new HashSet<>();
set.add(null);
set.add(null);
System.out.println(set);
List<String> list = new ArrayList<>();
list.add("first");
list.add("second");
list.add(null);
System.out.println(list);
list.stream()
.filter(e -> e != null && e.length() >= 1)
.forEach(b -> System.out.println(b));
String joined = list.stream()
.filter(e -> e != null && e.length() >= 1)
.map(Object::toString)
.collect(Collectors.joining(","));
System.out.println(joined);
Object[] objs = list.toArray();
System.out.println(objs.toString());
String[] strs = list.toArray(new String[0]);
System.out.println(strs.toString());
}
}
| true |
aff8ea4d051b09c87296239dfd507ec90b844bc9 | Java | junnikokuki/RobotApplication | /alpha2ctrl/src/main/java/com/ubtechinc/alpha2ctrlapp/third/TwitterWebView.java | UTF-8 | 1,403 | 2.09375 | 2 | [] | no_license | package com.ubtechinc.alpha2ctrlapp.third;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import com.orhanobut.logger.Logger;
import com.ubtechinc.alpha2ctrlapp.R;
public class TwitterWebView extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_twitter_webview_login );
WebView twitterWebView = (WebView) findViewById(R.id.webview_twitter);
twitterWebView.getSettings().setJavaScriptEnabled(true);
twitterWebView.setWebViewClient(new LoginToTwitterWebViewClient());
twitterWebView.loadUrl(getIntent().getExtras().get("twitter_url").toString());
}
private class LoginToTwitterWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.startsWith(TwitterManager.TWITTER_CALLBACK_URL)) {
Intent intent = new Intent();
intent.putExtra(TwitterManager.TWITTER_CALLBACK_URL, url);
setResult(Activity.RESULT_OK, intent);
finish();
}
return false;
}
}
@Override
protected void onStop() {
super.onStop();
Logger.d("TwitterWebView onStop", "onStop");
this.finish();
}
}
| true |
763eb0ad3e6ce6741cf2a305cb773a09b0038494 | Java | furongchi/MyWorkSpace | /JavaPractise/caseResult/src/listener/CreateButtonListener.java | UTF-8 | 872 | 2.453125 | 2 | [] | no_license | package listener;
import java.awt.event.ActionEvent;
import javax.xml.parsers.ParserConfigurationException;
import data.CreateParam;
import function.CreateResultXML;
public class CreateButtonListener implements java.awt.event.ActionListener {
private CreateParam createParam;
public CreateButtonListener(CreateParam createParam) {
// TODO Auto-generated constructor stub
this.createParam=createParam;
}
@Override
public void actionPerformed(ActionEvent paramActionEvent) {
// TODO Auto-generated method stub
CreateResultXML task= new CreateResultXML();
System.out.print("time");
System.out.print(System.currentTimeMillis() + "");
String temp = String.valueOf(System.currentTimeMillis());
try {
task.createXml(createParam);
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| true |
4d6d0003efb67b942b56945aca712a466f55c25d | Java | knokko/Enderpower-1.7.10 | /src/main/java/enderpower/wands/FlyWand.java | UTF-8 | 805 | 2.375 | 2 | [
"MIT"
] | permissive | package enderpower.wands;
import enderpower.magic.Magic;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.world.World;
public class FlyWand extends Item {
public FlyWand(){
super();
}
private int mana;
@Override
public ItemStack onItemRightClick(ItemStack item, World world, EntityPlayer player){
if(mana >= 5){
player.jumpMovementFactor = 0.5F;
player.fallDistance = 0.0F;
player.motionY = player.rotationPitch * -0.025;
Magic.get(world).editMana(-5, 0, 0, 0, 0, 0);
}
return item;
}
public void onUpdate(ItemStack item, World world, Entity entity, int a, boolean b){
if(!world.isRemote){
this.mana = Magic.get(world).getThauMana();
}
}
}
| true |
781cf157482886e5c79ea5a2811ba9a2da99b4cc | Java | ZiruiHua/Data-Structure-and-Algorithm-Practice | /3_RedBlackTree/RedBlackTree.java | UTF-8 | 7,991 | 3.046875 | 3 | [] | no_license | import java.math.BigInteger;
/**
* The type Red black tree.
*/
public class RedBlackTree {
/**
* The Root.
*/
RedBlackNode root, /**
* The Nil.
*/
nil;
/**
* The Count.
*/
int count;
/**
* Instantiates a new Red black tree.
*/
public RedBlackTree() {
//leaf node is black, is a null node
nil = new RedBlackNode(null, 0, null, null, null);
root = nil;
count = 0;
}
/**
* Insert.
*
* @param z1 the z 1
*/
//Pre-condition: memory is available for insertion
public void insert(ResultType z1) {
RedBlackNode z = new RedBlackNode(z1, -1, null, null, null);
RedBlackNode y = nil;
RedBlackNode x = root;
while (x != nil) {
y = x;
//z - x < 0 lexicographically
if (z1.compareTo(x.getData()) < 0) {
x = x.getLc();
} else {
x = x.getRc();
}
}
z.setP(y);
if (y == nil) {
root = z;
} else {
if (z1.compareTo(y.getData()) < 0) {
y.setLc(z);
} else {
y.setRc(z);
}
}
z.setLc(nil);
z.setRc(nil);
z.setColor(1);
RBInsertFixup(z);
}
/**
* Rb insert fixup.
*
* @param z the z
*/
//z is the new node
public void RBInsertFixup(RedBlackNode z) {
RedBlackNode y;
//parent node is red as well
while (z.getP().getColor() == 1) {
if (z.getP() == z.getP().getP().getLc()) {
y = z.getP().getP().getRc();
if (y.getColor() == 1) {
z.getP().setColor(0);
y.setColor(0);
z.getP().getP().setColor(1);
z = z.getP().getP();
} else {
if (z == z.getP().getRc()) {
z = z.getP();
leftRotate(z);
}
z.getP().setColor(0);
z.getP().getP().setColor(1);
rightRotate(z.getP().getP());
}
} else {
y = z.getP().getP().getLc();
if (y.getColor() == 1) {
z.getP().setColor(0);
y.setColor(0);
z.getP().getP().setColor(1);
z = z.getP().getP();
} else {
if (z == z.getP().getLc()) {
z = z.getP();
rightRotate(z);
}
z.getP().setColor(0);
z.getP().getP().setColor(1);
leftRotate(z.getP().getP());
} //end else
} //end else
} //end while
root.setColor(0);
}
/**
* Left rotate.
*
* @param x the x
*/
// x.getRC is not nil
// root's parent is nil
public void leftRotate(RedBlackNode x) {
RedBlackNode y = x.getRc();
x.setRc(y.getLc());
y.getLc().setP(x);
y.setP(x.getP());
if (x.getP() == nil)
root = y;
else {
if (x == x.getP().getLc())
x.getP().setLc(y);
else
x.getP().setRc(y);
}
y.setLc(x);
x.setP(y);
}
/**
* Right rotate.
*
* @param x the x
*/
// x.getLC is not nil
// root's parent is nil
public void rightRotate(RedBlackNode x) {
RedBlackNode y = x.getLc();
x.setLc(y.getRc());
y.getRc().setP(x);
y.setP(x.getP());
// if x is at root then y becomes new root
if (x.getP() == nil)
root = y;
else {
// if x is a left child then adjust x's parent's left child or...
if (x == x.getP().getLc())
x.getP().setLc(y);
else
// adjust x's parent's right child
x.getP().setRc(y);
}
y.setRc(x);
x.setP(y);
}
/**
* Lookup big integer.
*
* @param v1 the v 1
* @return the big integer
*/
//same as binary search tree
public BigInteger lookup(String v1) {
RedBlackNode search = root;
ResultType v = new ResultType(v1, new BigInteger("0"));
while (search != nil) {
count++;
if (search.getData().equals(v))
return search.getData().value;
else if (search.getData().compareTo(v) > 0)
search = search.getLc();
else
search = search.getRc();
}
return null;
}
/**
* Gets recent compares.
*
* @return the recent compares
*/
public int getRecentCompares() {
// int temp = count;
// count = 0;
return count;
}
/**
* In order traversal.
*
* @param t the t
*/
//Perfrom an inorder traversal of the tree. The inOrderTraversal(RedBlackNode) method is recursive and displays the content of the tree. It makes calls on System.out.println(). This method would normally be private.
public void inOrderTraversal(RedBlackNode t) {
if (t.getLc() != nil)
inOrderTraversal(t.getLc());
System.out.println(t.getData());
if (t.getRc() != nil)
inOrderTraversal(t.getRc());
}
/**
* In order traversal.
*/
//The no argument inOrderTraversal() method calls the recursive inOrderTraversal(RedBlackNode) - passing the root.
public void inOrderTraversal() {
inOrderTraversal(root);
}
/**
* Max height helper int.
*
* @param t the t
* @return the int
*/
public int maxHeightHelper(RedBlackNode t) {
if (t == nil)
return 0;
else
return Math.max(maxHeightHelper(t.getLc()), maxHeightHelper(t.getRc())) + 1;
}
/**
* Max height int.
*
* @return the int
*/
public int maxHeight() {
return maxHeightHelper(root);
}
/**
* Min height helper int.
*
* @param t the t
* @return the int
*/
//if a tree only has right subtree or left subtree
public int minHeightHelper(RedBlackNode t) {
if (t == nil) {
return Integer.MAX_VALUE;
}
if (root.getLc() == nil && root.getRc() == nil) {
return 1;
}
return Math.min(maxHeightHelper(t.getLc()), maxHeightHelper(t.getRc())) + 1;
}
/**
* Min height int.
*
* @return the int
*/
public int minHeight() {
return minHeightHelper(root);
}
/**
* The entry point of application.
*
* @param args the input arguments
*/
public static void main(String[] args) {
RedBlackTree redBlackTree = new RedBlackTree();
for (int i = 1; i <= 1000; i++) {
//add 1 to 1000 into the tree, key is String, value is BigInteger
String key = String.valueOf(i);
BigInteger value = new BigInteger(key);
ResultType res = new ResultType(key, value);
redBlackTree.insert(res);
}
//print the tree as in-order
redBlackTree.inOrderTraversal();
/*
* When inserting 1000 nodes into the tree, 2 * lg(1000 + 1) is 19.91
* In this case, the maximum height of this black red tree is 16, which is smaller than 19.91
*/
System.out.println("Maximum height of this red black tree is: " + redBlackTree.maxHeight());
System.out.println("Minimum height of this red black tree is: " + redBlackTree.minHeight());
//test look up
System.out.println("Find value of the node 8: " + redBlackTree.lookup("8"));
System.out.println("Number of nodes passed to look up this node: " +redBlackTree.getRecentCompares());
}
}
| true |
58d81eb6cc26a1e63b1c0a2a6d06dc185df291be | Java | bsmaat/Shithead | /src/ShitModel.java | UTF-8 | 390 | 2.265625 | 2 | [] | no_license | import java.util.ArrayList;
import java.util.List;
public class ShitModel extends java.util.Observable {
Deck deck = new Deck();
Pile pile = new Pile();
List<ShitHand> hands;// = new ArrayList<ShitHand>();
public ShitModel() {
hands = new ArrayList<ShitHand>();
}
public void updateChanges() {
Game.debug("updateChanges()");
setChanged();
notifyObservers(this);
}
}
| true |
3da9c384df98ca898d95e18d8294a4d216f1aebf | Java | Jacob-Hughey/MedBot | /AndroidStudioProjects/MedBot/app/src/main/java/health/medbot/medbot/OpenDB.java | UTF-8 | 662 | 2.421875 | 2 | [] | no_license | package health.medbot.medbot;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
/**
*
* Created by brandon on 10/14/18.
*/
public class OpenDB {
public OpenDB() {}
private static String DB_PATH =
"/data/data/medbot/src/main/assets/please_dont_delete_this_data";
public SQLiteDatabase openDB() throws SQLiteException {
SQLiteDatabase db = SQLiteDatabase.openDatabase(DB_PATH, null, SQLiteDatabase.OPEN_READWRITE);
return db;
}
public static void main(String[] args) {
// OpenDB db = new OpenDB();
System.out.println("DB is open: ");
}
}
| true |
f322757135f5f289b100340c07317d405763462b | Java | PuddleHound/All-Dem-Dimensions | /alldemdimensions/block/BlockBeehive.java | UTF-8 | 4,036 | 2.140625 | 2 | [] | no_license | package alldemdimensions.block;
import java.util.List;
import java.util.Random;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.IIcon;
import net.minecraft.util.MathHelper;
import net.minecraft.world.World;
import alldemdimensions.entity.EntityBee;
import alldemdimensions.util.TextureLibrary;
public class BlockBeehive extends Block
{
public BlockBeehive()
{
super(Material.gourd);
}
@Override
public int damageDropped(int i)
{
if(i == WAX || i == HONEYCOMB)
{
return i;
}
return 0;
}
@Override
public IIcon getIcon(int i, int j)
{
if((i == 0 && j == HONEYCOMB_SIDE_0) || (i == 1 && j == HONEYCOMB_SIDE_1) ||
(i == 2 && j == HONEYCOMB_SIDE_2) || (i == 3 && j == HONEYCOMB_SIDE_3) ||
(i == 4 && j == HONEYCOMB_SIDE_4) || (i == 5 && j == HONEYCOMB_SIDE_5) ||
j == HONEYCOMB || (i != 1 && j == ROYAL_JELLY))
{
return TextureLibrary.getBlockTexture("zenith/beehiveInterior");
} else
if(j == WAX)
{
return TextureLibrary.getBlockTexture("zenith/waxGrassTop");
} else
if(i == 1 && j == ROYAL_JELLY)
{
return TextureLibrary.getBlockTexture("zenith/royalJelly");
}
return TextureLibrary.getBlockTexture("zenith/beehiveExterior");
}
@Override
public void onBlockPlacedBy(World world, int i, int j, int k, EntityLivingBase entityliving, ItemStack itemstack)
{
if(world.getBlockMetadata(i, j, k) != 0)
{
return;
}
int metadata = 0;
boolean set = false;
if(MathHelper.abs((float)entityliving.posX - (float)i) < 2.0F && MathHelper.abs((float)entityliving.posZ - (float)k) < 2.0F)
{
double d = entityliving.posY + 1.82D - (double)entityliving.yOffset;
if (d - (double)j > 2.0D)
{
metadata = 1;
set = true;
}
if ((double)j - d > 0.0D)
{
metadata = 0;
set = true;
}
}
if(!set)
{
int l = MathHelper.floor_double((double)(entityliving.rotationYaw * 4.0F / 360.0F) + 0.5D) & 3;
if(l == 0)
{
metadata = 2;
}
if(l == 1)
{
metadata = 5;
}
if(l == 2)
{
metadata = 3;
}
if(l == 3)
{
metadata = 4;
}
}
world.setBlockMetadataWithNotify(i, j, k, metadata, 2);
}
@Override
public void updateTick(World world, int i, int j, int k, Random random)
{
//spawn bees?
}
@Override
public boolean removedByPlayer(World world, EntityPlayer entityplayer, int i, int j, int k)
{
int metadata = world.getBlockMetadata(i, j, k);
if(metadata <= ROYAL_JELLY || metadata == HONEYCOMB)
{
EntityBee.alertBeesOfAttack(world, entityplayer);
}
return super.removedByPlayer(world, entityplayer, i, j, k);
}
@Override
public void getSubBlocks(Item item, CreativeTabs creativetabs, List list)
{
list.add(new ItemStack(item, 1, HONEYCOMB_SIDE_0));
list.add(new ItemStack(item, 1, ROYAL_JELLY));
list.add(new ItemStack(item, 1, WAX));
list.add(new ItemStack(item, 1, HONEYCOMB));
}
public static final byte HONEYCOMB_SIDE_0 = 0;
public static final byte HONEYCOMB_SIDE_1 = 1;
public static final byte HONEYCOMB_SIDE_2 = 2;
public static final byte HONEYCOMB_SIDE_3 = 3;
public static final byte HONEYCOMB_SIDE_4 = 4;
public static final byte HONEYCOMB_SIDE_5 = 5;
public static final byte ROYAL_JELLY = 6;
public static final byte WAX = 8;
public static final byte HONEYCOMB = 9;
}
| true |
17c9a333116b3bb0774e25cfedc7c1a88bb7705a | Java | ab2564939195/spring | /ckxz/src/main/java/com/app/ckxz/util/MyInterceptor.java | UTF-8 | 1,380 | 2.34375 | 2 | [] | no_license | package com.app.ckxz.util;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Component
public class MyInterceptor implements HandlerInterceptor {
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
System.out.println(request.toString());
System.out.println(response.toString());
System.out.println(handler.toString());
System.out.println(">>>MyInterceptor1>>>>>>>在请求处理之前进行调用(Controller方法调用之前)");
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
System.out.println(">>>MyInterceptor1>>>>>>>在请求处理之前进行调用(Controller方法调用之后)");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
System.out.println(">>>MyInterceptor1>>>>>>>在整个请求结束之后被调用,也就是在DispatcherServlet 渲染了对应的视图之后执行(主要是用于进行资源清理工作)");
}
}
| true |
57808dd20ed10e7fd970df9d295dac040e5e49d5 | Java | asharma2/iot-learnings | /device-aas/src/main/java/com/iot/learnings/device/service/DeviceService.java | UTF-8 | 226 | 1.890625 | 2 | [] | no_license | package com.iot.learnings.device.service;
import java.util.Optional;
import com.iot.learnings.device.model.Device;
public interface DeviceService {
void save(Device device);
Optional<Device> findByImei(String imei);
}
| true |
61787056d86c909bc7aa434e908fc974b502892d | Java | hyperledger/besu | /metrics/core/src/main/java/org/hyperledger/besu/metrics/RunnableCounter.java | UTF-8 | 2,100 | 2.703125 | 3 | [
"Apache-2.0",
"LicenseRef-scancode-free-unknown"
] | permissive | /*
* Copyright ConsenSys AG.
*
* 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.
*
* SPDX-License-Identifier: Apache-2.0
*/
package org.hyperledger.besu.metrics;
import org.hyperledger.besu.plugin.services.metrics.Counter;
import java.util.concurrent.atomic.AtomicLong;
/** Counter that triggers a specific task each time a step is hit. */
public class RunnableCounter implements Counter {
/** The Backed counter. */
protected final Counter backedCounter;
/** The Task. */
protected final Runnable task;
/** The Step. */
protected final int step;
/** The Step counter. */
protected final AtomicLong stepCounter;
/**
* Instantiates a new Runnable counter.
*
* @param backedCounter the backed counter
* @param task the task
* @param step the step
*/
public RunnableCounter(final Counter backedCounter, final Runnable task, final int step) {
this.backedCounter = backedCounter;
this.task = task;
this.step = step;
this.stepCounter = new AtomicLong(0);
}
/**
* Increments the stepCounter by 1
*
* <p>{@link #inc(long) inc} method
*/
@Override
public void inc() {
this.inc(1);
}
/**
* Increments the stepCounter by amount. Triggers the runnable if the step is hit.
*
* @param amount the value to add to the stepCounter.
*/
@Override
public void inc(final long amount) {
backedCounter.inc(amount);
if (stepCounter.addAndGet(amount) % step == 0) {
task.run();
}
}
/**
* Get Step Counter.
*
* @return the long
*/
public long get() {
return stepCounter.get();
}
}
| true |
58f5917d3ede73b6d37ef4cc012b3a0f9dc663d5 | Java | dmitryako/kingroup | /kingroup_v2_java/kingroup_v2/pop/sample/sys/SysPopPart.java | UTF-8 | 508 | 2.109375 | 2 | [] | no_license | package kingroup_v2.pop.sample.sys;
import kingroup.partition.bitsets.Partition;
import kingroup.partition.bitsets.PartitionGroupFactory;
/**
* Copyright KinGroup Team.
* User: jc138691, Date: 7/10/2005, Time: 15:49:28
*/
public class SysPopPart extends SysPop {
private int[] groups;
public SysPopPart(Partition part, SysPop pop) {
shallowCopyFrom(pop);
groups = PartitionGroupFactory.getGroups(part);
}
public int getGroupId(int i) {
return groups[i];
}
}
| true |
90ae143180394e61a9f9e2cf83af12e3e9f71e21 | Java | glelouet/servertools | /consumption/consumption-model/src/main/java/fr/lelouet/consumption/basic/UseCase.java | UTF-8 | 5,894 | 2.28125 | 2 | [] | no_license | package fr.lelouet.consumption.basic;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.rmi.registry.Registry;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import fr.lelouet.consumption.model.ConsumptionList;
import fr.lelouet.consumption.model.Driver;
import fr.lelouet.consumption.model.DriverFactory;
import fr.lelouet.tools.main.Args;
import fr.lelouet.tools.main.Args.KeyValArgs;
public class UseCase {
private static final Logger logger = LoggerFactory.getLogger(UseCase.class);
public static final String TIMEOUT_KEY = "timeout";
public static final String DEFAULT_TIMEOUT = "2";
public static final String OUTPUT_KEY = "write";
public static final String OUTPUT_CONSOLE = "console";
public static final String DEFAULT_OUTPUT = OUTPUT_CONSOLE;
public static final String DELAY_KEY = "delay";
public static final String DEFAULT_DELAY = "-1";
public static final String EXPORT_RMI = "exportrmi";
public static final String EXPORT_WEB = "exportweb";
/**
* load the drivers according to the args. The drivers must be specified as a
* list of URI, separated by spaces
*
* @param factory
* the factory to load drivers from
* @param margs
* the arguments to load drivers from, specified by the user
* @return a map of driver names -> driver
*/
public static Map<String, Driver> getDriversFromArgs(DriverFactory factory,
KeyValArgs margs) {
Registry reg = null;
try {
if (Boolean.parseBoolean(margs.props.getProperty(EXPORT_RMI,
"false"))) {
reg = DriverInRMI.findDefaultRegistry();
}
} catch (Exception e) {
logger.warn("While getting defaut registry", e);
}
boolean exportWEB = Boolean.parseBoolean(margs.props.getProperty(
EXPORT_WEB, "false"));
logger.debug("exporting through rmi:" + (reg != null) + ", web:"
+ exportWEB + ", props are:" + margs.props);
Map<String, Driver> drivers = new HashMap<String, Driver>();
for (String arg : margs.targets) {
Driver driver = factory.getDriver(arg);
if (driver == null) {
logger.info(arg + " : cannot load with factory " + factory);
continue;
} else {
drivers.put(arg, driver);
if (reg != null) {
try {
DriverInRMI.export(driver, reg, arg);
} catch (Exception e) {
logger.warn("", e);
}
}
if (exportWEB) {
new DriverWEBEncapsulation(driver).export();
}
}
}
return drivers;
}
/**
* <p>
* use case to call from other classes' mains.
* </p>
* <p>
* parse args to make a proper invocation of the factory given as parameter.
* <br />
* creates the specified drivers on the given factory, and starts probing
* them according to the parameters :<br />
* {@value #INVOCATION} if cannot write data in the specified file (
* specified with key {@value #OUTPUT_KEY} )
* </p>
*
* @param factory
* the factory to create the drivers
* @param args
* the args to specify the factory behaviour.
* @throws IOException
*/
@SuppressWarnings("deprecation")
public static void main(DriverFactory factory, String[] args)
throws IOException {
int ret = 0;
KeyValArgs margs = Args.getArgs(args);
if (margs.props.containsKey("help") || margs.targets.contains("help")) {
showHelp();
System.exit(0);
}
long timeout = (long) (1000L * Double.parseDouble(margs.props
.getProperty(TIMEOUT_KEY, DEFAULT_TIMEOUT)));
long delay = (long) (1000L * Double.parseDouble(margs.props
.getProperty(DELAY_KEY, DEFAULT_DELAY)));
boolean exportRMI = Boolean.parseBoolean(margs.props.getProperty(
EXPORT_RMI, "false"));
boolean exportWEB = Boolean.parseBoolean(margs.props.getProperty(
EXPORT_WEB, "false"));
boolean export = exportRMI || exportWEB;
String output = margs.props.getProperty(OUTPUT_KEY, DEFAULT_OUTPUT);
ConsumptionList list = new BasicConsumptionList();
Writer writer = null;
if (output.equals(OUTPUT_CONSOLE)) {
writer = new OutputStreamWriter(System.out);
} else {
if (output.length() == 0) {
output = "consumption_" + new Date().toString() + ".log";
}
writer = new FileWriter(output, false);
}
list.setWriter(writer);
Map<String, Driver> drivers = getDriversFromArgs(factory, margs);
do {
if (!export || delay > 0) {
long start = System.currentTimeMillis();
for (Entry<String, Driver> e : drivers.entrySet()) {
Driver d = e.getValue();
d.retrieve();
}
for (Entry<String, Driver> e : drivers.entrySet()) {
Driver d = e.getValue();
while (!d.hasNewVal()
&& System.currentTimeMillis() < start + timeout) {
try {
Thread.sleep(1);
} catch (InterruptedException ex) {
logger.debug("", e);
ret = 1;
}
}
if (d.hasNewVal()) {
list.addData(System.currentTimeMillis(), d.lastVal());
} else {
System.out.println(e.getKey() + " : timeout");
ret = 1;
}
}
list.commit();
try {
long waitMS = delay - (System.currentTimeMillis() - start);
if (waitMS <= 0) {
waitMS = 0;
} else {
Thread.sleep(waitMS);
}
} catch (InterruptedException e1) {
logger.debug("", e1);
}
} else {
Thread.currentThread().suspend();
}
} while (delay > -1 || export);
System.exit(ret);
}
public static final String INVOCATION = "program ["
+ TIMEOUT_KEY
+ "=<timeout of the drivers in s>("
+ DEFAULT_TIMEOUT
+ ")]["
+ OUTPUT_KEY
+ "=<file to write, or null to create one>("
+ DEFAULT_OUTPUT
+ ")]["
+ DELAY_KEY
+ "=<seconds between drivers probings or -1 to make only one probe>("
+ DEFAULT_DELAY + ")]";
public static void showHelp() {
System.err.println(INVOCATION);
}
}
| true |
d02f891e4b340001c6aa0ea795a8dbc693be3623 | Java | ferdibulus/JavaProjects3 | /JavaCollecetionFramework/src/arrayListMain/Main.java | UTF-8 | 470 | 2.859375 | 3 | [] | no_license | package arrayListMain;
import java.util.List;
import java.util.ArrayList;
import java.util.Collection;
public class Main {
public static void main(String[] args) {
//ArrayList<String> arrayList = new ArrayList<String>();
List<String> list = new ArrayList<String>();
list.add("Java");
list.add("Mysql");
list.add("Php");
for(String s:list) {
System.out.println(s);
}
list.remove(0);
for(String s:list) {
System.out.println(s);
}
}
}
| true |
789078288be56e515e8b055a766aa2fa97715afe | Java | liijiankang/java_learn | /designModel/src/main/java/org/ljk/template/AbstractTemplate.java | UTF-8 | 371 | 2.546875 | 3 | [] | no_license | package org.ljk.template;
/**
* @DESCRIPTION:
* @AUTHOR: Lijiankanglc
* @DATE: 2020/8/11 19:16
*/
public abstract class AbstractTemplate {
public void operation(){
System.out.println("step1...");
System.out.println("step2...");
System.out.println("step3...");
templateMethod();
}
public abstract void templateMethod();
}
| true |
dad549b4561f3916385614ba738ac5909d568ecf | Java | tianxiao666/rno-indoor | /.svn/pristine/06/06e51264b7acbb2f48cae50de40d78bac8db83dc.svn-base | UTF-8 | 435 | 1.632813 | 2 | [] | no_license | package com.hgicreate.rno.service.dto;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* @author chao.xj
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class CbFloorDTO {
private Long floorId;
private Long buildingId;
private String floorName;
private String physicalFloor;
private String floorType;
private String floorNote;
private String status;
}
| true |
f6411fe20d809bbedd8b2348ea85b14ddf7e9b62 | Java | Pashan501/List_of_Cars_with_Composition | /src/com/company/Main.java | UTF-8 | 887 | 3.015625 | 3 | [] | no_license | package com.company;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Car>list = new ArrayList<>();
Car car = new Car("Mercedes","2020", new Body(
new Transmission(new Wheel(1,"lb"),new Wheel(2,"lb"),new Wheel(3,"lb"),new Wheel(4,"lb")),
new Engine("Volvo V12",9000)));
Car car2 = new Car("BMW","2015", new Body(
new Transmission(new Wheel(1,"lb"),new Wheel(2,"lb"),new Wheel(3,"lb"),new Wheel(4,"lb")),
new Engine("BMW V6",6000)));
list.add(car);
list.add(car2);
for(Car a :list){
System.out.println(a);
}
car.getBody().getEngine().engineOn();
System.out.println(car.getMark_name()+" прогріла двигун...");
car.getBody().getEngine().engineOff();
}
}
| true |
1224fa2fb38c797cc345403097f6a7736af27eca | Java | hashsdn/hashsdn-snbi | /southplugin/src/main/java/org/opendaylight/snbi/southplugin/Snbi.java | UTF-8 | 1,670 | 2.125 | 2 | [] | no_license | /*
* Copyright (c) 2014, 2015 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
package org.opendaylight.snbi.southplugin;
import java.security.InvalidParameterException;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* Provide services to start SNBI in the system.
*
*/
public class Snbi {
ConcurrentHashMap <String, SnbiRegistrar> registrarList = null;
private static final Logger log = LoggerFactory.getLogger(Snbi.class);
public Snbi(String domainName) throws InvalidParameterException {
SnbiRegistrar registrar = null;
if (domainName == null || domainName.equals(null)
|| (domainName.length() == 0)) {
throw new InvalidParameterException(domainName
+ " is not a valid domain name");
}
if (registrarList == null) {
registrarList = new ConcurrentHashMap <String, SnbiRegistrar>();
}
log.debug("Creating registrar");
log.debug("Validating domain name ");
if(!SnbiRegistrar.validateDomain(domainName))
{
log.error(" No domains configured. Use POST http://localhost:8080/restconf/config/ to create a domain");
return;
}
registrar = new SnbiRegistrar(domainName);
registrarList.put(domainName, registrar);
}
protected void finalize () {
}
}
| true |
f02b536a5e522802283b1eea757fcede4f109e87 | Java | zjw-swun/android | /designer/src/com/android/tools/idea/naveditor/scene/targets/ActionHandleTarget.java | UTF-8 | 10,051 | 1.609375 | 2 | [] | no_license | /*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.tools.idea.naveditor.scene.targets;
import static com.android.tools.idea.naveditor.scene.NavDrawHelperKt.ACTION_HANDLE_OFFSET;
import static com.android.tools.idea.naveditor.scene.NavDrawHelperKt.DRAW_ACTION_HANDLE_BACKGROUND_LEVEL;
import static com.android.tools.idea.naveditor.scene.NavDrawHelperKt.DRAW_ACTION_HANDLE_LEVEL;
import static com.android.tools.idea.naveditor.scene.NavDrawHelperKt.INNER_RADIUS_LARGE;
import static com.android.tools.idea.naveditor.scene.NavDrawHelperKt.INNER_RADIUS_SMALL;
import static com.android.tools.idea.naveditor.scene.NavDrawHelperKt.OUTER_RADIUS_LARGE;
import static com.android.tools.idea.naveditor.scene.NavDrawHelperKt.OUTER_RADIUS_SMALL;
import com.android.tools.adtui.common.SwingCoordinate;
import com.android.tools.idea.common.model.Coordinates;
import com.android.tools.idea.common.model.NlComponent;
import com.android.tools.idea.common.scene.LerpFloat;
import com.android.tools.idea.common.scene.Scene;
import com.android.tools.idea.common.scene.SceneComponent;
import com.android.tools.idea.common.scene.SceneContext;
import com.android.tools.idea.common.scene.ScenePicker;
import com.android.tools.idea.common.scene.draw.DisplayList;
import com.android.tools.idea.common.scene.draw.DrawCircle;
import com.android.tools.idea.common.scene.draw.DrawFilledCircle;
import com.android.tools.idea.common.scene.target.Target;
import com.android.tools.idea.common.surface.SceneView;
import com.android.tools.idea.naveditor.model.NavComponentHelperKt;
import com.android.tools.idea.naveditor.model.NavCoordinate;
import com.android.tools.idea.naveditor.scene.draw.DrawActionHandleDrag;
import com.android.tools.idea.uibuilder.handlers.constraint.drawing.ColorSet;
import com.google.common.collect.ImmutableList;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.util.Computable;
import com.intellij.openapi.util.text.StringUtil;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.geom.Point2D;
import java.util.List;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* {@linkplain ActionHandleTarget} is a target for handling drag-creation of actions.
* It appears as a circular grab handle on the right side of the navigation screen.
*/
public class ActionHandleTarget extends NavBaseTarget {
private static final int DURATION = 200;
@SwingCoordinate private static final int STROKE_WIDTH = 2;
private static String DRAG_CREATE_IN_PROGRESS = "DRAG_CREATE_IN_PROGRESS";
private static final BasicStroke STROKE = new BasicStroke(STROKE_WIDTH);
private enum HandleState {
INVISIBLE(0, 0),
SMALL(INNER_RADIUS_SMALL, OUTER_RADIUS_SMALL),
LARGE(INNER_RADIUS_LARGE, OUTER_RADIUS_LARGE);
HandleState(@NavCoordinate float innerRadius, @NavCoordinate float outerRadius) {
myInnerRadius = innerRadius;
myOuterRadius = outerRadius;
}
@NavCoordinate private final float myInnerRadius;
@NavCoordinate private final float myOuterRadius;
}
private HandleState myHandleState;
private boolean myIsDragging = false;
public ActionHandleTarget(@NotNull SceneComponent component) {
super(component);
myHandleState = calculateState();
}
@Override
public int getPreferenceLevel() {
return Target.ANCHOR_LEVEL;
}
@Override
public boolean layout(@NotNull SceneContext sceneTransform,
@NavCoordinate int l,
@NavCoordinate int t,
@NavCoordinate int r,
@NavCoordinate int b) {
@NavCoordinate int x = r;
if (NavComponentHelperKt.isFragment(getComponent().getNlComponent())) {
x += ACTION_HANDLE_OFFSET;
}
layoutCircle(x, t + (b - t) / 2, (int)myHandleState.myOuterRadius);
return false;
}
@Override
public void mouseDown(@NavCoordinate int x, @NavCoordinate int y) {
Scene scene = myComponent.getScene();
scene.getDesignSurface().getSelectionModel().setSelection(ImmutableList.of(getComponent().getNlComponent()));
myIsDragging = true;
scene.needsRebuildList();
SceneComponent parent = myComponent.getParent();
assert parent != null;
parent.getNlComponent().putClientProperty(DRAG_CREATE_IN_PROGRESS, true);
getComponent().setDragging(true);
scene.repaint();
}
@Override
public void mouseRelease(@NavCoordinate int x,
@NavCoordinate int y,
@NotNull List<Target> closestTargets) {
myIsDragging = false;
Scene scene = myComponent.getScene();
SceneComponent parent = myComponent.getParent();
assert parent != null;
parent.getNlComponent().removeClientProperty(DRAG_CREATE_IN_PROGRESS);
getComponent().setDragging(false);
SceneComponent closestComponent =
scene.findComponent(SceneContext.get(getComponent().getScene().getSceneManager().getSceneView()), x, y);
if (closestComponent != null &&
closestComponent != getComponent().getScene().getRoot() &&
StringUtil.isNotEmpty(closestComponent.getId())) {
NlComponent action = createAction(closestComponent);
if (action != null) {
getComponent().getScene().getDesignSurface().getSelectionModel().setSelection(ImmutableList.of(action));
}
}
scene.needsRebuildList();
}
/* When true, this causes Scene.mouseRelease to change the selection to the associated SceneComponent.
We don't have SceneComponents for actions so we need to return false here and set the selection to the
correct NlComponent in Scene.mouseRelease */
@Override
public boolean canChangeSelection() {
return false;
}
@Nullable
public NlComponent createAction(@NotNull SceneComponent destination) {
if (mIsOver) {
return null;
}
NlComponent destinationNlComponent = destination.getNlComponent();
if (!NavComponentHelperKt.isDestination(destinationNlComponent)) {
return null;
}
NlComponent myNlComponent = getComponent().getNlComponent();
return WriteCommandAction.runWriteCommandAction(myNlComponent.getModel().getProject(),
(Computable<NlComponent>)() -> NavComponentHelperKt
.createAction(myNlComponent, destinationNlComponent.getId()));
}
@Override
public void render(@NotNull DisplayList list, @NotNull SceneContext sceneContext) {
HandleState newState = calculateState();
if (newState == HandleState.INVISIBLE && myHandleState == HandleState.INVISIBLE) {
return;
}
SceneView view = myComponent.getScene().getDesignSurface().getCurrentSceneView();
@SwingCoordinate float centerX = Coordinates.getSwingXDip(view, getCenterX());
@SwingCoordinate float centerY = Coordinates.getSwingYDip(view, getCenterY());
@SwingCoordinate Point2D.Float center = new Point2D.Float(centerX, centerY);
@SwingCoordinate float initialRadius = Coordinates.getSwingDimension(view, myHandleState.myOuterRadius);
@SwingCoordinate float finalRadius = Coordinates.getSwingDimension(view, newState.myOuterRadius);
int duration = (int)Math.abs(DURATION * (myHandleState.myOuterRadius - newState.myOuterRadius) / OUTER_RADIUS_LARGE);
ColorSet colorSet = sceneContext.getColorSet();
list.add(new DrawFilledCircle(DRAW_ACTION_HANDLE_BACKGROUND_LEVEL, center, colorSet.getBackground(),
new LerpFloat(initialRadius, finalRadius, duration)));
initialRadius = Coordinates.getSwingDimension(view, myHandleState.myInnerRadius);
finalRadius = Coordinates.getSwingDimension(view, newState.myInnerRadius);
Color color = getComponent().isSelected() ? colorSet.getSelectedFrames() : colorSet.getSubduedFrames();
if (myIsDragging) {
list.add(new DrawFilledCircle(DRAW_ACTION_HANDLE_LEVEL, center, color, finalRadius));
list.add(new DrawActionHandleDrag(getSwingCenterX(sceneContext), getSwingCenterY(sceneContext)));
}
else {
list.add(new DrawCircle(DRAW_ACTION_HANDLE_LEVEL, center, color, STROKE, new LerpFloat(initialRadius, finalRadius, duration)));
}
myHandleState = newState;
}
@Override
public void addHit(@NotNull SceneContext transform, @NotNull ScenePicker picker) {
picker.addCircle(this, 0, getSwingCenterX(transform), getSwingCenterY(transform),
transform.getSwingDimension((int)OUTER_RADIUS_LARGE));
}
@Override
public Cursor getMouseCursor() {
return Cursor.getPredefinedCursor(Cursor.HAND_CURSOR);
}
private HandleState calculateState() {
if (myIsDragging) {
return HandleState.SMALL;
}
if (myComponent.getScene().getDesignSurface().getInteractionManager().isInteractionInProgress()) {
return HandleState.INVISIBLE;
}
if (mIsOver) {
return HandleState.LARGE;
}
if (getComponent().getDrawState() == SceneComponent.DrawState.HOVER) {
return HandleState.SMALL;
}
if (getComponent().isSelected() && myComponent.getScene().getSelection().size() == 1) {
return HandleState.SMALL;
}
return HandleState.INVISIBLE;
}
public static boolean isDragCreateInProgress(@NotNull NlComponent component) {
NlComponent parent = component.getParent();
return parent != null && parent.getClientProperty(DRAG_CREATE_IN_PROGRESS) != null;
}
}
| true |
1756f21d8092b9fe34f61a1f45dfb83ead829c96 | Java | verxm/RPG-Character-Sheets | /RPG-Character-Sheets/src/br/com/while42/rpgcs/model/equip/armor/shields/ShieldLightSteel.java | UTF-8 | 692 | 2.3125 | 2 | [] | no_license | package br.com.while42.rpgcs.model.equip.armor.shields;
import br.com.while42.rpgcs.R;
import br.com.while42.rpgcs.model.equip.armor.Armor;
import br.com.while42.rpgcs.model.equip.armor.BasicArmor;
public class ShieldLightSteel extends AbstractShieldArmor implements Armor {
private static final long serialVersionUID = 1L;
private static final BasicArmor armor;
static {
armor = new BasicArmor(R.string.armor_shield_light_steel);
armor.setCost(9L);
armor.setArmorBonus(1);
armor.setMaximumDexBonus(0);
armor.setArmorCheckPenalty(-1);
armor.setArcaneSpellFailureChance(5);
armor.setSpeed(0);
armor.setWeight(3.0);
}
public ShieldLightSteel() {
super(armor);
}
}
| true |
593ee675342490456501a1bbbe762fb16d451e06 | Java | harshadusa1938/Sorting-Serching | /SortingAlgorithm.java | UTF-8 | 2,665 | 4.3125 | 4 | [] | no_license | /* Author Name: Harshad Patel
Due Date: 12/07/2017
Description:- Sorting Algorithm
Create a class called SortingAlgorithms that takes an unsorted array and sorts it using
selection sort and insertion sort. The program should include methods to sort using
the selection sort and insertion sort algorithms. The array should be contain 10 int
values. The program should output the array unsorted and then the array sorted with
each method. The program should also include comments about how the sorting
methods are sorting the array. This assignment is an exercise to understand how the
algorithms work, therefore, it should be heavily commented.
*/
package com.sorting;
public class SortingAlgorithm
{
//=========Start-Selection Sort===================
public static int[] selectionSort(int[] array)
{
for (int i = 0; i < array.length - 1; i++)
{
int min_index = i;
for (int j = i + 1; j < array.length; j++)
if (array[j] < array[min_index])
min_index = j;
int temp = array[min_index];
array[min_index] = array[i];
array[i] = temp;
}
return array;
}
//=========Start-Insertion Sort===================
public static void insertionSort(int array[])
{
int n = array.length;
for (int j = 1; j < n; j++)
{
int key = array[j];
int i = j-1;
while ( (i > -1) && ( array [i] > key ) )
{
array [i+1] = array [i];
i--;
}
array[i+1] = key;
showInsertion(array);
}
}
private static void showInsertion(int[] arr1)
{
for (int i = 0; i < arr1.length; i++)
{
System.out.print(arr1[i] + ", ");
}
System.out.println("\n");
}
// Main Method for Both Algorithm like Selection Sort and Insertion Sort
public static void main(String a[])
{
System.out.print("-----------Selection Sort--------------- \n\n");
int[] arr1 = {4, 2, 9, 6, 23, 12, 34, 0, 1};
// Display Insertion Sort
insertionSort(arr1);
System.out.print("\n-----------Insertion Sort--------------- \n\n");
int[] arr2 = selectionSort(arr1);
for(int i:arr2)
{
System.out.print(i);
System.out.print(" | ");
}
System.out.print("\n\n---------------------------------------- \n");
}
} | true |
bb73ef54205f365715534ba742247c9230700e85 | Java | SredniyBot/3D | /src/main/java/GamePanel.java | UTF-8 | 1,337 | 2.796875 | 3 | [] | no_license | import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferedImage;
public class GamePanel extends JPanel {
public static int SizeX=Toolkit.getDefaultToolkit().getScreenSize().width,SizeY=
Toolkit.getDefaultToolkit().getScreenSize().height;
public void paint(Graphics g){
g.setColor(Color.BLACK);
g.fillRect(0,0,SizeX,SizeY);
PlayerList.update();
PlayerList.paint3d(g);
g.drawImage(Book.paintBook(),(int)(-SizeX/9+Math.sin(Math.toRadians(Player.deltaX))*10),(int)(SizeY*2/3+Math.cos(Math.toRadians(Player.deltaX))*10),SizeX*4/9,SizeY*4/9,null);
g.drawImage(light.paintLight(),(int)(SizeX*8/9+Math.cos(Math.toRadians(Player.deltaX))*10),(int)(SizeY*2/3+Math.cos(Math.toRadians(Player.deltaX))*10),SizeX/9,SizeY*4/9,null);
if(KeyBoard.getInstance().isKeyDown(77)){
g.drawImage(paintMap(),0,0,SizeX,SizeY,null);
}else{
g.drawImage(paintMap(),10,10,SizeX/5,SizeY/5,null);
}
repaint();
}
public static BufferedImage paintMap(){
BufferedImage img = new BufferedImage(SizeX,SizeY,BufferedImage.TYPE_INT_RGB);
Graphics2D g = (Graphics2D)img.createGraphics();
Map.paint(g);
return img;
}
}
| true |
9683c3c375857b1e8c6548f74dc506b8b8e77b88 | Java | shihabuddinbuet/su-problem-solution | /leetcode/algorithm/java/src/com/su/leetCode/easy/Problem344ReverseString.java | UTF-8 | 752 | 3.3125 | 3 | [] | no_license | package com.su.leetCode.easy;
public class Problem344ReverseString {
public static void main(String[] args) {
System.out.println(reverseString("hello"));
char []ch = new char[1];
ch[0] = 'i';
ch[0] = (char) (ch[0] ^ ch[0]);
ch[0] = (char) (ch[0] ^ ch[0]);
ch[0] = (char) (ch[0] ^ ch[0]);
System.out.println(ch[0]);
}
public static String reverseString(String s) {
char[]ch = s.toCharArray();
int begin = 0;
int end = s.length() - 1;
while(end > begin){
ch[begin] = (char) (ch[begin] ^ ch[end]);
ch[end] = (char)(ch[begin] ^ ch[end]);
ch[begin] = (char)(ch[end] ^ ch[begin]);
begin ++;
end --;
}
return new String(ch);
}
}
| true |
b0626bfa4e02f8c7963a5001964018436f7bf5d0 | Java | kamild706/ShopClientAndroid | /app/src/main/java/pl/p32/shopclient/viewmodel/HomepageViewModel.java | UTF-8 | 785 | 2.203125 | 2 | [] | no_license | package pl.p32.shopclient.viewmodel;
import android.app.Application;
import java.util.List;
import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import pl.p32.shopclient.model.Product;
import pl.p32.shopclient.repository.ProductRepository;
public class HomepageViewModel extends AndroidViewModel {
private final ProductRepository repository;
private final LiveData<List<Product>> randomProducts;
public HomepageViewModel(@NonNull Application application) {
super(application);
repository = ProductRepository.getInstance(application);
randomProducts = repository.getProducts();
}
public LiveData<List<Product>> getRandomProducts() {
return randomProducts;
}
}
| true |
41280f142a49e87e2a2006996f9b052b156d4ea8 | Java | jarvis3907/ArchiUnitSample | /src/main/java/org/example/layers/anticorruption/InternalUtility.java | UTF-8 | 232 | 2.03125 | 2 | [] | no_license | package org.example.layers.anticorruption;
import org.example.layers.anticorruption.internal.InternalType;
class InternalUtility {
InternalType okaySinceTheVisibilityIsNonPublic() {
return new InternalType();
}
}
| true |
8f17af5a7cd0c242a2b02cfa2bac05ccce4a11cb | Java | xuxiang1991/Commonpj | /app/src/main/java/com/xuxiang/pj/activity/MainActivity.java | UTF-8 | 3,971 | 2.15625 | 2 | [] | no_license | package com.xuxiang.pj.activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.xuxiang.pj.R;
import com.xuxiang.pj.activity.base.BaseToolbarActivity;
import com.xuxiang.pj.entity.eventbus.MessageEvent;
import com.xuxiang.pj.entity.eventbus.ToastMessage;
import com.xuxiang.pj.network.config.DailogUtil;
import com.xuxiang.pj.network.config.DomainUrl;
import com.xuxiang.pj.network.service.CommonApiProvider;
import com.xuxiang.pj.network.service.CommonRequest;
import com.xuxiang.pj.network.service.CommonResponse;
import com.xuxiang.pj.observer.MyObserver;
import com.xuxiang.pj.observer.MyPerson;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
/**
* 类名称:
* 类描述:
* 创建人:
* 修改人:
*/
public class MainActivity extends BaseToolbarActivity {
@BindView(R.id.bt_go)
Button btGo;
@BindView(R.id.tv_message)
TextView tvMessage;
int i = 0;
MyPerson person;
String[] names = new String[]{"张三", "李四", "王五"};
@Override
protected int getLayoutId() {
return R.layout.activity_main;
}
@Override
protected void setupViews() {
person = new MyPerson();
// btGo.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// i++;
// MyObserver observer = new MyObserver(i);
// person.addObserver(observer);
//
//
//// DevTechFrontier devTechFrontier=new DevTechFrontier();
//// Coder mrsimple=new Coder("mr.simple");
//// Coder coder1=new Coder("code-1");
//// Coder coder2=new Coder("code-2");
//// Coder coder3=new Coder("code-3");
////
//// devTechFrontier.addObserver(mrsimple);
//// devTechFrontier.addObserver(coder1);
//// devTechFrontier.addObserver(coder2);
//// devTechFrontier.addObserver(coder3);
////
//// devTechFrontier.postNewPublication("新学期开始了");
//
//// startActivity(new Intent(self, LoginActivity.class));
// }
// });
btGo.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
person.setName(names[i % 3]);
return true;
}
});
EventBus.getDefault().register(self);
}
@Override
protected void initialized() {
DailogUtil.showNetDialog(self);
CommonApiProvider.getNetGetCommon(DomainUrl.UPLOAD_DATA, new CommonResponse<String>() {
@Override
public void onSuccess(CommonRequest request, String data) {
super.onSuccess(request, data);
errorLog(data + "");
}
@Override
public void onFail(int errorCode, String errorMsg) {
super.onFail(errorCode, errorMsg);
}
@Override
public void onComplete() {
super.onComplete();
DailogUtil.closeNetDialog();
}
});
}
@Subscribe(threadMode = ThreadMode.MAIN)
public void onEvent(MessageEvent event) {
tvMessage.setText(event.getMessage());
}
@Subscribe(threadMode = ThreadMode.MAIN)
public void onToastEvent(ToastMessage event) {
ShowToast(event.getMessage());
}
@OnClick(R.id.bt_go)
public void onClick(View v) {
switch (v.getId()) {
case R.id.bt_go:
i++;
MyObserver observer = new MyObserver(i);
person.addObserver(observer);
break;
}
}
}
| true |
85caf61879958718625606bd5a5d694c4bee7555 | Java | finalfantasy357/Rose | /JavaTestGof/src/com/Gof/Adapter/MainTest.java | UTF-8 | 319 | 2.15625 | 2 | [] | no_license | package com.Gof.Adapter;
public class MainTest {
public static void main(String[] args) {
Player forwardPlayer = new Forwards("B");
Player backPlayer = new Background("M");
Player foreignCenterPlayer = new Translator("Y");
forwardPlayer.Attack();
backPlayer.Attack();
foreignCenterPlayer.Attack();
}
}
| true |
478989b40c397f47c941dd044b697aef9fff3a03 | Java | funing1/SuanFa | /SuanFa/src/suanfa/XuanZePaiXu.java | UTF-8 | 699 | 2.96875 | 3 | [] | no_license | package suanfa;
import java.util.Arrays;
public class XuanZePaiXu {
public static void main(String[] args) {
int[] arr = {2,2,1,7,11,9,10};
System.out.println(Arrays.toString(arr));
xuanze(arr);
System.out.println(Arrays.toString(arr));
}
public static void xuanze(int[] arr){
for(int i = 0 ; i < arr.length;i++){
int min_index = 0;
int min = Integer.MAX_VALUE;
for(int j = i ; j < arr.length;j++){
if(arr[j] < min){
min_index = j;
min = arr[j];
}
}
int temp = arr[i];
arr[i] = arr[min_index];
arr[min_index]=temp;
}
}
}
| true |
15cc1a116e3f747df4fae8afc0cb08554cf0b021 | Java | claudiogonclvs/ProjetoFinal | /ProjetoFinal/src/PC2/Main.java | UTF-8 | 6,917 | 3.125 | 3 | [] | no_license | package PC2;
import util.Consola;
public class Main {
private static Gestao g = new Gestao();
public static void main(String[] args) {
//Só se fazem sout's na main, todas as funcoes devem ser modelaveis!!!
int opcao, opcao2;
do {
opcao = menu();
switch (opcao) {
case 1:
do {
opcao2 = gerirVeiculos();
switch (opcao2) {
case 1:
break;
case 2:
break;
case 3:
break;
case 0:
}
} while (opcao2 != 0);
break;
case 2:
do {
opcao2 = gerirFuncionarios();
switch (opcao2) {
case 1:
break;
case 2:
break;
case 0:
}
} while (opcao2 != 0);
break;
case 3:
do {
opcao2 = gerirClientes();
switch (opcao2) {
case 1:
break;
case 2:
break;
case 0:
}
}while (opcao2 != 0);
break;
case 4:
do {
opcao2 = gerirManutencoes();
switch (opcao2) {
case 1:
break;
case 2:
break;
case 3:
break;
case 0:
}
} while (opcao2 != 0);
break;
case 5:
do {
opcao2 = gerirNegociacoes();
switch (opcao2) {
case 1:
break;
case 2:
break;
case 3:
break;
case 4:
break;
case 5:
break
case 0:
}
} while (opcao2 != 0);
break;
case 6:
do {
opcao2 = estatisticas();
switch (opcao2) {
case 1:
break;
case 2:
break;
case 3:
break;
case 4:
break;
case 0:
}
} while (opcao2 != 0);
break;
case 0:
System.out.println("FIM DO PROGRAMA");
}
Consola.sc.nextLine();
} while (opcao != 0);
}
private static int menu() {
int opcao;
System.out.println();
System.out.println("1 - Gerir Veículos");
System.out.println("2 - Gerir Funcionários");
System.out.println("3 - Gerir Clientes");
System.out.println("4 - Gerir Manutenções");
System.out.println("5 - Gerir Negociações");
System.out.println("6 - Estatísticas");
System.out.println("0 - Sair\n");
opcao = Consola.lerInt("Opção: ", 0, 6);
return opcao;
}
private static int gerirVeiculos() {
int opcao;
System.out.println("1 - Registar Veículos");
System.out.println("2 - Consultar por Matrícula");
System.out.println("3 - Alterar dados");
System.out.println("0 - Voltar ao menu anterior");
opcao = Consola.lerInt("Opção: ", 0, 3);
return opcao;
}
private static int gerirFuncionarios() {
int opcao;
System.out.println("1 - Registar");
System.out.println("2 - Consultar por numero");
System.out.println("0 - Voltar ao menu anterior");
opcao = Consola.lerInt("Opção: ", 0, 2);
return opcao;
}
private static int gerirClientes() {
int opcao;
System.out.println("1 - Registar novo Cliente");
System.out.println("2 - Consultar cliente por NIF");
System.out.println("0 - Voltar ao menu anterior");
opcao = Consola.lerInt("Opção: ", 0, 2);
return opcao;
}
private static int gerirCompras() {
int opcao;
System.out.println("1 - Registar");
System.out.println("2 - Consultar numero");
System.out.println("3 - Alterar estado");
System.out.println("4 - Alterar condicao");
System.out.println("5 - Registar negociação");
System.out.println("0 - Voltar ao menu anterior");
opcao = Consola.lerInt("Opção: ", 0, 5);
return opcao;
}
private static int gerirVendas() {
int opcao;
System.out.println("1 - Registar");
System.out.println("2 - Consultar numero");
System.out.println("3 - Alterar estado");
System.out.println("4 - Alterar condicao");
System.out.println("5 - Registar negociação");
System.out.println("0 - Voltar ao menu anterior");
opcao = Consola.lerInt("Opção: ", 0, 5);
return opcao;
}
private static int gerirManutencoes() {
int opcao;
System.out.println("1 - Registar");
System.out.println("2 - Consultar por matricula");
System.out.println("3 - Alterar estado");
System.out.println("0 - Voltar ao menu anterior");
opcao = Consola.lerInt("Opção: ", 0, 3);
return opcao;
}
private static int estatisticas() {
int opcao;
System.out.println("1 - Percentagem de serviços não concluídos com sucesso");
System.out.println("2 - Funcionário(s) com mais vendas realizadas");
System.out.println("3 - Preço total em vendas/compras, por ano");
System.out.println("4 - Número total de serviços registados por mês num determinado ano (ordenado de forma decrescente pelo total)");
System.out.println("0 - Voltar ao menu anterior");
opcao = Consola.lerInt("Opção: ", 0, 2);
return opcao;
}
}
| true |
1bdcf7c7992f520e399d44aa472c783fad71b6d2 | Java | leya191099/sportsShoppe | /SportsShoppe/src/main/java/com/cp/sports/Exception/OrderServiceException.java | UTF-8 | 613 | 1.976563 | 2 | [] | no_license | package com.cp.sports.Exception;
/************************************************************************************
* @author Leya Varghese
* Description It is a OrderServiceException exception class that handles the exception occurs at
* service level
* Version 1.0
* Created Date 22-MARCH-2021
************************************************************************************/
public class OrderServiceException extends RuntimeException {
public OrderServiceException(String message) {
super(message);
}
}
| true |
fbe52faca0391fbe0ce2716726895c4dee6db361 | Java | dj9308/Project | /Project_Dalhada/src/main/java/com/spring/dalhada/PathFinder.java | UTF-8 | 699 | 2.5 | 2 | [] | no_license | package com.spring.dalhada;
import java.io.IOException;
import java.io.Reader;
import java.util.Properties;
import org.apache.ibatis.io.Resources;
public class PathFinder {
private static PathFinder pathFinder = new PathFinder();
private PathFinder() {}
public static PathFinder getInstance() {
return pathFinder;
}
protected static String findImagePath(String what) {
String imageurl = null;
Properties properties = new Properties();
try {
Reader reader = Resources.getResourceAsReader("config/path.properties");
properties.load(reader);
imageurl = properties.getProperty("imageurl")+what;
}catch(IOException e) {
e.printStackTrace();
}
return imageurl;
}
}
| true |
bb09b36f1989b916e4f537e309e19c32b7e40512 | Java | panthers/s2si-backend | /src/main/java/com/cp/s2si/persistence/ProcessorRepository.java | UTF-8 | 268 | 1.65625 | 2 | [
"MIT"
] | permissive | package com.cp.s2si.persistence;
import java.util.UUID;
import org.springframework.data.repository.CrudRepository;
import com.cp.s2si.persistence.models.ProcessorMainModel;
public interface ProcessorRepository extends CrudRepository<ProcessorMainModel, UUID> {
}
| true |
66a3a1e6e8b70032b1cead2fb45551cd84a7df3e | Java | dennisvoliver/minecraft | /net/minecraft/client/render/VertexConsumer.java | UTF-8 | 5,203 | 2.25 | 2 | [] | no_license | package net.minecraft.client.render;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.minecraft.client.render.model.BakedQuad;
import net.minecraft.client.util.math.MatrixStack;
import net.minecraft.client.util.math.Vector3f;
import net.minecraft.client.util.math.Vector4f;
import net.minecraft.util.math.Matrix3f;
import net.minecraft.util.math.Matrix4f;
import net.minecraft.util.math.Vec3i;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.lwjgl.system.MemoryStack;
@Environment(EnvType.CLIENT)
public interface VertexConsumer {
Logger LOGGER = LogManager.getLogger();
VertexConsumer vertex(double x, double y, double z);
VertexConsumer color(int red, int green, int blue, int alpha);
VertexConsumer texture(float u, float v);
VertexConsumer overlay(int u, int v);
VertexConsumer light(int u, int v);
VertexConsumer normal(float x, float y, float z);
void next();
default void vertex(float x, float y, float z, float red, float green, float blue, float alpha, float u, float v, int overlay, int light, float normalX, float normalY, float normalZ) {
this.vertex((double)x, (double)y, (double)z);
this.color(red, green, blue, alpha);
this.texture(u, v);
this.overlay(overlay);
this.light(light);
this.normal(normalX, normalY, normalZ);
this.next();
}
default VertexConsumer color(float red, float green, float blue, float alpha) {
return this.color((int)(red * 255.0F), (int)(green * 255.0F), (int)(blue * 255.0F), (int)(alpha * 255.0F));
}
default VertexConsumer light(int uv) {
return this.light(uv & '\uffff', uv >> 16 & '\uffff');
}
default VertexConsumer overlay(int uv) {
return this.overlay(uv & '\uffff', uv >> 16 & '\uffff');
}
default void quad(MatrixStack.Entry matrixEntry, BakedQuad quad, float red, float green, float blue, int light, int overlay) {
this.quad(matrixEntry, quad, new float[]{1.0F, 1.0F, 1.0F, 1.0F}, red, green, blue, new int[]{light, light, light, light}, overlay, false);
}
default void quad(MatrixStack.Entry matrixEntry, BakedQuad quad, float[] brightnesses, float red, float green, float blue, int[] lights, int overlay, boolean useQuadColorData) {
int[] is = quad.getVertexData();
Vec3i vec3i = quad.getFace().getVector();
Vector3f vector3f = new Vector3f((float)vec3i.getX(), (float)vec3i.getY(), (float)vec3i.getZ());
Matrix4f matrix4f = matrixEntry.getModel();
vector3f.transform(matrixEntry.getNormal());
int i = true;
int j = is.length / 8;
MemoryStack memoryStack = MemoryStack.stackPush();
Throwable var17 = null;
try {
ByteBuffer byteBuffer = memoryStack.malloc(VertexFormats.POSITION_COLOR_TEXTURE_LIGHT_NORMAL.getVertexSize());
IntBuffer intBuffer = byteBuffer.asIntBuffer();
for(int k = 0; k < j; ++k) {
intBuffer.clear();
intBuffer.put(is, k * 8, 8);
float f = byteBuffer.getFloat(0);
float g = byteBuffer.getFloat(4);
float h = byteBuffer.getFloat(8);
float r;
float s;
float t;
float v;
float w;
if (useQuadColorData) {
float l = (float)(byteBuffer.get(12) & 255) / 255.0F;
v = (float)(byteBuffer.get(13) & 255) / 255.0F;
w = (float)(byteBuffer.get(14) & 255) / 255.0F;
r = l * brightnesses[k] * red;
s = v * brightnesses[k] * green;
t = w * brightnesses[k] * blue;
} else {
r = brightnesses[k] * red;
s = brightnesses[k] * green;
t = brightnesses[k] * blue;
}
int u = lights[k];
v = byteBuffer.getFloat(16);
w = byteBuffer.getFloat(20);
Vector4f vector4f = new Vector4f(f, g, h, 1.0F);
vector4f.transform(matrix4f);
this.vertex(vector4f.getX(), vector4f.getY(), vector4f.getZ(), r, s, t, 1.0F, v, w, overlay, u, vector3f.getX(), vector3f.getY(), vector3f.getZ());
}
} catch (Throwable var38) {
var17 = var38;
throw var38;
} finally {
if (memoryStack != null) {
if (var17 != null) {
try {
memoryStack.close();
} catch (Throwable var37) {
var17.addSuppressed(var37);
}
} else {
memoryStack.close();
}
}
}
}
default VertexConsumer vertex(Matrix4f matrix, float x, float y, float z) {
Vector4f vector4f = new Vector4f(x, y, z, 1.0F);
vector4f.transform(matrix);
return this.vertex((double)vector4f.getX(), (double)vector4f.getY(), (double)vector4f.getZ());
}
default VertexConsumer normal(Matrix3f matrix, float x, float y, float z) {
Vector3f vector3f = new Vector3f(x, y, z);
vector3f.transform(matrix);
return this.normal(vector3f.getX(), vector3f.getY(), vector3f.getZ());
}
}
| true |
ba76907e4ec286e48f23a4c31e7dcaf1d031b834 | Java | kotdark/clone_phone_booster | /QuickestPhoneBooster/app/src/main/java/utility/quickest/phonebooster/fragment/PowerSavingFinishFragment_ViewBinding.java | UTF-8 | 1,927 | 1.859375 | 2 | [] | no_license | package utility.quickest.phonebooster.fragment;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import butterknife.Unbinder;
import butterknife.internal.Utils;
import utility.quickest.phonebooster.view.CustomCircularProgress1;
import utility.quickest.phonebooster.R;
public class PowerSavingFinishFragment_ViewBinding<T extends PowerSavingFinishFragment> implements Unbinder {
protected T f13433b;
private View f13434c;
private View f13435d;
public PowerSavingFinishFragment_ViewBinding(T t, View view) {
this.f13433b = t;
t.mActionBarTitle = (TextView) Utils.findRequiredViewAsType(view, R.id.action_bar_title, "field 'mActionBarTitle'", TextView.class);
t.mActionBarTitle1 = (TextView) Utils.findRequiredViewAsType(view, R.id.action_bar_title1, "field 'mActionBarTitle1'", TextView.class);
t.mTagContainer = (ViewGroup) Utils.findRequiredViewAsType(view, R.id.tag_container, "field 'mTagContainer'", ViewGroup.class);
t.mAdContainerContainer = (ViewGroup) Utils.findRequiredViewAsType(view, R.id.ad_container_container, "field 'mAdContainerContainer'", ViewGroup.class);
t.mAdContainer = (ViewGroup) Utils.findRequiredViewAsType(view, R.id.ad_container, "field 'mAdContainer'", ViewGroup.class);
t.mFinishTag = (TextView) Utils.findRequiredViewAsType(view, R.id.finish_tag, "field 'mFinishTag'", TextView.class);
t.mProgress = (CustomCircularProgress1) Utils.findRequiredViewAsType(view, R.id.progress, "field 'mProgress'", CustomCircularProgress1.class);
View a = Utils.findRequiredView(view, R.id.action_bar_back_icon, "method 'doBack'");
this.f13434c = a;
a.setOnClickListener(new fr(this, t));
a = Utils.findRequiredView(view, R.id.action_bar_back_icon1, "method 'doBack'");
this.f13435d = a;
a.setOnClickListener(new fs(this, t));
}
}
| true |
7b19a617b232e2ecd3804c61e6abddc50f451d03 | Java | alysongustavo/app-almoxarifado | /src/main/java/br/gov/prefeitura/almoxarifado/domain/TipoEmbalagem.java | UTF-8 | 272 | 2.453125 | 2 | [] | no_license | package br.gov.prefeitura.almoxarifado.domain;
public enum TipoEmbalagem {
CAIXA("Caixa"),
SACOLA("Sacola");
private String descricao;
TipoEmbalagem(String descricao){
this.descricao = descricao;
}
public String getDescricao() {
return descricao;
}
}
| true |
88eae25cc04ef05d34843d0d589dee3c9f56f08b | Java | GreenTo/KTV | /src/client_function/EditBorder_confirm.java | WINDOWS-1252 | 1,131 | 2.171875 | 2 | [] | no_license | package client_function;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import client.EditBorder;
import util.Client_tips;
import util.JdbcUtils;
public class EditBorder_confirm implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("dddddddddddddddddddd");
String s1 = EditBorder.telephone.getText().trim();
String s2 = EditBorder.idCard.getText().trim();
String s3 = EditBorder.userAddress.getText().trim();
Connection con = null;
Statement st = null;
ResultSet rs = null;
try {
con = JdbcUtils.getConnection();
st = con.createStatement();
System.out.println("sssssssssssssssssssss");
String sql = "update users set tele = '"+ s1 +"',Id = '"+ s2 +"',address = '"+ s3 +"' where userName = '"+ EditBorder.name +"'";
st.executeUpdate(sql);
new Client_tips(EditBorder.frame, "༭ɹ");
}catch(SQLException s) {
s.printStackTrace();
}finally {
JdbcUtils.release(con, st, rs);
}
}
}
| true |
17da304163485a43ec546593c0b559795bc14949 | Java | jamieHH/LwjglEngine | /src/engine/entities/Light.java | UTF-8 | 310 | 2.53125 | 3 | [] | no_license | package engine.entities;
import org.lwjgl.util.vector.Vector3f;
public class Light extends Point {
private Vector3f color;
private float intensity;
public Light(Vector3f color, float intensity) {
this.color = color;
this.intensity = intensity;
}
public Vector3f getColor() {
return color;
}
}
| true |
934b32f3c208eaf9a57daea51110669c88540db8 | Java | alalse/BlockBlitz | /app/src/main/java/com/albin/blockblitz/gameobjects/GameOverMenu.java | UTF-8 | 3,159 | 2.390625 | 2 | [] | no_license | package com.albin.blockblitz.gameobjects;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import com.albin.blockblitz.R;
import com.albin.blockblitz.enums.GameAction;
import com.albin.blockblitz.enums.Statistic;
import com.albin.blockblitz.framework.FirestoreHandler;
import com.albin.blockblitz.framework.ResourceLoader;
public class GameOverMenu extends GameMenuObject {
private final RectF gameOverRect;
private final RectF restart;
private final RectF returnToMainMenu;
private int score;
public GameOverMenu() {
super();
textPaint.setColor(Color.WHITE);
textPaint.setTextAlign(Paint.Align.CENTER);
textPaint.setTextSize(70);
gameOverRect = new RectF(0, 0, 0, 0);
restart = new RectF(0, 0, 0, 0);
returnToMainMenu = new RectF(0, 0, 0, 0);
}
@Override
public void update() {}
@Override
public void draw(Canvas canvas) {
super.draw(canvas);
p.setColor(Color.GRAY);
p.setAlpha(225);
int margin = x;
int textMargin = (x/8) * 7;
int top = y + margin;
textPaint.setTextSize((margin / 10) * 7); //Random size calculation that according to my tests fits well and scales with screens
gameOverRect.set(x + margin, top, x + width - margin, top + x * 3);
canvas.drawRoundRect(gameOverRect, 10, 10, p);
canvas.drawText(ResourceLoader.getString(R.string.game_over), gameOverRect.centerX(), top + textMargin, textPaint);
canvas.drawText(ResourceLoader.getString(R.string.game_over_score, String.valueOf(score)), gameOverRect.centerX(), top + textMargin * 2, textPaint);
String highscore = String.valueOf(FirestoreHandler.getStatistic(Statistic.HIGHSCORE));
canvas.drawText(ResourceLoader.getString(R.string.game_over_highscore, highscore), gameOverRect.centerX(), top + textMargin * 3, textPaint);
int smallMargin = x/12;
top += x * 3 + margin;
restart.set(x + margin, top + smallMargin, x + width - margin, top + x * 2 - smallMargin);
canvas.drawRoundRect(restart, 10, 10, p);
canvas.drawText(ResourceLoader.getString(R.string.restart_game), restart.centerX(), restart.centerY() + margin/4, textPaint);
top += x + margin;
returnToMainMenu.set(x + margin, top + smallMargin, x + width - margin, top + x * 2 - smallMargin);
canvas.drawRoundRect(returnToMainMenu, 10, 10, p);
canvas.drawText(ResourceLoader.getString(R.string.return_to_main_menu), returnToMainMenu.centerX(), returnToMainMenu.centerY() + margin/4, textPaint);
}
@Override
public GameAction onTouchDownEvent(int clickedX, int clickedY) {
if (contains(clickedX, clickedY)) {
if (returnToMainMenu.contains(clickedX, clickedY)) {
return GameAction.BACK_TO_MAIN_MENU;
}
else if (restart.contains(clickedX, clickedY)) {
return GameAction.RESTART;
}
}
return null;
}
public void setScore(int score) { this.score = score; }
} | true |
239a00e8ae69f1f0c87a76bcc060d604da2257ed | Java | tongluyang/leetcode | /1227.飞机座位分配概率.java | UTF-8 | 1,224 | 3.5625 | 4 | [] | no_license | /*
* @lc app=leetcode.cn id=1227 lang=java
*
* [1227] 飞机座位分配概率
*
* https://leetcode-cn.com/problems/airplane-seat-assignment-probability/description/
*
* algorithms
* Medium (65.14%)
* Likes: 59
* Dislikes: 0
* Total Accepted: 6.5K
* Total Submissions: 9.9K
* Testcase Example: '1'
*
* 有 n 位乘客即将登机,飞机正好有 n 个座位。第一位乘客的票丢了,他随便选了一个座位坐下。
*
* 剩下的乘客将会:
*
*
*
* 如果他们自己的座位还空着,就坐到自己的座位上,
*
* 当他们自己的座位被占用时,随机选择其他座位
*
*
* 第 n 位乘客坐在自己的座位上的概率是多少?
*
*
*
* 示例 1:
*
*
* 输入:n = 1
* 输出:1.00000
* 解释:第一个人只会坐在自己的位置上。
*
* 示例 2:
*
*
* 输入: n = 2
* 输出: 0.50000
* 解释:在第一个人选好座位坐下后,第二个人坐在自己的座位上的概率是 0.5。
*
*
*
*
* 提示:
*
*
* 1 <= n <= 10^5
*
*
*/
// @lc code=start
class Solution {
public double nthPersonGetsNthSeat(int n) {
return n == 1 ? 1.0 : 0.5;
}
}
// @lc code=end
| true |
280c0a0797ffb8d0a626f12fba1be64c3ca665ee | Java | pablo09/AnotherRepository | /EJB_statefulbean-ejb/src/main/java/ejb/Cart.java | UTF-8 | 1,330 | 2.296875 | 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 ejb;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.ejb.Stateful;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceContextType;
/**
*
* @author Pawel
*/
@Stateful
public class Cart implements CartLocal {
// Add business logic below. (Right-click in editor and choose
// "Insert Code > Add Business Method")
// @PersistenceContext(unitName = "pu", type = PersistenceContextType.EXTENDED)
// private EntityManager em;
private List<Product> products;
@PostConstruct
private void initBean() {
products = new ArrayList<>();
}
@Override
public void addProductToCart(Product p) {
products.add(p);
}
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void checkout() {
for(Product p : products) {
// em.persist(p);
}
products.clear();
}
}
| true |
4e32b0c65258335fe95b4bb4566f39c9f79a8385 | Java | marcelvaldhano/tutorial-apap | /traveloke/src/main/java/apap/tutorial/traveloke/repository/RoleDb.java | UTF-8 | 395 | 2 | 2 | [] | no_license | package apap.tutorial.traveloke.repository;
import apap.tutorial.traveloke.model.HotelModel;
import apap.tutorial.traveloke.model.RoleModel;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface RoleDb extends JpaRepository<RoleModel,Long> {
public List<RoleModel> findAll();
}
| true |
4a090b77878aad9156dea78d7c7459efccb95ee1 | Java | kevin82008/KCool-RSF | /drive-msg-base/src/main/java/com/drive/cool/message/event/IEventError.java | UTF-8 | 361 | 1.960938 | 2 | [
"Apache-2.0"
] | permissive | /**
* kevin 2015年9月27日
*/
package com.drive.cool.message.event;
/**
* @author kevin
*
*/
public interface IEventError {
/**
* 请求超时
*/
public static final int TIMEOUT = -900001;
/**
* 连接超时
*/
public static final int CONNECT_ERROR = -900002;
/**
* 无可用通道
*/
public static final int NO_CHANNEL = -900003;
}
| true |
6e0267b7e78b00378efa7db4d65fc6e2edd4811a | Java | radem359/MasterRadBackend | /src/main/java/com/radosav/master/rad/dto/NationalityDB.java | UTF-8 | 1,268 | 2.4375 | 2 | [] | no_license | package com.radosav.master.rad.dto;
import java.io.Serializable;
import java.util.LinkedList;
import java.util.List;
import com.radosav.master.rad.model.Author;
import com.radosav.master.rad.model.Nationality;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Getter;
import lombok.Setter;
import lombok.NoArgsConstructor;
@NoArgsConstructor
@Setter
@Getter
@JsonInclude(value = Include.NON_NULL)
public class NationalityDB implements Serializable {
private static final long serialVersionUID = 8217078635779576165L;
private Integer id;
private String nationalityName;
private List<AuthorDB> authors;
public NationalityDB(Nationality ent) {
this(ent, false);
}
public NationalityDB(Nationality ent, boolean includeFKs) {
this.id = ent.getId();
this.nationalityName = ent.getNationalityName();
if(includeFKs) {
authors = new LinkedList<AuthorDB>();
for(Author a: ent.getAuthors()) {
AuthorDB author = new AuthorDB(a);
if(author != null) {
authors.add(author);
}
}
}
}
@Override
public String toString() {
return "NationalityDB [id=" + id + ", nationalityName=" + nationalityName + ", authors=" + authors + "]";
}
}
| true |
713585fde779456e668e0ab4c47356eadf2a842c | Java | Organization-16/Group-16-repository | /OurApp/BotanistCompanionApp/src/uk/ac/aber/dcs/cs221/group16/util/PreventScreenRotation.java | UTF-8 | 1,668 | 2.640625 | 3 | [] | no_license | package uk.ac.aber.dcs.cs221.group16.util;
import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.util.DisplayMetrics;
import android.view.WindowManager;
/**
* @author http://stackoverflow.com/questions/3723823/i-want-my-android-application-to-be-only-run-in-portrait-mode
* @author Steven(Sta17)
*
* from site, modified by me slightly
*
*/
public class PreventScreenRotation {
public Activity acti;
public PreventScreenRotation(Activity acti){
this.acti = acti;
initActivityScreenOrientPortrait();
}
private void initActivityScreenOrientPortrait() {
// Avoid screen rotations (use the manifests android:screenOrientation
// setting)
// Set this to nosensor or potrait
// Set window fullscreen
acti.getWindow().setFlags(
WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
DisplayMetrics metrics = new DisplayMetrics();
acti.getWindowManager().getDefaultDisplay()
.getMetrics(metrics);
// Test if it is VISUAL in portrait mode by simply checking it's size
boolean bIsVisualPortrait = (metrics.heightPixels >= metrics.widthPixels);
if (!bIsVisualPortrait) {
// Swap the orientation to match the VISUAL portrait mode
if (acti.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
acti.setRequestedOrientation(
ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
} else {
acti.setRequestedOrientation(
ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
} else {
acti.setRequestedOrientation(
ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);
}
}
}
| true |
fdf527bf4acbd81ff84fd8dd4394309db3734351 | Java | unloserv/platform | /platform-common/src/main/java/com/sds/vo/RiskTypeCountVo.java | UTF-8 | 166 | 1.539063 | 2 | [] | no_license | package com.sds.vo;
import lombok.Data;
@Data
public class RiskTypeCountVo {
private String typeName;
private Integer type;
private Integer count;
}
| true |
16ee89bc2725b0a3b1159dadbcb464e4cd262537 | Java | RoboCafaz/RPG-Engine | /RPG_Common/src/com/robocafaz/rpg/common/constants/skills/SkillTree.java | UTF-8 | 443 | 2.296875 | 2 | [] | no_license | package com.robocafaz.rpg.common.constants.skills;
import com.robocafaz.rpg.common.constants.Constant;
public class SkillTree extends Constant
{
private final SkillRequirement[] skillRequirements;
protected SkillTree(String id, SkillRequirement... skillRequirements)
{
super(id);
this.skillRequirements = skillRequirements;
}
public SkillRequirement[] getSkillRequirements()
{
return this.skillRequirements;
}
}
| true |
73d74a926b200889a757f33147b37a6a5c960f07 | Java | backpaper0/hello-ui-api-docker-sample | /hello-api/src/main/java/com/example/helloapi/HelloController.java | UTF-8 | 489 | 2.21875 | 2 | [
"MIT"
] | permissive | package com.example.helloapi;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/hello")
public class HelloController {
@PostMapping
public String sayHello(@RequestParam final String name) {
return String.format("Hello, %s!", name);
}
}
| true |
45f1c11b0f0e68516b535b9cf470382a91b1df26 | Java | ronglang/qidongmes | /src/main/java/com/css/business/web/subsyscraft/craManage/service/CraBomRelaSeqManageService.java | UTF-8 | 680 | 1.835938 | 2 | [] | no_license | package com.css.business.web.subsyscraft.craManage.service;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.css.business.web.subsyscraft.bean.CraBomRelaSeq;
import com.css.business.web.subsyscraft.craManage.dao.CraBomRelaSeqManageDAO;
import com.css.common.web.syscommon.service.impl.BaseEntityManageImpl;
@Service("craBomRelaSeqService")
public class CraBomRelaSeqManageService extends BaseEntityManageImpl<CraBomRelaSeq,CraBomRelaSeqManageDAO> {
@Resource(name="craBomRelaSeqManageDAO")
//@Autowired
private CraBomRelaSeqManageDAO dao;
@Override
public CraBomRelaSeqManageDAO getEntityDaoInf() {
return dao;
}
}
| true |
fb3d193d8527db19ddb1f7f572b7fb52444e4a2a | Java | yu199195/jsb | /src/main/java/com/taobao/api/domain/OrderItemswlbwmsstockinorderconfirm.java | UTF-8 | 1,586 | 1.75 | 2 | [] | no_license | package com.taobao.api.domain;
import com.taobao.api.TaobaoObject;
import com.taobao.api.internal.mapping.ApiField;
import com.taobao.api.internal.mapping.ApiListField;
import java.util.List;
public class OrderItemswlbwmsstockinorderconfirm
extends TaobaoObject {
private static final long serialVersionUID = 8569682932451441133L;
@ApiField("is_completed")
private Boolean isCompleted;
@ApiField("item_code")
private String itemCode;
@ApiField("item_id")
private String itemId;
@ApiListField("items")
@ApiField("itemswlbwmsstockinorderconfirmwl")
private List<Itemswlbwmsstockinorderconfirmwl> items;
@ApiField("order_item_id")
private String orderItemId;
public Boolean getIsCompleted() {
return this.isCompleted;
}
public void setIsCompleted(Boolean isCompleted) {
this.isCompleted = isCompleted;
}
public String getItemCode() {
return this.itemCode;
}
public void setItemCode(String itemCode) {
this.itemCode = itemCode;
}
public String getItemId() {
return this.itemId;
}
public void setItemId(String itemId) {
this.itemId = itemId;
}
public List<Itemswlbwmsstockinorderconfirmwl> getItems() {
return this.items;
}
public void setItems(List<Itemswlbwmsstockinorderconfirmwl> items) {
this.items = items;
}
public String getOrderItemId() {
return this.orderItemId;
}
public void setOrderItemId(String orderItemId) {
this.orderItemId = orderItemId;
}
}
| true |
fa658895edf97bbd6ae91056534c4dcc6f7e2393 | Java | puha4/retrofittest | /app/src/main/java/com/pollux/retrofitdemo/RetrofitDemo.java | UTF-8 | 240 | 1.515625 | 2 | [] | no_license | package com.pollux.retrofitdemo;
import android.app.Application;
/**
* Created by SreeKumar on 13/10/15
*/
public class RetrofitDemo extends Application {
@Override
public void onCreate() {
super.onCreate();
}
}
| true |
a025daeb84913d39cf8d83e6a94f6cdc018b3b22 | Java | Altraman/Review | /src/observer/Observer.java | UTF-8 | 197 | 2.328125 | 2 | [] | no_license | package observer;
/**
* Created by HuQiang on 2018/1/9.
*/
public interface Observer {
String getName();
void setName(String name);
void help();
void beAttacked(Ally ally);
}
| true |
29bf7d3819f38256bc41e37eb7d37a58bcd3a9db | Java | MrYoiYoi/test | /test_music/src/main/java/global/sesoc/music/controller/ShoppingController.java | UTF-8 | 3,001 | 2.078125 | 2 | [] | no_license | package global.sesoc.music.controller;
import java.util.List;
import javax.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import global.sesoc.music.service.ShoppingService;
import global.sesoc.music.service.UserService;
import global.sesoc.music.vo.MusicVO;
import global.sesoc.music.vo.SalesVO;
import global.sesoc.music.vo.UserVO;
/**
* 쇼핑 관련 콘트롤러
*/
@Controller
public class ShoppingController {
private static final Logger logger = LoggerFactory.getLogger(ShoppingController.class);
@Autowired
ShoppingService service;
//음반 리스트
@RequestMapping("/musiclist")
public String bookList(Model model) {
List<MusicVO> list = service.musicList();
// System.out.println(list);
model.addAttribute("list", list);
return "music/musiclist";
}
//음반 상세정보
@RequestMapping(value = "/detailmusic")
public String detailmusic(int cdnum, Model model,HttpSession session) {
String userid = (String)session.getAttribute("loginId");
MusicVO music = service.musicDetail(cdnum);
model.addAttribute("music", music);
return "music/musicdetail";
}
/*
* @RequestMapping("/detailboard")
public String detailboard(String userid, int cdnum, Model model, HttpSession session) {
MusicVO music = dao.selectOne(cdnum);
model.addAttribute("music", music);
System.out.println(music);
return "detailBoard";
}
@RequestMapping(value="/detailboard", method=RequestMethod.POST)
public String detailboard(String userid, SalesVO sales, HttpSession session) {
int result = dao.insert(sales);
logger.info("등록 여부 : {}", result);
return "redirect:buylist?userid=" + userid;
}
*/
@RequestMapping("/orderlist")
public String orderList(SalesVO orderlist,Model model, HttpSession session,
int cdnum
) {
String userid = (String)session.getAttribute("loginId");
orderlist.setUserid(userid);
service.orderlist(orderlist);
System.out.println(orderlist);
return "redirect:musiclist";
}
@RequestMapping("orderitemList")
public String orderitemList(String userid,Model model, HttpSession session) {
List<SalesVO> list = service.orderitemList(userid);
model.addAttribute("list", list);
return "music/orderlist";
}
@RequestMapping("/rank")
public String salesRank(Model model) {
List<SalesVO> sales = service.salesRank();
model.addAttribute("sales", sales);
System.out.println(sales);
return "music/rank";
}
}
| true |
7a9f504b69015c3404746b6c7cf4a62fe411cdb3 | Java | jurek512/wordfreq | /src/de/ziminski/words/lieferant/I_WoerterLieferant.java | ISO-8859-1 | 937 | 2.375 | 2 | [] | no_license | package de.ziminski.words.lieferant;
import java.util.TreeSet;
import de.words.guikomponenten.listen.IWortliste;
public interface I_WoerterLieferant {
public abstract String getText();
/**
* Liest Die Datei mit den bekannten Wrtern
*
* @return TreeSet bekannte Wrter
*/
public abstract TreeSet<String> getKnownWords();
/**
* Liest die Datei mit den Wrtern die ausgelassen werden sollen
*
* @return TreeSet die Wrter
*/
public abstract TreeSet<String> getOmitedWords();
/**
* Liest die Datei mit den Wrtern die ausgelassen werden sollen
*
* @return TreeSet die Wrter
*/
public abstract TreeSet<String> getNotWellKnownWords();
public abstract void saveKnownWords(IWortliste wl);
public abstract void saveUnimportantWords(IWortliste wl);
public abstract void saveNotWellKnownWords(IWortliste wl);
public void setStarPoint(String start);
public void setEndPoint(String end);
} | true |
f36c89f21c92c0585ea51ca133d8b88796fb6c69 | Java | ShizeXu/LeetCode | /2013_2017/Additional/beta03_theKthBasedOnQsort.java | UTF-8 | 793 | 3.46875 | 3 | [] | no_license | package Additional;
import java.util.Random;
public class beta03_theKthBasedOnQsort {
public int rank(int[] num, int l, int r, int k) {
if (l > r)
return -1;
int rand = l + new Random().nextInt(r - l + 1);
swap(num, l, rand);
int begin = l + 1, end = r;
while (begin <= end) {
while (begin <= end && num[begin] <= num[l]) {
begin++;
}
while (begin <= end && num[l] < num[end]) {
end--;
}
if (begin > end)
break;
swap(num, begin++, end--);
}
swap(num, l, end);
// decide which side to search
if (end == k) // found
return num[end];
if (end > k) // left
return rank(num, l, end - 1, k);
return rank(num, end + 1, r, k); // right
}
void swap(int[] num, int x, int y) {
int tmp = num[x];
num[x] = num[y];
num[y] = tmp;
}
}
| true |
eafa419419cdda75e2e8a7a68bdc9593694b1a46 | Java | mariamiawad/JavaExercises | /MyJavaFX/src/chapter16/Exercise_16_08.java | UTF-8 | 4,287 | 3.0625 | 3 | [] | no_license | package chapter16;
import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;
public class Exercise_16_08 extends Application {
public Exercise_16_08() {
}
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception {
Label intersectionLabel = new Label("Two circle intersect? No");
Label infoLabel1 = new Label("Enter circle 1 info");
Label center1XLabel = new Label("Center X");
TextField center1XField = new TextField();
Label center1YLabel = new Label("Center Y");
TextField center1YField = new TextField();
Label radius1Label = new Label("Radius");
TextField radius1Field = new TextField();
Label infoLabel2 = new Label("Enter circle 2 info");
Label center2XLabel = new Label("Center X");
TextField center2XField = new TextField();
Label center2YLabel = new Label("Center Y");
TextField center2YField = new TextField();
Label radius2Label = new Label("Radius");
TextField radius2Field = new TextField();
Button redrawButton = new Button("Redraw circle");
GridPane pane1 = new GridPane();
pane1.add(infoLabel1, 0, 0);
pane1.add(center1XLabel, 0, 1);
pane1.add(center1XField, 1, 1);
pane1.add(center1YLabel, 0, 2);
pane1.add(center1YField, 1, 2);
pane1.add(radius1Label, 0, 3);
pane1.add(radius1Field, 1, 3);
GridPane pane2 = new GridPane();
pane2.add(infoLabel2, 0, 0);
pane2.add(center2XLabel, 0, 1);
pane2.add(center2XField, 1, 1);
pane2.add(center2YLabel, 0, 2);
pane2.add(center2YField, 1, 2);
pane2.add(radius2Label, 0, 3);
pane2.add(radius2Field, 1, 3);
Circle circle1 = new Circle(10);
Circle circle2 = new Circle(10);
circle1.setFill(Color.WHITE);
circle2.setFill(Color.WHITE);
circle1.setStroke(Color.BLACK);
circle2.setStroke(Color.BLACK);
HBox vBox = new HBox(400);
vBox.getChildren().add(circle1);
vBox.getChildren().add(circle2);
StackPane pane = new StackPane();
HBox hbox2 = new HBox(30);
hbox2.getChildren().add(pane1);
hbox2.getChildren().add(pane2);
StackPane.setAlignment(circle1, Pos.TOP_LEFT);
StackPane.setAlignment(intersectionLabel, Pos.TOP_CENTER);
StackPane.setAlignment(circle2, Pos.TOP_RIGHT);
BorderPane.setAlignment(hbox2, Pos.CENTER);
BorderPane.setAlignment(redrawButton, Pos.BOTTOM_CENTER);
pane.getChildren().addAll(intersectionLabel, circle1, circle2);
BorderPane pane3 = new BorderPane();
pane3.setTop(pane);
pane3.setCenter(hbox2);
pane3.setBottom(redrawButton);
Scene scene = new Scene(pane3, 500, 500);
primaryStage.setScene(scene);
primaryStage.setResizable(false);
primaryStage.show();
redrawButton.setOnAction(e -> {
if (!radius1Field.getText().isEmpty() && radius1Field.getText() != null) {
circle1.setRadius(Double.parseDouble(radius1Field.getText()));
}
if (!center1XField.getText().isEmpty() && center1XField.getText() != null) {
circle1.setTranslateX(Double.parseDouble(center1XField.getText()));
}
if (!center1YField.getText().isEmpty() && center1YField.getText() != null) {
circle1.setTranslateY(Double.parseDouble(center1YField.getText()));
}
if (!radius2Field.getText().isEmpty() && radius2Field.getText() != null) {
circle2.setRadius(Double.parseDouble(radius2Field.getText()));
}
if (!center2XField.getText().isEmpty() && center2XField.getText() != null) {
circle2.setTranslateX(Double.parseDouble(center2XField.getText()));
}
if (!center2YField.getText().isEmpty() && center2YField.getText() != null) {
circle2.setTranslateY(Double.parseDouble(center2YField.getText()));
}
if (isIntersect(circle1, circle2)) {
intersectionLabel.setText("Two circle intersect? Yes");
}
});
}
public boolean isIntersect(Circle circle1, Circle circle2) {
return circle1.getBoundsInParent().intersects(circle2.getBoundsInParent());
}
}
| true |
c68b93123349a6354388137b6a6ec77301569de7 | Java | raulastu/Algorithm-Competitions-EWS | /TCProject/src/judges/UVA/Equidivisions.java | UTF-8 | 1,727 | 2.75 | 3 | [] | no_license | package judges.UVA;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Scanner;
class Equidivisions {
public static void main(String[] args) throws Exception {
// BufferedReader in = new BufferedReader(new InputStreamReader(new BufferedInputStream(System.in)));
Scanner in = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
while (true) {
int n = Integer.parseInt(in.nextLine().trim());
if(n==0)
break;
grid=new int [n][n];
memo= new boolean[n][n];
for (int i = 1; i < n; i++) {
String[] p = in.nextLine().split(" ");
for (int j = 0; j < p.length; j+=2) {
int a = Integer.parseInt(p[j])-1;
int b = Integer.parseInt(p[j+1])-1;
grid[a][b]=i;
}
}
// print(grid);
counter = new int[n];
String res = "good";
cx:
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[i].length; j++) {
if(memo[i][j])
continue;
if(counter[grid[i][j]]>0){
res="wrong";
break cx;
}else{
go(i,j,grid[i][j]);
}
}
}
System.out.println(res);
}
in.close();
out.close();
}
static int []counter;
static boolean memo [][];
static int [][] grid;
static int[] di={0,0,1,-1};
static int[] dj={-1,1,0,0};
static void go(int x, int y, int k){
memo[x][y]=true;
counter[k]++;
for (int i = 0; i < di.length; i++) {
int X = di[i]+x;
int Y = dj[i]+y;
if(X>=0 && Y>=0 && X<grid.length && Y<grid[X].length && grid[X][Y]==k && !memo[X][Y]){
go(X,Y,k);
}
}
}
static void print(Object... ob){
System.out.println(Arrays.deepToString(ob));
}
}
| true |
16f44c516fd8c0b0804d814475835a66b39f045a | Java | csucla2015/BYR-master | /src/com/BeatYourRecord/LeaderBoard.java | UTF-8 | 15,405 | 2.015625 | 2 | [
"Apache-2.0"
] | permissive | package com.BeatYourRecord;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
public class LeaderBoard extends Activity {
List<Cookie> cookies;
String result="";
String [] ids = new String[20];
String [] ids1 = new String[20];
String [] ids2 = new String[20];
String [] ids3 = new String[20];
Button [] buttons = new Button[50];
String login="";
String output11="";
String store="";
int count = 0;
int count1 = 0;
int count2 = 0;
int count3 = 0;
ImageButton imageItem;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.v("hre","hre");
setContentView(R.layout.leader_test);
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
SharedPreferences pref = getApplicationContext().getSharedPreferences("TourPref", 0); // 0 - for private mode
Editor editor = pref.edit();
//Log.v("dsadsa","http://ec2-54-212-221-3.us-west-2.compute.amazonaws.com/tournaments/"+ids[forfor1]+".json");
// editor.putString("log", "yes");
editor.commit();
String print = pref.getString("tour",null);
HttpGet httpget = new HttpGet(print);
// Depends on your web service
httpget.setHeader("Content-type", "application/json");
httpget.setHeader("Accept","application/json");
InputStream inputStream = null;
String someresult = null;
try {
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
someresult = sb.toString();
} catch (Exception e) {
// Oops
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
Log.v("test1",someresult);
try {
JSONObject jobject1 = new JSONObject(someresult);
JSONObject jobject2 = jobject1.getJSONObject("data");
JSONObject jobject3 = jobject2.getJSONObject("tournament");
JSONArray jarray = jobject3.getJSONArray("top_10");
Log.v("here",String.valueOf(jarray.length()));
for (int i=0; i < jarray.length(); i++)
{
try {
Log.v("ere","ere");
JSONArray oneObject = jarray.getJSONArray(i);
// JSONObject oneObject = oneObject1.getJSONObject(i);
// Pulling items from the array
Log.v("rerere","rere");
Log.v("oneObjectsItem", oneObject.toString());
String[] s = oneObject.toString().split(",");
Log.v("finally",s[0].substring(1,s[0].length()));
Log.v("finally",s[1].substring(1,s[1].length()-1));
Log.v("finally",s[2].substring(1,s[2].length()-2));
ids1[i] = s[1].substring(1,s[1].length()-1);
ids[i] = s[0].substring(1,s[0].length());
ids2[i] = s[2].substring(1,s[2].length()-2);
if (s[3].length() > 20)
ids3[i] = s[3].substring(1, 6) + s[3].substring(7, 8) + s[3].substring(9, 25) + s[3].substring(26, s[3].length() - 2);
else
ids3[i] = s[3].substring(1, s[3].length() - 2);
count++;
} catch (JSONException e) {
//Log.v("rerere","rere");
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for(int ii=0;ii<count;ii++)
{
Log.v("re"+String.valueOf(ii),ids[ii]);
}
for(int ii=0;ii<count;ii++)
{
Log.v("re1"+String.valueOf(ii),ids1[ii]);
}
for(int ii=0;ii<count;ii++)
{
Log.v("re2"+String.valueOf(ii),ids2[ii]);
}
for(int ii=0;ii<count;ii++)
{
Log.v("re3"+String.valueOf(ii),ids3[ii]);
}
/*
for(int i=0;i<ids1.length;i++)
{
System.out.print(ids1[i]);
}
for(int i=0;i<ids2.length;i++)
{
System.out.print(ids2[i]);
}*/
String wholetext = ids1 [0];
SharedPreferences pref17 = LeaderBoard.this.getSharedPreferences("TourPref", 0); // 0 - for private mode
Editor editor17 = pref17.edit();
String link = pref17.getString("tournamentname",null);
TextView textview02 = (TextView) findViewById(R.id.textView1);
textview02.setText(link);
TextView textview4 = (TextView) findViewById(R.id.textView4);
textview4.setTextSize(TypedValue.COMPLEX_UNIT_SP,25);
textview4.setText(wholetext);
TextView widget37 = (TextView) findViewById(R.id.widget37);
widget37.setTextSize(TypedValue.COMPLEX_UNIT_SP,25);
widget37.setText(ids[0]);
Log.v("this", ids3[0]);
ImageView imageview2 = (ImageView) findViewById(R.id.imageView2);
imageview2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startActivity(new Intent(Intent.ACTION_VIEW,Uri.parse(ids3[0])));
}
});
wholetext = ids1 [1];
TextView textview5 = (TextView) findViewById(R.id.textView5);
textview5.setTextSize(TypedValue.COMPLEX_UNIT_SP,25);
textview5.setText(wholetext);
TextView widget38 = (TextView) findViewById(R.id.widget38);
widget38.setTextSize(TypedValue.COMPLEX_UNIT_SP,25);
widget38.setText(ids[1]);
ImageView imageview3 = (ImageView) findViewById(R.id.imageView3);
imageview3.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startActivity(new Intent(Intent.ACTION_VIEW,Uri.parse(ids3[1])));
}
});
wholetext = ids1 [2];
TextView textview6 = (TextView) findViewById(R.id.textView6);
textview6.setTextSize(TypedValue.COMPLEX_UNIT_SP,25);
textview6.setText(wholetext);
TextView widget39 = (TextView) findViewById(R.id.widget39);
widget39.setTextSize(TypedValue.COMPLEX_UNIT_SP,25);
widget39.setText(ids[2]);
ImageView imageview4 = (ImageView) findViewById(R.id.imageView4);
imageview4.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startActivity(new Intent(Intent.ACTION_VIEW,Uri.parse(ids3[2])));
}
});
TextView widget50 = (TextView) findViewById(R.id.widget50);
widget50.setTextSize(TypedValue.COMPLEX_UNIT_SP,15);
widget50.setText(ids1 [3]);
TextView textView9 = (TextView) findViewById(R.id.textView9);
textView9.setTextSize(TypedValue.COMPLEX_UNIT_SP,15);
textView9.setText(ids [3]);
ImageView imageview8 = (ImageView) findViewById(R.id.imageView8);
imageview8.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startActivity(new Intent(Intent.ACTION_VIEW,Uri.parse(ids3[3])));
}
});
TextView widget74 = (TextView) findViewById(R.id.widget74);
widget74.setTextSize(TypedValue.COMPLEX_UNIT_SP,15);
widget74.setText(ids1 [4]);
TextView textView10 = (TextView) findViewById(R.id.textView10);
textView10.setTextSize(TypedValue.COMPLEX_UNIT_SP,15);
textView10.setText(ids [4]);
ImageView imageview9 = (ImageView) findViewById(R.id.imageView9);
imageview9.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startActivity(new Intent(Intent.ACTION_VIEW,Uri.parse(ids3[4])));
}
});
TextView widget75 = (TextView) findViewById(R.id.widget75);
widget75.setTextSize(TypedValue.COMPLEX_UNIT_SP,15);
widget75.setText(ids1 [5]);
TextView textView11 = (TextView) findViewById(R.id.textView11);
textView11.setTextSize(TypedValue.COMPLEX_UNIT_SP,15);
textView11.setText(ids [5]);
ImageView imageview10 = (ImageView) findViewById(R.id.imageView10);
imageview10.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startActivity(new Intent(Intent.ACTION_VIEW,Uri.parse(ids3[5])));
}
});
TextView textView8 = (TextView) findViewById(R.id.textView8);
textView8.setTextSize(TypedValue.COMPLEX_UNIT_SP,15);
textView8.setText(ids1 [6]);
TextView textView12 = (TextView) findViewById(R.id.textView12);
textView12.setTextSize(TypedValue.COMPLEX_UNIT_SP,15);
textView12.setText(ids [6]);
ImageView imageview11 = (ImageView) findViewById(R.id.imageView11);
imageview11.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startActivity(new Intent(Intent.ACTION_VIEW,Uri.parse(ids3[6])));
}
});
TextView widget78 = (TextView) findViewById(R.id.widget78);
widget78.setTextSize(TypedValue.COMPLEX_UNIT_SP,15);
widget78.setText(ids1 [7]);
TextView textView13 = (TextView) findViewById(R.id.textView13);
textView13.setTextSize(TypedValue.COMPLEX_UNIT_SP,15);
textView13.setText(ids [7]);
ImageView imageview12 = (ImageView) findViewById(R.id.imageView12);
imageview12.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startActivity(new Intent(Intent.ACTION_VIEW,Uri.parse(ids3[7])));
}
});
TextView textView01 = (TextView) findViewById(R.id.TextView01);
textView01.setTextSize(TypedValue.COMPLEX_UNIT_SP,15);
textView01.setText(ids1 [8]);
TextView textView14 = (TextView) findViewById(R.id.textView14);
textView14.setTextSize(TypedValue.COMPLEX_UNIT_SP,15);
textView14.setText(ids [8]);
ImageView imageview13 = (ImageView) findViewById(R.id.imageView13);
imageview13.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startActivity(new Intent(Intent.ACTION_VIEW,Uri.parse(ids3[8])));
}
});
TextView widget485 = (TextView) findViewById(R.id.widget485);
widget485.setTextSize(TypedValue.COMPLEX_UNIT_SP,15);
widget485.setText(ids1 [9]);
TextView textView15 = (TextView) findViewById(R.id.textView15);
textView15.setTextSize(TypedValue.COMPLEX_UNIT_SP,15);
textView15.setText(ids [9]);
ImageView imageview14 = (ImageView) findViewById(R.id.imageView14);
imageview14.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startActivity(new Intent(Intent.ACTION_VIEW,Uri.parse(ids3[9])));
}
});
SharedPreferences pref2 = getApplicationContext().getSharedPreferences("Tester15", 0); // 0 - for private mode
Editor editor2 = pref2.edit();
String authtoke = pref2.getString("BYR_session", null);
SharedPreferences pref1 = getApplicationContext().getSharedPreferences("TourPref", 0); // 0 - for private mode
Editor editor1 = pref1.edit();
String id = pref1.getString("id", null);
String authTokenLink = "http://ec2-54-212-221-3.us-west-2.compute.amazonaws.com/api/v3/users/profile?auth_token="+authtoke;
DefaultHttpClient httpclient1 = new DefaultHttpClient(new BasicHttpParams());
//HttpGet httpget1 = new HttpGet(authTokenLink);
HttpGet httpget1 = new HttpGet(authTokenLink);
// Depends on your web service
httpget.setHeader("Content-type", "application/json");
httpget.setHeader("Accept","application/json");
InputStream inputStream1 = null;
String someresult1 = null;
try {
HttpResponse response = httpclient1.execute(httpget1);
HttpEntity entity = response.getEntity();
inputStream1 = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream1, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
someresult1 = sb.toString();
} catch (Exception e) {
// Oops
}
finally {
try{if(inputStream1 != null)inputStream1.close();}catch(Exception squish){}
}
int maximumScore = 0;
Log.v("test123;",someresult1);
try {
JSONObject jobject1 = new JSONObject(someresult1);
JSONObject jobject2 = jobject1.getJSONObject("profile");
JSONArray jarray = jobject2.getJSONArray("entries");
Log.v("hereasdf",String.valueOf(jarray.length()));
for (int i=0; i < jarray.length(); i++)
{
try
{
JSONObject oneObject = jarray.getJSONObject(i);
int score = oneObject.getInt("score");
String tournamentID = oneObject.getString("tournament_id");
Log.v("score is", String.valueOf(score));
Log.v("id is", id);
Log.v("tournament ID is", tournamentID);
if (tournamentID.equals(id)==true && maximumScore < score)
{
Log.v("heremax","max");
maximumScore = score;
}
}
catch (JSONException e) {
//Log.v("rerere","rere");
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.v("this is the maximum score", String.valueOf(maximumScore));
TextView textview112 = (TextView) findViewById(R.id.textView17);
textview112.setText(String.valueOf(maximumScore));
ImageView imageview22 = (ImageView) findViewById(R.id.imageView22);
imageview22.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startActivity(new Intent(Intent.ACTION_VIEW,Uri.parse(ids3[0])));
}
});
}
}
| true |
b95f749e026a1941736bd5d81923f6e191c11ede | Java | hardcorelife/spring-netty-demo | /netty-server/src/main/java/com/example/imserver/ImServer.java | UTF-8 | 1,953 | 2.4375 | 2 | [] | no_license | package com.example.imserver;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.util.AttributeKey;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;
import lombok.extern.slf4j.Slf4j;
/**
* @author qiweigang
* @date 2020-01-10 10:18
*/
@Slf4j
public class ImServer {
private static final int PORT = 8090;
public void start() {
//new 主线程组
NioEventLoopGroup bossGroup = new NioEventLoopGroup();
//new 工作线程组
NioEventLoopGroup workerGroup = new NioEventLoopGroup();
final AttributeKey<Object> clientKey = AttributeKey.newInstance("clientKey");
final ServerBootstrap bootstrap = new ServerBootstrap()
.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.attr(AttributeKey.newInstance("serverName"), "nettyServer")
.childAttr(clientKey, "clientValue")
.childOption(ChannelOption.SO_KEEPALIVE, true)
.childOption(ChannelOption.TCP_NODELAY, true)
.option(ChannelOption.SO_BACKLOG, 1024)
.childHandler(new ImServerInitializer());
bind(bootstrap, PORT);
}
private void bind(final ServerBootstrap bootstrap, final int port) {
bootstrap.bind(port).addListener(new GenericFutureListener<Future<? super Void>>() {
@Override
public void operationComplete(Future<? super Void> future) throws Exception {
if (future.isSuccess()) {
log.info("端口[" + port + "]绑定成功!");
} else {
log.info("端口[" + port + "]绑定失败!");
bind(bootstrap, port + 1);
}
}
});
}
}
| true |
1dfc7ba8c568dc809f60a172f47be604d1af7eaf | Java | DesBisous/PhotoShow | /src/com/service/AdminHomeManager.java | UTF-8 | 341 | 1.617188 | 2 | [] | no_license | package com.service;
import com.forms.UserAndAlbumForm;
import com.forms.UserForm;
import java.util.List;
/**
* Created by ruihe on 16-5-22.
*/
public interface AdminHomeManager {
//count album
public long numOfAlbum(String keyWords);
public List<UserAndAlbumForm> maxNumOrderBy();
public List<UserForm> betterUser();
}
| true |
527e156dedc1ef78fd8f0e5d6f82db1f2fa1eef6 | Java | gustavoJSantos/AtividadeJogoDaVelha | /Simbolo.java | UTF-8 | 1,095 | 2.703125 | 3 | [] | no_license | package atividadeFinal_JogoDaVelha;
public class Simbolo extends Jogador {
private String simbolo;
public Simbolo (String nome, String simbolo, int vitorias){
super(nome, vitorias);
this.simbolo = simbolo;
}
public String getSimbolo(){
return simbolo;
}
public boolean vencer(JogoDaVelha t1){
if((t1.achaJV(0,0) == simbolo && t1.achaJV(0,1) == simbolo && t1.achaJV(0,2) == simbolo) ||(t1.achaJV(1,0) == simbolo && t1.achaJV(1,1) == simbolo && t1.achaJV(1,2) == simbolo) ||(t1.achaJV(2,0) == simbolo && t1.achaJV(2,1) == simbolo && t1.achaJV(2,2) == simbolo) ||(t1.achaJV(0,0) == simbolo && t1.achaJV(1,0) == simbolo && t1.achaJV(2,0) == simbolo) ||(t1.achaJV(0,1) == simbolo && t1.achaJV(1,1) == simbolo && t1.achaJV(2,1) == simbolo) || (t1.achaJV(0,2) == simbolo && t1.achaJV(1,2) == simbolo && t1.achaJV(2,2) == simbolo) || (t1.achaJV(0,0) == simbolo && t1.achaJV(1,1) == simbolo && t1.achaJV(2,2) == simbolo) || (t1.achaJV(0,2) == simbolo && t1.achaJV(1,1) == simbolo && t1.achaJV(2,0) == simbolo)){
return true;
}else{
return false;
}
}
}
| true |
209380b79488d1043e502a0490d384977c873bd3 | Java | Youhoseong/verpic-backend | /src/main/java/teamverpic/verpicbackend/domain/studyroom/dto/WebSocketMessageDto.java | UTF-8 | 687 | 2.28125 | 2 | [] | no_license | package teamverpic.verpicbackend.domain.studyroom.dto;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import teamverpic.verpicbackend.domain.studyroom.domain.WebSocketMessage;
@Getter
@Setter
@Data
public class WebSocketMessageDto {
private String from;
private String type;
private String data;
private Object candidate;
private Object sdp;
public WebSocketMessage toEntity(){
WebSocketMessage build = WebSocketMessage.builder()
.from(from)
.type(type)
.data(data)
.candidate(candidate)
.sdp(sdp)
.build();
return build;
}
}
| true |
f3274bf067788ef11ba54412c8ede6ea1a8a74a9 | Java | guezandy/snagtag_android | /workspace/CSC120_1/src/Diving.java | UTF-8 | 1,015 | 3.1875 | 3 | [] | no_license | import java.util.Scanner;
public class Diving {
public static Scanner keyboard = new Scanner(System.in);
static double dive_depth = 0.0;
static double percent_oxygen = 0.0;
static double ambient_pressure = 0.0;
static double ft_per_atm_constant = 33.0;
static double PP_oxygen = 0.0;
static boolean maximal_pressure = false;
public static void main(String[] args) {
System.out.println(65);
System.out.print("Enter Depth and Percentage 02: ");
dive_depth = keyboard.nextDouble();
percent_oxygen = keyboard.nextDouble();
ambient_pressure= 1+(dive_depth/ft_per_atm_constant);
System.out.print("Ambient Pressure: ");
System.out.println(ambient_pressure);
PP_oxygen = (percent_oxygen/100.0)*ambient_pressure;
System.out.print("02 Pressure: ");
System.out.println(PP_oxygen);
if (PP_oxygen >1.4 ) {
maximal_pressure = true;
}
else {
maximal_pressure = false;
}
System.out.print("Exceeds Maximal 02 Pressure: ");
System.out.println(maximal_pressure);
}
}
| true |
28834e990242ff2a95a80f00aa5fda8a1ba0f577 | Java | Czzzzzzzzz/book | /src/main/java/cn/book/bus/aop/HttpAspect.java | UTF-8 | 2,276 | 2.484375 | 2 | [
"Apache-2.0"
] | permissive | package cn.book.bus.aop;
import cn.book.bus.utils.IpUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
/**
* 通过aop拦截请求 记录运行信息
*/
@Aspect
@Component
public class HttpAspect {
private static long startTime;
private static long endTime;
private static final Logger log = LoggerFactory.getLogger(HttpAspect.class);
/**
* 切点表达式
*/
@Pointcut("execution(public * cn.book.bus.controller..*.*(..))")
/**
* 切点签名
*/
public void print() {
}
/**
* @Before注解表示在具体的方法之前执行
* @param joinPoint
*/
@Before("print()")
public void before(JoinPoint joinPoint) {
startTime = System.currentTimeMillis();
ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = requestAttributes.getRequest();
String requestURI = request.getRequestURI();
String remoteAddr = IpUtil.getIpAddr(request);
String requestMethod = request.getMethod();
String declaringTypeNamepeName = joinPoint.getSignature().getDeclaringTypeName();
String methodName = joinPoint.getSignature().getName();
Object[] args = joinPoint.getArgs();
log.info("请求url:=" + requestURI + ",客户端ip:=" + remoteAddr + ",请求方式:=" + requestMethod + ",请求的类名:=" + declaringTypeNamepeName + ",方法名:=" + methodName);
}
/**
* @After注解表示在方法执行之后执行
*/
@After("print()")
public void after() {
endTime = System.currentTimeMillis() - startTime;
}
/**
* @AfterReturning注解用于获取方法的返回值
* @param object
*/
@AfterReturning(pointcut = "print()", returning = "object")
public void getAfterReturn(Object object) {
log.info("本次接口耗时={}ms", endTime);
}
}
| true |
31b5a094554f83f79e101a8f7abed7946d9b32bd | Java | yhjun0523/ApplicationForm | /src/main/java/com/spring/biz/form/impl/FormServiceImpl.java | UTF-8 | 2,763 | 1.757813 | 2 | [] | no_license | package com.spring.biz.form.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.spring.biz.form.CommonVO;
import com.spring.biz.form.FormService;
import com.spring.biz.form.FormVO;
import com.spring.biz.form.SeqnotblVO;
@Service("formService")
public class FormServiceImpl implements FormService {
@Autowired
private FormDAO formDAO;
public FormServiceImpl() {
}
public void insertForm(FormVO vo) {
formDAO.insertForm(vo);
}
public void insertCustomer(FormVO vo) {
formDAO.insertCustomer(vo);
}
public void insertCard(FormVO vo) {
formDAO.insertCard(vo);
}
public void insertBill(FormVO vo) {
formDAO.insertBill(vo);
}
public void updateCustNo(SeqnotblVO vo) {
formDAO.updateCustNo(vo);
}
public void updateCrdNo(SeqnotblVO vo) {
formDAO.updateCrdNo(vo);
}
public void updateForm(FormVO vo) {
formDAO.updateForm(vo);
}
public FormVO getForm(FormVO vo) {
return formDAO.getForm(vo);
}
public List<FormVO> getFormList(FormVO vo) {
return formDAO.getFormList(vo);
}
public List<CommonVO> getApplClasList(CommonVO vo) {
return formDAO.getApplClasList(vo);
}
public List<CommonVO> getBrdList(CommonVO vo) {
return formDAO.getBrdList(vo);
}
public List<CommonVO> getStlDdList(CommonVO vo) {
return formDAO.getStlDdList(vo);
}
public List<CommonVO> getStlMtdList(CommonVO vo) {
return formDAO.getStlMtdList(vo);
}
public List<CommonVO> getBnkCdList(CommonVO vo) {
return formDAO.getBnkCdList(vo);
}
public List<CommonVO> getStmtSndMtdList(CommonVO vo) {
return formDAO.getStmtSndMtdList(vo);
}
public FormVO selectImpsb01(FormVO vo) {
return formDAO.selectImpsb01(vo);
}
public int selectImpsb04_11(FormVO vo) {
int result = formDAO.selectImpsb04_11(vo);
return result;
}
public void insertMember_impsb(FormVO vo) {
formDAO.insertMember_impsb(vo);
}
public void insertMember(FormVO vo) {
formDAO.insertMember(vo);
}
public int selectImpsb04_21(FormVO vo) {
int result = formDAO.selectImpsb04_21(vo);
return result;
}
public List<FormVO> selectAppl_d(FormVO vo) {
return formDAO.selectAppl_d(vo);
}
public List<FormVO> selectAppl_clas(FormVO vo) {
return formDAO.selectAppl_clas(vo);
}
public List<FormVO> selectAppl_d_Appl_clas(FormVO vo) {
return formDAO.selectAppl_d_Appl_clas(vo);
}
public List<FormVO> selectSsn(FormVO vo) {
return formDAO.selectSsn(vo);
}
public List<FormVO> selectAppl_d_ssn(FormVO vo) {
return formDAO.selectAppl_d_ssn(vo);
}
public List<FormVO> selectAppl_clas_ssn(FormVO vo) {
return formDAO.selectAppl_clas_ssn(vo);
}
public List<FormVO> selectAll(FormVO vo) {
return formDAO.selectAll(vo);
}
}
| true |
ab4789d2640d22748aff8598af5408e8dcfbcb42 | Java | lullaaaby13/design-pattern | /StrategyPattern/solution/src/problem1/answer/Robot.java | UTF-8 | 685 | 3.3125 | 3 | [] | no_license | package problem1.answer;
import java.util.Optional;
public abstract class Robot {
private String name;
private Attackable attackable;
private Movable movable;
public Robot(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void attack() {
Optional.ofNullable(attackable).ifPresent(Attackable::attack);
}
public void move() {
Optional.ofNullable(movable).ifPresent(Movable::move);
}
public void setAttackable(Attackable attackable) {
this.attackable = attackable;
}
public void setMovable(Movable movable) {
this.movable = movable;
}
}
| true |
46081d696de4f1cbeb71b17545781fea688e71f2 | Java | gdevanla/fusion_tests | /jconsole/CPCommandGenTest.java | UTF-8 | 2,788 | 2.359375 | 2 | [] | no_license | package org.jconsole;
import java.lang.String;
import org.jconsole.JConsole;
import java.lang.System;
import org.junit.*;
import static org.junit.Assert.*;
public class CPCommandGenTest {
/**
* Test method for the class org.jconsole.CPCommand
*/
@Test
public void testCPCommand30() throws Exception {
CPCommand var38 = new CPCommand();
JConsole var39 = JConsole.instance();
String var40 = System.getProperty("user.dir");
var39.setCurrentDir(var40);
var38.setConsole(var39);
String[] var42 = new String[0];
var38.execute(var42);
var39.setCurrentDir(var40);
var38.setConsole(var39);
String var43 = var40 + "/testResource/testDoc.txt";
String[] var44 = { var43, "." };
var38.execute(var44);
}
/**
* Test method for the class org.jconsole.CPCommand
*/
@Test
public void testCPCommand31() throws Exception {
CPCommand var38 = new CPCommand();
JConsole var39 = JConsole.instance();
String var40 = System.getProperty("user.dir");
var39.setCurrentDir(var40);
var38.setConsole(var39);
String[] var42 = new String[0];
var38.execute(var42);
var39.setCurrentDir(var40);
var38.setConsole(var39);
String[] var45 = { "*stDoc2.txt", "./testResource" };
var38.execute(var45);
}
/**
* Test method for the class org.jconsole.CPCommand
*/
@Test
public void testCPCommand32() throws Exception {
CPCommand var38 = new CPCommand();
JConsole var39 = JConsole.instance();
String var40 = System.getProperty("user.dir");
var39.setCurrentDir(var40);
var38.setConsole(var39);
String var43 = var40 + "/testResource/testDoc.txt";
String[] var44 = { var43, "." };
var38.execute(var44);
var39.setCurrentDir(var40);
var38.setConsole(var39);
String[] var42 = new String[0];
var38.execute(var42);
}
/**
* Test method for the class org.jconsole.CPCommand
*/
@Test
public void testCPCommand33() throws Exception {
CPCommand var38 = new CPCommand();
JConsole var39 = JConsole.instance();
String var40 = System.getProperty("user.dir");
var39.setCurrentDir(var40);
var38.setConsole(var39);
String[] var45 = { "*stDoc2.txt", "./testResource" };
var38.execute(var45);
var39.setCurrentDir(var40);
var38.setConsole(var39);
String var43 = var40 + "/testResource/testDoc.txt";
String[] var44 = { var43, "." };
var38.execute(var44);
}
/**
* Test method for the class org.jconsole.CPCommand
*/
@Test
public void testCPCommand34() throws Exception {
CPCommand var38 = new CPCommand();
JConsole var39 = JConsole.instance();
String var40 = System.getProperty("user.dir");
var39.setCurrentDir(var40);
var38.setConsole(var39);
String[] var45 = { "*stDoc2.txt", "./testResource" };
var38.execute(var45);
var39.setCurrentDir(var40);
var38.setConsole(var39);
var38.execute(var45);
}
} | true |
fe4d482b8f310de1b30c4ee143334f93898f7e9b | Java | JavaServerGroup/jtool-httpclient | /src/main/java/com/jtool/http/CommonCommand.java | UTF-8 | 2,616 | 2.546875 | 3 | [
"Apache-2.0"
] | permissive | package com.jtool.http;
import com.jtool.http.exception.RequestBeanErrorException;
import org.apache.commons.beanutils.BeanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class CommonCommand {
private static Logger log = LoggerFactory.getLogger(CommonCommand.class);
public static String readRequest(String host, String uri, Map<String, String> map) {
if(log.isDebugEnabled()) {
log.debug("curl '" + host + uri + "?" + join(getParamStrings(map)) + "'");
}
String content;
int i = 0;
do {
content = WebGet.sent(host + uri, map);
i++;
} while ((content == null || content.equals("")) && i < 5);
log.debug("response: " + content);
return content;
}
public static String writeRequest(String host, String uri, Map<String, String> map) {
if(log.isDebugEnabled()) {
log.debug("curl -X POST -d \"" + join(getParamStrings(map)) + "\" " + host + uri);
}
String content = WebPost.sent(host + uri, map);
log.debug("response: " + content);
return content;
}
public static String readRequest(String host, String uri, Object param) {
return readRequest(host, uri, convertBeanToRequestMap(param));
}
public static String writeRequest(String host, String uri, Object param) {
return writeRequest(host, uri, convertBeanToRequestMap(param));
}
private static List<String> getParamStrings(Map<String, ?> paramsMap) {
List<String> paramsList = new ArrayList<>();
for(String key : paramsMap.keySet()){
try {
if(paramsMap.get(key) != null) {
paramsList.add(URLEncoder.encode(key, "UTF-8") + "=" + URLEncoder.encode(paramsMap.get(key).toString(), "UTF-8"));
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
return paramsList;
}
private static Map<String, String> convertBeanToRequestMap(Object bean) {
Map<String, String> params;
try {
params = BeanUtils.describe(bean);
} catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
throw new RequestBeanErrorException(e);
}
params.remove("class");
return params;
}
private static String join(final List<String> params){
StringBuilder sb = new StringBuilder();
for(int i = 0; i < params.size(); i++){
if(i != 0) {
sb.append("&");
}
sb.append(params.get(i));
}
return sb.toString();
}
}
| true |
f6e04125e71222a540aa4389aac256083f2958a5 | Java | shuangcode/CustomView | /app/src/main/java/com/daniel/custom/example/TestA.java | UTF-8 | 201 | 1.804688 | 2 | [] | no_license | package com.daniel.custom.example;
import android.util.Log;
/**
* Created by daniel.xiao on 2016/11/14.
*/
public class TestA {
public TestA(){
Log.i("test", "TestA" + this);
}
}
| true |
1f8abfb5a9514c778ac83efdc0487455027ec923 | Java | hucom-docker/AXmlSwing | /src/org/arong/axmlswing/attribute/AttributeTransfer.java | UTF-8 | 8,440 | 2.59375 | 3 | [
"MIT"
] | permissive | package org.arong.axmlswing.attribute;
import java.awt.Color;
import java.awt.Component;
import java.awt.Cursor;
import java.awt.Font;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseWheelEvent;
import java.awt.event.WindowEvent;
import java.awt.event.WindowFocusListener;
import java.awt.event.WindowListener;
import java.awt.event.WindowStateListener;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import org.arong.axmlswing.manager.ColorManager;
import org.arong.axmlswing.manager.ComponentManager;
import org.arong.axmlswing.manager.CursorManager;
import org.arong.axmlswing.manager.FontManager;
/**
* 属性转换,与AttributeValidator配合使用
* @author dipoo
* @since 2015-01-29
*/
public class AttributeTransfer {
public static int[] size(String value){
String[] arr = value.split(",");
int[] ret = new int[2];
for(int i = 0; i < arr.length; i ++){
ret[i] = Integer.parseInt(arr[i].trim());
}
return ret;
}
public static int[] intArray(String value, String tag){
String[] a = value.split(tag);
int[] ints = new int[a.length];
for(int i = 0; i < a.length; i++){
ints[i] = Integer.parseInt(a[i]);
}
return ints;
}
public static int[] bounds(String value){
String[] arr = value.split(",");
int[] ret = new int[4];
for(int i = 0; i < arr.length; i ++){
ret[i] = Integer.parseInt(arr[i].trim());
}
return ret;
}
public static Cursor cursor(String value){
return CursorManager.getCursors().get(value.toUpperCase());
}
public static Color color(String value){
Color color = ColorManager.getColors().get(value.toUpperCase());
if(color == null){
try {
color = new Color(Integer.parseInt(value, 16));
ColorManager.getColors().put(value.toUpperCase(), color);
} catch(NumberFormatException e) {
}
}
return color;
}
public static Font font(String value){
Font font = FontManager.getFonts().get(value);
if(font == null){
String[] arr = value.split(",");
font = new Font(arr[0], Integer.parseInt(arr[1].trim()), Integer.parseInt(arr[2].trim()));
FontManager.getFonts().put(value, font);
}
return font;
}
public static Icon icon(String value){
return new ImageIcon(value);
}
/**
* 解析表达式返回鼠标接听器<br>
* 格式为:action(id1,id2……)<br/>
* action:动作指令
* id:组件id
*/
public static MouseListener onclick(final String value, final int clickCount){
return new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if(e.getClickCount() != clickCount)
return;
actionEvent(e.getSource(), value);
}
};
}
public static MouseListener mouseListener(final String value, final int i){
return new MouseAdapter() {
public void mouseEntered(MouseEvent e) {
if(i == 1){
actionEvent(e.getSource(), value);
}
}
public void mouseExited(MouseEvent e) {
if(i == 2){
actionEvent(e.getSource(), value);
}
}
public void mousePressed(MouseEvent e) {
if(i == 3){
actionEvent(e.getSource(), value);
}
}
public void mouseReleased(MouseEvent e) {
if(i == 4){
actionEvent(e.getSource(), value);
}
}
public void mouseDragged(MouseEvent e) {
if(i == 5){
actionEvent(e.getSource(), value);
}
}
public void mouseMoved(MouseEvent e) {
if(i == 6){
actionEvent(e.getSource(), value);
}
}
public void mouseWheelMoved(MouseWheelEvent e) {
if(i == 7){
actionEvent(e.getSource(), value);
}
}
};
}
public static KeyListener keyListener(final String value, final int i) {
return new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if(i == 1){
actionEvent(e.getSource(), value);
}
}
public void keyReleased(KeyEvent e) {
if(i == 2){
actionEvent(e.getSource(), value);
}
}
public void keyTyped(KeyEvent e) {
if(i == 3){
actionEvent(e.getSource(), value);
}
}
};
}
public static FocusListener focusListener(final String value, final int i) {
return new FocusAdapter() {
public void focusGained(FocusEvent e) {
if(i == 1){
actionEvent(e.getSource(), value);
}
}
public void focusLost(FocusEvent e) {
if(i == 2){
actionEvent(e.getSource(), value);
}
}
};
}
public static WindowListener windowListener(final String value, final int i) {
return new WindowListener() {
public void windowClosed(WindowEvent e) {
if(i == 1){
actionEvent(e.getSource(), value);
}
}
public void windowOpened(WindowEvent e) {
if(i == 2){
actionEvent(e.getSource(), value);
}
}
public void windowClosing(WindowEvent e) {
if(i == 3){
actionEvent(e.getSource(), value);
}
}
public void windowActivated(WindowEvent e) {
if(i == 4){
actionEvent(e.getSource(), value);
}
}
public void windowDeactivated(WindowEvent e) {
if(i == 5){
actionEvent(e.getSource(), value);
}
}
public void windowIconified(WindowEvent e) {
if(i == 6){
actionEvent(e.getSource(), value);
}
}
public void windowDeiconified(WindowEvent e) {
if(i == 7){
actionEvent(e.getSource(), value);
}
}
};
}
public static WindowStateListener windowStateListener(final String value){
return new WindowStateListener() {
public void windowStateChanged(WindowEvent e) {
actionEvent(e.getSource(), value);
}
};
}
public static WindowFocusListener windowFocusListener(final String value, final int i){
return new WindowFocusListener() {
public void windowLostFocus(WindowEvent e) {
if(i == 1){
actionEvent(e.getSource(), value);
}
}
public void windowGainedFocus(WindowEvent e) {
if(i == 2){
actionEvent(e.getSource(), value);
}
}
};
}
public static ActionListener actionListener(final String value){
return new ActionListener() {
public void actionPerformed(ActionEvent e) {
actionEvent(e.getSource(), value);
}
};
}
public final static void actionEvent(Object source, String value){
String[] a = value.split("\\(");
String action = a[0];
//退出应用程序:exit
if("exit".equals(action)){//不带参数
System.exit(0);
}else if(a.length == 2){//带参数
if(a[1].indexOf(")") != -1){
a[1] = a[1].replaceAll("\\)", "");//去掉右括号
}
String[] params = a[1].split(",");
/**
* 字符串
*/
if("alert".equals(action)){
if(params.length == 1){
JOptionPane.showMessageDialog(null, params[0]);
}else{
JOptionPane.showMessageDialog("this".equals(params[0].trim()) ? (Component)source : ComponentManager.getComponent(params[0].trim()), params[1]);
}
}else{
/**
* 作用于组件
*/
//关闭某些窗口:close:helpWindow|settingWindow
Component c;
for(String id : params){
if("this".equals(id.trim())){
c = (Component)source;
}else{
c = ComponentManager.getComponent(id.trim());
}
if(c != null){
setAction(c, action);
}
}
}
}
}
private static void setAction(Component c, String action){
if("close".equals(action)){
if(c instanceof Window){//只有Window的子类才能关闭
((Window)c).dispose();
}
}else if("show".equals(action)){
c.setVisible(true);
}else if("hide".equals(action)){
c.setVisible(false);
}else if("enabled".equals(action)){
c.setEnabled(true);
}else if("disabled".equals(action)){
c.setEnabled(false);
}else if("click".equals(action)){
MouseListener[] mls = c.getMouseListeners();
if(mls != null){
for (int i = 0; i < mls.length; i++) {
mls[i].mouseClicked(new MouseEvent(c, 1, System.currentTimeMillis(), 1, 1, 1, 1, false, 1));
}
}
}else if("dblclick".equals(action)){
MouseListener[] mls = c.getMouseListeners();
if(mls != null){
for (int i = 0; i < mls.length; i++) {
mls[i].mouseClicked(new MouseEvent(c, 1, System.currentTimeMillis(), 1, 1, 1, 2, false, 1));
}
}
}
}
}
| true |
56743378d33644c5580f9677c604716b46a6ff6c | Java | damaimrs/blibli-future-project-1 | /src/main/java/com/blibli/future/project1/service/PurchaseService.java | UTF-8 | 5,108 | 2.265625 | 2 | [] | no_license | package com.blibli.future.project1.service;
import com.blibli.future.project1.model.Purchase;
import com.blibli.future.project1.model.PurchaseItem;
import com.blibli.future.project1.model.PurchaseStatus;
import com.blibli.future.project1.repository.PurchaseItemRepository;
import com.blibli.future.project1.repository.PurchaseRepository;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Date;
import java.util.List;
@Transactional
@Service
public class PurchaseService {
private PurchaseRepository purchaseRepository;
private PurchaseItemRepository purchaseItemRepository;
public PurchaseService(PurchaseRepository purchaseRepository, PurchaseItemRepository purchaseItemRepository) {
this.purchaseRepository = purchaseRepository;
this.purchaseItemRepository = purchaseItemRepository;
}
public List<Purchase> findAll() {
return purchaseRepository.findAll();
}
public List<Purchase> findAllPurchaseByCashierId(Integer userId) {
return purchaseRepository.findPurchasesByCashier_UserId(userId);
}
public List<Purchase> findAllPurchaseByPurchaseStatus(PurchaseStatus purchaseStatus) {
return purchaseRepository.findPurchasesByPurchaseStatus(purchaseStatus);
}
public Page<Purchase> findAllPurchaseByPurchaseStatus(PurchaseStatus purchaseStatus, Pageable pageable) {
return purchaseRepository.findPurchasesByPurchaseStatus(purchaseStatus, pageable);
}
public Page<Purchase> findAllPurchaseByPurchaseStatus(PurchaseStatus purchaseStatus,
Date startDate,
Date endDate,
Pageable pageable) {
return purchaseRepository.findPurchasesByPurchaseStatusAndPurchaseDateBetween(purchaseStatus,
startDate, endDate, pageable);
}
public Long getPurchaseCount() {
return purchaseRepository.count();
}
public Long getPurchaseCountByPurchaseStatus(PurchaseStatus purchaseStatus) {
return purchaseRepository.countAllByPurchaseStatus(purchaseStatus);
}
public Long getPurchaseCountByPurchaseDate(Date startDate, Date endDate) {
return purchaseRepository.countAllByPurchaseDateBetween(startDate, endDate);
}
public Long getPurchaseCountByPurchaseStatusAndPurchaseTable(PurchaseStatus purchaseStatus, Integer purchaseTable) {
return purchaseRepository.countAllByPurchaseStatusAndPurchaseTable(purchaseStatus, purchaseTable);
}
public Page<Purchase> findAllPageable(Pageable pageable) {
return purchaseRepository.findAll(pageable);
}
public Purchase findPurchaseById(int id) {
return purchaseRepository.findOne(id);
}
public Purchase addPurchase(Purchase purchase) {
return purchaseRepository.save(purchase);
}
public Purchase addPurchaseWithPurchaseItem(Purchase purchase) {
Purchase newPurchase = purchase;
//menghapus item pemesanan di database kalau ada id pemesanan, kalo gaada id pemesanan ga dihapus tapi langsung disimpen
if (purchase.getPurchaseId() != 0) //get id, kalau sudah ada id pemesanan, item yg dipesan dihapus (untuk edit)
purchaseItemRepository.deleteAllByPurchase_PurchaseId(purchase.getPurchaseId());
purchase = purchaseRepository.save(purchase);
if (purchase != null) {
boolean isSuccess = true;
//untuk save itemnya
for (PurchaseItem purchaseItem : newPurchase.getPurchaseItems()) {
if (purchaseItem != null) {
purchaseItem.setPurchase(newPurchase);
purchaseItem = purchaseItemRepository.save(purchaseItem);
isSuccess = purchaseItem != null;
if (!isSuccess)
break;
}
}
if (!isSuccess) {
purchase = null;
}
}
return purchase;
}
public void deletePurchase(Integer purchaseId) {
purchaseItemRepository.deleteAllByPurchase_PurchaseId(purchaseId);
purchaseRepository.delete(purchaseId);
}
public Long getTotalPurchaseTotal() {
return purchaseRepository.getTotalPurchaseTotal();
}
public Long getTotalPurchaseTotal(PurchaseStatus purchaseStatus) {
return purchaseRepository.getTotalPurchaseTotalByPurchaseStatus(purchaseStatus);
}
public Long getTotalPurchaseTotal(Date startDate, Date endDate) {
return purchaseRepository.getTotalPurchaseTotalByPurchaseDateBetween(startDate, endDate);
}
public Long getTotalPurchaseTotal(PurchaseStatus purchaseStatus, Date startDate, Date endDate) {
return purchaseRepository.getTotalPurchaseTotalByPurchaseStatusAndPurchaseDateBetween(purchaseStatus, startDate, endDate);
}
}
| true |
886ba7f7e089bdf8d01cace5c5e5e104a2d38a98 | Java | oscarcs/Tatai | /src/views/user_dashboard/UserDashboard.java | UTF-8 | 5,220 | 2.59375 | 3 | [] | no_license | package views.user_dashboard;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.chart.LineChart;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;
import javafx.scene.control.Button;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableRow;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.image.Image;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import game.GameData;
import game.User;
import views.game_info.GameInfo;
import views.game_info.GameInfoView;
import views.main_container.MainContainer;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
/**
* User dashboard controller.
* @author szhu842, osim082
*/
public class UserDashboard {
@FXML
TableView<GameData> tableView;
@FXML
Text headerText, descriptionText, scoreText;
private User user;
@FXML
Button chart;
/**
* Method that returns a ObservableList for tableView.
*
* @return
*/
public ObservableList<GameData> getItems() {
return FXCollections.observableList(user.getGames());
}
class GameDataComparator implements Comparator<GameData> {
@Override
public int compare(GameData o1, GameData o2) {
return o1.getTime().compareTo(o2.getTime());
}
}
public void chartHit() {
final NumberAxis xAxis = new NumberAxis(1, user.getGames().size(), 1);
final NumberAxis yAxis = new NumberAxis(0, 10, 1);
xAxis.setLabel("Games");
yAxis.setLabel("Scores");
// creating the chart
final LineChart<Number, Number> lineChart = new LineChart<Number, Number>(xAxis, yAxis);
lineChart.setTitle("Game Progress Line Chart");
XYChart.Series series = new XYChart.Series();
series.setName(user.getUsername());
ArrayList<GameData> gameData = user.getGames();
Collections.sort(gameData, new GameDataComparator());
int count = 1;
for (GameData data : gameData) {
series.getData().add(new XYChart.Data(count, data.getScore()));
count++;
}
Scene scene = new Scene(lineChart, 400, 300);
lineChart.getData().add(series);
Stage stage = new Stage();
stage.setScene(scene);
stage.setTitle("Game Plot");
stage.show();
stage.getIcons().add(new Image("resources/maori.png"));
}
/**
* Method called on initialization, it sets up the table.
*/
@FXML
private void initialize() {
// Get the user.
user = MainContainer.instance().getUser();
headerText.setText("Hi, " + user.getUsername());
scoreText.setText("Score: " + user.getScore());
descriptionText.setText("You can double click on a game to see its details!");
// Create Columns
TableColumn<GameData, LocalDate> dateColumn = new TableColumn<>("Date");
dateColumn.setMinWidth(100);
dateColumn.setCellValueFactory(new PropertyValueFactory<>("time"));
TableColumn<GameData, String> gameTypeColumn = new TableColumn<>("Game Type");
gameTypeColumn.setMinWidth(100);
gameTypeColumn.setCellValueFactory(new PropertyValueFactory<>("gameType"));
TableColumn<GameData, Integer> maxNumberColumn = new TableColumn<>("Max");
maxNumberColumn.setMinWidth(75);
maxNumberColumn.setCellValueFactory(new PropertyValueFactory<>("maxNumber"));
TableColumn<GameData, Double> scorePercentageColumn = new TableColumn<>("%");
scorePercentageColumn.setMinWidth(50);
scorePercentageColumn.setCellValueFactory(new PropertyValueFactory<>("scoreAsPercentage"));
TableColumn<GameData, Integer> scoreColumn = new TableColumn<>("Score");
scoreColumn.setMinWidth(50);
scoreColumn.setCellValueFactory(new PropertyValueFactory<>("score"));
TableColumn<GameData, Integer> roundsColumn = new TableColumn<>("Rounds");
roundsColumn.setMinWidth(50);
roundsColumn.setCellValueFactory(new PropertyValueFactory<>("totalRounds"));
tableView.setItems(getItems());
tableView.getColumns().addAll(dateColumn, gameTypeColumn, maxNumberColumn, scorePercentageColumn, scoreColumn,
roundsColumn);
// This sets it up so when you double on on a row it wil bring up the
// gameInfoView of it.
tableView.setRowFactory(tv -> {
TableRow<GameData> row = new TableRow<>();
row.setOnMouseClicked(event -> {
if (event.getClickCount() > 1 && !row.isEmpty()) {
GameData gameData = row.getItem();
Stage stage = new Stage();
stage.setTitle(gameData.getTime().toString());
GameInfoView gameInfoView = new GameInfoView();
Scene gameInfoScene = new Scene((Parent) gameInfoView.view());
GameInfo gameInfo = (GameInfo) gameInfoView.controller();
gameInfo.setGameData(gameData);
stage.setTitle("Game on " + gameData.getTime());
stage.setScene(gameInfoScene);
stage.show();
stage.getIcons().add(new Image("resources/maori.png"));
}
});
return row;
});
tableView.getSortOrder().add(dateColumn);
tableView.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
}
}
| true |
f3a7f0560d83a86d1096631f85bc37718591e791 | Java | CDDL/MyBets | /app/src/main/java/project/catalin/mybets/datos/excepciones/JuegoInexistenteException.java | UTF-8 | 157 | 1.5 | 2 | [] | no_license | package project.catalin.mybets.datos.excepciones;
/**
* Created by Trabajo on 19/04/2016.
*/
public class JuegoInexistenteException extends Exception{
}
| true |
41e7490020824c5830f6a9f1de7fb0450b597f8e | Java | Explorer1092/vox | /utopia-service/utopia-afenti/utopia-afenti-api/src/main/java/com/voxlearning/utopia/service/afenti/api/constant/AfentiPracticeAchievement.java | UTF-8 | 1,310 | 2.5625 | 3 | [] | no_license | package com.voxlearning.utopia.service.afenti.api.constant;
import lombok.Getter;
/**
* @author peng.zhang.a
* @since 2016/5/16
*/
@Getter
public enum AfentiPracticeAchievement {
NUM_MIN_0(0,0,"继续努力"),
NUM_1_9(1,9,"小有进步$值得鼓励$持续提高$坚持不懈"),
NUM_10_50(10,50,"进步神速$聪明伶俐$融会贯通$快速提高$勤学苦练"),
NUM_51_99(51,99,"出类拔萃$力争上游$孜孜不倦$突飞猛进"),
NUM_100_MAX(100,Integer.MAX_VALUE,"名列榜首$独占鳌头"),
NUM_ERROR(Integer.MIN_VALUE,-1,"没有称号");
AfentiPracticeAchievement(Integer min, Integer max, String desc) {
this.min = min;
this.max = max;
this.desc = desc;
}
private Integer min;
private Integer max;
private String desc;
public static String getTitle(int num) {
for (AfentiPracticeAchievement afentiPracticeAchievement : AfentiPracticeAchievement.values()) {
if (num >= afentiPracticeAchievement.min && num <= afentiPracticeAchievement.max) {
String cols[] = afentiPracticeAchievement.desc.split("[$]");
int index = num % cols.length;
return cols[index];
}
}
return NUM_ERROR.desc;
}
}
| true |
fb52b2b75a032536222ac9f868c20aedb249e6e0 | Java | 1976222027/BaseAndroid | /app/src/main/java/com/yanb/daqsoft/baseandroid/wxapi/SocialUtil.java | UTF-8 | 406 | 1.6875 | 2 | [] | no_license | package com.yanb.daqsoft.baseandroid.wxapi;
import io.agora.yshare.SocialHelper;
public enum SocialUtil {
INSTANCE();
public SocialHelper socialHelper;
SocialUtil() {
socialHelper = new SocialHelper.Builder()
.setQqAppId("101585934")
.setWxAppId("wx13ee55166072b68c")
.setWxAppSecret("wxAppSecret")
.build();
}
}
| true |
29270d5f4c360dd5d6efb52b183f5e118497d67c | Java | Chaitranjali/SuryaSoft | /app/src/main/java/com/hello/assignment/auth/common/ui/view/BaseParentActivity.java | UTF-8 | 1,190 | 2.09375 | 2 | [] | no_license | package com.hello.assignment.auth.common.ui.view;
import android.app.ProgressDialog;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import com.hello.assignment.R;
public class BaseParentActivity extends AppCompatActivity {
private ProgressDialog progressDialog;
public Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = BaseParentActivity.this;
}
public void showLoader(String message) {
progressDialog = new ProgressDialog(context, R.style.AppCompatProgressDialogStyle);
progressDialog.setCancelable(false);
if (!TextUtils.isEmpty(message)) {
progressDialog.setMessage(message);
} else {
progressDialog.setMessage(getString(R.string.please_wait));
}
if (!isFinishing()) {
progressDialog.show();
}
}
public void hideLoader() {
if (progressDialog != null && progressDialog.isShowing() && !isFinishing()) {
progressDialog.dismiss();
}
}
}
| true |
e750a8cab6779de44b73416c7747c9ce146a2e87 | Java | Navi-nk/Bernard-InMoov | /myrobotlab/src/org/myrobotlab/service/interfaces/Invoker.java | UTF-8 | 322 | 2.015625 | 2 | [
"Apache-2.0"
] | permissive | package org.myrobotlab.service.interfaces;
import org.myrobotlab.framework.Message;
public interface Invoker {
public Object invoke(Message msg);
public Object invoke(String method);
public Object invoke(String method, Object... params);
public Object invokeOn(Object obj, String method, Object... params);
}
| true |
6c6cbac7080ba2ce10d976172ae8e897ac650f80 | Java | ganzes/arkadiusz-charczuk-kodilla-java | /kodilla-good-patterns/src/main/java/com/kodilla/good/patterns/challenges/Food2Door/BoughtService.java | UTF-8 | 198 | 1.921875 | 2 | [] | no_license | package com.kodilla.good.patterns.challenges.Food2Door;
import java.time.LocalDateTime;
public interface BoughtService {
boolean bought (User user, LocalDateTime boughtTime, Order order);
}
| true |
25c72bc6f26ebef02e664a7e39cd0e3e6f0dd486 | Java | Annieli0717/USC-CSCI455x-Programming-Systems-Design | /PA1/Tester2.java | UTF-8 | 4,525 | 3.34375 | 3 | [] | no_license | // Name: Dunxuan Li (Annie)
// USC NetID: 6625999096
// CS 455 PA1
// Spring 2019
import java.util.Scanner;
// Test the CoinTossSimulator class
public class Tester2 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter number of trials (>= 1): ");
int input = in.nextInt();
if(input > 0 ) {
int numTrials = input;
// Call the CoinTossSimulator to simulate the process
CoinTossSimulator coinToss= new CoinTossSimulator();
//Test case 1
System.out.println("After constructor: ");
System.out.println("Number of trials [exp: 0]: " + coinToss.getNumTrials() );
System.out.println("Two-head tosses: " + coinToss.getTwoHeads());
System.out.println("Two-tail tosses: " + coinToss.getTwoTails());
System.out.println("One-head one-tail tosses: " + coinToss.getHeadTails());
System.out.println("Tosses add up correctly? " + (coinToss.getTwoHeads() + coinToss.getTwoTails() + coinToss.getHeadTails() == coinToss.getNumTrials()));
//Test case 2
coinToss.run(1);
System.out.println();
System.out.println("After run(10) ");
System.out.println("Number of trials [exp: 1]: " + coinToss.getNumTrials() );
System.out.println("Two-head tosses: " + coinToss.getTwoHeads());
System.out.println("Two-tail tosses: " + coinToss.getTwoTails());
System.out.println("One-head one-tail tosses: " + coinToss.getHeadTails());
System.out.println("Tosses add up correctly? " + (coinToss.getTwoHeads() + coinToss.getTwoTails() + coinToss.getHeadTails() == coinToss.getNumTrials()));
//Test case 3
coinToss.run(10);
System.out.println();
System.out.println("After run(10) ");
System.out.println("Number of trials [exp: 11]: " + coinToss.getNumTrials() );
System.out.println("Two-head tosses: " + coinToss.getTwoHeads());
System.out.println("Two-tail tosses: " + coinToss.getTwoTails());
System.out.println("One-head one-tail tosses: " + coinToss.getHeadTails());
System.out.println("Tosses add up correctly? " + (coinToss.getTwoHeads() + coinToss.getTwoTails() + coinToss.getHeadTails() == coinToss.getNumTrials()));
//Test case 4
coinToss.run(100);
System.out.println();
System.out.println("After run(111) ");
System.out.println("Number of trials [exp: 1]: " + coinToss.getNumTrials() );
System.out.println("Two-head tosses: " + coinToss.getTwoHeads());
System.out.println("Two-tail tosses: " + coinToss.getTwoTails());
System.out.println("One-head one-tail tosses: " + coinToss.getHeadTails());
System.out.println("Tosses add up correctly? " + (coinToss.getTwoHeads() + coinToss.getTwoTails() + coinToss.getHeadTails() == coinToss.getNumTrials()));
//Test case 5 -- After Reset
coinToss.reset();
System.out.println();
System.out.println("After reset: ");
System.out.println("Number of trials [exp: 1]: " + coinToss.getNumTrials() );
System.out.println("Two-head tosses: " + coinToss.getTwoHeads());
System.out.println("Two-tail tosses: " + coinToss.getTwoTails());
System.out.println("One-head one-tail tosses: " + coinToss.getHeadTails());
System.out.println("Tosses add up correctly? " + (coinToss.getTwoHeads() + coinToss.getTwoTails() + coinToss.getHeadTails() == coinToss.getNumTrials()));
//Test case 6
coinToss.run(1000);
System.out.println();
System.out.println("After run(1000): ");
System.out.println("Number of trials [exp: 1]: " + coinToss.getNumTrials() );
System.out.println("Two-head tosses: " + coinToss.getTwoHeads());
System.out.println("Two-tail tosses: " + coinToss.getTwoTails());
System.out.println("One-head one-tail tosses: " + coinToss.getHeadTails());
System.out.println("Tosses add up correctly? " + (coinToss.getTwoHeads() + coinToss.getTwoTails() + coinToss.getHeadTails() == coinToss.getNumTrials()));
//Test case 7
coinToss.run(1);
System.out.println();
System.out.println("After run(1) ");
System.out.println("Number of trials [exp: 1001]: " + coinToss.getNumTrials() );
System.out.println("Two-head tosses: " + coinToss.getTwoHeads());
System.out.println("Two-tail tosses: " + coinToss.getTwoTails());
System.out.println("One-head one-tail tosses: " + coinToss.getHeadTails());
System.out.println("Tosses add up correctly? " + (coinToss.getTwoHeads() + coinToss.getTwoTails() + coinToss.getHeadTails() == coinToss.getNumTrials()));
}
else {
System.out.println("ERROR: Number entered must be greater than 0.");
}
}
}
| true |
54367e1dcc8998dab643213db11229f9bd9c5dcc | Java | 6baobao9/NettyDemo | /src/com/gerry/netty/client/EchoClientHandler.java | UTF-8 | 1,305 | 2.78125 | 3 | [] | no_license | package com.gerry.netty.client;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;
public class EchoClientHandler extends SimpleChannelInboundHandler<ByteBuf> {
@Override
protected void channelRead0(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf) {
String receive = byteBuf.toString(CharsetUtil.UTF_8);
System.out.println("Client Receive:" + receive);
}
//与服务器建立连接
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
//给服务器发消息
ctx.channel().writeAndFlush(Unpooled.copiedBuffer("i am client !\n", CharsetUtil.UTF_8));
ctx.channel().flush();
System.out.println("channelActive");
}
//与服务器断开连接
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
System.out.println("channelInactive");
}
//异常
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
//关闭管道
ctx.channel().close();
//打印异常信息
cause.printStackTrace();
}
} | true |
3cd5f74ee569ecf4d79abac0c44ec78f4ead50b7 | Java | abutalal93/SchoolApp-Backend | /src/main/java/com/decoders/school/service/impl/SchoolServiceImpl.java | UTF-8 | 869 | 2.15625 | 2 | [] | no_license | package com.decoders.school.service.impl;
import com.decoders.school.entities.School;
import com.decoders.school.repository.SchoolRepo;
import com.decoders.school.service.SchoolService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
import java.util.List;
@Service
@Transactional
public class SchoolServiceImpl implements SchoolService {
@Autowired
private SchoolRepo schoolRepo;
@Override
public List<School> findAll() {
return schoolRepo.findAll();
}
@Override
public School findSchoolByUsername(String username) {
return schoolRepo.findSchoolByUsername(username);
}
}
| true |
6804cb7293b8843d199d99add710dd05b576d720 | Java | RenHaiRenWjc/JcDemoList | /app/src/main/java/com/wjc/jcdemolist/demo/mvp/mvpDagger2Demo01/login/di/LoginComponent.java | UTF-8 | 817 | 2.1875 | 2 | [] | no_license | package com.wjc.jcdemolist.demo.mvp.mvpDagger2Demo01.login.di;
import com.wjc.jcdemolist.demo.mvp.mvpDagger2Demo01.di.AppComponent;
import com.wjc.jcdemolist.demo.mvp.mvpDagger2Demo01.login.LoginActivity01;
import dagger.Component;
/**
* ClassName:com.wjc.jcdemolist.demo.mvp.mvpDagger2Demo01.login.di
* Description:注射器
* 以理解为快递员,那么他需要送的货物就是 modules 里面包含的包裹
* JcChen on 2019/7/13 16:38
*/
@Component(modules = LoginModule.class, dependencies = AppComponent.class)
public interface LoginComponent {
/**
* @param loginActivity01 目标容器
* inject的参数。。。不能是父类,必须是你注入的那个内
* 快递地址
*/
void inject(LoginActivity01 loginActivity01);
}
| true |
93c8d617d7ea8551d95b0bef23d8142ae8b04e7b | Java | renhuiyong/cocoker | /src/main/java/com/cocoker/beans/Recharge.java | UTF-8 | 875 | 1.789063 | 2 | [] | no_license | package com.cocoker.beans;
import com.cocoker.utils.serializer.DateFormatSerializer;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import lombok.Data;
import javax.persistence.*;
import java.math.BigDecimal;
import java.util.Date;
/**
* @Description:
* @Author: y
* @CreateDate: 2019/1/4 12:13 PM
* @Version: 1.0
*/
@Data
@Entity
@Table(name = "tbl_recharge")
public class Recharge {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer tid;
private BigDecimal tmoney;
private String tnickname;
private BigDecimal tyue;
private String topenid;
private Integer tstatus;
private String torderid;
//商户订单号
private String tsdorderno;
//平台订单号
private String tsdpayno;
@JsonSerialize(using = DateFormatSerializer.class)
private Date createTime;
}
| true |