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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
9f6a2a38704ba966f143d906aa1d6c619e382552 | Java | Pushkov/FX_2 | /src/main/java/calculate/Calculate.java | UTF-8 | 8,238 | 2.40625 | 2 | [] | no_license | package calculate;
import varianty.Variant;
import java.util.ArrayList;
import java.util.HashMap;
public class Calculate {
private double limitX1;
private double limitX2;
private double limitX3;
HashMap<String,Object> gruz;
byte kol;
public void setGruz(HashMap<String, Object> gruz, byte kol) {
this.gruz = gruz;
this.kol = kol;
}
public void calc(){
if (Truck.existTransport() & Trailer.existTransport()){
System.out.println("Ok");
} else System.out.println("Bad");
}
// public ArrayList<byte[]> generatedVariants (byte kol, byte inRow){ // Пока только для однотипного одинаково расположенного груза
// GenerateVariants gV = new GenerateVariants();
// ArrayList<byte []> suitableG = new ArrayList<>();
//// int vc = 0;
// for (int i = 0; i < gV.genVariants(kol,inRow).size(); i++) {
// byte[] current_variant = (byte[]) gV.genVariants(kol,inRow).get(i);
// if (getLoadedAP_X1(current_variant) < getLimitX1() &
// getLoadedAP_X2(current_variant) < getLimitX2() &
// getLoadedAP_X3(current_variant) < getLimitX3() &
// getGruz_VarLength(current_variant) < Trailer.getTransport_distPP_POGRUZ_L()){
// suitableG.add(current_variant);
// System.out.print(getLoadedAP_X1(current_variant) + " ** ");
// System.out.print(getLoadedAP_X2(current_variant) + " ** ");
// System.out.print(getLoadedAP_X3(current_variant));
// System.out.println("");
// }
// }
// return suitableG;
// }
public ArrayList<byte[]> genTest (byte kol, byte inRow){ // Пока только для однотипного одинаково расположенного груза
GenerateVariants gV = new GenerateVariants();
ArrayList<byte []> suitableG = new ArrayList<>();
// int vc = 0;
for (int i = 0; i < gV.genVariants(kol,inRow).size(); i++) {
byte[] current_variant = (byte[]) gV.genVariants(kol,inRow).get(i);
suitableG.add(current_variant);
// System.out.print(getLoadedAP_X1(current_variant) + " ** ");
// System.out.print(getLoadedAP_X2(current_variant) + " ** ");
// System.out.print(getLoadedAP_X3(current_variant));
// System.out.println("");
}
return suitableG;
}
// public ArrayList<byte[]> seqVariants(ArrayList<byte[]> arrayList){
//
// ArrayList<byte []> suitableG = new ArrayList<>();
//
// for (byte[] x: arrayList) {
// if (getGruz_VarLength(x) < Trailer.getTransport_distPP_POGRUZ_L() &
// getLoadedAP_X3(x) < getLimitX3() &
// getLoadedAP_X2(x) < getLimitX2() &
// getLoadedAP_X1(x) < getLimitX1() ) {
// suitableG.add(x);
// }
// }
// return suitableG;
// }
public double getLimitX1() {
return limitX1;
}
public void setLimitX1(double limitX1) {
this.limitX1 = limitX1;
}
public double getLimitX2() {
return limitX2;
}
public void setLimitX2(double limitX2) {
this.limitX2 = limitX2;
}
public double getLimitX3() {
return limitX3;
}
public void setLimitX3(double limitX3) {
this.limitX3 = limitX3;
}
// public double getGruz_FullMass(){ // Пока для одиночного груза будет так
// return Math.round((double)gruz.get("massG") * kol);
// }
public double getGruz_VarLength(byte[] current_variant){
double L=0;
for (byte x: current_variant){
if (x !=0) L += (double)gruz.get("lengthG");
}
return L;
}
// public double getGruzCT_var1(byte[] current_variant) {
// double dist_ct_row;
// double moment_row = 0;
// for (int i = 0; i < current_variant.length; i++) {
// dist_ct_row = (double)gruz.get("lengthG") * i + (double)gruz.get("lengthG") / 2;
// moment_row = moment_row + (dist_ct_row * (double)gruz.get("massG") * current_variant[i]);
// }
// return Math.round(moment_row / getGruz_FullMass());
// }
public double getEmptyAP_X1() {
return Math.round(Truck.getTransport_loadT_X1() + (Trailer.getTransport_loadPP_SEDLO() * Truck.getTransport_distT_SEDLO() / Truck.getTransport_distT_OSI()));
}
public double getEmptyAP_X2() {
return Math.round(Truck.getTransport_loadT_X2() + (Trailer.getTransport_loadPP_SEDLO() * (Truck.getTransport_distT_OSI() - Truck.getTransport_distT_SEDLO()) / Truck.getTransport_distT_OSI()));
}
public double getEmptyAP_X3() {
return Math.round(Trailer.getTransport_loadPP_TEL());
}
public double getLoadedAP_X1(Variant variant) {
double distG_BORT = 0;
double distG_CT_BORT = distG_BORT + variant.getVariantCT() - Trailer.getTransport_distPP_BORT(); //фактическое положение центра тяжести груза на полуприцепе
double loadG_SEDLO = variant.getVariantMass()*(Trailer.getTransport_distPP_OSI()-distG_CT_BORT)/Trailer.getTransport_distPP_OSI();// нагрузка от груза на седельное устройство
return Math.round(Truck.getTransport_loadT_X1() + ((Trailer.getTransport_loadPP_SEDLO() + loadG_SEDLO) * Truck.getTransport_distT_SEDLO() / Truck.getTransport_distT_OSI()));
}
public double getLoadedAP_X2(Variant variant) {
double distG_BORT = 0;
double distG_CT_BORT = distG_BORT + variant.getVariantCT() - Trailer.getTransport_distPP_BORT(); //фактическое положение центра тяжести груза на полуприцепе
double loadG_SEDLO = Math.round( variant.getVariantMass()*(Trailer.getTransport_distPP_OSI()-distG_CT_BORT)/Trailer.getTransport_distPP_OSI());// нагрузка от груза на седельное устройство
return Math.round(Truck.getTransport_loadT_X2() + ((Trailer.getTransport_loadPP_SEDLO() + loadG_SEDLO) * (Truck.getTransport_distT_OSI() - Truck.getTransport_distT_SEDLO()) / Truck.getTransport_distT_OSI()));
}
public double getLoadedAP_X3(Variant variant) {
double distG_BORT = 0;
double distG_CT_BORT = distG_BORT + variant.getVariantCT() - Trailer.getTransport_distPP_BORT(); //фактическое положение центра тяжести груза на полуприцепе
double loadG_TEL =Math.round(variant.getVariantMass() * (distG_CT_BORT / Trailer.getTransport_distPP_OSI()));// нагрузка от груза на седельное устройство
return Math.round(Trailer.getTransport_loadPP_TEL() + loadG_TEL);
}
// double getGruzCT_optimal (byte[] current_variant){
// double koef = getLimitX2()/getLimitX3();
// double q1 = getEmptyAP_X2() + getGruz_FullMass()*((double)1-(Truck.getTransport_distT_SEDLO() / Truck.getTransport_distT_OSI())) - Trailer.getTransport_loadPP_TEL() * koef;
// double q2 = (getGruz_FullMass() / Trailer.getTransport_distPP_OSI())*(koef+1)
// - (getGruz_FullMass() * Truck.getTransport_distT_SEDLO()) /(Trailer.getTransport_distPP_OSI() * Truck.getTransport_distT_OSI());
// double distCT_bort = q1/q2;
//// System.out.println("* " + distCT_bort + " q1 = " + q1 + " q2 = " + q2 );
// return distCT_bort + Trailer.getTransport_distPP_BORT() - getGruzCT_var1(current_variant);
// }
public double getNedogruz_X1 (Variant current_variant){
return Math.round((1 - getLoadedAP_X1(current_variant) / limitX1)*100);
}
public double getNedogruz_X2 (Variant current_variant){
return Math.round((1 - getLoadedAP_X2(current_variant) / limitX2)*100);
}
public double getNedogruz_X3 (Variant current_variant){
return Math.round((1 - getLoadedAP_X3(current_variant) / limitX3)*100);
}
}
| true |
66913b82f61778ddc42a66c33abfbbdea2ee59c2 | Java | dbi1463/async-test | /async-server/src/main/java/tw/funymph/async/server/SleepyRepository.java | UTF-8 | 1,716 | 2.578125 | 3 | [
"MIT"
] | permissive | package tw.funymph.async.server;
import static java.lang.Thread.sleep;
import static java.util.concurrent.CompletableFuture.runAsync;
import static java.util.concurrent.CompletableFuture.supplyAsync;
import static java.util.concurrent.Executors.newVirtualThreadPerTaskExecutor;
import static tw.funymph.async.server.Config.virtualThreadedRepository;
import static tw.funymph.async.server.RequestTracker.track;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.function.Supplier;
@SuppressWarnings("preview")
public class SleepyRepository {
private ExecutorService executor = newVirtualThreadPerTaskExecutor();
int count(final String requestId) {
track(requestId, "SleepyRepository::count");
asleep(1000, requestId);
return 1;
}
void save(final String requestId) {
track(requestId, "SleepyRepository::save");
asleep(1000, requestId);
}
CompletableFuture<Integer> countAsync(final String requestId) {
Supplier<Integer> supplier = () -> {
track(requestId, "SleepyRepository::supplyAsync::count");
return this.count(requestId);
};
return virtualThreadedRepository ? supplyAsync(supplier, executor) : supplyAsync(supplier);
}
CompletableFuture<Void> saveAsync(final String requestId) {
Runnable runnable = () -> {
track(requestId, "SleepyRepository::supplyAsync::save");
this.save(requestId);
};
return virtualThreadedRepository ? runAsync(runnable, executor) : runAsync(runnable);
}
private void asleep(final long milliseconds, final String requestId) {
try {
track(requestId, "SleepyRepository::sleep");
sleep(milliseconds);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
| true |
7bb08ef8af3bfc11257c15b1e505d21a6393ae07 | Java | abiquo/abiquo | /api/src/main/java/com/abiquo/api/tracer/hierarchy/HierarchyProcessor.java | UTF-8 | 1,286 | 1.945313 | 2 | [] | no_license | /**
* Abiquo community edition
* cloud management application for hybrid clouds
* Copyright (C) 2008-2010 - Abiquo Holdings S.L.
*
* This application is free software; you can redistribute it and/or
* modify it under the terms of the GNU LESSER GENERAL PUBLIC
* LICENSE as published by the Free Software Foundation under
* version 3 of the License
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* LESSER GENERAL PUBLIC LICENSE v.3 for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
package com.abiquo.api.tracer.hierarchy;
import java.util.Map;
/**
* Processes hierarchy URIs to extract resource data.
*
* @author ibarrera
*/
public interface HierarchyProcessor
{
/**
* Processes the given URI to extract the resource data.
*
* @param uri The URI to process.
* @param resourceData The acumulated resource data.
*/
public void process(String uri, Map<String, String> resourceData);
}
| true |
1ad914d4fb9a4e3386fb4206e9486efb1131a88b | Java | SpartanSpark/diseasesimulator | /data/Person.java | UTF-8 | 4,432 | 2.40625 | 2 | [] | no_license | package data;
import static helpers.Artist.*;
import java.util.concurrent.CopyOnWriteArrayList;
import org.newdawn.slick.opengl.Texture;
import helpers.SmartAI;
import items.Item;
import helpers.Artist;
public class Person extends DiseaseEntity {
public boolean bdParty, concert, building;
public float age, size, mx, my;
public int buildingCycles;
public Person child;
public Entity t;
public String gender;
private SmartAI s;
private CopyOnWriteArrayList<Item> items;
public Person(int x, int y, float age) {
super(x, y);
if(Math.random() > 0.5) gender = "male";
else gender = "female";
super.cycles = (int) (age * 100);
this.age = age;
grow();
s = new SmartAI(this);
}
@Override
public boolean infect() {
if(!super.sick) {
World.infected++;
return super.infect();
}
return false;
}
public float getSusceptibility() {
if(age < 4 || age > 65) return 2;
else return 1;
}
public void infectthis(DiseaseEntity d) {
d.infect();
}
public Person with(CopyOnWriteArrayList<Item> items) {
this.items = items;
return this;
}
public Person breed(Person parent) {
Person child = new Person((super.x+parent.x)/2,(super.y+parent.y)/2,0);
if(super.sick || parent.sick) child.sick = true;
this.child = child;
parent.child = child;
return child;
}
@Override
public void die() {
super.die();
World.curPop--;
if(super.sick) World.infected--;
}
private void age() {
age+=0.00002777777;
}
private void move() {
mx = 0;
my = 0;
if(t != null) {
if(t.x - super.x != 0) mx += (float) ((t.x - super.x)*(Math.random()*0.5)/Math.abs(t.x - super.x));
if(t.y - super.y != 0) my += (float) ((t.y - super.y)*(Math.random()*0.5)/Math.abs(t.y - super.y));
}
if(child != null && child.age < 4) {
if(child.x - super.x!= 0) mx += (float) ((child.x - super.x)*(Math.random()*0.25)/Math.abs(child.x - super.x));
if(child.y - super.y!= 0) my += (float) ((child.y - super.y)*(Math.random()*0.25)/Math.abs(child.y - super.y));
}
if(super.cycles % 23 == 0 || super.cycles % 41 == 0) {
mx += (float) ((Math.random() * 1) - 0.25);
my += (float) ((Math.random() * 1) - 0.25);
}
if(t == null) {
mx *= 2;
my *= 2;
}
super.x += s.mx(null, t, child, (float) (Math.random()*2));
super.y += s.my();
}
@Override
public void update(int tx, int ty, float zm) {
super.update(tx, ty, size);
if(building) buildingCycles++;
if(alive) {
if(super.sick && items != null) for(Item i : items) if(this.doesCollide(i)) i.infect();
// if(age >= 65 && Math.random() > 0.99992) die();
// if(super.sick && Math.random() > 0.9999) die();
age();
grow();
move();
draw(super.x-tx,super.y-ty,size*zm);
// Sanitizer
// if((super.cycles % 2493 == 0 || super.cycles % 2171 == 0) && Math.random() > 0.97) {
// if(super.sick) World.infected--;
// super.sick = false;
// }
// Washing Hands
// if((buildingCycles % 7493 == 100 || buildingCycles % 8171 == 100) && Math.random() > 0.95) {
// if(super.sick) World.infected--;
// super.sick = false;
// }
}
}
private void grow() {
if (age < 35) size = (float) age * 2;
else size = 35 * 2;
}
@Override
public void draw(int ax, int ay, float size) {
if(ax >= 0 && ax < Width && ay >= 0 && ay < Height) {
if(bdParty) DrawQuadTex(Artist.birthday, ax-size/4,ay-size,size/2,size/2);
if(concert) DrawQuadTex(Artist.concert, ax-size/4,ay-size,size/2,size/2);
DrawQuadTex(findTex(), ax-size/2,ay-size/2,size,size);
}
}
private Texture findTex() {
if(age < 4) {
if(gender == "male" && sick) return maleChildSick;
if(gender == "male" && !sick) return maleChild;
if(gender == "female" && sick) return femaleChildSick;
if(gender == "female" && !sick) return femaleChild;
} else if(age > 65) {
if(gender == "male" && sick) return maleOldSick;
if(gender == "male" && !sick) return maleOld;
if(gender == "female" && sick) return femaleOldSick;
if(gender == "female" && !sick) return femaleOld;
} else {
if(gender == "male" && sick) return maleSick;
if(gender == "male" && !sick) return male;
if(gender == "female" && sick) return femaleSick;
if(gender == "female" && !sick) return female;
}
return black;
}
}
| true |
adb08f66d4840918dcb456b0660e93155afe4a3f | Java | absn2/loja_acai | /src/produtos/ProdutoJaCadastrado.java | UTF-8 | 144 | 2.140625 | 2 | [] | no_license | package produtos;
public class ProdutoJaCadastrado extends Exception {
public ProdutoJaCadastrado() {
super("Produto ja cadastrado");
}
}
| true |
bd1e228881b5e38f85a898b3463d0e426c737f9c | Java | payencai/MicaiW | /app/src/main/java/cn/micaiw/mobile/activity/AmendLoginPswActivity.java | UTF-8 | 5,639 | 1.890625 | 2 | [] | no_license | package cn.micaiw.mobile.activity;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
import butterknife.BindView;
import butterknife.OnClick;
import cn.micaiw.mobile.R;
import cn.micaiw.mobile.base.component.BaseActivity;
import cn.micaiw.mobile.constant.PlatformContans;
import cn.micaiw.mobile.custom.KyLoadingBuilder;
import cn.micaiw.mobile.http.HttpProxy;
import cn.micaiw.mobile.http.ICallBack;
import cn.micaiw.mobile.sharedpre.UserInfoSharedPre;
import cn.micaiw.mobile.util.ActivityManager;
import cn.micaiw.mobile.util.ToaskUtil;
public class AmendLoginPswActivity extends BaseActivity {
@BindView(R.id.backImg)
ImageView backImg;
@BindView(R.id.title)
TextView title;
@BindView(R.id.messageImg)
ImageView messageImg;
@BindView(R.id.boundPhoneNumber)
TextView boundPhoneNumber;
@BindView(R.id.submit)
Button submit;
@BindView(R.id.primevalPassword)
EditText primevalPassword;
@BindView(R.id.newPassword)
EditText newPassword;
private String mTel;
private int count = 5;//原始密码修改错误次数
private KyLoadingBuilder mLoadView;
@Override
protected int getContentViewId() {
return R.layout.activity_amend_login_psw;
}
@Override
protected void init(Bundle savedInstanceState) {
super.init(savedInstanceState);
title.setText("修改登录密码");
backImg.setVisibility(View.VISIBLE);
messageImg.setVisibility(View.GONE);
initView();
}
private void initView() {
mTel = getIntent().getStringExtra("tel");
if (!TextUtils.isEmpty(mTel)) {
boundPhoneNumber.setText("当前手机号:" + mTel);
}
}
@OnClick({R.id.backImg, R.id.submit})
public void onViewClicked(View view) {
switch (view.getId()) {
case R.id.backImg:
finish();
break;
case R.id.submit:
if (checkAll()) {
requestData();
}
break;
}
}
private boolean checkAll() {
String password = primevalPassword.getEditableText().toString();
String pwd = newPassword.getEditableText().toString();
String savePassword = UserInfoSharedPre.getIntance(this).getPassword();
if (TextUtils.isEmpty(password)) {
ToaskUtil.showToast(this, "请输入原始密码");
return false;
}
if (TextUtils.isEmpty(pwd)) {
ToaskUtil.showToast(this, "请输入新密码");
return false;
}
if (pwd.length() < 6) {
ToaskUtil.showToast(this, "密码长度必须大于6位");
return false;
}
if (!password.equals(savePassword)) {
count--;
ToaskUtil.showToast(this, "原始密码错误,当前还可以输入:" + count + "次");
if (count <= 0) {
ToaskUtil.showToast(this, "操作频繁,休息一下吧");
finish();
return false;
}
return false;
}
return true;
}
private void requestData() {
String password = primevalPassword.getEditableText().toString();
String pwd = newPassword.getEditableText().toString();
Map<String, Object> paramsMap = new HashMap<>();
Map<String, Object> tokenMap = new HashMap<>();
UserInfoSharedPre intance = UserInfoSharedPre.getIntance(this);
String token = intance.getToken();
if (TextUtils.isEmpty(token)) {
ToaskUtil.showToast(this, "您还未登录");
return;
}
paramsMap.put("userName", mTel);
paramsMap.put("password", password);//原始密码
paramsMap.put("pwd", pwd);//新密码
tokenMap.put("token", token);
mLoadView = openLoadView("");
HttpProxy.obtain().post(PlatformContans.User.sUpdatePasswordByUserName, tokenMap, paramsMap, new ICallBack() {
@Override
public void OnSuccess(String result) {
if (mLoadView != null) {
mLoadView.dismiss();
}
try {
JSONObject object = new JSONObject(result);
int resultCode = object.getInt("resultCode");
String message = object.getString("message");
if (resultCode == 0) {
ToaskUtil.showToast(AmendLoginPswActivity.this, message + ",请重新登录");
UserInfoSharedPre.getIntance(AmendLoginPswActivity.this).clearUserInfo();
ActivityManager.getInstance().finishAllActivity();
startActivity(new Intent(AmendLoginPswActivity.this, LoginActivity.class));
} else {
ToaskUtil.showToast(AmendLoginPswActivity.this, message);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(String error) {
if (mLoadView != null) {
mLoadView.dismiss();
}
}
});
}
}
| true |
7024ef124dd626fc560bd09b73c57d2dac91441d | Java | chopkinz/COMP-1213 | /Activities/Activity_09/OnlineTextItem.java | UTF-8 | 515 | 3.0625 | 3 | [] | no_license | /**
* Online text item program for Activity_09.
*
* @author Chase Hopkins - COMP-1213 - Activity_09
* @version 3/30/21
*/
public abstract class OnlineTextItem extends InventoryItem {
/**
* constructor.
*
* @param nameIn input for name
* @param priceIn input for price
*/
public OnlineTextItem(String nameIn, double priceIn) {
super(nameIn, priceIn);
}
/**
* calculates the cost.
* @return returns the price.
*/
public double calculateCost() {
return price;
}
} | true |
5357f34af2c2cf9e506beabfa142913e765698b5 | Java | phobus/plantero | /backend/src/main/java/io/home/plantero/config/FacadeConfig.java | UTF-8 | 1,149 | 2 | 2 | [
"Apache-2.0"
] | permissive | package io.home.plantero.config;
import io.home.plantero.application.PlantService;
import io.home.plantero.application.SpeciesService;
import io.home.plantero.interfaces.api.facade.LifeTimeServiceFacade;
import io.home.plantero.interfaces.api.facade.internal.LifeTimeServiceFacadeImpl;
import io.home.plantero.interfaces.api.facade.PlantServiceFacade;
import io.home.plantero.interfaces.api.facade.SpeciesServiceFacade;
import io.home.plantero.interfaces.api.facade.internal.PlantServiceFacadeImpl;
import io.home.plantero.interfaces.api.facade.internal.SpeciesServiceFacadeImpl;
import org.springframework.context.annotation.Bean;
public class FacadeConfig {
@Bean
public SpeciesServiceFacade speciesRestServiceFacade(SpeciesService speciesService) {
return new SpeciesServiceFacadeImpl(speciesService);
}
@Bean
public PlantServiceFacade plantRestServiceFacade(PlantService plantService) {
return new PlantServiceFacadeImpl(plantService);
}
@Bean
public LifeTimeServiceFacade lifeTimeServiceFacade(PlantService plantService) {
return new LifeTimeServiceFacadeImpl(plantService);
}
}
| true |
29f831ef7afd73b5abe86197bb77d963ef093019 | Java | eee269/Project | /src/board/BoardReplyDAO.java | UTF-8 | 3,910 | 2.625 | 3 | [] | no_license | package board;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class BoardReplyDAO {
Connection con;
String sql;
PreparedStatement pr;
ResultSet rs;
public Connection getConnection() throws ClassNotFoundException, SQLException {
con = null;
Class.forName("com.mysql.jdbc.Driver");
String dbUrl = "jdbc:mysql://localhost:3306/jspyj";
String dbUser = "testid";
String dbPass = "testpass";
con = DriverManager.getConnection(dbUrl, dbUser, dbPass);
return con;
}
public BoardReplyBean getBoardReply(int reno) {
BoardReplyBean brb = null;
try{
con = getConnection();
sql = "select * from board_reply where reno = ?";
pr = con.prepareStatement(sql);
pr.setInt(1, reno);
rs = pr.executeQuery();
if(rs.next()) {
brb = new BoardReplyBean();
brb.setBrdno(rs.getInt("brdno"));
brb.setReno(rs.getInt("reno"));
brb.setRememo(rs.getString("rememo"));
brb.setRewriter(rs.getString("rewriter"));
brb.setRedate(rs.getTimestamp("redate"));
}
} catch (Exception e) {
e.printStackTrace();
}
return brb;
}
public List getBoardReplyList() {
List boardReplyList = new ArrayList();
try {
con = getConnection();
sql = "select * from board_reply order by reno";
pr = con.prepareStatement(sql);
rs = pr.executeQuery();
while(rs.next()) {
BoardReplyBean brb = new BoardReplyBean();
brb.setBrdno(rs.getInt("brdno"));
brb.setReno(rs.getInt("reno"));
brb.setRewriter(rs.getString("rewriter"));
brb.setRedate(rs.getTimestamp("redate"));
brb.setRememo(rs.getString("rememo"));
boardReplyList.add(brb);
}
} catch (Exception e) {
e.printStackTrace();
}
return boardReplyList;
}
public void insertBoardReply(BoardReplyBean brb) {
try{
con = getConnection();
sql="select max(reno) from board_reply";
pr = con.prepareStatement(sql);
rs = pr.executeQuery();
int num=0;
if(rs.next()) {
num = rs.getInt("max(reno)")+1;
}
sql = "INSERT INTO board_reply(brdno, reno, rewriter, rememo, redate)" +
"values(?, ?, ?, ?, ?)";
pr = con.prepareStatement(sql);
pr.setInt(1, brb.getBrdno());
pr.setInt(2, num);
pr.setString(3, brb.getRewriter());
pr.setString(4, brb.getRememo());
pr.setTimestamp(5, brb.getRedate());
pr.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}
}
public void updateBoardReply(BoardReplyBean brb) {
try{
con = getConnection();
sql = "UPDATE board_reply SET rememo = ? WHERE reno = ? and rewriter = ?";
pr = con.prepareStatement(sql);
pr.setString(1, brb.getRememo());
pr.setInt(2, brb.getReno());
pr.setString(3, brb.getRewriter());
pr.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}
}
public void deleteBoardReply(int reno, String rewriter) {
try{
con = getConnection();
sql = "DELETE FROM board_reply WHERE reno=? and rewriter=?";
pr = con.prepareStatement(sql);
pr.setInt(1, reno);
pr.setString(2, rewriter);
pr.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}
}
}
| true |
93592bca50210902f54760948d87fac9366f7027 | Java | ManojGollamudi/FretTeacher | /app/src/main/java/com/manojgollamudi/fretteacher/End.java | UTF-8 | 2,508 | 2.328125 | 2 | [] | no_license | package com.manojgollamudi.fretteacher;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class end extends AppCompatActivity{
int fretnos = 0;
boolean lefty_bool = false;
boolean sound_bool = true;
int score;
int total;
String Saved_Data = "Saved_Data";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_end);
TextView textview = (TextView)findViewById(R.id.result);
Button b = (Button)findViewById(R.id.return_button);
b.setBackgroundResource(R.drawable.border_tan);
Intent end_intent = getIntent();
score = end_intent.getIntExtra("score_value", -1);
total = end_intent.getIntExtra("total_value", -1);
fretnos = end_intent.getIntExtra("fretnos", -1);
String score_string = score + "/" + total;
textview.setText(score_string);
updateScore();
}
//for return to menu button
public void returnMenu(View view){
Intent return_intent = new Intent(this, gameList.class);
return_intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(return_intent);
finish();
}
//for restart button
public void restart(View view) {
Intent end_intent = getIntent();
fretnos = end_intent.getIntExtra("fretnos", -1);
lefty_bool = end_intent.getBooleanExtra("lefty_bool", false);
sound_bool = end_intent.getBooleanExtra("sound_bool", false);
Intent restart_intent = new Intent(this, quiz.class);
restart_intent.putExtra("fretnos", fretnos);
restart_intent.putExtra("lefty_bool", lefty_bool);
restart_intent.putExtra("sound_bool", sound_bool);
startActivity(restart_intent);
finish();
}
public void updateScore(){
SharedPreferences sharedpreferences = getSharedPreferences(Saved_Data, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
String fretnos_string = "" + fretnos;
int old_score = sharedpreferences.getInt(fretnos_string, 0);
if(old_score == 0 || score > old_score){
editor.putInt(fretnos_string, score);
}
editor.apply();
}
}
| true |
cbd88f80afd56c1639c641cb5a7f7f4b7cc418f8 | Java | semih-git/webdriveruniversity | /src/main/java/org/cb/ta/ToDoList.java | UTF-8 | 1,957 | 2.640625 | 3 | [] | no_license | package org.cb.ta;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
public class ToDoList {
WebDriver driver;
WebElement toDoListElement;
public ToDoList() {
this.driver = Driver.getdriver();
driver.get("http://www.webdriveruniversity.com/To-Do-List/index.html");
webElementDefination();
}
public void webElementDefination(){
toDoListElement=driver.findElement(By.xpath("//i[@ id='plus-icon']"));
}
public void clickPlus() throws InterruptedException {
System.out.println(toDoListElement.getText());
toDoListElement.isDisplayed();
toDoListElement.click();
Thread.sleep(1000);
toDoListElement.click();
}
public void addNewToDo() throws InterruptedException {
toDoListElement = driver.findElement(By.xpath("//input[@placeholder='Add new todo']"));
toDoListElement.clear();
toDoListElement.sendKeys("ABC");
Thread.sleep(1000);
toDoListElement.clear();
toDoListElement.sendKeys("do Something");
Thread.sleep(1000);
//toDoListElement.sendKeys(Keys.RETURN); // RETURN yada ENTER ikiside olabilir.
toDoListElement.sendKeys(Keys.ENTER);
}
public void deleteToDo() {
toDoListElement=driver.findElement(By.xpath("//li[contains(text(),'Buy new robes')]"));
toDoListElement.click();
}
public boolean isTaskDisplayed(String taskName){
return driver.findElement(By.xpath("//ul/li[contains(text(), '"+ taskName +"')]")).isDisplayed();
}
public boolean deleteOneTask(String taskName) {
if (isTaskDisplayed(taskName)){
WebElement trashButton = driver.findElement(By.xpath("//*/ul/li[contains(text(), '"+taskName+"')]/span/i"));
trashButton.click();
return true;
}
return false;
}
}
| true |
c6f97c31aa7d1df546370286952b26fb26ddec63 | Java | muleforge/Mule-IDE | /src/main/org.mule.ide.launching/src/org/mule/ide/launching/MuleBreakpoint.java | UTF-8 | 710 | 1.703125 | 2 | [] | no_license | /**
* $Id$
* --------------------------------------------------------------------------------------
* Copyright (c) MuleSource, Inc. All rights reserved. http://www.mulesource.com
*
* The software in this package is published under the terms of the MuleSource MPL
* license, a copy of which has been included with this distribution in the
* MULE_LICENSE.txt file.
*/
package org.mule.ide.launching;
import org.eclipse.debug.core.model.Breakpoint;
public class MuleBreakpoint extends Breakpoint {
public final static String MODEL_IDENTIFIER = "org.mule.ide.launching.breakpoint";
public MuleBreakpoint() {
super();
}
public String getModelIdentifier() {
return MODEL_IDENTIFIER;
}
}
| true |
875acdd7e768ea3b657ecc5031cce7331e7f672e | Java | jdferron2/FF_Portal | /src/main/java/com/jdf/ff_portal/views/AdminView.java | UTF-8 | 6,903 | 2.203125 | 2 | [] | no_license | package com.jdf.ff_portal.views;
import com.jdf.ff_portal.UI.elements.ConfirmButton;
import com.jdf.ff_portal.backend.PlayerService;
import com.jdf.ff_portal.backend.SbfTeamService;
import com.jdf.ff_portal.backend.data.DraftRank;
import com.jdf.ff_portal.backend.data.DraftRankings;
import com.jdf.ff_portal.backend.data.Player;
import com.jdf.ff_portal.backend.data.Players;
import com.jdf.ff_portal.backend.data.SbfRank;
import com.jdf.ff_portal.backend.data.SbfTeam;
import com.jdf.ff_portal.utils.LeagueInfoManager;
import com.jdf.ff_portal.utils.RestAPIUtils;
import com.vaadin.navigator.View;
import com.vaadin.navigator.ViewChangeListener.ViewChangeEvent;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Button.ClickListener;
import com.vaadin.ui.ComboBox;
import com.vaadin.ui.GridLayout;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.Notification;
import com.vaadin.ui.UI;
import com.vaadin.ui.VerticalLayout;
@SuppressWarnings("serial")
public class AdminView extends VerticalLayout implements View {
public static final String NAME = "Admin Functions";
private ComboBox<Integer> team1PickSelector = createTradeBox(1);
private ComboBox<Integer> team2PickSelector = createTradeBox(2);
private ComboBox<SbfTeam> team1Selector = this.createTeamSelectorCB("Team 1", team1PickSelector);
private ComboBox<SbfTeam> team2Selector = this.createTeamSelectorCB("Team 2",team2PickSelector);
private Button processTrade = new Button("Process Trade");
private GridLayout tradeLayout = new GridLayout(3,3);
private boolean viewBuilt = false;
@Override
public void enter(ViewChangeEvent event) {
if(!viewBuilt){
buildView();
viewBuilt=true;
}
}
private void buildView(){
setSpacing(true);
setMargin(true);
Button resetPlayerList = new Button("Reset Players Table");
resetPlayerList.addClickListener(new ClickListener() {
private static final long serialVersionUID = 1L;
public void buttonClick(ClickEvent event) {
//delete current player table
PlayerService.getInstance().deleteAllPlayers();
//re-load active players from api
Players players = RestAPIUtils.getInstance().invokeQueryPlayers();
for(Player player : players.getPlayers()){
if (player.getActive() == 1){
PlayerService.getInstance().insertPlayer(player);
}
}
//set pro ranks for all players
DraftRankings ranks = RestAPIUtils.getInstance().invokeQueryRanks();
for(DraftRank rank: ranks.getDraftRanks()){
Player player = PlayerService.getInstance().getPlayerById(rank.getPlayerId());
if (player != null){
player.setProRank(rank.getProRank());
PlayerService.getInstance().updatePlayer(player);
}
}
int newPlayerRank = 1000;
for (Player p : PlayerService.getInstance().getAllPlayers()){
if (p.getProRank() == 0){
p.setProRank(PlayerService.getInstance().getMaxProRank()+1);
PlayerService.getInstance().updatePlayer(p);
}
if (PlayerService.getInstance().getSbfRankById(p.getPlayerId()) == null){
SbfRank rank = new SbfRank(1, p.getPlayerId(), newPlayerRank++);
PlayerService.getInstance().insertSbfRank(rank);
}
}
Notification.show("Player list update successfully!");;
}
});
ConfirmButton resetMyRanks = new ConfirmButton("Reset My Ranks");
resetMyRanks.setConfirmationText("This will reset custom ranks to the default pro ranks.");
resetMyRanks.addClickListener(new ClickListener() {
private static final long serialVersionUID = 1L;
public void buttonClick(ClickEvent event) {
//delete current ranks
PlayerService.getInstance().deleteAllSbfRanks(1);
//add default ranks based on pro ranks
for(Player player : PlayerService.getInstance().getAllPlayers()){
SbfRank rank = new SbfRank(1, player.getPlayerId(), player.getProRank());
PlayerService.getInstance().insertSbfRank(rank);
}
Notification.show("Ranks updated successfully!");
}
});
processTrade.addClickListener(new ClickListener() {
private static final long serialVersionUID = 1L;
public void buttonClick(ClickEvent event) {
if(team2PickSelector.getValue()!= null){
LeagueInfoManager.getInstance().addPickToTeam(team1Selector.getValue(), team2PickSelector.getValue());
}
if(team1PickSelector.getValue()!=null){
LeagueInfoManager.getInstance().addPickToTeam(team2Selector.getValue(), team1PickSelector.getValue());
}
team1PickSelector.clear();
team2PickSelector.clear();
team1Selector.clear();
team2Selector.clear();
Notification.show("Trade Processed successfully!");
}
});
processTrade.setVisible(false);
tradeLayout.addComponent(team1Selector,0,0);
tradeLayout.addComponent(team2Selector,1,0);
tradeLayout.addComponent(processTrade, 1,2);
team1PickSelector.setVisible(false);
team2PickSelector.setVisible(false);
tradeLayout.addComponent(team1PickSelector,0,1);
tradeLayout.addComponent(team2PickSelector,1,1);
HorizontalLayout buttonLayout = new HorizontalLayout();
buttonLayout.addComponents(resetPlayerList, resetMyRanks);
addComponents(buttonLayout, new Label("PROCESS TRADE"), tradeLayout);
}
public ComboBox<Integer> createTradeBox(int teamId){
ComboBox<Integer> teamPicksCB = new ComboBox<Integer>("Picks");
teamPicksCB.setItemCaptionGenerator(
i->"Pick: " + Integer.toString(i) + " (r" +
Integer.toString(LeagueInfoManager.getInstance().getRound(i))+
" p" + LeagueInfoManager.getInstance().getPickInRound(i) + ")");
teamPicksCB.setItems(LeagueInfoManager.getInstance().getPicksForTeam(teamId));
teamPicksCB.addValueChangeListener(event-> {
setSubmitVisible();
});
return teamPicksCB;
}
public ComboBox<SbfTeam> createTeamSelectorCB(String name, ComboBox<Integer> connectedBox){
ComboBox<SbfTeam> teamCB = new ComboBox<SbfTeam>(name);
teamCB.setItems(SbfTeamService.getInstance().getAllSbfTeams());
teamCB.setItemCaptionGenerator(SbfTeam::getOwnerName);
teamCB.addValueChangeListener(event-> {
if(event.getValue()!= null){
connectedBox.clear();
connectedBox.setItems(LeagueInfoManager.getInstance().getPicksForTeam(event.getValue().getSbfId()));
connectedBox.setVisible(true);
setSubmitVisible();
}else{
connectedBox.clear();
connectedBox.setVisible(false);
setSubmitVisible();
}
});
return teamCB;
}
public void setSubmitVisible(){
if ((team1PickSelector.getValue() != null || team2PickSelector.getValue() != null) &&
(team1Selector.getValue() !=null && team2Selector.getValue() !=null)){
processTrade.setVisible(true);
}else{
processTrade.setVisible(false);
}
}
}
| true |
4437d7f49e8262fad5fcc9354538eda4bc76ab2b | Java | bellmit/jigsaw-cms | /portal/source/framework/source/com/fulong/longcon/system/Configuration.java | UTF-8 | 835 | 2.109375 | 2 | [] | no_license | package com.fulong.longcon.system;
/**
* <p>Title: 龙驭网站内容管理系统核心引擎</p>
*
* <p>Description: 龙驭网站内容管理系统核心引擎</p>
*
* <p>Copyright: 北京中科辅龙计算机技术有限公司 2006</p>
*
* <p>Company: 北京中科辅龙计算机技术有限公司</p>
*
* @author <a href='mailto:lixf@fulong.com.cn'>lixf</a>
* @version 2.0
*/
public interface Configuration {
/**
* 全局属性
* @param name String
* @return String
*/
public String getProperty(String name);
/**
* 获取已激活的模块列表
* @param name String
* @return Module
*/
public Module[] getActiveModules(String position);
/**
* 根据Id来获取模块
* @param id String
* @return Module
*/
public Module getModule(String id);
}
| true |
7e675c9bbddeea6f0ed08fddd23e05fd0bd73ef5 | Java | syedfuzail18/worldpay-test | /worldFood/src/main/java/com/example/worldfood/order/ThreeDsResponse.java | UTF-8 | 728 | 2.21875 | 2 | [] | no_license | package com.example.worldfood.order;
import com.worldpay.ResponseError;
import com.worldpay.WorldPayError;
/**
* 3-D Secure callback methods.
*/
interface ThreeDsResponse {
/**
* Callback invoked if the transaction was successful.
*
* @param response The 3-D Secure response.
*/
void onSuccess(final String response);
/**
* Callback invoked if the transaction failed.
*
* @param responseError The {@link ResponseError}.
*/
void onResponseError(final ResponseError responseError);
/**
* Callback invoked if the transaction failed.
*
* @param worldPayError The {@link WorldPayError}.
*/
void onError(final WorldPayError worldPayError);
}
| true |
83e44d60f220d28f0baec7d6dc8534b8e42fd1cb | Java | Voloodya/fast_water_web_java | /src/main/java/config/MainWebAppInitializer.java | UTF-8 | 1,549 | 2.359375 | 2 | [] | no_license | package config;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
//Класс инициализатор для загрузки приложения, который загружает конфигурацию WEB and Spring
//WebApplicationInitializer реализации обнаруживаются автоматически, поэтому можно свободно упаковывать их в свое приложение по своему усмотрению
public class MainWebAppInitializer implements WebApplicationInitializer {
@Override
public void onStartup(final ServletContext servletContext) throws ServletException {
// Load Spring web application configuration
AnnotationConfigWebApplicationContext context =
new AnnotationConfigWebApplicationContext();
context.register(HibernateConfig.class, WebConfig.class,SpringConfig.class);
context.setServletContext(servletContext);
// Create and register the DispatcherServlet
DispatcherServlet servlet = new DispatcherServlet(context);
ServletRegistration.Dynamic dispather =
servletContext.addServlet("dispather", servlet);
dispather.setLoadOnStartup(1);
dispather.addMapping("/");
}
}
| true |
b325e5302295fcad7ecae731dd4d0fd1ef30c9fc | Java | HiraogluMatt/java-practice | /src/day19_loops_continued/Amazon.java | UTF-8 | 422 | 3.390625 | 3 | [] | no_license | package day19_loops_continued;
public class Amazon {
public static void main(String[] args) {
/*
*
* convert Amazon to azonAm without substring... use charAt and loop
*
*
*
*/
String am = "Amazon";
int i = 2;
String am2 = "";
while (i < am.length()) {
am2 += am.charAt(i);
i++;
}
i = 0;
while (i < 2) {
am2 += am.charAt(i);
i++;
}
System.out.println(am2);
}
}
| true |
487ae06c49818d82f3f09a9162d2e472cd3f7f08 | Java | sergio-ordine-metrocamp/android-cafeteira | /app/src/main/java/br/com/metrocamp/example/sergio/cafeteira/Cafeteira.java | UTF-8 | 4,037 | 2.21875 | 2 | [] | no_license | package br.com.metrocamp.example.sergio.cafeteira;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.Switch;
public class Cafeteira extends AppCompatActivity {
private boolean on = false;
private CoffeType type = CoffeType.SHORT;
public boolean isOn() {
return on;
}
public void setOn(boolean on) {
this.on = on;
setupLight(on);
changeCoffeButtons(on);
changeOrderButtonStatus(on);
}
public CoffeType getType() {
return type;
}
public void setType(CoffeType type) {
this.type = type;
Log.d("COFFE","type is "+type);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cafeteira);
Switch switchOn = (Switch) findViewById(R.id.chaveLigar);
setOn(false);
switchOn.setChecked(false);
switchOn.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton,
boolean enabled) {
setOn(enabled);
}
});
FloatingActionButton button = (FloatingActionButton) findViewById(R.id.btnCurto);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
setType(CoffeType.SHORT);
}
});
button = (FloatingActionButton) findViewById(R.id.btnMedio);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
setType(CoffeType.MEDIUM);
}
});
button = (FloatingActionButton) findViewById(R.id.btnLongo);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
setType(CoffeType.LARGE);
}
});
Button orderButton = (Button) findViewById(R.id.btnPedir);
orderButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(Cafeteira.this, Resultado.class);
intent.putExtra("Type",getType());
Cafeteira.this.startActivity(intent);
}
});
}
private void changeCoffeButtons(boolean enabled) {
changeCoffeeButtonStatus( R.id.btnCurto, enabled);
changeCoffeeButtonStatus( R.id.btnMedio, enabled);
changeCoffeeButtonStatus( R.id.btnLongo, enabled);
}
private void changeOrderButtonStatus(boolean enabled) {
Button orderButton = (Button) findViewById(R.id.btnPedir);
orderButton.setEnabled(enabled);
changeButtonColor(orderButton, enabled);
}
private void changeButtonColor(View view, boolean enabled) {
int color = enabled ? R.color.frenteComponente : R.color.fundoComponente;
view.setBackgroundTintList(ColorStateList.valueOf(getResources().getColor(color)));
}
private void changeCoffeeButtonStatus(int buttonId, boolean enabled) {
FloatingActionButton button = (FloatingActionButton) findViewById(buttonId);
button.setEnabled(enabled);
changeButtonColor(button,enabled);
}
private void setupLight(boolean enabled) {
int imageId = enabled ? R.drawable.on : R.drawable.off;
ImageView lightImage = (ImageView) findViewById(R.id.lightImage);
lightImage.setImageDrawable(getResources().getDrawable(imageId));
}
}
| true |
1f801380dde5811f71c559d44f8a4e2ef648d5a7 | Java | k3nny46/PBO-Kenny | /src/org/uwiga/penjualan/cutomer/MasterCustomerController.java | UTF-8 | 316 | 1.804688 | 2 | [] | no_license | package org.uwiga.penjualan.cutomer;
public class MasterCustomerController {
MasterCustomerView view;
MasterCustomerModel model;
public MasterCustomerController(MasterCustomerModel parModel, MasterCustomerView parView){
this.view = parView;
view.reset();
}
public static void main(String[] args) {
}
}
| true |
9ba26b566cabfed405c8ac1592373222624f952d | Java | patilvc/mydata | /src/methods/Demo.java | UTF-8 | 253 | 2.46875 | 2 | [] | no_license | package methods;
public class Demo {
public void method ()
{
int a = 10;
String name ;
name = "vaibhav";
System.out.println( a+ " "+name );
}
public static void main(String[] args) {
Demo vc = new Demo();
vc.method();
}
}
| true |
86bd10c2d941d4b48e54acd6f1e8ba59cc9039ad | Java | zxj8784/news | /src/com/bdqn/news/test/getNewsTitle_ntid.java | UTF-8 | 1,241 | 2.375 | 2 | [] | no_license | package com.bdqn.news.test;
import java.util.List;
import com.bdqn.news.entity.News;
import com.bdqn.news.service.NewsService;
import com.bdqn.news.service.impl.NewsServiceImpl;
public class getNewsTitle_ntid {
/**
* @param args
*/
public static void main(String[] args) {
NewsService newsService = new NewsServiceImpl();
List<News> newsList = newsService.getNewsTitle();
List<News> chinaList = newsService.getContantNews(1);
List<News> foreignList = newsService.getContantNews(2);
List<News> ettmList = newsService.getContantNews(5);
for(int i = 0;i < chinaList.size();i ++){
System.out.println(chinaList.get(i).getNtid()+"\t"+chinaList.get(i).getNtitle());
}
System.out.println();
for(int i = 0;i < foreignList.size();i ++){
System.out.println(foreignList.get(i).getNtid()+"\t"+foreignList.get(i).getNtitle());
}
System.out.println();
for(int i = 0;i < ettmList.size();i ++){
System.out.println(ettmList.get(i).getNtid()+"\t"+ettmList.get(i).getNtitle());
}
System.out.println();
for(int i = 0;i < newsList.size();i ++){
System.out.println(newsList.get(i).getNtid()+"\t"+newsList.get(i).getNtitle());
}
}
}
| true |
11fdae0ccf1b1a75b26466251777393ba180c93d | Java | SalahAbuMsameh/customer-service | /src/main/java/com/apisoft/customer/util/JsonUtils.java | UTF-8 | 684 | 2.375 | 2 | [] | no_license | package com.apisoft.customer.util;
import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.spi.json.JsonProvider;
import com.jayway.jsonpath.spi.json.JsonSmartJsonProvider;
/**
* JSON related utilities.
*
* @author Salah Abu Msameh
*/
public final class JsonUtils {
/**
* extract a json object from a json string.
*
* @param json json string
* @param root root element to be extracted from the json string
* @return
*/
public static String extractJson(final String json, final String root) {
JsonProvider jsonProvider = new JsonSmartJsonProvider();
return jsonProvider.toJson(JsonPath.read(json, root));
}
}
| true |
8d5583cdee687e036cecbc8a6c3e4be08743af44 | Java | McLeodMoores/starling | /projects/financial/src/test/java/com/opengamma/financial/analytics/curve/RateFutureNodeCurrencyVisitorTest.java | UTF-8 | 15,359 | 1.617188 | 2 | [
"Apache-2.0"
] | permissive | /**
* Copyright (C) 2015-Present McLeod Moores Software Limited. All rights reserved.
*/
package com.opengamma.financial.analytics.curve;
import static com.opengamma.financial.analytics.curve.CurveNodeCurrencyVisitorTest.SCHEME;
import static org.testng.Assert.assertEquals;
import java.util.Collections;
import org.testng.annotations.Test;
import org.threeten.bp.LocalTime;
import com.opengamma.DataNotFoundException;
import com.opengamma.OpenGammaRuntimeException;
import com.opengamma.core.convention.ConventionSource;
import com.opengamma.core.id.ExternalSchemes;
import com.opengamma.core.security.SecuritySource;
import com.opengamma.engine.InMemoryConventionSource;
import com.opengamma.engine.InMemorySecuritySource;
import com.opengamma.financial.analytics.ircurve.strips.RateFutureNode;
import com.opengamma.financial.convention.FXSpotConvention;
import com.opengamma.financial.convention.FederalFundsFutureConvention;
import com.opengamma.financial.convention.IborIndexConvention;
import com.opengamma.financial.convention.InterestRateFutureConvention;
import com.opengamma.financial.convention.OvernightIndexConvention;
import com.opengamma.financial.convention.businessday.BusinessDayConventions;
import com.opengamma.financial.convention.daycount.DayCounts;
import com.opengamma.financial.security.index.IborIndex;
import com.opengamma.financial.security.index.OvernightIndex;
import com.opengamma.id.ExternalId;
import com.opengamma.util.money.Currency;
import com.opengamma.util.test.TestGroup;
import com.opengamma.util.time.Tenor;
/**
* Tests the retrieval of a currency from rate future nodes.
*/
@Test(groups = TestGroup.UNIT)
public class RateFutureNodeCurrencyVisitorTest {
/** US region. */
private static final ExternalId US = ExternalSchemes.financialRegionId("US");
/** An empty security source. */
private static final SecuritySource EMPTY_SECURITY_SOURCE = new InMemorySecuritySource();
/** An empty convention source. */
private static final ConventionSource EMPTY_CONVENTION_SOURCE = new InMemoryConventionSource();
/** The curve node id mapper name */
private static final String CNIM_NAME = "CNIM";
/** The id of the underlying LIBOR convention */
private static final ExternalId LIBOR_CONVENTION_ID = ExternalId.of(SCHEME, "USD LIBOR");
/** The id of the underlying LIBOR security */
private static final ExternalId LIBOR_SECURITY_ID = ExternalId.of(SCHEME, "USDLIBOR3M");
/** The id of the underlying overnight convention */
private static final ExternalId OVERNIGHT_CONVENTION_ID = ExternalId.of(SCHEME, "USD Overnight");
/** The id of the underlying overnight security */
private static final ExternalId OVERNIGHT_SECURITY_ID = ExternalId.of(SCHEME, "USDFEDFUNDS");
/** The id of the interest rate future convention */
private static final ExternalId STIR_CONVENTION_ID = ExternalId.of(SCHEME, "USD STIR Future");
/** The id of the Fed funds future convention */
private static final ExternalId FED_FUNDS_CONVENTION_ID = ExternalId.of(SCHEME, "USD FED FUNDS Future");
/** The LIBOR convention */
private static final IborIndexConvention LIBOR_CONVENTION = new IborIndexConvention("USD LIBOR", LIBOR_CONVENTION_ID.toBundle(),
DayCounts.ACT_360, BusinessDayConventions.MODIFIED_FOLLOWING, 2, false, Currency.USD, LocalTime.of(11, 0), "", US, US, "");
/** The overnight convention */
private static final OvernightIndexConvention OVERNIGHT_CONVENTION = new OvernightIndexConvention("USD Overnight",
OVERNIGHT_CONVENTION_ID.toBundle(), DayCounts.ACT_360, 0, Currency.USD, US);
/** The interest rate future convention */
private static final InterestRateFutureConvention STIR_CONVENTION = new InterestRateFutureConvention("USD STIR Future",
STIR_CONVENTION_ID.toBundle(), ExternalId.of(SCHEME, "IMM"), US, LIBOR_CONVENTION_ID);
/** The Fed funds future convention */
private static final FederalFundsFutureConvention FED_FUNDS_CONVENTION = new FederalFundsFutureConvention("USD FED FUNDS Future",
FED_FUNDS_CONVENTION_ID.toBundle(), ExternalId.of(SCHEME, "EOM"), US, OVERNIGHT_CONVENTION_ID, 1250000);
/** The LIBOR security */
private static final IborIndex LIBOR_SECURITY = new IborIndex("USD 3M LIBOR", Tenor.THREE_MONTHS, LIBOR_CONVENTION_ID);
static {
LIBOR_SECURITY.addExternalId(LIBOR_SECURITY_ID);
}
/** The overnight security */
private static final OvernightIndex OVERNIGHT_SECURITY = new OvernightIndex("USD FED FUNDS", OVERNIGHT_CONVENTION_ID);
static {
OVERNIGHT_SECURITY.addExternalId(OVERNIGHT_SECURITY_ID);
}
/**
* Tests the behaviour when the convention is not available from the source.
*/
@Test(expectedExceptions = DataNotFoundException.class)
public void testNoConvention() {
final RateFutureNode node = new RateFutureNode(1, Tenor.ONE_DAY, Tenor.THREE_MONTHS, Tenor.THREE_MONTHS, STIR_CONVENTION_ID, CNIM_NAME);
node.accept(new CurveNodeCurrencyVisitor(EMPTY_CONVENTION_SOURCE, EMPTY_SECURITY_SOURCE));
}
/**
* Tests the behaviour when the convention is not an interest rate or Fed funds future convention.
*/
@Test(expectedExceptions = OpenGammaRuntimeException.class)
public void testUnhandledConventionType() {
final InMemoryConventionSource conventionSource = new InMemoryConventionSource();
conventionSource.addConvention(new FXSpotConvention("FX", STIR_CONVENTION_ID.toBundle(), 2, false));
final RateFutureNode node = new RateFutureNode(1, Tenor.ONE_DAY, Tenor.THREE_MONTHS, Tenor.THREE_MONTHS, STIR_CONVENTION_ID, CNIM_NAME);
node.accept(new CurveNodeCurrencyVisitor(conventionSource, EMPTY_SECURITY_SOURCE));
}
/**
* Tests the behaviour when the convention is an interest rate future convention but the underlying
* convention and security are not available.
*/
@Test(expectedExceptions = OpenGammaRuntimeException.class)
public void testNoUnderlyingsAvailableForStirConvention() {
final InMemoryConventionSource conventionSource = new InMemoryConventionSource();
conventionSource.addConvention(STIR_CONVENTION.clone());
final RateFutureNode node = new RateFutureNode(1, Tenor.ONE_DAY, Tenor.THREE_MONTHS, Tenor.THREE_MONTHS, STIR_CONVENTION_ID, CNIM_NAME);
node.accept(new CurveNodeCurrencyVisitor(conventionSource, EMPTY_SECURITY_SOURCE));
}
/**
* Tests the behaviour when the convention is a Fed funds future convention but the underlying convention
* and security are not available.
*/
@Test(expectedExceptions = OpenGammaRuntimeException.class)
public void testNoUnderlyingsAvailableForFedFundsConvention() {
final InMemoryConventionSource conventionSource = new InMemoryConventionSource();
conventionSource.addConvention(FED_FUNDS_CONVENTION.clone());
final RateFutureNode node = new RateFutureNode(1, Tenor.ONE_DAY, Tenor.THREE_MONTHS, Tenor.THREE_MONTHS, FED_FUNDS_CONVENTION_ID, CNIM_NAME);
node.accept(new CurveNodeCurrencyVisitor(conventionSource, EMPTY_SECURITY_SOURCE));
}
/**
* Tests the behaviour for an interest rate future convention where the underlying convention from the
* future convention is available.
*/
@Test
public void testUnderlyingsConventionAvailableForStirConvention() {
final InMemoryConventionSource conventionSource = new InMemoryConventionSource();
conventionSource.addConvention(STIR_CONVENTION.clone());
conventionSource.addConvention(LIBOR_CONVENTION.clone());
final RateFutureNode node = new RateFutureNode(1, Tenor.ONE_DAY, Tenor.THREE_MONTHS, Tenor.THREE_MONTHS, STIR_CONVENTION_ID, CNIM_NAME);
assertEquals(node.accept(new CurveNodeCurrencyVisitor(conventionSource, EMPTY_SECURITY_SOURCE)), Collections.singleton(Currency.USD));
}
/**
* Tests the behaviour for a Fed funds future convention where the underlying convention from the future
* convention is available.
*/
@Test
public void testUnderlyingsConventionAvailableForFedFundsConvention() {
final InMemoryConventionSource conventionSource = new InMemoryConventionSource();
conventionSource.addConvention(FED_FUNDS_CONVENTION.clone());
conventionSource.addConvention(OVERNIGHT_CONVENTION.clone());
final RateFutureNode node = new RateFutureNode(1, Tenor.ONE_DAY, Tenor.THREE_MONTHS, Tenor.THREE_MONTHS, FED_FUNDS_CONVENTION_ID, CNIM_NAME);
assertEquals(node.accept(new CurveNodeCurrencyVisitor(conventionSource, EMPTY_SECURITY_SOURCE)), Collections.singleton(Currency.USD));
}
/**
* Tests the behaviour for an interest rate future convention where the underlying convention is
* unavailable and the underlying security is not an ibor index.
*/
@Test(expectedExceptions = OpenGammaRuntimeException.class)
public void testWrongSecurityTypeForStirConvention() {
final InMemoryConventionSource conventionSource = new InMemoryConventionSource();
conventionSource.addConvention(STIR_CONVENTION.clone());
final OvernightIndex overnightSecurity = OVERNIGHT_SECURITY.clone();
overnightSecurity.setExternalIdBundle(LIBOR_SECURITY_ID.toBundle());
final InMemorySecuritySource securitySource = new InMemorySecuritySource();
securitySource.addSecurity(overnightSecurity);
final RateFutureNode node = new RateFutureNode(1, Tenor.ONE_DAY, Tenor.THREE_MONTHS, Tenor.THREE_MONTHS, STIR_CONVENTION_ID, CNIM_NAME);
assertEquals(node.accept(new CurveNodeCurrencyVisitor(conventionSource, securitySource)), Collections.singleton(Currency.USD));
}
/**
* Tests the behaviour for a Fed funds future convention where the underlying convention is
* unavailable and the underlying security is not an overnight index.
*/
@Test(expectedExceptions = OpenGammaRuntimeException.class)
public void testWrongSecurityTypeForFedFundsConvention() {
final InMemoryConventionSource conventionSource = new InMemoryConventionSource();
conventionSource.addConvention(FED_FUNDS_CONVENTION.clone());
final IborIndex iborSecurity = LIBOR_SECURITY.clone();
iborSecurity.setExternalIdBundle(OVERNIGHT_SECURITY_ID.toBundle());
final InMemorySecuritySource securitySource = new InMemorySecuritySource();
securitySource.addSecurity(iborSecurity);
final RateFutureNode node = new RateFutureNode(1, Tenor.ONE_DAY, Tenor.THREE_MONTHS, Tenor.THREE_MONTHS, FED_FUNDS_CONVENTION_ID, CNIM_NAME);
assertEquals(node.accept(new CurveNodeCurrencyVisitor(conventionSource, securitySource)), Collections.singleton(Currency.USD));
}
/**
* Tests the behaviour for an interest rate future convention where the underlying convention is
* unavailable but the convention referenced in the index security is.
*/
@Test
public void testUnderlyingConventionAvailableFromSecurityForStirConvention() {
// convention uses the LIBOR security id
final InterestRateFutureConvention stirConvention = new InterestRateFutureConvention("USD STIR Future",
STIR_CONVENTION_ID.toBundle(), ExternalId.of(SCHEME, "IMM"), US, LIBOR_SECURITY_ID);
final InMemoryConventionSource conventionSource = new InMemoryConventionSource();
conventionSource.addConvention(stirConvention);
conventionSource.addConvention(LIBOR_CONVENTION.clone());
final InMemorySecuritySource securitySource = new InMemorySecuritySource();
securitySource.addSecurity(LIBOR_SECURITY);
final RateFutureNode node = new RateFutureNode(1, Tenor.ONE_DAY, Tenor.THREE_MONTHS, Tenor.THREE_MONTHS, STIR_CONVENTION_ID, CNIM_NAME);
assertEquals(node.accept(new CurveNodeCurrencyVisitor(conventionSource, securitySource)), Collections.singleton(Currency.USD));
}
/**
* Tests the behaviour for a Fed funds future convention where the underlying convention is
* unavailable but the convention referenced in the index security is.
*/
@Test
public void testUnderlyingConventionAvailableFromSecurityForFedFundConvention() {
// convention uses the overnight security id
final FederalFundsFutureConvention fedFundsConvention = new FederalFundsFutureConvention("USD FED FUNDS Future",
FED_FUNDS_CONVENTION_ID.toBundle(), ExternalId.of(SCHEME, "EOM"), US, OVERNIGHT_SECURITY_ID, 1250000);
final InMemoryConventionSource conventionSource = new InMemoryConventionSource();
conventionSource.addConvention(fedFundsConvention);
conventionSource.addConvention(OVERNIGHT_CONVENTION.clone());
final InMemorySecuritySource securitySource = new InMemorySecuritySource();
securitySource.addSecurity(OVERNIGHT_SECURITY);
final RateFutureNode node = new RateFutureNode(1, Tenor.ONE_DAY, Tenor.THREE_MONTHS, Tenor.THREE_MONTHS, FED_FUNDS_CONVENTION_ID, CNIM_NAME);
assertEquals(node.accept(new CurveNodeCurrencyVisitor(conventionSource, securitySource)), Collections.singleton(Currency.USD));
}
/**
* Tests the behaviour for an interest rate future convention where the underlying convention is
* unavailable and the convention from the security is not an ibor index convention.
*/
@Test(expectedExceptions = ClassCastException.class)
public void testWrongConventionTypeFromSecurityForStirConvention() {
final InterestRateFutureConvention stirConvention = new InterestRateFutureConvention("USD STIR Future",
STIR_CONVENTION_ID.toBundle(), ExternalId.of(SCHEME, "IMM"), US, LIBOR_SECURITY_ID);
final InMemoryConventionSource conventionSource = new InMemoryConventionSource();
conventionSource.addConvention(stirConvention);
conventionSource.addConvention(OVERNIGHT_CONVENTION.clone());
final IborIndex liborSecurity = new IborIndex("USD 3M LIBOR", Tenor.THREE_MONTHS, OVERNIGHT_CONVENTION_ID);
liborSecurity.addExternalId(LIBOR_SECURITY_ID);
final InMemorySecuritySource securitySource = new InMemorySecuritySource();
securitySource.addSecurity(liborSecurity);
final RateFutureNode node = new RateFutureNode(1, Tenor.ONE_DAY, Tenor.THREE_MONTHS, Tenor.THREE_MONTHS, STIR_CONVENTION_ID, CNIM_NAME);
assertEquals(node.accept(new CurveNodeCurrencyVisitor(conventionSource, securitySource)), Collections.singleton(Currency.USD));
}
/**
* Tests the behaviour for a Fed funds future convention where the underlying convention is
* unavailable and the convention from the security is not an overnight index convention.
*/
@Test(expectedExceptions = ClassCastException.class)
public void testWrongConventionTypeFromSecurityForFedFundsConvention() {
final FederalFundsFutureConvention fedFundsConvention = new FederalFundsFutureConvention("USD FED FUNDS Future",
FED_FUNDS_CONVENTION_ID.toBundle(), ExternalId.of(SCHEME, "EOM"), US, OVERNIGHT_SECURITY_ID, 1250000);
final InMemoryConventionSource conventionSource = new InMemoryConventionSource();
conventionSource.addConvention(fedFundsConvention);
conventionSource.addConvention(LIBOR_CONVENTION);
final OvernightIndex overnightSecurity = new OvernightIndex("USD FED FUNDS", LIBOR_CONVENTION_ID);
overnightSecurity.addExternalId(OVERNIGHT_SECURITY_ID);
final InMemorySecuritySource securitySource = new InMemorySecuritySource();
securitySource.addSecurity(overnightSecurity);
final RateFutureNode node = new RateFutureNode(1, Tenor.ONE_DAY, Tenor.THREE_MONTHS, Tenor.THREE_MONTHS, FED_FUNDS_CONVENTION_ID, CNIM_NAME);
assertEquals(node.accept(new CurveNodeCurrencyVisitor(conventionSource, securitySource)), Collections.singleton(Currency.USD));
}
}
| true |
965428d5a8576cef7b105fc7378aa758020b1089 | Java | javfuentesb/VCMatrix | /tarea2/src/cc3002/tarea3/twit/TwitList.java | UTF-8 | 2,531 | 3.8125 | 4 | [] | no_license | package cc3002.tarea3.twit;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.ListIterator;
import java.util.Scanner;
/** Define una lista con Twits, provee además de métodos para acceder y sacar información acerca de estos twits
*
* @author Javier
*
*/
public class TwitList {
/**Nuestra lista de twits**/
private ArrayList<Twit> twits;
public TwitList(){
twits= new ArrayList<Twit>();
}
/**Métodos para añadir twits a la lista**/
public void addTwit(String name, String language, String message){
twits.add(new Twit(name, language, message));
}
public void addTwit(Twit twit){
twits.add(twit);
}
/**Estos remueven un twit de la lista**/
public void removeTwit(int i){
twits.remove(i);
}
public void removeTwit(Twit twit){
twits.remove(twit);
}
/**Método para obtener un twit de la lista**/
public Twit getTwit(int i){
return twits.get(i);
}
/**Largo de la lista**/
public int length(){
return twits.size();
}
/** Función que entrega la cantidad twits que contienen una cadena de texto dada
*
* @param chains Arreglo de strings
* @return cantidad de twits que tienen la cadena
*/
public int numberofTwits(String[] chains){
int i=0;
ListIterator<Twit> li= twits.listIterator();
while(li.hasNext()){
if((li.next().inMessage(chains)))
i++;
}
return i;
}
public int numberofTwits(String chain){
int i=0;
ListIterator<Twit> li= twits.listIterator();
while(li.hasNext()){
if((li.next().inMessage(chain)))
i++;
}
return i;
}
/** Permite añadir twits a partir de un archivo. Lee el archivo, lo parsea y almacena cada dato en un Twit
*
* @param file dirección del archivo de texto
* @throws FileNotFoundException
*/
public void addTwitsfromFile(String file) throws FileNotFoundException{
Scanner in=new Scanner(new File(file),"UTF-8");
while(in.hasNext()){
String line=in.nextLine();
String[] data=line.split("\t",-1);
addTwit(data[0],data[1],data[2]);
}
}
/**
* Overloading del metodo equals
* @param twitlist
* @return true si son iguales, false en caso contrario
*/
public boolean equals(TwitList twitlist){
if(twitlist.length()==this.length()){
for(int i=0;i<twitlist.length();i++){
if(!twitlist.getTwit(i).equals(this.getTwit(i)))
return false;
}
return true;
}
return false;
}
}
| true |
5d2b561125651aaa53f2540fd9e16bb3cacfd309 | Java | JinyaConnect123/Morimoto-Project | /IMP_Jinyaconnect Java APL/src/IMP_Jinyaconnect/define/RakujanConst.java | UTF-8 | 1,330 | 2.015625 | 2 | [] | no_license | package IMP_Jinyaconnect.define;
import java.text.SimpleDateFormat;
public class RakujanConst {
/**
* SOQL文に、検索条件項目および項目タイプを区切る文字列
*/
public static final String KEY_TYPE_SPLIT = ":";
/**
* SOQL文に、日時検索時、日時範囲を表す区切り文字
*/
public static final String DATE_RANGE_SPLIT = "&";
/**
* 特別リクエスト:正規表現
* ・予約詳細: 一日ごとの大人子供人数の内訳、料金詳細などを出力する。
* 予約詳細情報は最初の情報が「ZZ」で始まり「,ZZ」で区切られる。
*/
public static final String REGEX_REQUEST = "[,]*ZZ([0-9]{4}/[0-9]{1,2}/[0-9]{1,2}) ([1-9]+)部屋目:([0-9]+)円[(](大人|子供)[)]×([0-9]+)名 = 小計([0-9]+)円";
/**
* 日時フォーマット1
* 例: 2012-07-20T15:00:00.000Z
*/
public static final SimpleDateFormat DATE_FMT1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
public static final SimpleDateFormat DATE_FMT2 = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS");
public static final SimpleDateFormat DATE_FMT3 = new SimpleDateFormat("yyyyMMdd_HHmmss");
public static final SimpleDateFormat DATE_FMT4 = new SimpleDateFormat("yyyy-MM-dd");
public static final String[] PARAMETER_NONE = new String[] {};
}
| true |
677e3aa9209ea495baf3834e9217a6a625a73bc2 | Java | vlastachu/Rubick | /src/com/example/Rubick/Corner.java | UTF-8 | 1,586 | 2.515625 | 3 | [] | no_license | package com.example.Rubick;
import android.opengl.Matrix;
import android.util.Log;
/**
* User: vlastachu
* Date: 30.10.13
* Time: 0:04
*/
public class Corner extends Mesh {
final int QUADS_PER_CORNER = 2;
public Corner(float[] center_vec3, float[] center2_vec3, float[] radius_vec3) {
float[] radius_vec4 = {radius_vec3[0], radius_vec3[1], radius_vec3[2], 1};
float[] center_vec4 = {center_vec3[0], center_vec3[1], center_vec3[2], 1};
float[] center2_vec4 = {center2_vec3[0], center2_vec3[1], center2_vec3[2], 1};
Log.d("RUB", "radiusvec4[" + radius_vec4[0] + ", " + radius_vec4[1] + ", " +radius_vec4[2] + ", " + radius_vec4[3]);
float[] centerDir = new float[3];
LinearUtils.minus(center2_vec3, center_vec3, centerDir);
LinearUtils.normalize(centerDir);
float[] tempRotateMatrix = new float[16];
Matrix.setRotateM(tempRotateMatrix, 0, 90.0f/QUADS_PER_CORNER, centerDir[0], centerDir[1], centerDir[2]);
coords = new float[COORDS_PER_VERTEX*2*(QUADS_PER_CORNER+1)];
float[] temp = new float[4];
for(int i = 0; i <= QUADS_PER_CORNER; i++){
LinearUtils.plus(center_vec4,radius_vec4,temp);
for(int j = 0; j < 4;j++) coords[j + i*COORDS_PER_VERTEX*2] = temp[j];
LinearUtils.plus(center2_vec4,radius_vec4,temp);
for(int j = 4; j < 8;j++) coords[j + i*COORDS_PER_VERTEX*2] = temp[j-4];
radius_vec4 = LinearUtils.multiply(tempRotateMatrix, radius_vec4);
}
Log.d("RUB", "radiusvec4[" + radius_vec4[0] + ", " + radius_vec4[1] + ", " +radius_vec4[2] + ", " + radius_vec4[3]);
for(float f: coords)
Log.d("RUB","f: "+f);
postInit();
}
}
| true |
94ef7c45dc00ae20fb97a78a7b4b3530b8a7f7d7 | Java | ShayneColomy/GiraffesEmailFiltration | /v3/EmailBucket.java | UTF-8 | 5,896 | 2.9375 | 3 | [] | no_license | package v3;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.SortedSet;
import java.util.logging.Level;
import java.util.logging.Logger;
public class EmailBucket implements Serializable
{
/*
* fields
*/
private String bucketName;
private ArrayList<MailObject> messages;
public static ArrayList<EmailBucket> emailBuckets;
private static Logger logger = Logger.getLogger(EmailBucket.class.getName());
private static final long serialVersionUID = 1L;
/*
* constructors
*/
public EmailBucket(String bucketName)
{
this.bucketName = bucketName;
this.messages = new ArrayList<MailObject>();
}
public EmailBucket(MailObject m)
{
this.bucketName = m.getFrom();
this.messages = new ArrayList<MailObject>() {
{
add(m);
}
};
}
public void addMessage(MailObject m)
{
messages.add(m);
}
public void deleteMessage(MailObject m)
{
messages.remove(m);
}
/**
* sortMail(ArrayList<MailObject>) sorts a ArrayList of MailObjects into the appropriate bucket.
* If a bucket doesn't exist, one is created.
* @param m is MailObject to be sorted into a folder.
*/
public static void sortMail(ArrayList<MailObject> mail)
{
for(MailObject m: mail)
{
boolean undelivered = true;
for(EmailBucket b: emailBuckets)
{
logger.log(Level.INFO, "b.getBucketName(): " + b.getBucketName());
logger.log(Level.INFO, "m.getFrom(): " + m.getFrom());
if(m.getFrom().equals(b.getBucketName()))
{
logger.log(Level.INFO, "Match: " + m.getFrom().equals(b.getBucketName()));
b.addMessage(m);
undelivered = false;
}
}
if(undelivered)
{
logger.log(Level.INFO, "In undelivered");
EmailBucket eb = new EmailBucket(m.getFrom());
eb.addMessage(m);
logger.log(Level.INFO, "name of new bucket:" + eb.getBucketName());
emailBuckets.add(eb);
}
}
logger.log(Level.INFO, "" + EmailBucket.getEmailBuckets().size());
}
/**
* sortMail(MailObject) sorts a single MailObject into the appropriate bucket. If a bucket doesn't
* exist, one is created.
* @param m is MailObject to be sorted into a folder.
*/
// public static void sortMail(MailObject m)
// {
// boolean undelivered = true;
//// for(EmailBucket b: emailBuckets)
//// {
//// if(m.getFrom().equals(b.getBucketName()))
//// {
//// b.addMessage(m);
//// undelivered = false;
//// break;
//// }
//// }
//// if(undelivered)
//// {
//// emailBuckets.add(new EmailBucket(m.getFrom()));
//// }
//// boolean undelivered = true;
// for(EmailBucket b: emailBuckets)
// {
// if(m.getFrom().equals(b.getBucketName()))
// {
// b.addMessage(m);
// undelivered = false;
// break;
// }
// }
// if(undelivered)
// {
// emailBuckets.add(new EmailBucket(m.getFrom()));
// }
// }
public static ArrayList<EmailBucket> sortMail(ArrayList<EmailBucket> oldBuckets, ArrayList<MailObject> mail)
{
ArrayList<EmailBucket> bucks = new ArrayList<EmailBucket>();
ArrayList<EmailBucket> newBuckets = EmailBucket.mailToBuckets(mail);
logger.log(Level.INFO, "buckets in sortMail: " + newBuckets.size());
for(EmailBucket b: oldBuckets)
{
logger.log(Level.INFO, "buckets from 'buckets': " + b.getBucketName());
}
for(EmailBucket b: newBuckets)
{
for(MailObject m: mail)
{
if (m.getFrom().equals(b.getBucketName()))
{
b.addMessage(m);
}
}
}
//good till here
/*
* For each newBucket, see if there is an oldBucket with that name. If yes,
* the buckets will be merged. Otherwise, the new bucket is added to the
* oldBucket list.
*/
for(EmailBucket n: newBuckets)
{
boolean noSuchBucket = true;
for(EmailBucket b: oldBuckets)
{
if(n.getBucketName().equals(b.getBucketName()))
{
bucks.add(EmailBucket.mergeBuckets(b, n));
logger.log(Level.INFO, "bucks size: " + bucks.size());
noSuchBucket = false;
break;
}
}
if(noSuchBucket)
{
bucks.add(n);
}
}
return bucks;
}
/**
* mailToBuckets() creates buckets for an ArrayList of MailObjects
* @param mail
* @return is {types} {tags}
*/
private static ArrayList<EmailBucket> mailToBuckets(ArrayList<MailObject> mail)
{
HashSet<String> names = new HashSet<String>();
ArrayList<EmailBucket> buckets = new ArrayList<EmailBucket>();
for(MailObject m: mail)
{
names.add(m.getFrom());
}
for(String s: names)
{
buckets.add(new EmailBucket(s));
}
return buckets;
}
private static EmailBucket mergeBuckets(EmailBucket one, EmailBucket two)
{
one.getMessages().forEach(e->{
two.addMessage(e);
});
return two;
}
/*
* Getters and Setters
*/
/**
* @return the bucketName
*/
public String getBucketName() {
return bucketName;
}
/**
* @param bucketName the bucketName to set
*/
public void setBucketName(String bucketName) {
this.bucketName = bucketName;
}
/**
* @return the messages
*/
public ArrayList<MailObject> getMessages() {
return messages;
}
/**
* @param messages the messages to set
*/
public void setMessages(ArrayList<MailObject> messages) {
this.messages = messages;
}
/**
* @return the emailBuckets
*/
public static ArrayList<EmailBucket> getEmailBuckets() {
return emailBuckets;
}
/**
* @param emailBuckets the emailBuckets to set
*/
public static void setEmailBuckets(ArrayList<EmailBucket> emailBuckets) {
EmailBucket.emailBuckets = emailBuckets;
}
/**
* @return the serialversionuid
*/
public static long getSerialversionuid() {
return serialVersionUID;
}
}
| true |
a7bb187082b341fc992f7ba0d628e74fb4977b13 | Java | sukmohadi/basic-inventory-web | /basic-inventory-web/src/main/java/com/jocki/inventory/repository/specification/Filter.java | UTF-8 | 1,047 | 2.1875 | 2 | [] | no_license | package com.jocki.inventory.repository.specification;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import org.springframework.util.StringUtils;
public abstract class Filter<T> {
@SuppressWarnings("rawtypes")
public Expression toPath(Root root, String name) {
Path result = null;
if (name.contains("_")) {
for (String node: name.split("_")) {
node = StringUtils.uncapitalize(node);
if (result == null) {
result = root.get(node);
} else {
result = result.get(node);
}
}
} else {
result = root.get(name);
}
return (Expression) result;
}
public abstract Predicate toPredicate(CriteriaBuilder cb, Root<T> root);
}
| true |
129b002a39356e0e701d4b06ec97f8757e5d5552 | Java | txyn81/txy_micorservice | /commons/common-redis/src/main/java/com/contral/common/redis/properties/CacheManagerProperties.java | UTF-8 | 620 | 2.046875 | 2 | [] | no_license | package com.contral.common.redis.properties;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import java.util.List;
/**
* @description: 缓存管理配置类
* @author: oren.tang
* @date: 2020/8/15 2:58 下午
*/
@Data
@ConfigurationProperties(prefix = "txy.cache-manager")
public class CacheManagerProperties {
private List<CacheConfig> configs;
@Data
public static class CacheConfig {
/**
* cache key
*/
private String key;
/**
* 过期时间
*/
private long second = 60;
}
}
| true |
e64648b816d2cf36fc85de62fed5544a9960cedb | Java | irisliu77/PicturePostProcessing | /ImageAdjusterView.java | UTF-8 | 3,403 | 3.078125 | 3 | [] | no_license | package a7;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.event.ChangeListener;
public class ImageAdjusterView extends JPanel {
private PictureView picture_view;
private JSlider blur_slider;
private JSlider saturation_slider;
private JSlider brightness_slider;
private JLabel blur;
private JLabel saturation;
private JLabel brightness;
private JPanel row1;
private JPanel row2;
private JPanel row3;
private ChangeListener blur_listener;
private ChangeListener saturation_listener;
private ChangeListener brightness_listener;
public ImageAdjusterView(ObservablePicture picture) {
setLayout(new BorderLayout());
//initialize sliders
blur_slider = new JSlider(0, 5, 0);
blur_slider.setMajorTickSpacing(1);
blur_slider.setPaintTicks(true);
blur_slider.createStandardLabels(1);
blur_slider.setPaintLabels(true);
blur_slider.setName("blur_slider");
saturation_slider = new JSlider(-100, 100, 0);
saturation_slider.setMajorTickSpacing(25);
saturation_slider.setPaintTicks(true);
saturation_slider.createStandardLabels(25);
saturation_slider.setPaintLabels(true);
saturation_slider.setName("saturation_slider");
brightness_slider = new JSlider(-100, 100, 0);
brightness_slider.setMajorTickSpacing(25);
brightness_slider.setPaintTicks(true);
brightness_slider.createStandardLabels(25);
brightness_slider.setPaintLabels(true);
brightness_slider.setName("brightness_slider");
//set the size of the slider
Dimension slider_dim1 = new Dimension(300,50);
Dimension slider_dim2 = new Dimension(340,50);
blur_slider.setPreferredSize(slider_dim1);
saturation_slider.setPreferredSize(slider_dim2);
brightness_slider.setPreferredSize(slider_dim2);
//initialize names of different functions
blur = new JLabel("Blur: ");
saturation = new JLabel("Saturation: ");
brightness = new JLabel("Brightness: ");
//set the size of the name panels
Dimension panel_dim1 = new Dimension(600, 50);
Dimension panel_dim2 = new Dimension(560, 50);
blur_slider.setPreferredSize(panel_dim1);
saturation_slider.setPreferredSize(panel_dim2);
brightness_slider.setPreferredSize(panel_dim2);
//combine correspondant slider and label
row1 = new JPanel();
row1.add(blur, BorderLayout.WEST);
row1.add(blur_slider, BorderLayout.EAST);
row2 = new JPanel();
row2.add(saturation, BorderLayout.WEST);
row2.add(saturation_slider, BorderLayout.EAST);
row3 = new JPanel();
row3.add(brightness, BorderLayout.WEST);
row3.add(brightness_slider, BorderLayout.EAST);
//the overall panel for adjuster
JPanel adjuster_panel = new JPanel();
adjuster_panel.setLayout(new GridLayout(3,1));
adjuster_panel.add(row1);
adjuster_panel.add(row2);
adjuster_panel.add(row3);
picture_view = new PictureView(picture);
//picture_view.addMouseListener(this);
add(picture_view, BorderLayout.CENTER);
add(adjuster_panel, BorderLayout.SOUTH);
}
public void addChangeListener(ChangeListener cl) {
blur_slider.addChangeListener(cl);
saturation_slider.addChangeListener(cl);
brightness_slider.addChangeListener(cl);
}
public void setPicture(ObservablePicture pic) {
picture_view.setPicture(pic);
}
}
| true |
2fa90d6508dd7ad9ff77626b5decb9e0153fdca6 | Java | NareshNalla/corejava | /corejava-generics/src/com/test/Test.java | UTF-8 | 415 | 2.75 | 3 | [] | no_license | package com.test;
import java.util.ArrayList;
import java.util.List;
/* What is the result of compiling and running the following program?*/
public class Test {
public static void main(String[] args) {
List<String> list1 = new ArrayList<String>();//line 1
List<Object> list2 = list1;//line 2
list2.add(new Integer(12));//line 3
System.out.println(list2.size());//line 4
}
}
| true |
acf0ec561783fd0a40ed2101824584048a4fab83 | Java | Birdilove/FirebaseDemo | /app/src/main/java/com/example/firebasedemo/SignUp.java | UTF-8 | 3,315 | 2.46875 | 2 | [] | no_license | package com.example.firebasedemo;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.HapticFeedbackConstants;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
public class SignUp extends AppCompatActivity {
private FirebaseAuth auth;
EditText email_text;
EditText pass_text;
final String TAG = "Come Here";
Button signup;
String email;
String password;
boolean connected = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_up);
auth = FirebaseAuth.getInstance();
signup = findViewById(R.id.signUpButton);
email_text = findViewById(R.id.signUpEmail);
pass_text = findViewById(R.id.signUpPass);
signup.setOnClickListener(v -> {
v.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY);
if(checkConnection()){
Signup();
}
else{
Toast.makeText(this, "Please connect to the Internet!", Toast.LENGTH_SHORT).show();
}
});
}
public void Signup(){
email = email_text.getText().toString();
password = pass_text.getText().toString();
if (email.length() > 0 && password.length() > 0){
if(password.length()>=9){
auth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this, task -> {
if (task.isSuccessful()) {
Log.d(TAG, "createUserWithEmail:success");
FirebaseUser user = auth.getCurrentUser();
Toast.makeText(this, "Successfully Registered", Toast.LENGTH_LONG).show();
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
} else {
Toast.makeText(this, "There's an exiting account with same Email.",Toast.LENGTH_SHORT).show();
}
});
}
else{
Toast.makeText(this, "Password should at least have 9 characters.", Toast.LENGTH_LONG).show();
}
}else{
Toast.makeText(this, "Oh no, seems like you missed a spot!", Toast.LENGTH_LONG).show();
}
}
public boolean checkConnection(){
ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
if(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED ||
connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED) {
connected = true;
}
else {
connected = false;
}
return connected;
}
} | true |
bcd77486706eae190b017f5c213302228c247904 | Java | McflyWZX/PhysicsSimulatorApp | /app/src/main/java/com/mcfly/ps/PhysicsPack/FieldPack/Mfield.java | UTF-8 | 631 | 2.234375 | 2 | [
"MIT"
] | permissive | package com.mcfly.ps.PhysicsPack.FieldPack;
import com.mcfly.ps.PhysicsPack.*;
import com.mcfly.ps.PhysicsPack.PhysicsObjPack.*;
import android.graphics.*;
public class Mfield extends Field
{
float B;
public Mfield(Vector2 startP, Vector2 endP, Vector2 a)
{
super(startP, endP);
//this.a = a;
addObjToPhysicsSystem();
}
@Override
public void addForceTo(PhysicsObj obj)
{
// TODO: Implement this method
obj.addForce(new Vector2(- obj.velocity.scale(obj.q * B).getY(), obj.velocity.scale(obj.q * B).getX()));
}
@Override
public void draw(Canvas ca, Paint pa)
{
// TODO: Implement this method
}
}
| true |
fd318aa95976d53f82e0deb45e287191d580026c | Java | apache/tuscany-sca-1.x | /modules/contribution/src/main/java/org/apache/tuscany/sca/contribution/service/ContributionService.java | UTF-8 | 6,535 | 1.796875 | 2 | [
"Apache-2.0"
] | permissive | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.tuscany.sca.contribution.service;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import org.apache.tuscany.sca.assembly.Composite;
import org.apache.tuscany.sca.contribution.Contribution;
import org.apache.tuscany.sca.contribution.resolver.ModelResolver;
/**
* Service interface that manages artifacts contributed to a Tuscany runtime.
*
* @version $Rev$ $Date$
*/
public interface ContributionService {
/**
* Contribute an artifact to the SCA Domain. The type of the contribution is
* determined by the Content-Type of the resource or, if that is undefined,
* by some implementation-specific means (such as mapping an extension in
* the URL's path).
*
* @param contributionURI The URI that is used as the contribution unique ID.
* @param sourceURL The location of the resource containing the artifact
* @param storeInRepository Flag that identifies if you want to copy the
* contribution to the repository
* @return The contribution model representing the contribution
* @throws ContributionException if there was a problem with the contribution
* @throws IOException if there was a problem reading the resource
*/
Contribution contribute(String contributionURI, URL sourceURL, boolean storeInRepository) throws ContributionException,
IOException;
/**
* Contribute an artifact to the SCA Domain. The type of the contribution is
* determined by the Content-Type of the resource or, if that is undefined,
* by some implementation-specific means (such as mapping an extension in
* the URL's path).
*
* @param contributionURI The URI that is used as the contribution unique ID.
* @param sourceURL The location of the resource containing the artifact
* @param modelResolver The model resolver to use to resolve models in the
* scope of this contribution
* @param storeInRepository Flag that identifies if you want to copy the
* contribution to the repository
* @return The contribution model representing the contribution
* @throws ContributionException if there was a problem with the contribution
* @throws IOException if there was a problem reading the resource
*/
Contribution contribute(String contributionURI, URL sourceURL, ModelResolver modelResolver, boolean storeInRepository) throws ContributionException,
IOException;
/**
* Contribute an artifact to the SCA Domain.
*
* @param contributionURI The URI that is used as the contribution unique ID.
* @param sourceURL The location of the resource containing the artifact.
* This is used to identify what name should be used when storing
* the contribution on the repository
* @param contributionContent A stream containing the resource being
* contributed; the stream will not be closed but the read
* position after the call is undefined
* @return The contribution model representing the contribution
* @throws ContributionException if there was a problem with the contribution
* @throws IOException if there was a problem reading the stream
*/
Contribution contribute(String contributionURI, URL sourceURL, InputStream contributionContent)
throws ContributionException, IOException;
/**
* Contribute an artifact to the SCA Domain.
*
* @param contributionURI The URI that is used as the contribution unique ID.
* @param sourceURL The location of the resource containing the artifact.
* This is used to identify what name should be used when storing
* the contribution on the repository
* @param modelResolver The model resolver to use to resolve models in the
* scope of this contribution
* @param contributionContent A stream containing the resource being
* contributed; the stream will not be closed but the read
* position after the call is undefined
* @return The contribution model representing the contribution
* @throws ContributionException if there was a problem with the contribution
* @throws IOException if there was a problem reading the stream
*/
Contribution contribute(String contributionURI, URL sourceURL, InputStream contributionContent, ModelResolver modelResolver)
throws ContributionException, IOException;
/**
* Get the model for an installed contribution
*
* @param contribution The URI of an installed contribution
* @return The model for the contribution or null if there is no such
* contribution
*/
Contribution getContribution(String contribution);
/**
* Adds or updates a deployment composite using a supplied composite
* ("composite by value" - a data structure, not an existing resource in the
* domain) to the contribution identified by a supplied contribution URI.
* The added or updated deployment composite is given a relative URI that
* matches the "name" attribute of the composite, with a ".composite"
* suffix.
*
* @param contribution The contribution to where
* @param composite
* @throws ContributionException
*/
void addDeploymentComposite(Contribution contribution, Composite composite) throws ContributionException;
/**
* Remove a contribution from the SCA domain
*
* @param contribution The URI of the contribution
* @throws DeploymentException
*/
void remove(String contribution) throws ContributionException;
} | true |
a22bfa69fb3d3b83eb979b632a881690b4264213 | Java | hemyan-ha1401812/Fundamentals-of-Database-Systems-Spring2018 | /Lab/Attempts/Try/src/Lab_10_ex_5/searchGUI.java | UTF-8 | 2,110 | 2.953125 | 3 | [] | no_license | package Lab_10_ex_5;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JTable;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import javax.swing.JScrollBar;
public class searchGUI extends JFrame {
private JPanel contentPane;
private JTextField textField;
private JTable table;
DAO e = new DAO();
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
searchGUI frame = new searchGUI();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public searchGUI() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblNewLabel = new JLabel("Search by employee name");
lblNewLabel.setBounds(28, 11, 156, 24);
contentPane.add(lblNewLabel);
textField = new JTextField();
textField.setBounds(204, 13, 86, 20);
contentPane.add(textField);
textField.setColumns(10);
JButton btnSearch = new JButton("Search");
btnSearch.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
ArrayList<Employee> ea = null;
String na = textField.getText();
if (na.length()==0)
ea= e.getAll();
else
ea= e.search(na);
EmployeeTableModel model = new EmployeeTableModel(ea);
table.setModel(model);
}
});
btnSearch.setBounds(319, 12, 89, 23);
contentPane.add(btnSearch);
JScrollBar scrollBar = new JScrollBar();
scrollBar.setBounds(407, 46, 17, 204);
contentPane.add(scrollBar);
table = new JTable();
table.setBounds(10, 43, 414, 207);
contentPane.add(table);
}
}
| true |
9915b9ad45274d010f640c02a78b7fe4f2862034 | Java | nosan/embedded-cassandra | /src/test/java/examples/CassandraExamples.java | UTF-8 | 10,390 | 1.546875 | 2 | [
"Apache-2.0"
] | permissive | /*
* Copyright 2020-2021 the original author or authors.
*
* 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
*
* https://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 examples;
import java.io.File;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Duration;
import com.datastax.oss.driver.api.core.CqlSession;
import org.junit.jupiter.api.BeforeAll;
import org.slf4j.LoggerFactory;
import com.github.nosan.embedded.cassandra.Cassandra;
import com.github.nosan.embedded.cassandra.CassandraBuilder;
import com.github.nosan.embedded.cassandra.DefaultWorkingDirectoryInitializer;
import com.github.nosan.embedded.cassandra.Settings;
import com.github.nosan.embedded.cassandra.SimpleSeedProviderConfigurator;
import com.github.nosan.embedded.cassandra.Version;
import com.github.nosan.embedded.cassandra.WebCassandraDirectoryProvider;
import com.github.nosan.embedded.cassandra.WorkingDirectoryCustomizer;
import com.github.nosan.embedded.cassandra.WorkingDirectoryDestroyer;
import com.github.nosan.embedded.cassandra.WorkingDirectoryInitializer;
import com.github.nosan.embedded.cassandra.commons.ClassPathResource;
import com.github.nosan.embedded.cassandra.commons.FileSystemResource;
import com.github.nosan.embedded.cassandra.commons.logging.ConsoleLogger;
import com.github.nosan.embedded.cassandra.commons.logging.Logger;
import com.github.nosan.embedded.cassandra.commons.logging.Slf4jLogger;
import com.github.nosan.embedded.cassandra.commons.web.JdkHttpClient;
import com.github.nosan.embedded.cassandra.cql.CqlDataSet;
import com.github.nosan.embedded.cassandra.cql.CqlScript;
/**
* Cassandra examples.
*
* @author Dmytro Nosan
*/
public class CassandraExamples {
//tag::start-shared-cassandra[]
@BeforeAll
public static void startCassandra() {
SharedCassandra.start();
}
//end::start-shared-cassandra[]
private void workingDirectoryInitializer() {
//tag::working-directory-initializer[]
new CassandraBuilder()
.workingDirectoryInitializer(new WorkingDirectoryInitializer() {
@Override
public void init(Path workingDirectory, Version version) throws IOException {
//Custom logic
}
})
.build();
//end::working-directory-initializer[]
//tag::working-directory-initializer-skip-existing[]
new CassandraBuilder()
.workingDirectoryInitializer(new DefaultWorkingDirectoryInitializer(new WebCassandraDirectoryProvider(),
DefaultWorkingDirectoryInitializer.CopyStrategy.SKIP_EXISTING))
.build();
//end::working-directory-initializer-skip-existing[]
}
private void workingDirectory() {
//tag::working-directory[]
new CassandraBuilder()
.workingDirectory(() -> Files.createTempDirectory("apache-cassandra-"))
.build();
//end::working-directory[]
}
private void customClasspath() {
//tag::custom-classpath[]
new CassandraBuilder()
.addWorkingDirectoryResource(new ClassPathResource("lib.jar"), "lib/lib.jar")
.build();
//end::custom-classpath[]
}
private void quickStart() {
// tag::quick-start[]
Cassandra cassandra = new CassandraBuilder().build();
cassandra.start();
try {
Settings settings = cassandra.getSettings();
try (CqlSession session = CqlSession.builder()
.addContactPoint(new InetSocketAddress(settings.getAddress(), settings.getPort()))
.withLocalDatacenter("datacenter1")
.build()) {
CqlScript.ofClassPath("schema.cql").forEachStatement(session::execute);
}
}
finally {
cassandra.stop();
}
// end::quick-start[]
}
private void version() {
//tag::version[]
new CassandraBuilder()
.version("3.11.11")
.build();
//end::version[]
}
private void configFile() {
//tag::config-file[]
new CassandraBuilder()
.configFile(new ClassPathResource("cassandra.yaml"))
.build();
//end::config-file[]
}
private void configProperties() {
//tag::config-property[]
new CassandraBuilder()
.addConfigProperty("native_transport_port", 9000)
.addConfigProperty("storage_port", 7000)
.addConfigProperty("client_encryption_options.enabled", true)
.build();
//end::config-property[]
}
private void systemProperties() {
//tag::system-property[]
new CassandraBuilder()
.addSystemProperty("cassandra.native_transport_port", 9042)
.addSystemProperty("cassandra.jmx.local.port", 7199)
.build();
//end::system-property[]
}
private void environmentVariables() {
//tag::environment-variable[]
new CassandraBuilder()
.addEnvironmentVariable("JAVA_HOME", System.getProperty("java.home"))
.build();
//end::environment-variable[]
}
private void jvmOptions() {
//tag::jvm-options[]
new CassandraBuilder()
.addJvmOptions("-Xmx512m")
.build();
//end::jvm-options[]
}
private void clientEncryptionOptions() {
//tag::client-encryption-options[]
ClassPathResource keystore = new ClassPathResource("server.keystore");
ClassPathResource truststore = new ClassPathResource("server.truststore");
new CassandraBuilder()
.addWorkingDirectoryResource(keystore, "conf/server.keystore")
.addWorkingDirectoryResource(truststore, "conf/server.truststore")
.addConfigProperty("client_encryption_options.enabled", true)
.addConfigProperty("client_encryption_options.require_client_auth", true)
.addConfigProperty("client_encryption_options.optional", false)
.addConfigProperty("client_encryption_options.keystore", "conf/server.keystore")
.addConfigProperty("client_encryption_options.truststore", "conf/server.truststore")
.addConfigProperty("client_encryption_options.keystore_password", "123456")
.addConfigProperty("client_encryption_options.truststore_password", "123456")
// Use a dedicated SSL port if necessary
.addConfigProperty("native_transport_port_ssl", 9142)
.build();
//end::client-encryption-options[]
}
private void authenticator() {
//tag::authenticator[]
new CassandraBuilder()
.addConfigProperty("authenticator", "PasswordAuthenticator")
.addConfigProperty("authorizer", "CassandraAuthorizer")
.addSystemProperty("cassandra.superuser_setup_delay_ms", 0) //<1>
.build();
//end::authenticator[]
}
private void randomPorts() {
//tag::random-ports[]
new CassandraBuilder()
.addSystemProperty("cassandra.native_transport_port", 0)
.addSystemProperty("cassandra.rpc_port", 0)
.addSystemProperty("cassandra.storage_port", 0)
.addSystemProperty("cassandra.jmx.local.port", 0)
//for Cassandra 4.x.x
.configure(new SimpleSeedProviderConfigurator("localhost:0"))
.build();
//end::random-ports[]
}
private void seeds() {
//tag::configure-seeds[]
new CassandraBuilder()
.configure(new SimpleSeedProviderConfigurator()
.addSeeds("localhost", "127.0.0.1")
//for Cassandra 4.x.x
.addSeed("localhost", 7199)
.addSeed("localhost", 0)) //<1>
.build();
//end::configure-seeds[]
}
private void startupTimeout() {
//tag::startup-timeout[]
new CassandraBuilder()
.startupTimeout(Duration.ofMinutes(1))
.build();
//end::startup-timeout[]
}
private void proxy() {
//tag::proxy[]
new CassandraBuilder()
.workingDirectoryInitializer(
new DefaultWorkingDirectoryInitializer(new WebCassandraDirectoryProvider(
new JdkHttpClient(Proxy.NO_PROXY))))
.build();
//end::proxy[]
}
private void shutdownHook() {
//tag::shutdown-hook[]
new CassandraBuilder()
.registerShutdownHook(true)
.build();
//end::shutdown-hook[]
}
private void logger() {
//tag::logger[]
new CassandraBuilder()
//Automatically detects logging implementation. Either slf4j or console.
.logger(Logger.get("Cassandra"))
//Use SLF4J Logger implementation
.logger(new Slf4jLogger(LoggerFactory.getLogger("Cassandra")))
//Use Console implementation.
.logger(new ConsoleLogger("Cassandra"))
.build();
//end::logger[]
}
private void workingDirectoryCustomizer() {
//tag::working-directory-customizer[]
new CassandraBuilder()
.addWorkingDirectoryCustomizers(new WorkingDirectoryCustomizer() {
@Override
public void customize(Path workingDirectory, Version version) throws IOException {
//Custom logic
}
}).build();
//end::working-directory-customizer[]
}
private void workingDirectoryDestroyer() {
//tag::working-directory-destroyer[]
new CassandraBuilder()
.workingDirectoryDestroyer(new WorkingDirectoryDestroyer() {
@Override
public void destroy(Path workingDirectory, Version version) throws IOException {
//Custom logic
}
})
.build();
//end::working-directory-destroyer[]
//tag::working-directory-destroyer-nothing[]
new CassandraBuilder()
.workingDirectoryDestroyer(WorkingDirectoryDestroyer.doNothing())
.build();
//end::working-directory-destroyer-nothing[]
//tag::working-directory-destroyer-all[]
new CassandraBuilder()
.workingDirectoryDestroyer(WorkingDirectoryDestroyer.deleteAll())
.build();
//end::working-directory-destroyer-all[]
}
private void addWorkingDirectoryResource() {
//tag::add-resource[]
new CassandraBuilder()
.addWorkingDirectoryResource(new ClassPathResource("cassandra-rackdc.properties"),
"conf/cassandra-rackdc.properties");
//end::add-resource[]
}
private void cqlStatements() {
CqlSession session = null;
//tag::cql[]
CqlScript.ofClassPath("schema.cql").forEachStatement(session::execute);
CqlDataSet.ofClassPaths("schema.cql", "V1__table.cql", "V2__table.cql").forEachStatement(session::execute);
CqlScript.ofResource(new FileSystemResource(new File("schema.cql"))).forEachStatement(session::execute);
CqlDataSet.ofResources(new FileSystemResource(new File("schema.cql")),
new FileSystemResource(new File("V1__table.cql"))).forEachStatement(session::execute);
//end::cql[]
}
}
| true |
395789b32b9e620199bdb5bbf5ac6929eb070872 | Java | apache/drill | /exec/java-exec/src/test/java/org/apache/drill/exec/physical/impl/scan/TestScanOperExecBasics.java | UTF-8 | 10,915 | 2.046875 | 2 | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0",
"MIT",
"LicenseRef-scancode-unknown"
] | permissive | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.drill.exec.physical.impl.scan;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import org.apache.drill.categories.RowSetTest;
import org.apache.drill.common.exceptions.ExecutionSetupException;
import org.apache.drill.common.exceptions.UserException;
import org.apache.drill.exec.physical.impl.scan.ScanTestUtils.ScanFixture;
import org.apache.drill.exec.physical.impl.scan.framework.SchemaNegotiator;
import org.apache.drill.exec.record.VectorContainer;
import org.junit.Test;
import org.junit.experimental.categories.Category;
/**
* Tests the basics of the scan operator protocol: error conditions,
* etc.
*/
@Category(RowSetTest.class)
public class TestScanOperExecBasics extends BaseScanOperatorExecTest {
/**
* Pathological case that a scan operator is provided no readers.
* It will throw a user exception because the downstream operators
* can't handle this case so we choose to stop the show early to
* avoid getting into a strange state.
*/
@Test
public void testNoReader() {
// Create the scan operator
ScanFixture scanFixture = simpleFixture();
ScanOperatorExec scan = scanFixture.scanOp;
try {
scan.buildSchema();
} catch (UserException e) {
// Expected
assertTrue(e.getCause() instanceof ExecutionSetupException);
}
// Must close the DAG (context and scan operator) even on failures
scanFixture.close();
}
public final String ERROR_MSG = "My Bad!";
@Test
public void testExceptionOnOpen() {
// Reader which fails on open with a known error message
// using an exception other than UserException.
MockEarlySchemaReader reader = new MockEarlySchemaReader() {
@Override
public boolean open(SchemaNegotiator schemaNegotiator) {
openCalled = true;
throw new IllegalStateException(ERROR_MSG);
}
};
reader.batchLimit = 0;
ScanFixture scanFixture = simpleFixture(reader);
ScanOperatorExec scan = scanFixture.scanOp;
try {
scan.buildSchema();
fail();
} catch (UserException e) {
assertTrue(e.getMessage().contains(ERROR_MSG));
assertTrue(e.getCause() instanceof IllegalStateException);
}
assertTrue(reader.openCalled);
assertEquals(0, scan.batchAccessor().rowCount());
scanFixture.close();
assertTrue(reader.closeCalled);
}
@Test
public void testUserExceptionOnOpen() {
// Reader which fails on open with a known error message
// using a UserException.
MockEarlySchemaReader reader = new MockEarlySchemaReader() {
@Override
public boolean open(SchemaNegotiator schemaNegotiator) {
openCalled = true;
throw UserException.dataReadError()
.addContext(ERROR_MSG)
.build(logger);
}
};
reader.batchLimit = 2;
ScanFixture scanFixture = simpleFixture(reader);
ScanOperatorExec scan = scanFixture.scanOp;
try {
scan.buildSchema();
fail();
} catch (UserException e) {
assertTrue(e.getMessage().contains(ERROR_MSG));
assertNull(e.getCause());
}
assertTrue(reader.openCalled);
assertEquals(0, scan.batchAccessor().rowCount());
scanFixture.close();
assertTrue(reader.closeCalled);
}
@Test
public void testExceptionOnFirstNext() {
MockEarlySchemaReader reader = new MockEarlySchemaReader() {
@Override
public boolean next() {
super.next(); // Load some data
throw new IllegalStateException(ERROR_MSG);
}
};
reader.batchLimit = 2;
ScanFixture scanFixture = simpleFixture(reader);
ScanOperatorExec scan = scanFixture.scanOp;
assertTrue(scan.buildSchema());
try {
scan.next();
fail();
} catch (UserException e) {
assertTrue(e.getMessage().contains(ERROR_MSG));
assertTrue(e.getCause() instanceof IllegalStateException);
}
assertTrue(reader.openCalled);
assertEquals(0, scan.batchAccessor().rowCount());
scanFixture.close();
assertTrue(reader.closeCalled);
}
@Test
public void testUserExceptionOnFirstNext() {
MockEarlySchemaReader reader = new MockEarlySchemaReader() {
@Override
public boolean next() {
super.next(); // Load some data
throw UserException.dataReadError()
.addContext(ERROR_MSG)
.build(logger);
}
};
reader.batchLimit = 2;
ScanFixture scanFixture = simpleFixture(reader);
ScanOperatorExec scan = scanFixture.scanOp;
assertTrue(scan.buildSchema());
// EOF
try {
scan.next();
fail();
} catch (UserException e) {
assertTrue(e.getMessage().contains(ERROR_MSG));
assertNull(e.getCause());
}
assertTrue(reader.openCalled);
assertEquals(0, scan.batchAccessor().rowCount());
scanFixture.close();
assertTrue(reader.closeCalled);
}
/**
* Test throwing an exception after the first batch, but while
* "reading" the second. Note that the first batch returns data
* and is spread over two next() calls, so the error is on the
* third call to the scan operator next().
*/
@Test
public void testExceptionOnSecondNext() {
MockEarlySchemaReader reader = new MockEarlySchemaReader() {
@Override
public boolean next() {
if (batchCount == 1) {
super.next(); // Load some data
throw new IllegalStateException(ERROR_MSG);
}
return super.next();
}
};
reader.batchLimit = 2;
ScanFixture scanFixture = simpleFixture(reader);
ScanOperatorExec scan = scanFixture.scanOp;
// Schema
assertTrue(scan.buildSchema());
// First batch
assertTrue(scan.next());
scan.batchAccessor().release();
// Fail
try {
scan.next();
fail();
} catch (UserException e) {
assertTrue(e.getMessage().contains(ERROR_MSG));
assertTrue(e.getCause() instanceof IllegalStateException);
}
scanFixture.close();
assertTrue(reader.closeCalled);
}
@Test
public void testUserExceptionOnSecondNext() {
MockEarlySchemaReader reader = new MockEarlySchemaReader() {
@Override
public boolean next() {
if (batchCount == 1) {
super.next(); // Load some data
throw UserException.dataReadError()
.addContext(ERROR_MSG)
.build(logger);
}
return super.next();
}
};
reader.batchLimit = 2;
ScanFixture scanFixture = simpleFixture(reader);
ScanOperatorExec scan = scanFixture.scanOp;
// Schema
assertTrue(scan.buildSchema());
// First batch
assertTrue(scan.next());
scan.batchAccessor().release();
// Fail
try {
scan.next();
fail();
} catch (UserException e) {
assertTrue(e.getMessage().contains(ERROR_MSG));
assertNull(e.getCause());
}
scanFixture.close();
assertTrue(reader.closeCalled);
}
@Test
public void testExceptionOnClose() {
MockEarlySchemaReader reader1 = new MockEarlySchemaReader() {
@Override
public void close() {
super.close();
throw new IllegalStateException(ERROR_MSG);
}
};
reader1.batchLimit = 2;
MockEarlySchemaReader reader2 = new MockEarlySchemaReader();
reader2.batchLimit = 2;
ScanFixture scanFixture = simpleFixture(reader1, reader2);
ScanOperatorExec scan = scanFixture.scanOp;
assertTrue(scan.buildSchema());
assertTrue(scan.next());
scan.batchAccessor().release();
assertTrue(scan.next());
scan.batchAccessor().release();
// Fail on close of first reader
try {
scan.next();
fail();
} catch (UserException e) {
assertTrue(e.getMessage().contains(ERROR_MSG));
assertTrue(e.getCause() instanceof IllegalStateException);
}
assertTrue(reader1.closeCalled);
assertFalse(reader2.openCalled);
scanFixture.close();
}
@Test
public void testUserExceptionOnClose() {
MockEarlySchemaReader reader1 = new MockEarlySchemaReader() {
@Override
public void close() {
super.close();
throw UserException.dataReadError()
.addContext(ERROR_MSG)
.build(logger);
}
};
reader1.batchLimit = 2;
MockEarlySchemaReader reader2 = new MockEarlySchemaReader();
reader2.batchLimit = 2;
ScanFixture scanFixture = simpleFixture(reader1, reader2);
ScanOperatorExec scan = scanFixture.scanOp;
assertTrue(scan.buildSchema());
assertTrue(scan.next());
scan.batchAccessor().release();
assertTrue(scan.next());
scan.batchAccessor().release();
// Fail on close of first reader
try {
scan.next();
fail();
} catch (UserException e) {
assertTrue(e.getMessage().contains(ERROR_MSG));
assertNull(e.getCause());
}
assertTrue(reader1.closeCalled);
assertFalse(reader2.openCalled);
scanFixture.close();
}
/**
* Test multiple readers, all EOF on first batch.
* The scan will return one empty batch to declare the
* early schema. Results in an empty (rather than null)
* result set.
*/
@Test
public void testMultiEOFOnFirstBatch() {
MockEarlySchemaReader reader1 = new MockEarlySchemaReader();
reader1.batchLimit = 0;
MockEarlySchemaReader reader2 = new MockEarlySchemaReader();
reader2.batchLimit = 0;
ScanFixture scanFixture = simpleFixture(reader1, reader2);
ScanOperatorExec scan = scanFixture.scanOp;
// EOF
assertTrue(scan.buildSchema());
assertTrue(scan.next());
VectorContainer container = scan.batchAccessor().container();
assertEquals(0, container.getRecordCount());
assertEquals(2, container.getNumberOfColumns());
assertTrue(reader1.closeCalled);
assertTrue(reader2.closeCalled);
assertEquals(0, scan.batchAccessor().rowCount());
assertFalse(scan.next());
scanFixture.close();
}
}
| true |
61cd1d1dbd62b205ec511e3a6a77b1022ce4eaff | Java | 2714rohit/DataStructure-Algorithm | /src/main/java/com/rohit/ds_algo/TicTacToe.java | UTF-8 | 1,557 | 3.515625 | 4 | [] | no_license | package com.rohit.ds_algo;
public class TicTacToe {
int n=0;
int[][] board;
TicTacToe(int n){
this.n = n;
board = new int[n][n];
}
boolean move(int player, int row, int col) throws IllegalArgumentException{
if(row<0 || col<0 || row>=n || col>=n)
throw new IllegalArgumentException("Invalid cell move");
if(board[row][col]!=0)
throw new IllegalArgumentException("wrong move");
if(player!=-1 && player!=1)
throw new IllegalArgumentException("Wrong Player");
board[row][col] = player;
boolean rowP =true, colP=true, diagP=true, rDiagP=true;
for(int i=0; i<n; ++i) {
if(board[row][i]!=player)
rowP=false;
if(board[i][col]!=player)
colP=false;
if(board[i][i]!=player)
diagP=false;
if(board[n-i-1][n-i-1]!=player)
rDiagP=false;
}
if(rowP||colP||diagP||rDiagP)
return true;
else return false;
}
public static void main(String[] args) {
TicTacToe ticTacToe = new TicTacToe(3);
if(ticTacToe.move(1, 0, 0)) {
System.out.println("player 1 won the match");
}
if(ticTacToe.move(-1, 0, 2)) {
System.out.println("player -1 won the match");
}
if(ticTacToe.move(1, 2, 2)) {
System.out.println("player 1 won the match");
}
if(ticTacToe.move(-1, 1, 1)) {
System.out.println("player -1 won the match");
}
if(ticTacToe.move(1, 2, 0)) {
System.out.println("player 1 won the match");
}
if(ticTacToe.move(-1, 1, 0)) {
System.out.println("player -1 won the match");
}
if(ticTacToe.move(1, 2, 1)) {
System.out.println("player 1 won the match");
}
}
}
| true |
88f5c0ece64ed44078ab99ee014246543d91f436 | Java | benhenda89/MiniMarket | /src/main/java/com/minimarket/core/domain/Payment.java | UTF-8 | 359 | 2.046875 | 2 | [] | no_license | package com.minimarket.core.domain;
import java.math.BigDecimal;
import java.util.Date;
public interface Payment {
Customer getCustomerNumber();
void setCustomerNumber(Customer customerNumber);
String getCheckNumber();
Date getPaymentDate();
void setPaymentDate(Date paymentDate);
BigDecimal getAmount();
void setAmount(BigDecimal amount);
}
| true |
74bda803544685d72e9386a036e1b200a6d637e7 | Java | meghanarang/garment-printing-with-voice- | /src/com/gui/Employee.java | UTF-8 | 4,977 | 2.59375 | 3 | [] | no_license | package com.gui;
import java.awt.EventQueue;
import java.awt.Window;
import javax.swing.JFrame;
import javax.swing.JLabel;
import com.Employee.EditEmployee;
import com.Employee.NewEmployee;
//import com.Employee.Newemployee;
import com.Employee.ViewEmployee;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.SQLException;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Employee {
public JFrame frame;
/**
* Launch the application.
*/
/**
* Create the application.
*/
public Employee() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
void initialize() {
frame = new JFrame();
frame.setSize(500, 500);
frame.setDefaultCloseOperation(frame.DISPOSE_ON_CLOSE);
frame.getContentPane().setLayout(null);
JButton btnNewButton_2 = new JButton("");
btnNewButton_2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
ViewEmployee e=new ViewEmployee();
e.frame.setVisible(true);
frame.dispose();
}
});
btnNewButton_2.addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent arg0) {
btnNewButton_2.setIcon(new ImageIcon(Employee.class.getResource("viewemployee.png")));
// btnNewButton_2.setIcon(new ImageIcon("D:\\my project\\home\\viewemployee.png"));
}
@Override
public void mouseExited(MouseEvent arg0) {
btnNewButton_2.setIcon(new ImageIcon(Employee.class.getResource("viewemployee1.png")));
//btnNewButton_2.setIcon(new ImageIcon("D:\\my project\\home\\viewemployee1.png"));
}
});
JButton btnNewButton_3 = new JButton("New button");
btnNewButton_3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
EditEmployee e = new EditEmployee();
e.setVisible(true);
frame.dispose();
}
});
btnNewButton_3.setIcon(new ImageIcon("D:\\my project\\home\\Editemployee1.png"));
btnNewButton_3.setBounds(196, 27, 151, 199);
frame.getContentPane().add(btnNewButton_3);
btnNewButton_2.setIcon(new ImageIcon(Employee.class.getResource("viewemployee1.png")));
//btnNewButton_2.setIcon(new ImageIcon("D:\\my project\\home\\viewemployee1.png"));
btnNewButton_2.setBounds(196, 283, 146, 168);
frame.getContentPane().add(btnNewButton_2);
JButton btnNewButton_1 = new JButton("");
btnNewButton_1.setBorder(null);
btnNewButton_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Dashboard dashboard = new Dashboard();
dashboard.frame.setVisible(true);
frame.dispose();
}
});
btnNewButton_1.setIcon(new ImageIcon(Employee.class.getResource("home.jpg")));
//btnNewButton_1.setIcon(new ImageIcon("D:\\my project\\home\\home.jpg"));
btnNewButton_1.addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent arg0) {
btnNewButton_1.setIcon(new ImageIcon(Employee.class.getResource("home1.jpg")));
//btnNewButton_1.setIcon(new ImageIcon("D:\\my project\\home\\home1.jpg"));
}
@Override
public void mouseExited(MouseEvent arg0) {
btnNewButton_1.setIcon(new ImageIcon(Employee.class.getResource("home.jpg")));
//btnNewButton_1.setIcon(new ImageIcon("D:\\my project\\home\\home.jpg"));
}
});
btnNewButton_1.setBounds(10, 11, 100, 100);
frame.getContentPane().add(btnNewButton_1);
JButton btnNewButton = new JButton("");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
NewEmployee e = new NewEmployee();
e.frame.setVisible(true);
frame.dispose();
}
});
btnNewButton.addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent arg0) {
btnNewButton.setIcon(new ImageIcon(Employee.class.getResource("new employee.png")));
//btnNewButton.setIcon(new ImageIcon("D:\\my project\\home\\new employee.png"));
}
@Override
public void mouseExited(MouseEvent arg0) {
btnNewButton.setIcon(new ImageIcon(Employee.class.getResource("new employee1.png")));
//btnNewButton.setIcon(new ImageIcon("D:\\my project\\home\\new employee1.png"));
}
});
btnNewButton.setIcon(new ImageIcon(Employee.class.getResource("new employee1.png")));
//btnNewButton.setIcon(new ImageIcon("D:\\my project\\home\\new employee1.png"));
btnNewButton.setBounds(10, 144, 176, 143);
frame.getContentPane().add(btnNewButton);
JLabel lblNewLabel = new JLabel("");
lblNewLabel.setIcon(new ImageIcon(Employee.class.getResource("Untitled1.jpg")));
lblNewLabel.setIcon(new ImageIcon("D:\\my project\\Untitled1.jpg"));
lblNewLabel.setBounds(0, 0, 500, 500);
frame.getContentPane().add(lblNewLabel);
}
}
| true |
ebb61a5f2ffdf516acaa1ac28ac90262e07375ed | Java | jweschenfelder/dcache | /modules/cells/src/main/java/dmg/cells/applets/login/SshLoginFPPanel.java | UTF-8 | 2,616 | 2.46875 | 2 | [] | no_license | package dmg.cells.applets.login ;
import java.awt.Button;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Label;
import java.awt.Panel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import dmg.cells.applets.spy.BorderPanel;
public class SshLoginFPPanel
extends SshActionPanel
implements ActionListener {
private static final long serialVersionUID = -6433181861280030266L;
private Button _acceptButton ;
private Button _rejectButton ;
private Label _hostLabel ;
private Label _fingerprintLabel ;
private Font _font = new Font( "TimesRoman" , 0 , 14 ) ;
private String _dummy = "00";
// private String _dummy = "00:00:00:00:00:00:00:00:00:00:00:00";
SshLoginFPPanel(){
// setLayout( new CenterLayout( ) ) ;
Panel p = new Panel( new GridLayout(0,1) ) ;
setFont( _font ) ;
p.setBackground( Color.yellow ) ;
p.add( new Label( "Dear User, the Host" , Label.CENTER ) ) ;
p.add( _hostLabel = new Label("",Label.CENTER ) ) ;
_hostLabel.setForeground( Color.blue ) ;
_hostLabel.setFont( _font ) ;
p.add( new Label( "has sent us the Fingerprint",Label.CENTER ) ) ;
p.add( _fingerprintLabel = new Label( _dummy , Label.CENTER ) ) ;
p.add( new Label( "do you want to", Label.CENTER ) ) ;
Panel yesNo = new Panel( new GridLayout(1,2) ) ;
yesNo.add( _acceptButton = new Button( "Accept it" ) ) ;
_acceptButton.setBackground( Color.green ) ;
yesNo.add( _rejectButton = new Button( "Reject it" ) ) ;
_rejectButton.setBackground( Color.red ) ;
_rejectButton.setForeground( Color.white ) ;
// p.validateTree() ;
p.add( yesNo ) ;
p.doLayout();
doLayout();
add( new BorderPanel( p ) ) ;
_acceptButton.addActionListener( this ) ;
_rejectButton.addActionListener( this ) ;
}
public void setFingerPrint( String host , String fp ){
_hostLabel.setText( host ) ;
_fingerprintLabel.setText( fp ) ;
System.out.println( "Enforcing layout" ) ;
doLayout() ;
System.out.println( "Layout done" ) ;
}
@Override
public void actionPerformed( ActionEvent event ){
String command = event.getActionCommand() ;
System.out.println( "Action : "+command ) ;
Object obj = event.getSource() ;
if( obj == _acceptButton ){
informActionListeners( "accept" ) ;
}else if( obj == _rejectButton ){
informActionListeners( "reject" ) ;
}
}
}
| true |
e325048d27e0a5efdd05ed239ca130a7ba52701b | Java | i-am-ajay/FP | /src/email/EmailSender.java | UTF-8 | 2,027 | 2.453125 | 2 | [] | no_license | package email;
import globals.SenderEmailConf;
import javax.mail.*;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
/**
* Created by ajay on 14-Nov-16.
*/
public class EmailSender {
Session session;
public EmailSender(){
session = getSession();
}
public boolean sendMail(Message msg) {
try {
//Message message = createMessage(mailSession, keys, mailId);
Message message =msg;
Transport.send(message);
}
catch(MessagingException ex){
ex.printStackTrace();
}
return true;
}
public Session getSession(){
Properties prop = new Properties();
prop.setProperty("mail.smtp.auth","true");
prop.setProperty("mail.smtp.starttls.enable","true");
prop.setProperty("mail.smtp.host", SenderEmailConf.host);
prop.setProperty("mail.smtp.port", SenderEmailConf.port);
Session session = Session.getDefaultInstance(prop, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication(SenderEmailConf.senderEmail, SenderEmailConf.senderPassword);
}
});
return session;
}
public Message createMessage(String mailMessage,String recipients) throws MessagingException {
String to = "";
Message message = new MimeMessage(session);
// set sender and recipients of the message
message.setFrom(new InternetAddress(SenderEmailConf.senderEmail));
message.addRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients));
// create message.
message.setSubject("Query Keys");
message.setText(mailMessage);
return message;
}
public static void main(String [] args){
EmailSender sender = new EmailSender();
//sender.sendMail("woueroiwur","ajaychandel.1987@gmail.com");
}
}
| true |
a181a1d316b82f7bb9f1fe0d1f2a3dc6ec6ff03b | Java | gabriel-ruffo/StudyTogether | /app/src/main/java/com/example/gabriel/studytogether2/dbMedium_package/DBMediumGetUser.java | UTF-8 | 2,121 | 2.109375 | 2 | [] | no_license | package com.example.gabriel.studytogether2.dbMedium_package;
import android.os.Bundle;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.AsyncTaskLoader;
import android.support.v4.content.Loader;
import com.example.gabriel.studytogether2.DatabaseAccess;
import com.example.gabriel.studytogether2.SignInActivity;
/**
* Created by Charley on 11/9/17.
*/
public class DBMediumGetUser implements LoaderManager.LoaderCallbacks<String> {
private SignInActivity signIn;
private String email;
private static final int DB_LOADER = 77;
public DBMediumGetUser(SignInActivity signIn) {
this.signIn = signIn;
}
public void getScheduleId(String email) {
this.email = email;
LoaderManager loaderManager = signIn.getSupportLoaderManager();
Loader<String> loader = loaderManager.getLoader(DB_LOADER);
if (loader == null)
loaderManager.initLoader(DB_LOADER, null, this).forceLoad();
else
loaderManager.restartLoader(DB_LOADER, null, this).forceLoad();
}
@Override
public Loader<String> onCreateLoader(int id, Bundle args) {
return new AsyncTaskLoader<String>(signIn) {
private String schedule_id;
@Override
public void onStartLoading() {
if (schedule_id != null) {
deliverResult(schedule_id);
} else {
forceLoad();
}
}
@Override
public String loadInBackground() {
DatabaseAccess dba = new DatabaseAccess();
schedule_id = dba.getScheduleId(email);
return schedule_id;
}
@Override
public void deliverResult(String data) {
schedule_id = data;
super.deliverResult(data);
}
};
}
@Override
public void onLoadFinished(Loader<String> loader, String data) {
signIn.loadFinished(data);
}
@Override
public void onLoaderReset(Loader<String> loader) {
}
}
| true |
0d8c54cad4262db2a970c9d8e9482710c4726ef1 | Java | leoclc/fj-26 | /src/br/com/caelum/notasfiscais/modelo/UsuarioLogado.java | UTF-8 | 684 | 2.0625 | 2 | [] | no_license | package br.com.caelum.notasfiscais.modelo;
import java.io.Serializable;
import javax.enterprise.context.SessionScoped;
import javax.inject.Named;
@Named
@SessionScoped
public class UsuarioLogado implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private String lastURL ="produto?faces-redirect=true";
private Usuario usuario;
public Usuario getUsuario() {
return usuario;
}
public boolean isLogado(){
return usuario != null;
}
public void setUsuario(Usuario usuario) {
this.usuario = usuario;
}
public String getLastURL() {
return lastURL;
}
public void setLastURL(String lastURL) {
this.lastURL = lastURL;
}
}
| true |
735b394de755c7a1b9c58ff56b243b942261393c | Java | kwishna/Cucumber_New_Versions | /src/test/java/Cucumber_v6_4_0/Hooks/Hooks.java | UTF-8 | 608 | 2.359375 | 2 | [] | no_license | package Cucumber_v6_4_0.Hooks;
import io.cucumber.java.After;
import io.cucumber.java.AfterStep;
import io.cucumber.java.Before;
import io.cucumber.java8.Scenario;
public class Hooks {
@After(order = 1)
public void after1(Scenario s){
System.out.println("After Each Scenario order1");
}
@After(order = 2)
public void after2(Scenario s){
System.out.println("After Each Scenario order2");
}
@Before("@int")
public void before1(Scenario s){
System.out.println("Before Each Scenario @int");
}
@AfterStep
public void afterEachStep(Scenario s){
System.out.println("After Each Step");
}
}
| true |
5168c0faa24e814cc5c77c8f086186ac41e2af15 | Java | mkharto/final-project | /source/JavaApplication25/src/MainPackage/Suite.java | UTF-8 | 1,698 | 2.890625 | 3 | [] | no_license | package MainPackage;
//class untuk pelanggan yang memilih tipe kamar Suite
public class Suite extends Jenis {
protected final static double harga=350000;
protected static int kamar=20;
protected double invoice;
public double getInvoice() {
return invoice;
}
//method untuk set tipe kamar yaitu Suite
public void setTipe() {
this.tipe = "Suite";
}
//method untuk set banyaknya hari tinggal di hotel
public void booking(int days){
kamar--;
invoice=days*harga;
pelanggan.setAkumulasi(days);
}
@Override
//override method dari class Jenis untuk menampilkam tipe kamar
public String tampilTpKamar() {
return tipe;
}
@Override
//override method dari class Jenis untuk menampilkan jumlah kamar yang tersedia
public int tampilJmlKamar() {
return kamar;
}
@Override
//override method dari class Jenis untuk menampilkan total harga invoice
public double tampilHarga() {
return invoice;
}
@Override
//override method dari class Jenis yang memberikan nilai kembali yaitu diskon yang didapatkan sesuai dengan akumulasi
public double getDiskon() {
double d;
if(pelanggan.getAkumulasi()>9&&pelanggan.getAkumulasi()<=30)
d=invoice*10/100;
else if(pelanggan.getAkumulasi()>30&&pelanggan.getAkumulasi()<=60)
d=invoice*15/100;
else if(pelanggan.getAkumulasi()>60)
d=invoice*25/100;
else
d=0;
return d;
}
//method yang mengembalikan nilai yaitu total pembayaran setelah dipotong diskon
public double total(){return (invoice-getDiskon());}
}
| true |
2f63449e1f677ccb7ecd9004e1233730e17d1907 | Java | ArkishaP/HackathonProject | /src/main/java/com/hackathon/dao/AdminDaoImpl.java | UTF-8 | 1,551 | 2.4375 | 2 | [] | no_license | package com.hackathon.dao;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.stereotype.Repository;
import com.hackathon.model.Admin;
import com.hackathon.model.Subject;
@Repository("admindao")
public class AdminDaoImpl implements AdminDaoIntf{
@PersistenceContext
EntityManager em;
public boolean loginAdmin(Admin admin) {
boolean flag= false;
Admin a =null;
try{
a=(Admin)em.createQuery("SELECT a FROM Admin a WHERE a.username=:username and a.password=:password")
.setParameter("username", admin.getUsername())
.setParameter("password",admin.getPassword())
.getSingleResult();
}
catch(Exception e) {System.out.println(e); }
if (a!=null)
flag=true;
System.out.println(a);
return flag;
}
public boolean addSubject(Subject subject) {
boolean flag = false;
try{
em.persist(subject);
flag = true;
}catch(Exception e){
System.out.println("Error:"+e);
}
return flag;
}
public List<Subject> getSubjects() {
List<Subject> subjects = new ArrayList<Subject>();
subjects = em.createQuery("SELECT s from Subject s").getResultList();
return subjects;
}
public boolean removeQuestion(String questionId) {
// TODO Auto-generated method stub
return false;
}
public boolean removeSubject(String subjectId) {
boolean flag = false;
Subject subject = em.find(Subject.class, subjectId);
em.remove(subject);
flag = true;
return flag;
}
}
| true |
b795fe9b9959bdf1ac3599ba2d4f03fdfbac6c3f | Java | zadjii/demigods | /src/gui/util/OnClickListener.java | UTF-8 | 171 | 1.851563 | 2 | [
"MIT"
] | permissive | package gui.util;
/**
* Created with IntelliJ IDEA.
* User: zadjii
* Date: 10/28/13
* Time: 11:47 AM
*/
public interface OnClickListener {
public void onClick();
}
| true |
d75fc3e59e9c4f8081607d0c9c35f827ae4c6cd0 | Java | Eugene1992/java-starter-10 | /vasiliy/src/main/java/lesson3/Task1.java | UTF-8 | 564 | 2.5625 | 3 | [] | no_license | package lesson3;
public class Task1 {
public static void main(String[] args) {
int b = 110_1011; //110_1011
int bb = 10000000 + b;
int b7 = (bb) / 10000000;
int b6 = (bb) / 1000000 % 10 * 64;
int b5 = (bb) / 100000 % 10 * 32;
int b4 = (bb) / 10000 % 10 * 16;
int b3 = (bb) / 1000 % 10 * 8;
int b2 = (bb) / 100 % 10 * 4;
int b1 = (bb) / 10 % 10 * 2;
int b0 = (bb) / 1 % 10;
int number = b0 + b1 + b2 + b3 + b4 + b5 + b6;
System.out.println(+number);
}
}
| true |
e232d5bac5626a8fbdd574da4b055d04de13ad36 | Java | lifeifeixz/comflyseureka | /src/main/java/learn/thread/intercefas/Cook.java | UTF-8 | 588 | 2.125 | 2 | [] | no_license | /*
* Copyright (c) 2018, 2018, Travel and/or its affiliates. All rights reserved.
* TRAVEL PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*/
package thread.intercefas;
/**
* @author flysLi
* @ClassName Cook
* @Decription TODO
* @Date 2018/10/22 10:58
* @Version 1.0
*/
public interface Cook {
default Cook brushPot() {
System.out.println("如果你不想刷锅,就当做郭已经刷好。");
return this;
}
Cook cutUpVegetables();
Cook cooking();
Cook outPot();
}
| true |
f7f5643b5a9dc1742032afc0cb1b72dcad48d879 | Java | konker/ProtocolBenchmarker | /src/fi/hiit/android/data/DbXmlParser.java | UTF-8 | 2,164 | 2.453125 | 2 | [] | no_license | package fi.hiit.android.data;
import android.util.Log;
import android.content.Context;
import java.util.HashMap;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.XMLReader;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
/* XML parser */
public class DbXmlParser extends DefaultHandler {
static final String NAME_QUERY = "query";
static final String NAME_NAME = "name";
private HashMap<String, String> rep;
private String curName = null;
private String curValue = null;
/*[FIXME: better exceptions?]*/
public DbXmlParser(Context context, int dbXmlResource) throws Exception {
this.rep = new HashMap<String, String>();
// read in and parse the xml
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
xr.setContentHandler(this);
xr.parse(new InputSource(context.getResources().openRawResource(dbXmlResource)));
}
public String getQuery(String name) {
return rep.get(name);
}
public void setQuery(String name, String sql) {
rep.put(name, sql);
}
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
if (localName.equals(NAME_QUERY)) {
curName = attributes.getValue(NAME_NAME);
}
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
if (localName.equalsIgnoreCase(NAME_QUERY)) {
if (curName != null && curValue != null) {
setQuery(curName, curValue);
}
curValue = null;
curName = null;
}
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
if (curName != null) {
if (curValue == null) {
curValue = "";
}
curValue += new String(ch, start, length);
}
}
}
| true |
7eb8c69c0bb9abc4f6c15cdea8f7b4e7599b00db | Java | itishsy/see-rpc | /src/main/java/com/see/rpc/nio/client/Proxy.java | UTF-8 | 4,149 | 2.296875 | 2 | [] | no_license | package com.see.rpc.nio.client;
import com.google.common.reflect.AbstractInvocationHandler;
import com.google.common.reflect.Reflection;
import com.see.rpc.cluster.Limit;
import com.see.rpc.cluster.LoadBalance;
import com.see.rpc.cluster.LoadBalanceFactory;
import com.see.rpc.common.exceptions.RpcException;
import com.see.rpc.config.PropertyConfiguration;
import com.see.rpc.nio.Client;
import com.see.rpc.nio.base.Request;
import com.see.rpc.nio.base.Response;
import com.see.rpc.nio.base.ResponseFuture;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.Set;
/**
* Created by Administrator on 2018/12/9.
*/
public class Proxy {
private static final Logger logger = LoggerFactory.getLogger(Proxy.class);
@SuppressWarnings("unchecked")
public static Builder create(Class<?> clazz) {
return new Builder(clazz);
}
public static class Builder<T> {
private final Class<T> clazz;
private String scope;
private long timeout;
private Builder(Class<T> clazz) {
this.clazz = clazz;
}
public Builder scope(String scope) {
this.scope = scope;
return this;
}
public Builder timeout(long timeout) {
this.timeout = timeout;
return this;
}
public T build() {
return Reflection.newProxy(clazz, new AbstractInvocationHandler() {
@Override
protected Object handleInvocation(Object proxy, Method method, Object[] args) throws Throwable {
Request request = new Request();
request.setTimeout(timeout);
request.setService(clazz.getName());
request.setMethod(method.getName());
request.setArgs(args);
return Proxy.getInstance().process(request);
}
});
}
}
private static class Singleton {
public static final Proxy instance = new Proxy();
}
public static Proxy getInstance() {
return Singleton.instance;
}
private Object process(Request request) throws Throwable {
Set<Client> clients = ClientFactory.getInstance().getClients(request.getService());
if(clients == null || clients.size() == 0){
throw new RpcException("remote server not found");
}
ResponseFuture future = clientSend(clients, request);
if(future == null){
throw new RpcException("remote server io exception");
}
return getResult(future);
}
private ResponseFuture clientSend(Set<Client> clients,Request request){
Client client;
if(clients.size() == 1){
client= clients.iterator().next();
} else {
Limit limit = LimitFactory.valueOf(PropertyConfiguration.LOAD_BALANCE);
LoadBalance loadBalance = LoadBalanceFactory.valueOf(PropertyConfiguration.LOAD_BALANCE).limit(limit).instance();
client = loadBalance.select(clients);
}
ResponseFuture future = null;
try {
future = client.send(request);
} catch (RpcException e) {
logger.warn("rpc exception. try next client .", e);
if (clients.size() > 1) {
Set<Client> nextClients = new HashSet<>(clients);
nextClients.remove(client);
return clientSend(nextClients, request);
}
}
return future;
}
private Object getResult(ResponseFuture future) throws Throwable {
Response response = future.get();
if(response == null){
throw new RpcException("request time out");
}
Throwable throwable;
if ((throwable = response.getThrowable()) == null) {
return response.getResult();
}
throwable.printStackTrace();
throw throwable;
}
}
| true |
799198943657596f752f1d6f9d80195bd853fe6f | Java | dadangeuy/rapunzel | /src/main/java/com/rizaldi/judgels/rapunzel/service/ScoreboardService.java | UTF-8 | 2,810 | 2.328125 | 2 | [] | no_license | package com.rizaldi.judgels.rapunzel.service;
import com.rizaldi.judgels.rapunzel.config.ScoreboardConfig;
import com.rizaldi.judgels.rapunzel.model.ScoreboardRow;
import com.rizaldi.judgels.rapunzel.model.judgels.Contest;
import com.rizaldi.judgels.rapunzel.model.judgels.Entry;
import com.rizaldi.judgels.rapunzel.model.judgels.User;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
@Service
public class ScoreboardService {
private static final ExecutorService requestExecutor = Executors.newFixedThreadPool(32);
private final ScoreboardConfig config;
private final JophielApiService jophiel;
private final UrielApiService uriel;
public ScoreboardService(ScoreboardConfig config, JophielApiService jophiel, UrielApiService uriel) {
this.config = config;
this.jophiel = jophiel;
this.uriel = uriel;
}
public List<String> getProblemAlias(String contestPath) throws IOException {
return uriel.getContest(config.getJid(contestPath), config.getType(contestPath))
.getScoreboard().getState().getProblemAliases();
}
public List<ScoreboardRow> getScoreboardRows(String contestPath) throws IOException, ExecutionException, InterruptedException {
Contest contest = uriel.getContest(config.getJid(contestPath), config.getType(contestPath));
List<Entry> entries = contest.getScoreboard().getContent().getEntries();
List<User> users = getUsers(entries);
List<ScoreboardRow> scoreboardRows = new ArrayList<>(entries.size());
for (int i = 0; i < entries.size(); i++) {
ScoreboardRow row = ScoreboardRow.from(entries.get(i), users.get(i));
scoreboardRows.add(row);
}
return scoreboardRows;
}
private List<User> getUsers(List<Entry> entries) throws ExecutionException, InterruptedException {
List<Callable<User>> callables = new ArrayList<>(entries.size());
for (Entry entry : entries) {
Callable<User> callable = () -> jophiel.getUser(entry.getContestantJid());
callables.add(callable);
}
return invokeAll(callables);
}
private <T> List<T> invokeAll(List<Callable<T>> callables) throws InterruptedException, ExecutionException {
List<Future<T>> futures = requestExecutor.invokeAll(callables);
List<T> results = new ArrayList<>(futures.size());
for (Future<T> future : futures) results.add(future.get());
return results;
}
public String getLastUpdateTime(String contestPath) throws IOException {
return uriel.getContest(config.getJid(contestPath), config.getType(contestPath))
.getLastUpdateTime();
}
}
| true |
8181c76196f31b8e0b50e09a5d718fd25f1ea96b | Java | ande8331/SEIS610-GeneticProgram-FinalProject | /GPFinalProject/src/GPFinalProject/GPCandidate.java | UTF-8 | 2,133 | 3.359375 | 3 | [] | no_license | package GPFinalProject;
import java.util.Comparator;
/**
* Comparators the fitness value.
* @author Anderson-Chow-Liberty-Osborn-Tran
* @version 0.5
* @since 11/05/2011
*/
class GPFitnessValueComparator implements Comparator<GPCandidate> {
/**
* Compares fitness values.
* @param gp1 Parameter description.
* @param gp2 Parameter description.
* @return Result
*/
public int compare(final GPCandidate gp1, final GPCandidate gp2) {
if (Double.isNaN(gp1.getFitnessValue())) {
return (1);
}
if (Double.isNaN(gp2.getFitnessValue())) {
return (-1);
}
if (gp1.getFitnessValue() < gp2.getFitnessValue()) {
return (-1);
}
if (gp1.getFitnessValue() > gp2.getFitnessValue()) {
return (1);
}
return (0);
}
}
/**
* Genetic Program Candidate.
* @author Anderson-Chow-Liberty-Osborn-Tran
* @version 0.5
* @since 11/05/2011
*/
public class GPCandidate {
/**
* The candidate.
*/
protected GPNode candidate;
/**
* The candidates fitness value.
*/
protected double fitnessValue;
/**
* Constructor.
*/
public GPCandidate() {
candidate = GPNode.generateNode();
fitnessValue = 0.0;
}
/**
* Update fitness values.
* @param x Parameters description.
* @param expected Parmater description.
* @return Result.
*/
public double updateFitnessValue(final double[] x, final double[] expected) {
double absSum = 0;
for (int i = 0; i < x.length; i++) {
double tmp = candidate.evaluateFitnessValue(x[i]);
tmp = Math.abs(tmp - expected[i]);
absSum += tmp;
}
fitnessValue = absSum;
return (absSum);
}
/**
* Access the fitnessValue.
* @return fitnessValue.
*/
public double getFitnessValue() {
return (fitnessValue);
}
/**
* Access the top node.
* @return candidate.
*/
public GPNode getTopNode() {
return (candidate);
}
}
| true |
c550f0bf080af579ae01af0e3226c4d99c1da7f1 | Java | fajuary/ArcheryApp | /view/MicSeatLayout.java | UTF-8 | 2,700 | 2.515625 | 3 | [] | no_license | package com.fajuary.archeryapp.view;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import com.fajuary.archeryapp.utils.DensityUtil;
/**
* @author zhangpengfei
* @date 2018/11/3
*/
public class MicSeatLayout extends ViewGroup {
private static final int rowsNum = 4;
private final int itemWidth;
private final int itemHeight;
public MicSeatLayout(Context context) {
this(context, null);
}
public MicSeatLayout(Context context, AttributeSet attrs) {
super(context, attrs);
itemWidth = DensityUtil.dip2px(context, 72);
itemHeight = DensityUtil.dip2px(context, 72);
initView(context);
}
private void initView(Context mContext) {
for (int count = 2 * rowsNum, i = 0; i < count; i++) {
boolean isLeft = i < rowsNum;
MicSeatView mic = new MicSeatView(mContext, isLeft);
mic.setSelfRole(MicSeatView.MIC);
addView(mic);
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int childCount = getChildCount();
int childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(itemWidth, MeasureSpec.EXACTLY);
int childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(itemHeight, MeasureSpec.EXACTLY);
for (int i = 0; i < childCount; i++) {
View view = getChildAt(i);
view.measure(childWidthMeasureSpec, childHeightMeasureSpec);
}
/**
* 最后设置的为真实值 前面的都是测量模式
*/
setMeasuredDimension(widthMeasureSpec, MeasureSpec.makeMeasureSpec(itemHeight * rowsNum, MeasureSpec.EXACTLY));
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
int childCount = getChildCount();
int parentWidth = getMeasuredWidth();
for (int i = 0; i < childCount; i++) {
View view = getChildAt(i);
if (i < rowsNum) {
/**
* 小于四个的时候 布局在左边 top为第几个高度
* 宽度为itemWidth
* top加itemHeight
*/
view.layout(0, i * itemHeight, itemWidth, (i + 1) * itemHeight);
} else {
/**
* 多余4个为右边的
* 左边为父布局宽度-每一个宽度
*/
view.layout(parentWidth - itemWidth,
(i % rowsNum) * itemHeight,
parentWidth, (i % rowsNum + 1) * itemHeight);
}
}
}
}
| true |
c84e377d2956bf5c64922282449d5aa79e82de13 | Java | JavaQualitasCorpus/nakedobjects-4.0.0 | /core/remoting/src/main/java/org/nakedobjects/remoting/client/ClientConnectionDefault.java | UTF-8 | 2,889 | 2.34375 | 2 | [
"Apache-2.0"
] | permissive | package org.nakedobjects.remoting.client;
import java.io.IOException;
import org.apache.log4j.Logger;
import org.nakedobjects.remoting.NakedObjectsRemoteException;
import org.nakedobjects.remoting.exchange.Request;
import org.nakedobjects.remoting.exchange.ResponseEnvelope;
import org.nakedobjects.remoting.protocol.ClientMarshaller;
import org.nakedobjects.remoting.transport.ConnectionException;
import org.nakedobjects.runtime.persistence.ConcurrencyException;
/**
* Default implementation of {@link ClientConnection} that delegates to
* {@link ClientMarshaller} supplied in {@link ClientConnectionDefault constructor}.
*/
public class ClientConnectionDefault implements ClientConnection {
@SuppressWarnings("unused")
private static final Logger LOG = Logger.getLogger(ClientConnectionDefault.class);
private final ClientMarshaller marshaller;
//////////////////////////////////////////////////////////
// Constructor
//////////////////////////////////////////////////////////
public ClientConnectionDefault(
final ClientMarshaller marshaller) {
this.marshaller = marshaller;
}
protected ClientMarshaller getMarshaller() {
return marshaller;
}
//////////////////////////////////////////////////////////
// init, shutdown
//////////////////////////////////////////////////////////
public void init() {
marshaller.init();
}
public void shutdown() {
marshaller.shutdown();
}
//////////////////////////////////////////////////////////
// reconnect, connect, disconnect
//////////////////////////////////////////////////////////
private void connect() {
try {
marshaller.connect();
} catch (final IOException e) {
throw new ConnectionException("Connection failure", e);
}
}
private void disconnect() {
marshaller.disconnect();
}
//////////////////////////////////////////////////////////
// executeRemotely
//////////////////////////////////////////////////////////
public ResponseEnvelope executeRemotely(final Request request) {
connect();
try {
return executeRemotelyElseException(request);
} catch (final IOException e) {
throw new ConnectionException("Failed request", e);
} finally {
disconnect();
}
}
private ResponseEnvelope executeRemotelyElseException(final Request request)
throws IOException {
Object response = marshaller.request(request);
if (response instanceof ConcurrencyException) {
throw (ConcurrencyException) response;
} else if (response instanceof Exception) {
throw new NakedObjectsRemoteException(
"Exception occurred on server", (Throwable) response);
} else {
return (ResponseEnvelope) response;
}
}
}
// Copyright (c) Naked Objects Group Ltd.
| true |
2a90864febc505aa4fa52197d61c17bdf258f12b | Java | akhial/tice-factory | /src/com/team33/model/csv/students/courses/Course.java | UTF-8 | 1,241 | 2.984375 | 3 | [] | no_license | package com.team33.model.csv.students.courses;
import java.io.Serializable;
/**
* Created by hamza on 18/04/2017.
*/
public class Course implements Serializable{
private String shortName;
private String fullName;
public Course(String shortName, String fullName) {
this.shortName = shortName;
this.fullName = fullName;
}
public String getShortName() {
return shortName;
}
public String getFullName() {
return fullName;
}
@Override
public String toString() {
return this.shortName +" : "+this.fullName;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Course)) return false;
Course course = (Course) o;
if (this.shortName != null ? !this.shortName.equals(course.shortName) : course.shortName != null) return false;
return this.fullName != null ? this.fullName.equals(course.fullName) : course.fullName == null;
}
@Override
public int hashCode() {
int result = this.shortName != null ? this.shortName.hashCode() : 0;
result = 31 * result + (this.fullName != null ? this.fullName.hashCode() : 0);
return result;
}
}
| true |
a0e3aae265e54334680ac7a635f77d07138dc482 | Java | hina0118/DomaTest | /app/controllers/Application.java | UTF-8 | 473 | 1.882813 | 2 | [] | no_license | package controllers;
import java.util.List;
import org.seasar.doma.jdbc.tx.LocalTransaction;
import play.mvc.Controller;
import play.mvc.With;
import doma.AppConfig;
import doma.user.User;
import doma.user.UserDao;
import doma.user.UserDaoImpl;
@With(Transaction.class)
public class Application extends Controller {
public static void index() {
UserDao userDao = new UserDaoImpl();
List<User> users = userDao.select();
render(users);
}
} | true |
b74cee663a1495227231d56aab1267dd7e66ca13 | Java | AbnerLv/FarmCalender | /app/src/main/java/com/pyp/farmcalender/ui/activity/RegisterActivity.java | UTF-8 | 2,921 | 2.234375 | 2 | [] | no_license | package com.pyp.farmcalender.ui.activity;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.pyp.farmcalender.R;
import com.pyp.farmcalender.service.UserService;
import com.pyp.farmcalender.service.handler.RegisterHandler;
import org.json.JSONException;
import org.json.JSONObject;
public class RegisterActivity extends Activity {
private EditText etUsername;
private EditText etPassword;
private EditText etEmail;
private Button btnRegister;
private Button btnBack;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register_layout);
init();
}
private void init() {
etUsername = (EditText) findViewById(R.id.et_register_username);
etPassword = (EditText) findViewById(R.id.et_register_password);
etEmail = (EditText) findViewById(R.id.et_register_email);
btnRegister = (Button) findViewById(R.id.btn_register);
btnBack = (Button)findViewById(R.id.btn_register_back);
btnRegister.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String username = etUsername.getText().toString().trim();
String password = etPassword.getText().toString().trim();
String email = etEmail.getText().toString().trim();
final JSONObject json = new JSONObject();
try {
json.put("username", username);
json.put("password", password);
json.put("email", email);
} catch (JSONException e) {
e.printStackTrace();
}
UserService.getInstance().register(getApplicationContext(), json, new RegisterHandler() {
@Override
public void register(int success) {
if (success == 1) {
Toast.makeText(getApplicationContext(),"注册成功",Toast.LENGTH_LONG).show();
Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
startActivity(intent);
}else{
Toast.makeText(getApplicationContext(),"注册失败",Toast.LENGTH_LONG).show();
}
}
});
}
});
btnBack.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
startActivity(intent);
}
});
}
}
| true |
4403171d16879d93300ebbf96b506ef9a61bb9f3 | Java | witqki/myMusic | /myMusic/src/main/java/com/example/myMusic/music/web/MusicController.java | UTF-8 | 3,214 | 1.96875 | 2 | [] | no_license | package com.example.myMusic.music.web;
import java.io.File;
import java.io.FileInputStream;
import java.util.List;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.example.myMusic.common.dto.music.SearchMusicDTO;
import com.example.myMusic.common.dto.music.SearchResponseDTO;
import com.example.myMusic.common.web.ExtAjaxResponse;
import com.example.myMusic.music.dao.MusicDao;
import com.example.myMusic.music.entities.Music;
import com.example.myMusic.music.service.MusicService;
import com.example.myMusic.user.web.UserController;
@RestController
@RequestMapping("/music")
public class MusicController {
private Logger logger = LoggerFactory.getLogger(MusicController.class);
@Autowired
private MusicService musicService=null;
@Autowired
private MusicDao musicDao=null;
@GetMapping(value="{songid}/{page}")
public String test(/*HttpServletResponse response*/@PathVariable("songid") Long songid,@PathVariable("page") int page) {
//这是进行下载的代码
String str=songid+""+page;
return str;
// String urlStr ="G://KuGou/Bigbang - LOSER(Japanese Ver.).mp3";
// File imageFile = new File(urlStr);
// response.setContentType("application/octet-stream");
// try {
// FileInputStream fis = new FileInputStream(urlStr);
// byte[] content = new byte[fis.available()];
// fis.read(content);
// fis.close();
//
// ServletOutputStream sos = response.getOutputStream();
// sos.write(content);
//
// sos.flush();
// sos.close();
// return "success";
// } catch (Exception e) {
// e.printStackTrace();
// return "fail";
// }
}
//用户查看歌曲
@GetMapping(value="/search")
public SearchResponseDTO searchmusic( HttpServletResponse response,String searchcontent) {
return musicService. searchContent(searchcontent);
}
// //返回下载流
// @GetMapping(value="/downsong/{songid}")
// public ExtAjaxResponse downsong(HttpServletResponse response,@PathVariable ("songid") Long songid) {
// return musicService.downsong(response, songid);
// }
// @GetMapping(value="/playsong/{songid}")
// public ExtAjaxResponse playsong(@PathVariable("songid") Long songid) {
//
// return musicService.playsong(songid);
// }
//热歌1
//新歌2
//国内榜3
//欧美榜 Occident4
//韩国榜Korean5
//日本榜Japanese6
// @GetMapping(value="/songlist/{id}")
// public SearchResponseDTO songlist(@PathVariable("id") Long id) {
// return musicService.songlist(id);
// }
}
| true |
46d79f327efe6c0c9ca06a73e86e8e2e07d45c54 | Java | Terasology/WorkstationCrafting | /src/main/java/org/terasology/heat/HeatUtils.java | UTF-8 | 9,902 | 2.234375 | 2 | [] | no_license | /*
* Copyright 2016 MovingBlocks
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.terasology.heat;
import org.joml.Vector3i;
import org.joml.Vector3ic;
import org.terasology.engine.core.Time;
import org.terasology.engine.entitySystem.entity.EntityRef;
import org.terasology.engine.math.Side;
import org.terasology.engine.registry.CoreRegistry;
import org.terasology.engine.world.BlockEntityRegistry;
import org.terasology.engine.world.block.BlockComponent;
import org.terasology.engine.world.block.BlockRegion;
import org.terasology.engine.world.block.regions.BlockRegionComponent;
import org.terasology.heat.component.HeatConsumerComponent;
import org.terasology.heat.component.HeatProducerComponent;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
/**
* Contains utility functions that define how heat flow works.
*/
public final class HeatUtils {
public static final float HEAT_MAGIC_VALUE = 2000f;
private HeatUtils() {
}
/**
* Calculates the heat of a heat producer.
*
* @param producer The heat producer component of the producer
* @return The heat produced by the producer
*/
public static float calculateHeatForProducer(HeatProducerComponent producer) {
long gameTime = CoreRegistry.get(Time.class).getGameTimeInMs();
return Math.min(producer.maximumTemperature, calculateHeatForProducerAtTime(producer, gameTime));
}
/**
* Calculates the final heat of a system using the heat equation.
*
* @param startingHeat The initial heat of the system
* @param appliedHeat The heat applied to the system
* @param heatTransferEfficiency The heat transfer efficiency of the process
* @param duration The duration for which heat was applied
* @return The final heat of the system
*/
public static float solveHeatEquation(float startingHeat, float appliedHeat, float heatTransferEfficiency, long duration) {
return startingHeat + (appliedHeat - startingHeat) * (1 - (float) Math.pow(Math.E, -duration * heatTransferEfficiency / HEAT_MAGIC_VALUE));
}
/**
* Calculate the heat of a heat producer at a given time.
*
* @param producer The heat producer component of the producer
* @param time The time at which the heat of the producer is to be calculated
* @return The heat of the producer at the given time
*/
private static float calculateHeatForProducerAtTime(HeatProducerComponent producer, long time) {
float heat = 20;
long lastCalculated = 0;
for (HeatProducerComponent.FuelSourceConsume fuelSourceConsume : producer.fuelConsumed) {
if (fuelSourceConsume.startTime < time) {
if (lastCalculated < fuelSourceConsume.startTime) {
heat = solveHeatEquation(heat, 20, producer.temperatureLossRate, fuelSourceConsume.startTime - lastCalculated);
lastCalculated = fuelSourceConsume.startTime;
}
long heatEndTime = Math.min(fuelSourceConsume.startTime + fuelSourceConsume.burnLength, time);
heat = Math.min(producer.maximumTemperature,
solveHeatEquation(heat, fuelSourceConsume.heatProvided, producer.temperatureAbsorptionRate, heatEndTime - lastCalculated));
lastCalculated = heatEndTime;
} else {
break;
}
}
if (lastCalculated < time) {
heat = solveHeatEquation(heat, 20, producer.temperatureLossRate, time - lastCalculated);
}
return heat;
}
/**
* Calculate the heat of an entity.
*
* @param entity The entity whose heat is to be calculated
* @param blockEntityRegistry The block entity registry of the world
* @return The heat of the given entity
*/
public static float calculateHeatForEntity(EntityRef entity, BlockEntityRegistry blockEntityRegistry) {
HeatProducerComponent producer = entity.getComponent(HeatProducerComponent.class);
HeatConsumerComponent consumer = entity.getComponent(HeatConsumerComponent.class);
if (producer != null) {
return calculateHeatForProducer(producer);
} else if (consumer != null) {
return calculateHeatForConsumer(entity, blockEntityRegistry, consumer);
} else {
return 20;
}
}
/**
* Calculates the heat of a heat consumer.
*
* @param entity The entity whose heat is to be calculated
* @param blockEntityRegistry The block entity registry of the world
* @param heatConsumer The heat consumer component of the consumer
* @return The heat of the heat consumer
*/
private static float calculateHeatForConsumer(EntityRef entity, BlockEntityRegistry blockEntityRegistry, HeatConsumerComponent heatConsumer) {
float result = 20;
for (Map.Entry<Vector3i, Side> heaterBlock : getPotentialHeatSourceBlocksForConsumer(entity).entrySet()) {
EntityRef potentialHeatProducer = blockEntityRegistry.getEntityAt(heaterBlock.getKey());
HeatProducerComponent producer = potentialHeatProducer.getComponent(HeatProducerComponent.class);
if (producer != null && producer.heatDirections.contains(heaterBlock.getValue().reverse())) {
result += calculateHeatForProducer(producer);
}
}
long gameTime = CoreRegistry.get(Time.class).getGameTimeInMs();
for (HeatConsumerComponent.ResidualHeat residualHeat : heatConsumer.residualHeat) {
double heat = calculateResidualHeatValue(gameTime, residualHeat);
result += heat;
}
return result * heatConsumer.heatConsumptionEfficiency;
}
/**
* Calculate the amount of residual heat in an entity at a given time.
*
* @param gameTime The time at which the residual heat is to be calculated
* @param residualHeat The residual heat object whose value is to be calculated
* @return The amount of residual heat contained by the entity at the given time
*/
public static double calculateResidualHeatValue(long gameTime, HeatConsumerComponent.ResidualHeat residualHeat) {
float timeSinceHeatWasEstablished = (gameTime - residualHeat.time) / 1000f;
return residualHeat.baseHeat * Math.pow(Math.E, -1 * timeSinceHeatWasEstablished);
}
public static BlockRegion getEntityBlocks(EntityRef entityRef) {
BlockComponent blockComponent = entityRef.getComponent(BlockComponent.class);
if (blockComponent != null) {
Vector3i blockPosition = blockComponent.getPosition(new Vector3i());
return new BlockRegion(blockPosition);
}
BlockRegionComponent blockRegionComponent = entityRef.getComponent(BlockRegionComponent.class);
return blockRegionComponent.region;
}
/**
* Gets a map containing the location of potential heat producers near a consumer and the direction from which they
* can heat the consumer.
*
* @param consumer The heat consumer
* @return A map containing the location and direction of potential heat sources near the consumer
*/
public static Map<Vector3i, Side> getPotentialHeatSourceBlocksForConsumer(EntityRef consumer) {
HeatConsumerComponent consumerComp = consumer.getComponent(HeatConsumerComponent.class);
if (consumerComp == null) {
return Collections.emptyMap();
}
BlockRegion entityBlocks = getEntityBlocks(consumer);
Map<Vector3i, Side> result = new HashMap<>();
for (Vector3ic entityBlock : entityBlocks) {
for (Side heatDirection : consumerComp.heatDirections) {
Vector3i heatedBlock = new Vector3i(entityBlock);
heatedBlock.add(heatDirection.direction());
if (!entityBlocks.contains(heatedBlock)) {
result.put(heatedBlock, heatDirection);
}
}
}
return result;
}
/**
* Gets the position and direction of blocks that a heat producer could potentially heat.
*
* @param producer The heat producer
* @return A map containing the location and direction of blocks that could potentially be heated by the producer
*/
public static Map<Vector3i, Side> getPotentialHeatedBlocksForProducer(EntityRef producer) {
HeatProducerComponent producerComp = producer.getComponent(HeatProducerComponent.class);
if (producerComp == null) {
return Collections.emptyMap();
}
BlockRegion entityBlocks = getEntityBlocks(producer);
Map<Vector3i, Side> result = new HashMap<>();
for (Vector3ic entityBlock : entityBlocks) {
for (Side heatDirection : producerComp.heatDirections) {
Vector3i heatedBlock = new Vector3i(entityBlock);
heatedBlock.add(heatDirection.direction());
if (!entityBlocks.contains(heatedBlock)) {
result.put(heatedBlock, heatDirection);
}
}
}
return result;
}
}
| true |
c5da488bee82709cb39f821571e6f0b10f1ca045 | Java | nostrado/Algorithm | /codeground_pratice_5/src/codeground_pratice_5/Solution.java | UTF-8 | 1,205 | 2.96875 | 3 | [] | no_license | package codeground_pratice_5;
import java.io.FileInputStream;
import java.util.Scanner;
public class Solution {
private static long[] arry;
private static int max_size = 2000003;
private static int div = 1000000007;
public static void main(String[] args) throws Exception
{
Scanner sc = new Scanner(new FileInputStream("sample_input.txt"));
//Scanner sc = new Scanner(System.in);
arry = new long[max_size];
pre_factorial();
int test_case = sc.nextInt();
for(int i=1;i<=test_case;i++)
{
int N = sc.nextInt();
int M = sc.nextInt();
long mmi = find_mmi(arry[N+1]*arry[M+1]%div);
long result = (arry[N+M+2] * mmi -1) % div;
System.out.println("Case #"+i);
System.out.println(result);
}
sc.close();
}
public static void pre_factorial()
{
arry[0] = 1;
for(int i=1;i<max_size;i++)
{
arry[i] = (i * arry[i-1]) % div;
}
}
public static long find_mmi(long num)
{
return power(num,div-2);
}
public static long power(long b, int n)
{
if(n == 0)
return 1;
else if(n == 1)
return b;
long half = power(b,n/2);
if(n % 2 == 0)
return half * half % div;
else
return (((half * half) % div) * b) % div;
}
}
| true |
74c4d1c998a1c7ccdef805c0b16d9468133a1523 | Java | Warkdev/account-service | /src/main/java/eu/getmangos/rest/IpBanResource.java | UTF-8 | 5,290 | 2.3125 | 2 | [
"Apache-2.0"
] | permissive | package eu.getmangos.rest;
import java.util.Date;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.eclipse.microprofile.openapi.annotations.Operation;
import org.eclipse.microprofile.openapi.annotations.media.Content;
import org.eclipse.microprofile.openapi.annotations.responses.APIResponse;
import org.eclipse.microprofile.openapi.annotations.responses.APIResponses;
import org.eclipse.microprofile.openapi.annotations.tags.Tag;
import org.eclipse.microprofile.openapi.annotations.media.Schema;
import org.eclipse.microprofile.openapi.annotations.parameters.Parameter;
import eu.getmangos.dto.IpBannedDTO;
public interface IpBanResource {
@GET
@Path("v1/banip/{ip}/{bandate}")
@Produces(MediaType.APPLICATION_JSON)
@Operation(summary = "Retrieves a ban given the id",
description = "This API is retrieving the ban with the given id/bandate from the database."
)
@APIResponses(
value = {
@APIResponse(responseCode = "200", description = "The ban", content = @Content(
mediaType = "application/json", schema = @Schema(implementation = IpBannedDTO.class)
)
),
@APIResponse(responseCode = "400", description = "Error with the request"),
@APIResponse(responseCode = "404", description = "Ban not found"),
@APIResponse(responseCode = "500", description = "An unexpected event occured")
}
)
@Tag(name = "ban ip")
public Response findIpBan(@PathParam("ip") @Parameter(
description = "The IP address to search for",
required = true,
example = "127.0.0.1"
) String ip, @PathParam("bandate") @Parameter(
description = "The ban date for this IP",
required = true
) Date banDate);
@GET
@Path("v1/banip")
@Produces(MediaType.APPLICATION_JSON)
@Operation(summary = "Retrieves all bans",
description = "This API is retrieving all bans from the database."
)
@APIResponses(
value = {
@APIResponse(responseCode = "200", description = "A list of bans", content = @Content(
mediaType = "application/json", schema = @Schema(implementation = IpBannedDTO.class)
)
),
@APIResponse(responseCode = "400", description = "Error with the request"),
@APIResponse(responseCode = "500", description = "An unexpected even occured")
}
)
@Tag(name = "ban ip")
public Response findAllIpBans();
@POST
@Path("v1/banip")
@Consumes(MediaType.APPLICATION_JSON)
@Operation(summary = "Create a new ban",
description = "This API is creating a new ban based on the provided input."
)
@APIResponses(
value = {
@APIResponse(responseCode = "201", description = "The ban has been created", content = @Content(
mediaType = "application/json"
)
),
@APIResponse(responseCode = "400", description = "Error with the request"),
@APIResponse(responseCode = "500", description = "An unexpected even occured")
}
)
@Tag(name = "ban ip")
public Response addIpBan(IpBannedDTO entity);
@PUT
@Path("v1/banip/{ip}/{bandate}")
@Consumes(MediaType.APPLICATION_JSON)
@Operation(summary = "Edit a ban",
description = "This API is updating an existing ban based on the provided input."
)
@APIResponses(
value = {
@APIResponse(responseCode = "200", description = "The ban has been updated", content = @Content(
mediaType = "application/json",
schema = @Schema(implementation=IpBannedDTO.class)
)
),
@APIResponse(responseCode = "400", description = "Error with the request"),
@APIResponse(responseCode = "404", description = "Ban not found"),
@APIResponse(responseCode = "500", description = "An unexpected even occured")
}
)
@Tag(name = "ban ip")
public Response editIpBan(@PathParam("ip") String ip, @PathParam("bandate") Date banDate, IpBannedDTO entity);
@DELETE
@Path("v1/banip/{ip}/{bandate}")
@Produces(MediaType.APPLICATION_JSON)
@Operation(summary = "Delete a ban",
description = "This API is deleting an existing ban based on the provided ip."
)
@APIResponses(
value = {
@APIResponse(responseCode = "204", description = "The ban has been deleted", content = @Content(
mediaType = "application/json"
)
),
@APIResponse(responseCode = "400", description = "Error with the request"),
@APIResponse(responseCode = "404", description = "Ban not found"),
@APIResponse(responseCode = "500", description = "An unexpected even occured")
}
)
@Tag(name = "ban ip")
public Response deleteIpBan(@PathParam("ip") String ip, @PathParam("bandate") Date banDate);
}
| true |
be840ec70d68161fb53ab026f8f0be9a0dd78328 | Java | YotamHa/RailcarModel | /src/playgo/systemmodel/classes/generated/ExitsManagerGenerated.java | UTF-8 | 13,849 | 2.140625 | 2 | [] | no_license |
package playgo.systemmodel.classes.generated;
import il.ac.wis.cs.playgo.playtoolkit.AppObjects;
import il.ac.wis.cs.systemmodel.SMBaseClass;
import il.ac.wis.cs.systemmodel.SystemModelGen;
import playgo.systemmodel.SystemModelAgent;
import playgo.systemmodel.SystemModelMain;
/**
* This file was automatically generated using PlayGo system-model.
* This class shouldn't be changed. Any change to this class will be overridden!!!
*
*/
public class ExitsManagerGenerated
extends SMBaseClass
{
protected int ID = (0);
protected int platformHandling = (0);
public ExitsManagerGenerated(java.lang.String name) {
super(name);
oneTimeInit();
}
public ExitsManagerGenerated(java.lang.String name, boolean init) {
super(name);
if(init)oneTimeInit();
}
protected void oneTimeInit() {
AppObjects.addObject(this);
SystemModelAgent.getInstance().construct((getClass().getSimpleName()), (name));
//GUI handling
SystemModelMain.getInstance().getPlayable().construct((getClass().getSimpleName()), (name));
Object source = il.ac.wis.cs.playgo.playtoolkit.SyncMessageHandler.srcObj!=null ? il.ac.wis.cs.playgo.playtoolkit.SyncMessageHandler.srcObj : this;
java.util.ArrayList<String> argTypes = new java.util.ArrayList<String>();
argTypes.add("String");
java.util.ArrayList<Object> argValues = new java.util.ArrayList<Object>();
argValues.add(name);
il.ac.wis.cs.s2a.runtime.lib.PlaygoCoordinator.getInstance().publish(
(source), (source.getClass().getSimpleName()), this, this.getClass().getSimpleName(), "create", argTypes, argValues);
}
@SystemModelGen
public String getName() {
return name;
}
public void delete() {
AppObjects.remove(this);
SystemModelAgent.getInstance().destroy((getClass().getSimpleName()), (name));
//GUI handling
SystemModelMain.getInstance().getPlayable().destroy((getClass().getSimpleName()), (name));
java.util.ArrayList<String> argTypes = new java.util.ArrayList<String>();
java.util.ArrayList<Object> argValues = new java.util.ArrayList<Object>();
Object source = il.ac.wis.cs.playgo.playtoolkit.SyncMessageHandler.srcObj!=null ? il.ac.wis.cs.playgo.playtoolkit.SyncMessageHandler.srcObj : this;
il.ac.wis.cs.s2a.runtime.lib.PlaygoCoordinator.getInstance().publish((source), (source.getClass().getSimpleName()), (this), (this.getClass().getSimpleName()), ("delete"), (argTypes), (argValues));
}
@SystemModelGen
public int getID() {
return ID;
}
@SystemModelGen
public void setID(int arg0) {
java.util.ArrayList<String> argTypes = new java.util.ArrayList<String>();
java.util.ArrayList<Object> argValues = new java.util.ArrayList<Object>();
argTypes.add("int");
argValues.add(arg0);
Object source = il.ac.wis.cs.playgo.playtoolkit.SyncMessageHandler.srcObj!=null ? il.ac.wis.cs.playgo.playtoolkit.SyncMessageHandler.srcObj : this;
il.ac.wis.cs.s2a.runtime.lib.PlaygoCoordinator.getInstance().publishBefore((source), (source.getClass().getSimpleName()), (this), (this.getClass().getSimpleName()), ("setID"), (argTypes), (argValues));
il.ac.wis.cs.playgo.playtoolkit.SyncMessageHandler.srcObj=null;
this.ID=arg0;
if(java.lang.System.getProperty("SYSTEM_MODEL_DEBUG")!=null){
java.lang.System.out.println(">>> method call: >>> setID(int) : void .Object name: " + name);
}
//GUI handling
playgo.systemmodel.SystemModelMain.getInstance().getPlayable().
setPropertyValue("ExitsManager", name, "ID", String.valueOf(arg0));
il.ac.wis.cs.playgo.playtoolkit.api.impl.java.SystemModelAgent.getInstance()
.setPropertyValue("ExitsManager", name, "ID", String.valueOf(arg0));
//ExecutionBridge handling
SystemModelMain.getInstance().setPropertyValue(("ExitsManager"), (name), ("ID"), ("int"), (String.valueOf(arg0)));
il.ac.wis.cs.s2a.runtime.lib.PlaygoCoordinator.getInstance().publish((source), (source.getClass().getSimpleName()), (this), (this.getClass().getSimpleName()), ("setID"), (argTypes), (argValues));
}
@SystemModelGen
public void pgInitID(int arg0) {
this.ID=arg0;
il.ac.wis.cs.playgo.playtoolkit.api.impl.java.SystemModelAgent.getInstance()
.setPropertyValue("ExitsManager", name, "ID", String.valueOf(arg0));
}
@SystemModelGen
public void exitClear() {
if(java.lang.System.getProperty("SYSTEM_MODEL_DEBUG")!=null){
java.lang.System.out.println(">>> method call: >>> exitClear() : void .Object name: " + name);
}
//ExecutionBridge handling
SystemModelMain.getInstance().activateMethod(("ExitsManager"), (name), ("exitClear"));
java.util.ArrayList<String> argTypes = new java.util.ArrayList<String>();
java.util.ArrayList<Object> argValues = new java.util.ArrayList<Object>();
Object source = il.ac.wis.cs.playgo.playtoolkit.SyncMessageHandler.srcObj!=null ? il.ac.wis.cs.playgo.playtoolkit.SyncMessageHandler.srcObj : this;
il.ac.wis.cs.s2a.runtime.lib.PlaygoCoordinator.getInstance().publish((source), (source.getClass().getSimpleName()), (this), (this.getClass().getSimpleName()), ("exitClear"), (argTypes), (argValues));
il.ac.wis.cs.playgo.playtoolkit.SyncMessageHandler.srcObj=null;
return;
}
@SystemModelGen
public void exitAllocated() {
if(java.lang.System.getProperty("SYSTEM_MODEL_DEBUG")!=null){
java.lang.System.out.println(">>> method call: >>> exitAllocated() : void .Object name: " + name);
}
//ExecutionBridge handling
SystemModelMain.getInstance().activateMethod(("ExitsManager"), (name), ("exitAllocated"));
java.util.ArrayList<String> argTypes = new java.util.ArrayList<String>();
java.util.ArrayList<Object> argValues = new java.util.ArrayList<Object>();
Object source = il.ac.wis.cs.playgo.playtoolkit.SyncMessageHandler.srcObj!=null ? il.ac.wis.cs.playgo.playtoolkit.SyncMessageHandler.srcObj : this;
il.ac.wis.cs.s2a.runtime.lib.PlaygoCoordinator.getInstance().publish((source), (source.getClass().getSimpleName()), (this), (this.getClass().getSimpleName()), ("exitAllocated"), (argTypes), (argValues));
il.ac.wis.cs.playgo.playtoolkit.SyncMessageHandler.srcObj=null;
return;
}
@SystemModelGen
public void validAllocation(int platform) {
if(java.lang.System.getProperty("SYSTEM_MODEL_DEBUG")!=null){
java.lang.System.out.println(">>> method call: >>> validAllocation(int) : void .Object name: " + name);
}
//ExecutionBridge handling
SystemModelMain.getInstance().activateMethod(("ExitsManager"), (name), ("validAllocation"));
java.util.ArrayList<String> argTypes = new java.util.ArrayList<String>();
java.util.ArrayList<Object> argValues = new java.util.ArrayList<Object>();
argTypes.add("int");
argValues.add(platform);
Object source = il.ac.wis.cs.playgo.playtoolkit.SyncMessageHandler.srcObj!=null ? il.ac.wis.cs.playgo.playtoolkit.SyncMessageHandler.srcObj : this;
il.ac.wis.cs.s2a.runtime.lib.PlaygoCoordinator.getInstance().publish((source), (source.getClass().getSimpleName()), (this), (this.getClass().getSimpleName()), ("validAllocation"), (argTypes), (argValues));
il.ac.wis.cs.playgo.playtoolkit.SyncMessageHandler.srcObj=null;
return;
}
@SystemModelGen
public void allocateExit1() {
if(java.lang.System.getProperty("SYSTEM_MODEL_DEBUG")!=null){
java.lang.System.out.println(">>> method call: >>> allocateExit1() : void .Object name: " + name);
}
//ExecutionBridge handling
SystemModelMain.getInstance().activateMethod(("ExitsManager"), (name), ("allocateExit1"));
java.util.ArrayList<String> argTypes = new java.util.ArrayList<String>();
java.util.ArrayList<Object> argValues = new java.util.ArrayList<Object>();
Object source = il.ac.wis.cs.playgo.playtoolkit.SyncMessageHandler.srcObj!=null ? il.ac.wis.cs.playgo.playtoolkit.SyncMessageHandler.srcObj : this;
il.ac.wis.cs.s2a.runtime.lib.PlaygoCoordinator.getInstance().publish((source), (source.getClass().getSimpleName()), (this), (this.getClass().getSimpleName()), ("allocateExit1"), (argTypes), (argValues));
il.ac.wis.cs.playgo.playtoolkit.SyncMessageHandler.srcObj=null;
return;
}
@SystemModelGen
public void allocateExit2() {
if(java.lang.System.getProperty("SYSTEM_MODEL_DEBUG")!=null){
java.lang.System.out.println(">>> method call: >>> allocateExit2() : void .Object name: " + name);
}
//ExecutionBridge handling
SystemModelMain.getInstance().activateMethod(("ExitsManager"), (name), ("allocateExit2"));
java.util.ArrayList<String> argTypes = new java.util.ArrayList<String>();
java.util.ArrayList<Object> argValues = new java.util.ArrayList<Object>();
Object source = il.ac.wis.cs.playgo.playtoolkit.SyncMessageHandler.srcObj!=null ? il.ac.wis.cs.playgo.playtoolkit.SyncMessageHandler.srcObj : this;
il.ac.wis.cs.s2a.runtime.lib.PlaygoCoordinator.getInstance().publish((source), (source.getClass().getSimpleName()), (this), (this.getClass().getSimpleName()), ("allocateExit2"), (argTypes), (argValues));
il.ac.wis.cs.playgo.playtoolkit.SyncMessageHandler.srcObj=null;
return;
}
@SystemModelGen
public void allocateExit3() {
if(java.lang.System.getProperty("SYSTEM_MODEL_DEBUG")!=null){
java.lang.System.out.println(">>> method call: >>> allocateExit3() : void .Object name: " + name);
}
//ExecutionBridge handling
SystemModelMain.getInstance().activateMethod(("ExitsManager"), (name), ("allocateExit3"));
java.util.ArrayList<String> argTypes = new java.util.ArrayList<String>();
java.util.ArrayList<Object> argValues = new java.util.ArrayList<Object>();
Object source = il.ac.wis.cs.playgo.playtoolkit.SyncMessageHandler.srcObj!=null ? il.ac.wis.cs.playgo.playtoolkit.SyncMessageHandler.srcObj : this;
il.ac.wis.cs.s2a.runtime.lib.PlaygoCoordinator.getInstance().publish((source), (source.getClass().getSimpleName()), (this), (this.getClass().getSimpleName()), ("allocateExit3"), (argTypes), (argValues));
il.ac.wis.cs.playgo.playtoolkit.SyncMessageHandler.srcObj=null;
return;
}
@SystemModelGen
public void allocateExit4() {
if(java.lang.System.getProperty("SYSTEM_MODEL_DEBUG")!=null){
java.lang.System.out.println(">>> method call: >>> allocateExit4() : void .Object name: " + name);
}
//ExecutionBridge handling
SystemModelMain.getInstance().activateMethod(("ExitsManager"), (name), ("allocateExit4"));
java.util.ArrayList<String> argTypes = new java.util.ArrayList<String>();
java.util.ArrayList<Object> argValues = new java.util.ArrayList<Object>();
Object source = il.ac.wis.cs.playgo.playtoolkit.SyncMessageHandler.srcObj!=null ? il.ac.wis.cs.playgo.playtoolkit.SyncMessageHandler.srcObj : this;
il.ac.wis.cs.s2a.runtime.lib.PlaygoCoordinator.getInstance().publish((source), (source.getClass().getSimpleName()), (this), (this.getClass().getSimpleName()), ("allocateExit4"), (argTypes), (argValues));
il.ac.wis.cs.playgo.playtoolkit.SyncMessageHandler.srcObj=null;
return;
}
@SystemModelGen
public int getPlatformHandling() {
return platformHandling;
}
@SystemModelGen
public void setPlatformHandling(int arg0) {
java.util.ArrayList<String> argTypes = new java.util.ArrayList<String>();
java.util.ArrayList<Object> argValues = new java.util.ArrayList<Object>();
argTypes.add("int");
argValues.add(arg0);
Object source = il.ac.wis.cs.playgo.playtoolkit.SyncMessageHandler.srcObj!=null ? il.ac.wis.cs.playgo.playtoolkit.SyncMessageHandler.srcObj : this;
il.ac.wis.cs.s2a.runtime.lib.PlaygoCoordinator.getInstance().publishBefore((source), (source.getClass().getSimpleName()), (this), (this.getClass().getSimpleName()), ("setPlatformHandling"), (argTypes), (argValues));
il.ac.wis.cs.playgo.playtoolkit.SyncMessageHandler.srcObj=null;
this.platformHandling=arg0;
if(java.lang.System.getProperty("SYSTEM_MODEL_DEBUG")!=null){
java.lang.System.out.println(">>> method call: >>> setPlatformHandling(int) : void .Object name: " + name);
}
//GUI handling
playgo.systemmodel.SystemModelMain.getInstance().getPlayable().
setPropertyValue("ExitsManager", name, "platformHandling", String.valueOf(arg0));
il.ac.wis.cs.playgo.playtoolkit.api.impl.java.SystemModelAgent.getInstance()
.setPropertyValue("ExitsManager", name, "platformHandling", String.valueOf(arg0));
//ExecutionBridge handling
SystemModelMain.getInstance().setPropertyValue(("ExitsManager"), (name), ("platformHandling"), ("int"), (String.valueOf(arg0)));
il.ac.wis.cs.s2a.runtime.lib.PlaygoCoordinator.getInstance().publish((source), (source.getClass().getSimpleName()), (this), (this.getClass().getSimpleName()), ("setPlatformHandling"), (argTypes), (argValues));
}
@SystemModelGen
public void pgInitPlatformHandling(int arg0) {
this.platformHandling=arg0;
il.ac.wis.cs.playgo.playtoolkit.api.impl.java.SystemModelAgent.getInstance()
.setPropertyValue("ExitsManager", name, "platformHandling", String.valueOf(arg0));
}
}
| true |
feeae19f577e287657f231da02d7e59a08128dda | Java | henrik242/openiam-idm | /openiam-webconsole/src/main/java/org/openiam/webadmin/user/UserAttributeValidator.java | UTF-8 | 448 | 1.96875 | 2 | [] | no_license | package org.openiam.webadmin.user;
import org.springframework.validation.Validator;
import org.springframework.validation.Errors;
public class UserAttributeValidator implements Validator {
public boolean supports(Class cls) {
return UserAttributeCommand.class.equals(cls);
}
public void validate(Object cmd, Errors err) {
UserAttributeCommand attrCmd = (UserAttributeCommand) cmd;
}
}
| true |
a76b842f211bc1f48b8569c88dcf6b78dfa53eb3 | Java | InhoAndrewJung/way_learning | /src/main/java/com/way/learning/service/course/CourseServiceImpl.java | UTF-8 | 4,126 | 2.25 | 2 | [
"MIT"
] | permissive | package com.way.learning.service.course;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import com.way.learning.model.course.dao.CourseDAO;
import com.way.learning.model.course.vo.Course;
import com.way.learning.model.member.vo.Member;
@Service
public class CourseServiceImpl implements CourseService {
@Autowired
private CourseDAO courseDAO;
public int insertCourse(Course cvo,HttpServletRequest request ) throws Exception{
System.out.println("Before cvo :: "+cvo.getCourseNo());
// 파일 업로드 로직을 추가
HttpSession session = request.getSession();
MultipartFile mFile = cvo.getUploadFile();
System.out.println(mFile.getSize() + "============" + mFile.isEmpty());
if (mFile.isEmpty() == false) { // 파일 업로드를 했다면
String fileName = mFile.getOriginalFilename();
Date today = new Date();
SimpleDateFormat df = new SimpleDateFormat("YYYYMMddHHmmssSSS");
String now = df.format(today);
String newfilename = now + "_" + fileName;
cvo.setCourseImage(newfilename); // vo의 완벽한 세팅이 완료
String root = session.getServletContext().getRealPath("/");
String path = root + "\\resources\\upload\\";
File copyFile = new File(path + newfilename);
mFile.transferTo(copyFile); // upload 폴더에 newfilename이 저장
} else {
String defaultImg = "coding.jpg";
cvo.setCourseImage(defaultImg);
}
int result=courseDAO.insertCourse(cvo);
System.out.println("After cvo :: "+cvo.getCourseNo()); //3
List<String> tag=cvo.getTags();
for(String tags:tag){
courseDAO.insertTags(tags,cvo.getCourseNo());
}
return result;
}
public List<Course> selectMycourseList(String userId) throws Exception{
return courseDAO.selectMycourseList(userId);
}
public Course selectMyCourse(String userId,int courseNo) throws Exception{
return courseDAO.selectMyCourse(userId, courseNo);
}
public List<String> selectCourseTag(int courseNo) throws Exception{
return courseDAO.selectCourseTag(courseNo);
}
public int deleteCourse(int courseNo) throws Exception{
return courseDAO.deleteCourse(courseNo);
}
public int updateCourse(Course cvo, HttpServletRequest request) throws Exception{
System.out.println("updateCourse서비스입성");
//이전 이미지 넣을수 있어서 받아놓는다.
Member pvo = (Member) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
// 파일 업로드 로직을 추가
HttpSession session = request.getSession();
MultipartFile mFile = cvo.getUploadFile();
if (mFile.isEmpty() == false) { // 파일 업로드를 했다면
System.out.println(mFile.getSize() + "============" + mFile.isEmpty());
String fileName = mFile.getOriginalFilename();
Date today = new Date();
SimpleDateFormat df = new SimpleDateFormat("YYYYMMddHHmmssSSS");
String now = df.format(today);
String newfilename = now + "_" + fileName;
cvo.setCourseImage(newfilename); // vo의 완벽한 세팅이 완료
String root = session.getServletContext().getRealPath("/");
String path = root + "\\resources\\upload\\";
File copyFile = new File(path + newfilename);
mFile.transferTo(copyFile); // upload 폴더에 newfilename이 저장
}
int result=courseDAO.updateCourse(cvo);
courseDAO.deleteTags(cvo.getCourseNo());
List<String> tag=cvo.getTags();
for(String tags:tag){
courseDAO.insertTags(tags,cvo.getCourseNo());
}
return result;
}
public List<Course> selectAccetpedCourseList() throws Exception{
return courseDAO.selectAccetpedCourseList();
}
}
| true |
aa90a6bf8f1e367047a92b6b3b3d18e77c4792d3 | Java | gabrielbsouz/ms-corinthans | /src/main/java/br/com/rest/api/spring/mscorinthans/repositories/SoccerPlayerRepository.java | UTF-8 | 272 | 1.609375 | 2 | [] | no_license | package br.com.rest.api.spring.mscorinthans.repositories;
import br.com.rest.api.spring.mscorinthans.models.SoccerPlayer;
import org.springframework.data.jpa.repository.JpaRepository;
public interface SoccerPlayerRepository extends JpaRepository<SoccerPlayer, Long> {
}
| true |
9367ed2c3a39ec454e4ce8dbf47e37d45cf9b1cc | Java | DavidShi1017/AndroidR9 | /NMBS/src/main/java/com/nmbs/util/ComparatorMyTicketDate.java | UTF-8 | 723 | 2.875 | 3 | [] | no_license | package com.nmbs.util;
import com.nmbs.model.MyTicket;
import java.util.Comparator;
import java.util.Date;
/**
* Order Schedule
*
* @author David
*
*/
public class ComparatorMyTicketDate implements Comparator<MyTicket> {
public static final int ASC = 0;
public static final int DESC = 1;
private int sort;
public ComparatorMyTicketDate(int sort){
this.sort = sort;
}
public int compare(MyTicket ticket1, MyTicket myTicket2) {
Date acceptTime1 = ticket1.getSortedDate();
Date acceptTime2 = myTicket2.getSortedDate();
if(sort == ASC){
if(acceptTime1.after(acceptTime2)) {
return 1;
}
return -1;
}else{
if(acceptTime1.before(acceptTime2)) {
return 1;
}
return -1;
}
}
}
| true |
c08cdf94dd1e646705abd949e7998719b6fc100f | Java | mohdhamzakhan/Java_Seession1Assignment3 | /Assignment3.java | UTF-8 | 179 | 1.96875 | 2 | [] | no_license | package session1;
public class Assignment3 {
public static void main(String[] args)
{
String s="HAMZA";
int a=(int)s;
Boolean ch=true;
int b=(int)ch;
}
}
| true |
0430a3e12ef84fee7c8c936dc1351cd2854a5368 | Java | golsung/simple-calculator | /src/main/java/sig/oss/Calc.java | UTF-8 | 363 | 3.359375 | 3 | [] | no_license | public class Calc {
private int r=0;
public int add(int x, int y) {
return x+y; //add method
}
public int sub(int x, int y) {
return x-y; //subtraction method
}
public int mul(int x, int y) {
return x*y; //multiplication method 1 2
}
public void dec(int x) {
r = r-x; //multiplication method 1 2
}
public void inc(int x) {
r = r+x;
}
}
| true |
ce0bf7aa89c4eb810fedee875c3a91054d198b81 | Java | kavt/feiniu_pet | /pet/pet_back/src/main/java/com/lvmama/pet/sweb/visa/document/DocumentAction.java | UTF-8 | 8,170 | 1.960938 | 2 | [] | no_license | package com.lvmama.pet.sweb.visa.document;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import com.lvmama.comm.BackBaseAction;
import com.lvmama.comm.pet.po.visa.VisaApplicationDocument;
import com.lvmama.comm.pet.po.visa.VisaApplicationDocumentDetails;
import com.lvmama.comm.pet.service.visa.VisaApplicationDocumentService;
import com.lvmama.comm.utils.WebUtils;
import com.lvmama.comm.vo.Constant;
/**
* 签证资料管理
* @author Brian
*
*/
@Results({
@Result(name = "list", location = "/WEB-INF/pages/back/visa/document/list.jsp"),
@Result(name = "add", location = "/WEB-INF/pages/back/visa/document/add.jsp"),
@Result(name = "view", location = "/WEB-INF/pages/back/visa/document/view.jsp"),
@Result(name = "copy", location = "/WEB-INF/pages/back/visa/document/copy.jsp"),
@Result(name = "page", location = "/WEB-INF/pages/back/visa/document/page.jsp")
})
public class DocumentAction extends BackBaseAction {
/**
* 序列值
*/
private static final long serialVersionUID = 5281368066239846011L;
/**
* 签证材料远程服务
*/
private VisaApplicationDocumentService visaApplicationDocumentService;
/**
* 查询条件——资料标识
*/
private Long documentId;
/**
* 查询条件——国家
*/
private String country;
/**
* 查询条件——签证类型
*/
private String visaType;
/**
* 查询条件——出签城市
*/
private String city;
/**
* 查询条件——人群
*/
private String occupation;
/**
* 签证资料
*/
private VisaApplicationDocument visaApplicationDocument;
/**
* 签证资料明细
*/
private List<VisaApplicationDocumentDetails> visaApplicationDocumentDetailsList;
private List<VisaApplicationDocument> documentlist;
@Action("/visa/document/index")
public String index() {
Map<String,Object> param = initParam();
pagination = initPage();
param.put("_startRow", pagination.getStartRows() - 1);
param.put("_endRow", pagination.getEndRows());
pagination.setTotalResultSize(visaApplicationDocumentService.count(param));
pagination.setItems(visaApplicationDocumentService.query(param));
pagination.setUrl(WebUtils.getUrl(this.getRequest()));
return "list";
}
@Action("/visa/document/query")
public String query(){
Map<String,Object> param = initParam();
param.put("_startRow",0);
param.put("_endRow",100);
documentlist=visaApplicationDocumentService.query(param);
return "page";
}
@Action("/visa/document/add")
public String add() {
return "add";
}
@Action("/visa/document/save")
public void save() throws IOException {
JSONObject json = new JSONObject();
json.put("success", false);
json.put("message", "");
if (null == visaApplicationDocument
|| StringUtils.isBlank(visaApplicationDocument.getCountry())
|| StringUtils.isBlank(visaApplicationDocument.getVisaType())
|| StringUtils.isBlank(visaApplicationDocument.getCity())
|| StringUtils.isBlank(visaApplicationDocument.getOccupation())) {
json.put("message", "缺失必要数据,无法保存");
}
if (null == visaApplicationDocument.getDocumentId()) {
visaApplicationDocument = visaApplicationDocumentService.insert(visaApplicationDocument.getCountry(), visaApplicationDocument.getVisaType(), visaApplicationDocument.getCity(), visaApplicationDocument.getOccupation(), getSessionUserNameAndCheck());
if (null == visaApplicationDocument) {
json.put("message", "该材料已经存在,无法重复保存");
} else {
json.put("success", true);
json.put("message", "新增签证材料成功");
}
} else {
json.put("success", true);
json.put("message", "更新签证材料成功");
}
getResponse().getWriter().print(json.toString());
}
@Action("/visa/document/view")
public String view() {
if (null == documentId) {
return ERROR;
}
visaApplicationDocument = visaApplicationDocumentService.queryByPrimaryKey(documentId);
visaApplicationDocumentDetailsList = visaApplicationDocumentService.queryDetailsByDocumentId(documentId);
return "view";
}
@Action("/visa/document/del")
public void del() throws IOException {
JSONObject json = new JSONObject();
if (null != documentId) {
visaApplicationDocumentService.delete(documentId, getSessionUserNameAndCheck());
}
json.put("success", true);
getResponse().getWriter().print(json.toString());
}
@Action("/visa/document/preCopy")
public String preCopy() {
if (null == documentId) {
return ERROR;
}
visaApplicationDocument = visaApplicationDocumentService.queryByPrimaryKey(documentId);
return "copy";
}
@Action("/visa/document/copy")
public void copy() throws IOException {
JSONObject json = new JSONObject();
if (null == documentId || null == visaApplicationDocument) {
json.put("success", false);
json.put("message", "缺失必要数据,无法保存");
} else {
visaApplicationDocument = visaApplicationDocumentService.copy(documentId, visaApplicationDocument, getSessionUserNameAndCheck());
if (null == visaApplicationDocument) {
json.put("success", false);
json.put("message", "目标签证资料已存在,无法复制");
} else {
json.put("success", true);
json.put("message", "复制成功");
}
}
getResponse().getWriter().print(json.toString());
}
/**
* 初始化查询参数
* @return
*/
private Map<String, Object> initParam() {
Map<String, Object> param = new HashMap<String, Object>();
if (StringUtils.isNotBlank(country)) {
param.put("country", country);
}
if (StringUtils.isNotBlank(visaType)) {
param.put("visaType", visaType);
}
if (StringUtils.isNotBlank(city)) {
param.put("city", city);
}
if (StringUtils.isNotBlank(occupation)) {
param.put("occupation", occupation);
}
return param;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getVisaType() {
return visaType;
}
public void setVisaType(String visaType) {
this.visaType = visaType;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getOccupation() {
return occupation;
}
public void setOccupation(String occupation) {
this.occupation = occupation;
}
public Map<String, String> getVisaTypeList() {
Map<String,String> map = Constant.VISA_TYPE.BUSINESS_VISA.getMap();
map.put("", "----请选择----");
return map;
}
public Map<String, String> getVisaCityList() {
Map<String,String> map = Constant.VISA_CITY.SH_VISA_CITY.getMap();
map.put("", "----请选择----");
return map;
}
public Map<String, String> getVisaOccupationList() {
Map<String,String> map = Constant.VISA_OCCUPATION.VISA_FOR_EMPLOYEE.getMap();
map.put("", "----请选择----");
return map;
}
public VisaApplicationDocument getVisaApplicationDocument() {
return visaApplicationDocument;
}
public void setVisaApplicationDocument(
VisaApplicationDocument visaApplicationDocument) {
this.visaApplicationDocument = visaApplicationDocument;
}
public Long getDocumentId() {
return documentId;
}
public void setDocumentId(Long documentId) {
this.documentId = documentId;
}
public List<VisaApplicationDocumentDetails> getVisaApplicationDocumentDetailsList() {
return visaApplicationDocumentDetailsList;
}
public void setVisaApplicationDocumentService(
VisaApplicationDocumentService visaApplicationDocumentService) {
this.visaApplicationDocumentService = visaApplicationDocumentService;
}
public List<VisaApplicationDocument> getDocumentlist() {
return documentlist;
}
}
| true |
ede1485b940595e5dfa16aedf7ac66981ef78236 | Java | openpreserve/bitwiser | /bitwiser-core/src/main/java/eu/scape_project/bitwiser/utils/LCS.java | UTF-8 | 1,587 | 3.375 | 3 | [
"Apache-2.0"
] | permissive | /**
*
*/
package eu.scape_project.bitwiser.utils;
/**
* @author AnJackson
*
*/
public class LCS {
/**
* Longest common substring algorithm
* @param a
* @param b
* @return
*/
public static String lcs(String a, String b) {
// Create match matrix, which Java auto-initializes to zeros
int[][] lengths = new int[a.length()+1][b.length()+1];
// Fill up the matrix:
for (int i = 0; i < a.length(); i++) {
for (int j = 0; j < b.length(); j++) {
if (a.charAt(i) == b.charAt(j)) {
lengths[i+1][j+1] = lengths[i][j] + 1;
} else {
lengths[i+1][j+1] =
Math.max(lengths[i+1][j], lengths[i][j+1]);
}
}
}
// Read the substring out from the matrix
StringBuffer sb = new StringBuffer();
for (int x = a.length(), y = b.length();
x != 0 && y != 0; ) {
if (lengths[x][y] == lengths[x-1][y]) {
x--;
} else if (lengths[x][y] == lengths[x][y-1]) {
y--;
} else {
assert a.charAt(x-1) == b.charAt(y-1);
sb.append(a.charAt(x-1));
x--;
y--;
}
}
// Reverse and pass-back:
return sb.reverse().toString();
}
/**
* A simple example of use.
*
* @param args
*/
public static void main( String[] args ) {
System.out.println("LCS: " + lcs("computer","internet"));
System.out.println("LCS: " + lcs("computer","input"));
System.out.println("LCS: " + lcs("computer","zzzaaakk"));
}
}
| true |
b44dd1e540d22913f0f269986d13c000d7404ae1 | Java | KYUUBl/school-register | /src/TeacherInterface.java | UTF-8 | 324 | 1.679688 | 2 | [] | no_license | /**
* Created by Kamil on 2015-02-04.
*/
public interface TeacherInterface {
public void teacherMain();
public void getTeacherSchedule();
public void addStudentGrade();
public void addStudentNote();
public void addCompletedLesson();
public void changeTeacherPassword();
}
| true |
f9420f529c5f144e0bf0cd915258e3a12e3ef0f1 | Java | DangLiem/be-authentication | /authentication/src/main/java/com/hdtcn/authentication/security/UserDetailIml.java | UTF-8 | 1,525 | 2.203125 | 2 | [] | no_license | package com.hdtcn.authentication.security;
import com.hdtcn.authentication.entity.Role;
import com.hdtcn.authentication.entity.User;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class UserDetailIml implements UserDetails {
User user;
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
Set<Role> roles = user.getRoles();
List<GrantedAuthority> authorities = new ArrayList<>();
for (Role role : roles) {
authorities.add(new SimpleGrantedAuthority(role.getNameRole()));
}
return authorities;
}
@Override
public String getPassword() {
return user.getPassword();
}
@Override
public String getUsername() {
return user.getEmail();
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
}
| true |
551e3c6078d1cc0dcde15377a18e81db7732d11d | Java | SoulShow/pq-agency-service | /src/main/java/com/pq/agency/service/impl/AgencyStudentServiceImpl.java | UTF-8 | 16,093 | 1.992188 | 2 | [] | no_license | package com.pq.agency.service.impl;
import com.alibaba.fastjson.JSON;
import com.pq.agency.dto.*;
import com.pq.agency.entity.*;
import com.pq.agency.exception.AgencyErrorCode;
import com.pq.agency.exception.AgencyErrors;
import com.pq.agency.exception.AgencyException;
import com.pq.agency.feign.UserFeign;
import com.pq.agency.mapper.*;
import com.pq.agency.param.AddStudentForm;
import com.pq.agency.param.StudentLifeForm;
import com.pq.agency.service.AgencyStudentService;
import com.pq.agency.utils.AgencyResult;
import com.pq.common.constants.CommonConstants;
import com.pq.common.exception.CommonErrors;
import com.pq.common.util.DateUtil;
import com.pq.common.util.HttpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* @author liutao
*/
@Service
public class AgencyStudentServiceImpl implements AgencyStudentService {
@Autowired
private AgencyStudentMapper studentMapper;
@Autowired
private AgencyStudentLifeMapper studentLifeMapper;
@Autowired
private AgencyStudentLifeImgMapper studentLifeImgMapper;
@Autowired
private AgencyClassMapper agencyClassMapper;
@Autowired
private AgencyUserMapper agencyUserMapper;
@Autowired
private AgencyUserStudentMapper agencyUserStudentMapper;
@Autowired
private AgencyClassInvitationCodeMapper invitationCodeMapper;
@Autowired
private AgencyGroupMemberMapper groupMemberMapper;
@Autowired
private AgencyGroupMapper agencyGroupMapper;
@Autowired
private UserFeign userFeign;
@Autowired
private RedisTemplate redisTemplate;
@Value("${php.url}")
private String phpUrl;
@Override
public void updateStudentInfo(AgencyStudent agencyStudent){
agencyStudent.setUpdatedTime(DateUtil.currentTime());
studentMapper.updateByPrimaryKey(agencyStudent);
}
@Override
public AgencyStudent getAgencyStudentById(Long id){
return studentMapper.selectByPrimaryKey(id);
}
@Override
public AgencyStudentLifeListDto getStudentLife(Long studentId, Long agencyClassId, int offset, int size){
List<AgencyStudentLife> agencyStudentLifeList = studentLifeMapper.selectByStudentIdAndAgencyClassId(studentId,agencyClassId, offset, size);
if(agencyStudentLifeList==null || agencyStudentLifeList.size()==0){
return null;
}
List<AgencyStudentLifeDto> lifeList = new ArrayList<>();
AgencyStudentLifeListDto lifeListDto = new AgencyStudentLifeListDto();
for(AgencyStudentLife agencyStudentLife:agencyStudentLifeList){
List<AgencyStudentLifeImg> imgList = studentLifeImgMapper.selectByLifeId(agencyStudentLife.getId());
List<String> list = new ArrayList<>();
for(AgencyStudentLifeImg img:imgList){
list.add(img.getImg());
}
lifeListDto.setAgencyClassId(agencyStudentLife.getAgencyClassId());
lifeListDto.setStudentId(agencyStudentLife.getStudentId());
AgencyStudentLifeDto lifeDto = new AgencyStudentLifeDto();
lifeDto.setImgList(list);
lifeDto.setContent(agencyStudentLife.getContent());
lifeDto.setTitle(agencyStudentLife.getTitle());
lifeDto.setCreatedTime(DateUtil.formatDate(agencyStudentLife.getCreatedTime(),DateUtil.DEFAULT_DATE_FORMAT));
lifeDto.setId(agencyStudentLife.getId());
lifeList.add(lifeDto);
}
lifeListDto.setList(lifeList);
return lifeListDto;
}
@Transactional(rollbackFor = Exception.class)
@Override
public void createStudentLife(StudentLifeForm studentLifeForm){
AgencyStudentLife agencyStudentLife = new AgencyStudentLife();
agencyStudentLife.setAgencyClassId(studentLifeForm.getAgencyClassId());
agencyStudentLife.setStudentId(studentLifeForm.getStudentId());
agencyStudentLife.setContent(studentLifeForm.getContent());
agencyStudentLife.setTitle(studentLifeForm.getTitle());
agencyStudentLife.setState(true);
agencyStudentLife.setCreatedTime(DateUtil.currentTime());
agencyStudentLife.setUpdatedTime(DateUtil.currentTime());
studentLifeMapper.insert(agencyStudentLife);
for(String img:studentLifeForm.getImgList()){
AgencyStudentLifeImg studentLifeImg = new AgencyStudentLifeImg();
studentLifeImg.setImg(img);
studentLifeImg.setLifeId(agencyStudentLife.getId());
studentLifeImg.setCreatedTime(DateUtil.currentTime());
studentLifeImg.setUpdatedTime(DateUtil.currentTime());
studentLifeImg.setState(true);
studentLifeImgMapper.insert(studentLifeImg);
}
}
@Override
public int getStudentCount(Long classId){
Integer count = studentMapper.selectCountByAgencyClassId(classId);
if(count==null){
count=0;
}
return count;
}
@Override
public AgencyStudentDto getStudentInfoById(Long studentId){
AgencyStudent agencyStudent = studentMapper.selectByPrimaryKey(studentId);
if(agencyStudent==null){
AgencyException.raise(AgencyErrors.AGENCY_STUDENT_NOT_EXIST_ERROR);
}
AgencyClass agencyClass = agencyClassMapper.selectByPrimaryKey(agencyStudent.getAgencyClassId());
if(agencyClass==null){
AgencyException.raise(AgencyErrors.AGENCY_CLASS_NOT_EXIST_ERROR);
}
AgencyStudentDto agencyStudentDto = new AgencyStudentDto();
agencyStudentDto.setStudentId(studentId);
agencyStudentDto.setSex(agencyStudent.getSex());
agencyStudentDto.setAvatar(agencyStudent.getAvatar());
agencyStudentDto.setName(agencyStudent.getName());
agencyStudentDto.setClassName(agencyClass.getName());
agencyStudentDto.setClassId(agencyClass.getId());
agencyStudentDto.setParentList(getParentList(agencyClass.getId(),agencyStudent));
return agencyStudentDto;
}
private List<ParentDto> getParentList(Long classId, AgencyStudent agencyStudent){
List<ParentDto> parentList = new ArrayList<>();
List<AgencyUserStudent> userStudentList = agencyUserStudentMapper.
selectByAgencyClassIdAndStudentId(classId,agencyStudent.getId());
for(AgencyUserStudent userStudent : userStudentList){
ParentDto parentDto = new ParentDto();
parentDto.setUserId(userStudent.getUserId());
parentDto.setName(agencyStudent.getName()+userStudent.getRelation());
AgencyResult<UserDto> result = userFeign.getUserInfo(userStudent.getUserId());
if(!CommonErrors.SUCCESS.getErrorCode().equals(result.getStatus())){
throw new AgencyException(new AgencyErrorCode(result.getStatus(),result.getMessage()));
}
UserDto userDto = result.getData();
parentDto.setPhone(userDto.getUsername());
parentDto.setHuanxinId(userDto.getHuanxinId());
parentDto.setAvatar(userDto.getAvatar());
parentList.add(parentDto);
}
return parentList;
}
@Override
public List<AgencyTeacherDto> getClassTeachersByStudentId(Long studentId){
AgencyStudent agencyStudent = studentMapper.selectByPrimaryKey(studentId);
if(agencyStudent==null){
AgencyException.raise(AgencyErrors.AGENCY_USER_STUDENT_NOT_EXIST_ERROR);
}
AgencyClass agencyClass = agencyClassMapper.selectByPrimaryKey(agencyStudent.getAgencyClassId());
if(agencyClass==null){
AgencyException.raise(AgencyErrors.AGENCY_CLASS_NOT_EXIST_ERROR);
}
List<AgencyUser> userList = agencyUserMapper.selectByClassIdAndRole(agencyClass.getId(),
CommonConstants.PQ_LOGIN_ROLE_TEACHER);
List<AgencyTeacherDto> list = new ArrayList<>();
for(AgencyUser agencyUser:userList){
AgencyTeacherDto teacherDto = new AgencyTeacherDto();
AgencyResult<UserDto> result = userFeign.getUserInfo(agencyUser.getUserId());
if(!CommonErrors.SUCCESS.getErrorCode().equals(result.getStatus())){
throw new AgencyException(new AgencyErrorCode(result.getStatus(),result.getMessage()));
}
UserDto userDto = result.getData();
teacherDto.setUserId(agencyUser.getUserId());
teacherDto.setHuanxinId(userDto.getHuanxinId());
teacherDto.setName(userDto.getName());
teacherDto.setAvatar(userDto.getAvatar());
list.add(teacherDto);
}
return list;
}
@Override
public List<Long> getClassStudentList(Long classId){
List<Long> studentDtos = new ArrayList<>();
List<AgencyStudent> list = studentMapper.selectByAgencyClassId(classId);
for(AgencyStudent agencyStudent:list){
studentDtos.add(agencyStudent.getId());
}
return studentDtos;
}
@Override
public List<Long> getAgencyStudentList(Long classId){
List<Long> studentDtos = new ArrayList<>();
AgencyClass agencyClass = agencyClassMapper.selectByPrimaryKey(classId);
List<AgencyClass> classList = agencyClassMapper.selectGradeByAgencyId(agencyClass.getAgencyId());
for(AgencyClass classInfo:classList ){
List<AgencyStudent> list = studentMapper.selectByAgencyClassId(classInfo.getId());
for(AgencyStudent agencyStudent:list){
studentDtos.add(agencyStudent.getId());
}
}
return studentDtos;
}
@Override
public AgencyStudentRelationDto getStudentExistRelation(String code,String name,String userId){
AgencyClassInvitationCode invitationCode = invitationCodeMapper.selectByCode(code);
if(invitationCode==null){
AgencyException.raise(AgencyErrors.INVITATION_CODE_ERROR);
}
//check用户是否绑定过这个学生
List<AgencyStudent> list = studentMapper.selectByAgencyClassIdAndName(invitationCode.getAgencyClassId(),name);
AgencyUserStudent agencyUserStudent = agencyUserStudentMapper.selectByUserIdAndStudentId(userId,list.get(0).getId());
if(agencyUserStudent!=null){
AgencyException.raise(AgencyErrors.AGENCY_ADD_STUDENT_REPEAT_ERROR);
}
if(list==null||list.size()==0){
if(redisTemplate.hasKey("STUDENT_NAME_ERROR_TIME"+userId)){
int count = (int)redisTemplate.opsForValue().get("STUDENT_NAME_ERROR_TIME"+userId);
if(count>=3){
redisTemplate.delete("STUDENT_NAME_ERROR_TIME"+userId);
AgencyException.raise(AgencyErrors.AGENCY_GET_STUDENT_NAME_ERROR);
}
redisTemplate.opsForValue().set("STUDENT_NAME_ERROR_TIME"+userId,count+1);
}else {
redisTemplate.opsForValue().set("STUDENT_NAME_ERROR_TIME"+userId,1);
}
AgencyException.raise(AgencyErrors.AGENCY_STUDENT_NOT_EXIST_ERROR);
}
List<AgencyUserStudent> userStudentList = agencyUserStudentMapper.
selectByAgencyClassIdAndStudentId(invitationCode.getAgencyClassId(),list.get(0).getId());
AgencyStudentRelationDto relationDto = new AgencyStudentRelationDto();
List<String> relationList = new ArrayList<>();
for(AgencyUserStudent userStudent:userStudentList){
relationList.add(userStudent.getRelation());
}
relationDto.setRelationList(relationList);
relationDto.setStudentId(list.get(0).getId());
relationDto.setAgencyClassId(invitationCode.getAgencyClassId());
return relationDto;
}
@Override
public void userAddStudent(AddStudentForm addStudentForm){
AgencyUserStudent agencyUserStudent = agencyUserStudentMapper.selectByStudentIdAndRelation(addStudentForm.getStudentId(),addStudentForm.getRelation());
if(agencyUserStudent!=null){
AgencyException.raise(AgencyErrors.AGENCY_ADD_STUDENT_RELATION_ERROR);
}
AgencyUser agencyUser = agencyUserMapper.selectByUserAndClassId(addStudentForm.getUserId(),addStudentForm.getAgencyClassId());
if(agencyUser==null){
agencyUser = new AgencyUser();
agencyUser.setAgencyClassId(addStudentForm.getAgencyClassId());
agencyUser.setUserId(addStudentForm.getUserId());
agencyUser.setRole(CommonConstants.PQ_LOGIN_ROLE_PARENT);
agencyUser.setState(true);
agencyUser.setIsHead(0);
agencyUser.setChatStatus(0);
agencyUser.setCreatedTime(DateUtil.currentTime());
agencyUser.setUpdatedTime(DateUtil.currentTime());
agencyUserMapper.insert(agencyUser);
}
AgencyUserStudent userStudent = new AgencyUserStudent();
userStudent.setAgencyClassId(addStudentForm.getAgencyClassId());
userStudent.setUserId(addStudentForm.getUserId());
userStudent.setAgencyUserId(agencyUser.getId());
userStudent.setStudentId(addStudentForm.getStudentId());
userStudent.setStudentName(addStudentForm.getStudentName());
userStudent.setState(true);
userStudent.setRelation(addStudentForm.getRelation());
userStudent.setCreatedTime(DateUtil.currentTime());
userStudent.setUpdatedTime(DateUtil.currentTime());
agencyUserStudentMapper.insert(userStudent);
try {
if(agencyUser==null){
HashMap<String, String> paramMap = new HashMap<>();
AgencyResult<UserDto> result = userFeign.getUserInfo(addStudentForm.getUserId());
if(!CommonErrors.SUCCESS.getErrorCode().equals(result.getStatus())){
throw new AgencyException(new AgencyErrorCode(result.getStatus(),result.getMessage()));
}
UserDto userDto = result.getData();
paramMap.put("hxGroupId", agencyClassMapper.selectByPrimaryKey(addStudentForm.getAgencyClassId()).getGroupId());
paramMap.put("userHxId", userDto.getHuanxinId());
String huanxResult = HttpUtil.sendJson(phpUrl+"addHxGroup",new HashMap<>(),JSON.toJSONString(paramMap));
AgencyResult userResult = JSON.parseObject(huanxResult,AgencyResult.class);
if(userResult==null||!CommonErrors.SUCCESS.getErrorCode().equals(userResult.getStatus())){
AgencyException.raise(AgencyErrors.AGENCY_USER_ADD_GROUP_ERROR);
}
}
AgencyGroup agencyGroup = agencyGroupMapper.selectByClassId(userStudent.getAgencyClassId());
if(agencyGroup==null){
AgencyException.raise(AgencyErrors.AGENCY_GROUP_NOT_EXIST_ERROR);
}
AgencyGroupMember agencyGroupMember = groupMemberMapper.selectByGroupIdAndStudentOrUserId(agencyGroup.getId(),
userStudent.getStudentId(),null);
if(agencyGroupMember==null){
agencyGroupMember = new AgencyGroupMember();
}else {
return;
}
agencyGroupMember.setStudentId(userStudent.getStudentId());
agencyGroupMember.setGroupId(agencyGroup.getId());
agencyGroupMember.setDisturbStatus(1);
agencyGroupMember.setState(true);
agencyGroupMember.setIsHead(0);
agencyGroupMember.setUpdatedTime(DateUtil.currentTime());
agencyGroupMember.setCreatedTime(DateUtil.currentTime());
groupMemberMapper.insert(agencyGroupMember);
} catch (Exception e) {
e.printStackTrace();
AgencyException.raise(AgencyErrors.AGENCY_USER_ADD_GROUP_ERROR);
}
}
}
| true |
88ee3e31247bbe12eea9876d60f1873ef6aac34d | Java | wndeld777/Biz_403_2021_03_Java | /Java_013_Method/src/com/callor/method/service/NumberServiceV5.java | UTF-8 | 736 | 3.328125 | 3 | [] | no_license | package com.callor.method.service;
import java.util.Scanner;
public class NumberServiceV5 {
public Integer inputNum(String title) {
Scanner scan = new Scanner(System.in);
while (true) {
System.out.println(title + "의 값을 입력하세요");
System.out.println("끝내려면 QUIT를 입력하세요");
System.out.print(">> ");
String strNum = scan.nextLine();
Integer intNum = null;
if (strNum.equals("QUIT")) {
return null;
} else {
try {
intNum = Integer.valueOf(strNum);
} catch (NumberFormatException e) {
System.out.println("입력오류");
continue;
}
}
if (intNum < 0 ) {
System.out.println("값은 0 이상");
continue;
}
return intNum;
}
}
}
| true |
de2ed7dc7967dfb4d1d6a75391fd76e5b8db0bb4 | Java | eritter688/jMoria | /src/jMoria/game/screens/newplayer/ChooseNameScreen.java | UTF-8 | 2,652 | 2.6875 | 3 | [] | no_license | package jMoria.game.screens.newplayer;
import static jMoria.game.screens.newplayer.common.NewPlayerRenders.renderAgeBlock;
import static jMoria.game.screens.newplayer.common.NewPlayerRenders.renderBonusBlock;
import static jMoria.game.screens.newplayer.common.NewPlayerRenders.renderHPBlock;
import static jMoria.game.screens.newplayer.common.NewPlayerRenders.renderLevelBlock;
import static jMoria.game.screens.newplayer.common.NewPlayerRenders.renderMiscAbilitiesBlock;
import static jMoria.game.screens.newplayer.common.NewPlayerRenders.renderNameBlock;
import static jMoria.game.screens.newplayer.common.NewPlayerRenders.renderStatBlock;
import jMoria.game.ResourcePackage;
import jMoria.game.screens.AbstractScreen;
import java.util.regex.Pattern;
public class ChooseNameScreen extends AbstractScreen {
public ChooseNameScreen(ResourcePackage gameResources) {
super(gameResources);
}
@Override
public void init() {
}
@Override
public void render() {
gameResources.terminal.clearScreen();
renderNameBlock(gameResources.terminal, gameResources.player);
renderAgeBlock(gameResources.terminal, gameResources.player);
renderStatBlock(gameResources.terminal, gameResources.player);
renderBonusBlock(gameResources.terminal, gameResources.player);
renderLevelBlock(gameResources.terminal, gameResources.player);
renderHPBlock(gameResources.terminal, gameResources.player);
renderMiscAbilitiesBlock(gameResources.terminal, gameResources.player);
gameResources.terminal
.writeLine(21, " Enter your player's name [press <RETURN> when finished]");
}
@Override
public void handleKey(String key) {
System.out.println("Received Key: " + key.toString());
if ("ENTER".equals(key)) {
if (gameResources.player.name.equals("")) {
gameResources.player.name = "player";
renderNameBlock(gameResources.terminal, gameResources.player);
// gameResources.game.setCurrentScreen(new GameScreen(gameResources));
}
} else {
handleNameInput(key);
}
}
private static final Pattern ALPHANUMERIC = Pattern.compile("^[a-zA-Z0-9]+$");
private final StringBuilder nameStringBuilder = new StringBuilder();
private void handleNameInput(String s) {
if (s.equals("BACK_SPACE")) {
if (nameStringBuilder.length() > 0) {
nameStringBuilder.deleteCharAt(nameStringBuilder.length() - 1);
}
}
if (ALPHANUMERIC.matcher(s).matches()) {
if (nameStringBuilder.length() < 12) {
nameStringBuilder.append(s);
}
}
gameResources.player.name = nameStringBuilder.toString();
render();
}
}
| true |
ffda1a47c35672691bcb8b439f4889f9006c07a7 | Java | aarodrigues/MedRemind | /app/src/main/java/com/lifedev/medreminder/db/MedReminderContract.java | UTF-8 | 4,506 | 2.546875 | 3 | [] | no_license | package com.lifedev.medreminder.db;
import android.provider.BaseColumns;
/**
* Created by alano on 4/21/16.
*/
public class MedReminderContract {
public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "MedReminder.db";
private static final String TEXT_TYPE = " TEXT";
private static final String COMMA_SEP = ",";
private static final String DATETIME = " DATETIME";
/* Tables */
public static final String TABLE_NAME_MEDICINE = "medicine";
public static final String TABLE_NAME_CAREGIVER = "caregiver";
public static final String TABLE_NAME_PATIENT = "patient";
public static final String TABLE_NAME_MEDICINE_CAREGIVER = "medicine_caregiver";
public MedReminderContract(){
}
/* Inner class that defines the table medicine */
public static abstract class Medicine implements BaseColumns {
public static final String COLUMN_ID = "id";
public static final String COLUMN_NAME = "name";
public static final String COLUMN_LABORATORY = "laboratory";
public static final String COLUMN_DATE_CADASTRE = "date_cadastre";
public static final String COLUMN_BEGIN_HOUR = "begin_hour";
public static final String COLUMN_MEDICINE_INTERVAL = "interval";
public static final String CREATE_TABLE = "CREATE TABLE " +
TABLE_NAME_MEDICINE + " (" +
COLUMN_ID + " INTEGER PRIMARY KEY," +
COLUMN_NAME + TEXT_TYPE + COMMA_SEP +
COLUMN_LABORATORY + TEXT_TYPE + COMMA_SEP +
COLUMN_DATE_CADASTRE + DATETIME + COMMA_SEP +
COLUMN_BEGIN_HOUR + DATETIME + COMMA_SEP +
COLUMN_MEDICINE_INTERVAL + DATETIME + " )";
public static final String DELETE_TABLE = "DROP TABLE IF EXISTS " + TABLE_NAME_MEDICINE;
}
/* Inner class that defines the table receiver */
public static abstract class Caregiver implements BaseColumns {
public static final String COLUMN_ID = "id";
public static final String COLUMN_NAME = "name";
public static final String COLUMN_MOBILE_PHONE = "phone";
public static final String COLUMN_EMAIL = "email";
public static final String CREATE_TABLE = "CREATE TABLE " +
TABLE_NAME_CAREGIVER + " (" +
COLUMN_ID + " INTEGER PRIMARY KEY," +
COLUMN_NAME + TEXT_TYPE + COMMA_SEP +
COLUMN_EMAIL + TEXT_TYPE + COMMA_SEP +
COLUMN_MOBILE_PHONE + TEXT_TYPE + " )";
public static final String DELETE_TABLE = "DROP TABLE IF EXISTS " + TABLE_NAME_CAREGIVER;
}
/* Inner class that defines the table patient */
/*
public static abstract class Patient implements BaseColumns {
public static final String COLUMN_ID = "id";
public static final String COLUMN_NAME = "name";
public static final String COLUMN_MOBILE_PHONE = "phone";
public static final String COLUMN_GENDER = "gender";
public static final String CREATE_TABLE = "CREATE TABLE " +
TABLE_NAME_PATIENT + " (" +
COLUMN_ID + " INTEGER PRIMARY KEY," +
COLUMN_NAME + TEXT_TYPE + COMMA_SEP +
COLUMN_MOBILE_PHONE + TEXT_TYPE + COMMA_SEP +
COLUMN_GENDER + " )";
public static final String DELETE_TABLE = "DROP TABLE IF EXISTS " + TABLE_NAME_PATIENT;
}
*/
/* Inner class that defines the relationship between table medicine and caregiver */
public static abstract class MedicineToCaregiver implements BaseColumns {
public static final String COLUMN_ID = "id";
public static final String COLUMN_ID_MEDICINE = "id_medicine";
public static final String COLUMN_ID_CAREGIVER = "id_caregiver";
public static final String CREATE_TABLE = "CREATE TABLE " +
TABLE_NAME_MEDICINE_CAREGIVER + " (" +
COLUMN_ID + " INTEGER PRIMARY KEY," +
COLUMN_ID_MEDICINE + " INTEGER " + COMMA_SEP +
COLUMN_ID_CAREGIVER + " INTEGER " + COMMA_SEP + //" )";
"FOREIGN KEY(" + COLUMN_ID_MEDICINE + ") REFERENCES " + TABLE_NAME_MEDICINE + "("+ COLUMN_ID +")" + COMMA_SEP +
"FOREIGN KEY(" + COLUMN_ID_CAREGIVER + ") REFERENCES " + TABLE_NAME_CAREGIVER + "("+ COLUMN_ID +")" + " )";
public static final String DELETE_TABLE = "DROP TABLE IF EXISTS " + TABLE_NAME_MEDICINE_CAREGIVER;
}
}
| true |
bf046776331049d1fc63f7e5c68a27b21fc47aff | Java | richardhendricks/ExtraUtilities | /com/rwtema/extrautils/item/scanner/ItemScanner.java | UTF-8 | 3,845 | 2.046875 | 2 | [] | no_license | /* 1: */ package com.rwtema.extrautils.item.scanner;
/* 2: */
/* 3: */ import com.rwtema.extrautils.ExtraUtils;
/* 4: */ import com.rwtema.extrautils.network.packets.PacketTempChatMultiline;
/* 5: */ import java.util.List;
/* 6: */ import net.minecraft.block.Block;
/* 7: */ import net.minecraft.entity.Entity;
/* 8: */ import net.minecraft.entity.EntityLivingBase;
/* 9: */ import net.minecraft.entity.player.EntityPlayer;
/* 10: */ import net.minecraft.item.Item;
/* 11: */ import net.minecraft.item.ItemStack;
/* 12: */ import net.minecraft.util.ChatComponentText;
/* 13: */ import net.minecraft.world.World;
/* 14: */ import net.minecraftforge.common.util.ForgeDirection;
/* 15: */
/* 16: */ public class ItemScanner
/* 17: */ extends Item
/* 18: */ {
/* 19:18 */ public static boolean scannerOut = false;
/* 20: */
/* 21: */ public ItemScanner()
/* 22: */ {
/* 23:22 */ setTextureName("extrautils:scanner");
/* 24:23 */ setUnlocalizedName("extrautils:scanner");
/* 25:24 */ setCreativeTab(ExtraUtils.creativeTabExtraUtils);
/* 26:25 */ setMaxStackSize(1);
/* 27: */ }
/* 28: */
/* 29: */ public void onUpdate(ItemStack par1ItemStack, World par2World, Entity par3Entity, int par4, boolean par5)
/* 30: */ {
/* 31:30 */ scannerOut = true;
/* 32:31 */ super.onUpdate(par1ItemStack, par2World, par3Entity, par4, par5);
/* 33: */ }
/* 34: */
/* 35: */ public boolean onItemUse(ItemStack stack, EntityPlayer player, World world, int x, int y, int z, int side, float hitX, float hitY, float hitZ)
/* 36: */ {
/* 37:36 */ if (world.isClient) {
/* 38:37 */ return true;
/* 39: */ }
/* 40:40 */ Block b = world.getBlock(x, y, z);
/* 41: */
/* 42:42 */ PacketTempChatMultiline.addChatComponentMessage(new ChatComponentText("~~~~~Scan~~~~~"));
/* 43:43 */ PacketTempChatMultiline.addChatComponentMessage(new ChatComponentText("Block name: " + b.getUnlocalizedName()));
/* 44:44 */ PacketTempChatMultiline.addChatComponentMessage(new ChatComponentText("Block metadata: " + world.getBlockMetadata(x, y, z)));
/* 45: */
/* 46:46 */ Object tile = world.getTileEntity(x, y, z);
/* 47:48 */ if (tile == null)
/* 48: */ {
/* 49:49 */ PacketTempChatMultiline.sendCached(player);
/* 50:50 */ return false;
/* 51: */ }
/* 52:53 */ ForgeDirection dir = ForgeDirection.getOrientation(side);
/* 53:54 */ List<String> data = ScannerRegistry.getData(tile, dir, player);
/* 54:56 */ for (String aData : data) {
/* 55:57 */ PacketTempChatMultiline.addChatComponentMessage(new ChatComponentText(aData));
/* 56: */ }
/* 57:60 */ PacketTempChatMultiline.sendCached(player);
/* 58: */
/* 59:62 */ return true;
/* 60: */ }
/* 61: */
/* 62: */ public boolean itemInteractionForEntity(ItemStack par1ItemStack, EntityPlayer player, EntityLivingBase entity)
/* 63: */ {
/* 64:67 */ if (player.worldObj.isClient) {
/* 65:68 */ return true;
/* 66: */ }
/* 67:71 */ if (entity == null) {
/* 68:72 */ return false;
/* 69: */ }
/* 70:75 */ List<String> data = ScannerRegistry.getData(entity, ForgeDirection.UP, player);
/* 71:77 */ for (String aData : data) {
/* 72:78 */ PacketTempChatMultiline.addChatComponentMessage(new ChatComponentText(aData));
/* 73: */ }
/* 74:80 */ PacketTempChatMultiline.sendCached(player);
/* 75: */
/* 76:82 */ return true;
/* 77: */ }
/* 78: */ }
/* Location: E:\TechnicPlatform\extrautilities\extrautilities-1.2.13.jar
* Qualified Name: com.rwtema.extrautils.item.scanner.ItemScanner
* JD-Core Version: 0.7.0.1
*/ | true |
8042c57f071a1259579da9d509d7f0c3d8eb9b5d | Java | yangyuanlincn/ssh_crm | /src/com/linn/test/Person.java | UTF-8 | 185 | 2.453125 | 2 | [] | no_license | package com.linn.test;
public class Person {
public void fun() {
System.out.println("person");
}
public void print() {
this.fun();
System.out.println("我是人类");
}
}
| true |
1d62f71fd17c4359e1fa62d9b4bd34011c334859 | Java | wsscp/bsdemo | /BaoSheng/BaoShengMES-Core/src/main/java/cc/oit/bsmes/inv/action/.svn/text-base/WarehouseController.java.svn-base | UTF-8 | 5,689 | 2.046875 | 2 | [] | no_license | package cc.oit.bsmes.inv.action;
import java.util.List;
import javax.annotation.Resource;
import cc.oit.bsmes.common.mybatis.Sort;
import com.alibaba.fastjson.JSONArray;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import cc.oit.bsmes.common.constants.LocationType;
import cc.oit.bsmes.common.constants.WarehouseType;
import cc.oit.bsmes.common.util.SessionUtils;
import cc.oit.bsmes.common.view.TableView;
import cc.oit.bsmes.common.view.UpdateResult;
import cc.oit.bsmes.inv.model.Location;
import cc.oit.bsmes.inv.model.Warehouse;
import cc.oit.bsmes.inv.service.LocationService;
import cc.oit.bsmes.inv.service.WarehouseService;
import cc.oit.bsmes.pro.model.ProcessInformation;
import cc.oit.bsmes.pro.service.ProcessInformationService;
/**
*
* 仓库
* <p style="display:none">
* modifyRecord
* </p>
*
* @author leiwei
* @date 2014-9-17 下午3:48:51
* @since
* @version
*/
@Controller
@RequestMapping("/inv/warehouse")
public class WarehouseController {
@Resource
private WarehouseService warehouseService;
@Resource
private ProcessInformationService processInformationService;
@Resource
private LocationService locationService;
@RequestMapping(produces = "text/html")
public String index(Model model) {
model.addAttribute("moduleName", "inv");
model.addAttribute("submoduleName", "warehouse");
return "inv.warehouse";
}
@RequestMapping
@ResponseBody
@SuppressWarnings("rawtypes")
public TableView list(@ModelAttribute Warehouse param, @RequestParam(required = false) String sort,
@RequestParam(required = false) Integer start, @RequestParam(required = false) Integer limit) {
param.setOrgCode(warehouseService.getOrgCode());
List list = warehouseService.find(param, start, limit, JSONArray.parseArray(sort, Sort.class));
TableView tableView = new TableView();
tableView.setRows(list);
tableView.setTotal(warehouseService.count(param));
return tableView;
}
@RequestMapping(method = RequestMethod.POST, consumes = "application/json")
@ResponseBody
public UpdateResult save(@RequestBody String jsonText) throws ClassNotFoundException {
UpdateResult updateResult = new UpdateResult();
Warehouse warehouse = JSON.parseObject(jsonText, Warehouse.class);
warehouseService.insert(warehouse);
warehouse = warehouseService.getById(warehouse.getId());
List<ProcessInformation> list = processInformationService.findByCodeOrName(null);
for (ProcessInformation processInformation : list) {
Location location = new Location();
location.setProcessCode(processInformation.getCode());
location.setLocationName("临时库位");
location.setWarehouseId(warehouse.getId());
location.setOrgCode(SessionUtils.getUser().getOrgCode());
location.setType(LocationType.TEMP);
locationService.insert(location);
}
Location local = new Location();
local.setOrgCode(SessionUtils.getUser().getOrgCode());
local.setType(LocationType.STORE);
local.setProcessCode("-1");
local.setWarehouseId(warehouse.getId());
local.setLocationName("成品库");
locationService.insert(local);
updateResult.addResult(warehouse);
return updateResult;
}
@RequestMapping(value = "/{id}", method = RequestMethod.PUT, consumes = "application/json")
@ResponseBody
public UpdateResult update(@RequestBody String jsonText) throws ClassNotFoundException {
UpdateResult updateResult = new UpdateResult();
Warehouse warehouse = JSON.parseObject(jsonText, Warehouse.class);
warehouse.setModifyUserCode(SessionUtils.getUser().getUserCode());
warehouseService.update(warehouse);
updateResult.addResult(warehouse);
return updateResult;
}
@RequestMapping(value = "check/{warehouseCode}", method = RequestMethod.GET)
@ResponseBody
public JSONObject checkUserCodeUnique(@PathVariable String warehouseCode) throws ClassNotFoundException {
JSONObject object = new JSONObject();
Warehouse warehouse = new Warehouse();
warehouse.setWarehouseCode(warehouseCode);
warehouse.setOrgCode(SessionUtils.getUser().getOrgCode());
Warehouse house = warehouseService.checkExtist(warehouse);
object.put("codeExtist", house == null);
return object;
}
@RequestMapping(value = "checkType/{type}", method = RequestMethod.GET)
@ResponseBody
public JSONObject checkType(@PathVariable String type) throws ClassNotFoundException {
JSONObject object = new JSONObject();
Warehouse warehouse = new Warehouse();
warehouse.setType(WarehouseType.WIP);
warehouse.setOrgCode(SessionUtils.getUser().getOrgCode());
List<Warehouse> list = warehouseService.findByObj(warehouse);
object.put("checkExtist", list.size() > 0);
return object;
}
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
@ResponseBody
public void delete(@PathVariable String id) {
locationService.deleteByWarehouseId(id);
warehouseService.deleteById(id);
}
/**
* 获取企业下所有的仓库信息
* */
@RequestMapping(value = "getAll", method = RequestMethod.GET)
@ResponseBody
public List<Warehouse> getAll() {
Warehouse warehouse = new Warehouse();
warehouse.setOrgCode(SessionUtils.getUser().getOrgCode());
return warehouseService.getByObj(warehouse);
}
}
| true |
a09312f3dd4f9f31e70a9be8bd7495a5fbb3c6fd | Java | nilold/cdc_monitor | /src/main/java/com/nilo/cadence_test/exceptions/OpenedSessionException.java | UTF-8 | 457 | 2.65625 | 3 | [] | no_license | package com.nilo.cadence_test.exceptions;
import com.nilo.cadence_test.model.UserAccess;
public class OpenedSessionException extends Exception {
public OpenedSessionException(UserAccess userAccess) {
super(String.format(
"User %d already has an opened session on computer %d started at %s.",
userAccess.getUser().getId(), userAccess.getComputer().getId(), userAccess.getStartAt().toString()
));
}
}
| true |
f0786820ae5ec8be990f9a8936b933391ed12488 | Java | TheRealmOfEterus/EternalCraft | /eternalcraft/common/machines/EternalcraftMachines.java | UTF-8 | 1,720 | 2.359375 | 2 | [] | no_license | package eternalcraft.common.machines;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import cpw.mods.fml.common.registry.GameRegistry;
import eternalcraft.common.Eternalcraft;
import eternalcraft.common.core.EternalcraftSettings;
import eternalcraft.common.helpers.TextureHelper;
public class EternalcraftMachines {
public static Block machineBlock;
public static Block machines;
public static Item machinePartItem;
public static Item machineToolItem;
public static void initialize() {
TextureHelper.buildFurnaceTextureNames();
initBlocks();
registerMachineTileEntities();
}
private static void registerMachineTileEntities() {
for(MachineType machine : MachineType.values())
GameRegistry.registerTileEntity(machine.theMachine, "ec_machine_"+machine.name().toLowerCase());
}
private static void initBlocks(){
machines = new BlockECFurnace(settings().getMachinesID(), Material.iron).setUnlocalizedName("ec.machines").setCreativeTab(Eternalcraft.tabEternalCraft);
machineBlock = new MachineBlock(settings().getMachineBlockID(), Material.iron).setUnlocalizedName("ec.machineblock").setCreativeTab(Eternalcraft.tabEternalCraft);
GameRegistry.registerBlock(machineBlock, "ec_machineblock");
GameRegistry.registerBlock(machines, ItemBlockECMachine.class, "ec_machines");
}
public static EternalcraftSettings settings() {
return Eternalcraft.instance.settings;
}
public static void initRecipes() {
//FIXME
//GameRegistry.addShapelessRecipe(new ItemStack(machinePartItem, 1, 3), new Object[]{ new ItemStack(machinePartItem, 1, 1), new ItemStack(machinePartItem, 1, 2) });
}
}
| true |
93f2a3757492849030626764cb42164f76348fdc | Java | Habib223/004UnitTestingFirstApp | /src/main/java/com/app/calculator/Calculator.java | UTF-8 | 298 | 2.078125 | 2 | [] | no_license | package com.app.calculator;
public class Calculator {
public Integer add(int a,int b)
{
return a+b;
}
public Integer mul(int a,int b) {
return a*b;
}
//HIS-200 related changes
public doprocess(){
//logic write here
}
}
| true |
5f872fbb646a8a33b946c1cb8cd50eaa6fdb999d | Java | fzoli/DineUpServer | /DineUp-api/src/main/java/com/dineup/api/ApiConfig.java | UTF-8 | 3,129 | 2.421875 | 2 | [] | no_license | package com.dineup.api;
import com.dineup.api.service.impl.DineUpNoCacheManager;
public class ApiConfig {
private final SecurityConfig securityConfig;
private final DineUpCacheManager cacheManager;
private final long cacheLifetime;
private final Target target;
private final String languageCode;
private ApiConfig(Builder builder) {
securityConfig = builder.securityConfig;
cacheManager = builder.cacheManager;
cacheLifetime = builder.cacheLifetime;
target = builder.target;
languageCode = builder.languageCode;
}
public static Builder newBuilder() {
return new Builder();
}
public SecurityConfig getSecurityConfig() {
return securityConfig;
}
public DineUpCacheManager getCacheManager() {
return cacheManager;
}
public long getCacheLifetime() {
return cacheLifetime;
}
public Target getTarget() {
return target;
}
public String getLanguageCode() {
return languageCode;
}
public static final class Builder {
private SecurityConfig securityConfig;
private DineUpCacheManager cacheManager;
private long cacheLifetime;
private Target target;
private String languageCode;
private Builder() {
}
public Builder securityConfig(SecurityConfig securityConfig) {
this.securityConfig = securityConfig;
return this;
}
public Builder cacheManager(DineUpCacheManager cacheManager) {
this.cacheManager = cacheManager;
return this;
}
public Builder cacheLifetime(long cacheLifetime) {
this.cacheLifetime = cacheLifetime;
return this;
}
public Builder target(Target target) {
this.target = target;
return this;
}
public Builder languageCode(String languageCode) {
this.languageCode = languageCode;
return this;
}
public com.dineup.api.ApiConfig build() {
complete();
validate();
return new ApiConfig(this);
}
private static final int LANGUAGE_CODE_LENGTH = 2;
private void complete() {
if (securityConfig == null) {
securityConfig = SecurityConfig.newBuilder().build();
}
if (cacheManager == null) {
cacheManager = new DineUpNoCacheManager();
}
}
private void validate() {
if (target == null) {
throw new IllegalArgumentException("Target is not specified");
}
if (languageCode != null && languageCode.length() != LANGUAGE_CODE_LENGTH) {
throw new IllegalArgumentException("Invalid languageCode");
}
if (cacheLifetime < 0) {
throw new IllegalArgumentException("Cache lifetime must be positive number");
}
}
}
}
| true |
9268190c705c07f1311227b1ee2235c29095a090 | Java | ToFatToBat/JavaStart | /src/JavaStart10/homework/pojazdyWypozyczalnia/App.java | UTF-8 | 705 | 3.359375 | 3 | [] | no_license | package JavaStart10.homework.pojazdyWypozyczalnia;
public class App {
public static void main(String[] args) {
Person person1 = new Person("Robert", "Kubica", 1);
Person person2 = new Person("Sebastian", "Vettel", 2);
RentableCar[] rentableCars = new RentableCar[2];
RentableCar volvo = new RentableCar("Volvo", 2010, 4);
RentableCar bmw = new RentableCar("BMW", 2002, 2);
rentableCars[0] = volvo;
rentableCars[1] = bmw;
rentableCars[0].rent(person1);
System.out.println(rentableCars[0].isCarRentedBySomeone());
rentableCars[0].handOver();
System.out.println(rentableCars[0].isCarRentedBySomeone());
}
}
| true |
174caa77976ff49c01c68d3a226373af57d9b2fb | Java | gleywsonribeiro/Retaguarda | /src/java/modelo/Paciente.java | UTF-8 | 3,247 | 2.359375 | 2 | [] | no_license | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package modelo;
import java.io.Serializable;
import java.util.Calendar;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.OneToOne;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
/**
*
* @author Gleywson
*/
@Entity
public class Paciente implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false)
private String nome;
@Column(nullable = false)
private String rh;
private String especialidade;
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "DATA_ENTRADA", nullable = false)
private Date dataEntrada;
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "DATA_SAIDA")
private Date dataSaida;
@ManyToOne
private Hospital hospital;
@OneToOne
private Leito leito;
public Paciente() {
this.dataEntrada = Calendar.getInstance().getTime();
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Date getDataEntrada() {
return dataEntrada;
}
public void setDataEntrada(Date dataEntrada) {
this.dataEntrada = dataEntrada;
}
public Date getDataSaida() {
return dataSaida;
}
public void setDataSaida(Date dataSaida) {
this.dataSaida = dataSaida;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getRh() {
return rh;
}
public void setRh(String rh) {
this.rh = rh;
}
public String getEspecialidade() {
return especialidade;
}
public void setEspecialidade(String especialidade) {
this.especialidade = especialidade;
}
public Hospital getHospital() {
return hospital;
}
public void setHospital(Hospital hospital) {
this.hospital = hospital;
}
public Leito getLeito() {
return leito;
}
public void setLeito(Leito leito) {
this.leito = leito;
}
@Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Paciente)) {
return false;
}
Paciente other = (Paciente) object;
return (this.id != null || other.id == null) && (this.id == null || this.id.equals(other.id));
}
@Override
public String toString() {
return "modelo.Paciente[ id=" + id + " ]";
}
}
| true |
a127ce44cedb10c0047064578db7c508619bbcb9 | Java | v0l0d/RedPlanetApp | /RedPlanetTest/src/test/java/com/androidMobile/scripts/RP_008_RetriveBookingAsMember.java | UTF-8 | 4,694 | 2.140625 | 2 | [] | no_license | package com.androidMobile.scripts;
import com.androidMobile.scripts.testObjects.*;
import com.androidMobile.workflows.BookingPageHelper;
import com.androidMobile.workflows.LoginHelper;
import com.androidMobile.workflows.RetrieveBookingPageHelper;
import com.ctaf.accelerators.TestEngine;
import com.ctaf.support.ExcelReader;
import com.ctaf.support.HtmlReportSupport;
import com.ctaf.utilities.Reporter;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public class RP_008_RetriveBookingAsMember extends LoginHelper {
ExcelReader xlsRetrive = new ExcelReader(configProps.getProperty("AndroidTestData"),"RP_ANDR_008");
@Test(dataProvider = "testData")
public void retriveBookingAsMember(String userId, String password, String country,
String city, String fName, String lName, String email, String cardHolder,
String cardNum, String expMonthYear, String cvv, String description) throws Throwable {
String bookingCode = null;
try {
TestEngine.testDescription.put(HtmlReportSupport.tc_name, description);
logOutAndGotToMainScreen();
navigateToMyAccount();
click(AccountPageLocators.logInButton, "logInButton");
login(userId, password);
navigateToBookNow();
selectDestination(country, city);
handleRateAppPopUp();
waitForElementPresent(HomePageLocators.searchButton, "searchButton");
click(HomePageLocators.searchButton, "searchButton");
handleRateAppPopUp();
Reporter.createReport("Search for Hotels", isElementDisplayed(PickRoomPageLocators.pickRoomPage));
waitForElementPresent(PickRoomPageLocators.bookNowButton, "bookNowButton");
click(PickRoomPageLocators.bookNowButton, "bookNowButton");
handleRateAppPopUp();
if (isElementDisplayed(BookPageLocators.contiuneButton)) {
click(BookPageLocators.contiuneButton, "contiuneButton");
}
handleRateAppPopUp();
BookingPageHelper.populateGuestDetails("", fName, lName, email, "");
BookingPageHelper.populatePaymentDetails(cardHolder, cardNum, expMonthYear, cvv);
waitForElementPresent(BookPageLocators.doneButton, "doneButton", 10);
if (isElementDisplayed(BookPageLocators.bookingCode)) {
String temp = getText(BookPageLocators.bookingCode, "bookingCode");
bookingCode = temp.trim();
logger.info("bookingCode " + bookingCode);
Reporter.SuccessReport(description, "Successful" + " Booking code is: " + bookingCode);
} else if (isElementDisplayed(BookPageLocators.errorPayment)) {
Reporter.failureReport(description, "Failed to process payment, error message is: "
+ driver.findElement(BookPageLocators.errorPayment).getText());
click(BookPageLocators.okButton, "okButton");
} else {
Reporter.failureReport(description, "Failed");
}
click(BookPageLocators.doneButton, "doneButton");
if (isElementDisplayed(BookPageLocators.doneButton)) {
click(BookPageLocators.doneButton, "doneButton");
}
navigateToReirieveBookings();
RetrieveBookingPageHelper.RetrieveBooking(email, bookingCode);
if (isElementDisplayed(RetrieveBookingLocators.bookingDetailView)) {
Reporter.SuccessReport(description, "Successful and booking details retrived");
} else
Reporter.failureReport(description, "Failed");
} catch (Exception e) {
e.printStackTrace();
Reporter.failureReport(description, "Failed with exception");
}
}
@DataProvider(name = "testData")
public Object[][] createData() {
return new Object[][]{
{xlsRetrive.getCellValue("ValidUser", "Value"), xlsRetrive.getCellValue("ValidUser", "password"),
xlsRetrive.getCellValue("country", "Value"), xlsRetrive.getCellValue("city", "Value"),
xlsRetrive.getCellValue("fName", "Value"), xlsRetrive.getCellValue("lName", "Value"),
xlsRetrive.getCellValue("email", "Value"), xlsRetrive.getCellValue("cardHolder", "Value"),
xlsRetrive.getCellValue("cardNum", "Value"), xlsRetrive.getCellValue("expirationMonth", "Value"),
xlsRetrive.getCellValue("cvv", "Value"), "Validate Retrive Booking Details"}};
}
}
| true |
e72dac408199e05ab914789c4c86835cc9afffc5 | Java | drew-neely/Genetic-Algorithm-Class-Java | /GeneticAlgorithm.java | UTF-8 | 4,894 | 3.25 | 3 | [
"MIT"
] | permissive | import java.util.ArrayList;
/**
* @author Drew Neely
*/
interface GeneticAlgorithmInterface {
public void generatePool();
public int[] select();
public void mutate(int chromIndex);
public void crossover(int chromIndex1, int chromIndex2);
public double fitness(String chrom);
public String run();
}
public abstract class GeneticAlgorithm implements GeneticAlgorithmInterface {
int iterations = 200;
private ArrayList<String> pool = new ArrayList<>();
private int poolLength = 100;
private int elementSize = -1;
private double mutationRate = .002;
private double crossoverRate = .6;
public GeneticAlgorithm() {}
public GeneticAlgorithm(int poolLength, int elementSize) {
this.poolLength = poolLength;
this.elementSize = elementSize;
}
public GeneticAlgorithm(int poolLength, int elementSize, double mutationRate, double crossoverRate) {
this(poolLength, elementSize);
this.mutationRate = mutationRate;
this.crossoverRate = crossoverRate;
}
public GeneticAlgorithm(int poolLength, int elementSize, int iterations) {
this(poolLength, elementSize);
this.iterations = iterations;
}
public GeneticAlgorithm(int poolLength, int elementSize, double mutationRate, double crossoverRate, int iterations) {
this(poolLength, elementSize, mutationRate, crossoverRate);
this.iterations = iterations;
}
@Override
public void generatePool() {
while (pool.size() < poolLength) {
String chrom = "";
while (chrom.length() < elementSize) {
chrom += (int) (Math.random() * 2);
}
pool.add(chrom);
}
}
@Override
public int[] select() {
double[] fitnesses = new double[pool.size()];
for (int i = 0; i < pool.size(); i++) {
fitnesses[i] = fitness(pool.get(i));
}
double sum = 0;
for (double fitness : fitnesses) {
sum += fitness;
}
double val = Math.random() * sum;
int chrom1Index = -1;
int chrom2Index = -1;
for (int i = 0; chrom1Index < 0; i++) {
val -= fitnesses[i];
if (val <= 0) {
chrom1Index = i;
}
}
val = Math.random() * (sum - fitnesses[chrom1Index]);
for (int i = 0; chrom2Index < 0; i++) {
if (i != chrom1Index) {
val -= fitnesses[i];
if (val <= 0) {
chrom2Index = i;
}
}
}
return new int[]{chrom1Index, chrom2Index};
}
@Override
public void mutate(int chromIndex) {
boolean mutated = false;
char[] chrom = pool.get(chromIndex).toCharArray();
for (int i = 0; i < chrom.length; i++) {
if (Math.random() < mutationRate) {
chrom[i] = (chrom[i] == '1') ? '0' : '1';
mutated = true;
}
}
if (mutated) {
String res = new String(chrom);
pool.set(chromIndex, res);
}
}
@Override
public void crossover(int chromIndex1, int chromIndex2) {
if (Math.random() < crossoverRate) {
String chrom1 = pool.get(chromIndex1);
String chrom2 = pool.get(chromIndex2);
//split before chrom[bit]
int bit = (int) Math.floor(Math.random() * (elementSize - 1) + 1);
String chr1 = chrom1.substring(0, bit) + chrom2.substring(bit);
String chr2 = chrom2.substring(0, bit) + chrom1.substring(bit);
pool.set(chromIndex1, chr1);
pool.set(chromIndex2, chr2);
}
}
@Override
public String run() {
if (elementSize < 0) {
Exception e = new Exception("elementSize < 0");
e.printStackTrace();
System.exit(-1);
}
pool.clear();
generatePool();
String bestSolution = "";
double bestFitness = -1;
for (int i = 0; i < iterations; i++) {
ArrayList<String> newPool = new ArrayList<>();
while (pool.size() > 0) {
int[] pair = select();
crossover(pair[0], pair[1]);
mutate(pair[0]);
mutate(pair[1]);
newPool.add(pool.get(pair[0]));
newPool.add(pool.get(pair[1]));
pool.remove(pair[0]);
pool.remove(pair[1] - ((pair[0] < pair[1]) ? 1 : 0));
}
pool = newPool;
for (String chrom : pool) {
double fitness = fitness(chrom);
if (fitness > bestFitness) {
bestSolution = chrom;
bestFitness = fitness;
}
}
}
return bestSolution;
}
}
| true |
62e89f514e95c2d65731c4eb33c84689cae54dc5 | Java | KleinerHacker/scm-fx | /plugin/scm-system/common/src/main/java/org/pcsoft/tools/scm_fx/plugin/scm_system/common/ScmSystemPluginNotAvailableException.java | UTF-8 | 376 | 2.03125 | 2 | [] | no_license | package org.pcsoft.tools.scm_fx.plugin.scm_system.common;
/**
* Created by pfeifchr on 09.10.2014.
*/
public class ScmSystemPluginNotAvailableException extends ScmSystemPluginExecutionException {
public ScmSystemPluginNotAvailableException(String scmSystemName) {
super("The SCM system '" + scmSystemName + "' is not available on this host machine!");
}
}
| true |
e869f466fb8898b1d755b37d628ee5c945b2868e | Java | anrooid/PycanMessenger | /app/src/main/java/com/example/pycanmessenger/Activity/ProfileEditor.java | UTF-8 | 7,836 | 1.9375 | 2 | [] | no_license | package com.example.pycanmessenger.Activity;
import android.Manifest;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.ColorFilter;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffColorFilter;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import com.example.pycanmessenger.Models.BitMapHolder;
import com.example.pycanmessenger.R;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.theartofdev.edmodo.cropper.CropImageView;
public class ProfileEditor extends AppCompatActivity implements View.OnClickListener {
private ImageView imgRotate, imgFilter, imgFlip , changeImg;
private TextView txtPath;
private CropImageView img_edt;
private FloatingActionButton saveFab;
private Uri uri;
private boolean discard;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile_editor);
imgRotate = findViewById(R.id.img_rotate);
imgFilter = findViewById(R.id.img_filter);
imgFlip = findViewById(R.id.img_flip);
txtPath = findViewById(R.id.txtPath);
changeImg = findViewById(R.id.changeImg);
img_edt = findViewById(R.id.img_edit);
imgFilter.setOnClickListener(this);
imgRotate.setOnClickListener(this);
imgFlip.setOnClickListener(this);
changeImg.setOnClickListener(this);
saveFab = findViewById(R.id.saveFab);
saveFab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
BitMapHolder.getBitMapHolder().setBitmap(img_edt.getCroppedImage());
setResult(RESULT_OK, intent);
discard =true ;
onBackPressed();
}
});
if (getIntent().getExtras() != null) {
if (getIntent().getExtras().get("Uri")!=null){
uri = (Uri) getIntent().getExtras().get("Uri");
img_edt.setImageUriAsync(uri);
StringBuilder path = new StringBuilder("");
String[] pathArray = uri.getPath().split("/");
for (int i = pathArray.length - 3; i < pathArray.length; i++) {
path.append(pathArray[i]);
if (i < pathArray.length - 1) path.append("/");
}
txtPath.setText(path.toString());
}
}
}
@Override
protected void onResume() {
super.onResume();
}
@Override
public void onBackPressed() {
if (!discard) {
AlertDialog alertDialog = new AlertDialog.Builder(this)
.setTitle("Editor")
.setMessage("Are Your Sure To Discard ? ")
.setPositiveButton("Discard", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
discard = true;
dialogInterface.dismiss();
onBackPressed();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
})
.show();
} else
super.onBackPressed();
}
@Override
public void onClick(View view) {
ColorFilter filter = new PorterDuffColorFilter(getResources().getColor(R.color.ac_color), PorterDuff.Mode.SRC_IN);
switch (view.getId()) {
case R.id.img_filter:
AlertDialog alertDialog = new AlertDialog.Builder(this)
.setTitle("Sorry")
.setMessage("This feature is not available in this version" + "\n" + "Coming soon ...")
.setPositiveButton("Yes",null)
.show();
break;
case R.id.img_flip:
img_edt.flipImageHorizontally();
if (imgFlip.getScaleX() == 1) {
discard = false ;
imgFlip.setScaleX(-1);
imgFlip.getDrawable().setColorFilter(filter);
} else if (imgFlip.getScaleX() == -1) {
imgFlip.setScaleX(1);
discard =true ;
imgFlip.getDrawable().setColorFilter(null);
}
break;
case R.id.img_rotate:
imgRotate.setRotation(imgRotate.getRotation() - 90);
img_edt.rotateImage(-90);
if (imgRotate.getRotation() % 360 == 0) {
imgRotate.getDrawable().setColorFilter(null);
discard =true ;
}
else{
imgRotate.getDrawable().setColorFilter(filter);
discard = false ;
}
break;
case R.id.changeImg:
if (Build.VERSION.SDK_INT >= 23 && ActivityCompat.checkSelfPermission(ProfileEditor.this,
Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{
Manifest.permission.READ_EXTERNAL_STORAGE},
4000
);
} else {
getChosenImage();
}
break;
}
}
private void getChosenImage() {
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 5000);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
@NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 4000) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
getChosenImage();
}
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 5000) {
if (resultCode == Activity.RESULT_OK) {
try {
uri = (Uri) data.getData();
img_edt.setImageUriAsync(uri);
StringBuilder path = new StringBuilder("");
String[] pathArray = uri.getPath().split("/");
for (int i = pathArray.length - 3; i < pathArray.length; i++) {
path.append(pathArray[i]);
if (i < pathArray.length - 1) path.append("/");
}
txtPath.setText(path.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
} | true |
5a71fe9de07be427f4a77eac692dfd64c3a9454d | Java | Kachamas/LabFirebase | /app/src/main/java/com/example/kacha/helloworld/MainActivity.java | UTF-8 | 5,726 | 2.359375 | 2 | [] | no_license | package com.example.kacha.helloworld;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.text.format.DateUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class MainActivity extends AppCompatActivity {
EditText editTextUserName;
Button btnSet;
TextView tvShow;
Button btnDelete;
EditText editTextWritePost;
Button btnPost;
private static final String CHILD_USERS = "chat-users";
private static final String CHILD_MESSAGES = "chat";
private static final String USERID = "id-12345";
private DatabaseReference mesRoot, mesUser, mesMessage;
private String mUsername;
private String mMessage;
private ValueEventListener mValueEventListener;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.setTitle("Realtime Database");
init();
FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
mesRoot = firebaseDatabase.getReference();
mesUser = mesRoot.child(CHILD_USERS);
mesMessage = mesRoot.child(CHILD_MESSAGES);
btnSet.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mUsername = editTextUserName.getText().toString();
if (TextUtils.isEmpty(mUsername)) {
editTextUserName.setError("Required");
} else {
mesUser.child(USERID).setValue(mUsername);
editTextUserName.setText(null);
}
}
});
btnPost.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mMessage = editTextWritePost.getText().toString();
if (TextUtils.isEmpty(mMessage)) {
editTextWritePost.setError("Required");
} else {
FriendlyMessage friendlyMessage = new FriendlyMessage(mMessage, mUsername);
mesMessage.push().setValue(friendlyMessage);
editTextWritePost.setText(null);
}
}
});
btnDelete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mesMessage.removeValue();
}
});
}
private void init() {
editTextUserName = findViewById(R.id.editTextUserName);
btnSet = findViewById(R.id.btnSet);
tvShow = findViewById(R.id.tvShow);
btnDelete = findViewById(R.id.btnDelete);
editTextWritePost = findViewById(R.id.editTextWritePost);
btnPost = findViewById(R.id.btnPost);
}
//open app start key username..
@Override
protected void onStart() {
super.onStart();
mValueEventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
mUsername = dataSnapshot.child(CHILD_USERS).child(USERID).getValue(String.class);
tvShow.setText("Current Username: " + mUsername + "\n");
Iterable<DataSnapshot> children = dataSnapshot.child(CHILD_MESSAGES).getChildren();
while (children.iterator().hasNext()) {
String key = children.iterator().next().getKey();
FriendlyMessage friendlyMessage = dataSnapshot.child(CHILD_MESSAGES).child(key).getValue(FriendlyMessage.class);
long now = System.currentTimeMillis();
long past = now - (60 * 60 * 24 * 45 * 1000L);
String x = DateUtils.getRelativeTimeSpanString(past, now, DateUtils.MINUTE_IN_MILLIS).toString();
tvShow.append("username : " + friendlyMessage.getUsername() + " | ");
tvShow.append("text : " + friendlyMessage.getText() + " (" + x + ")" + "\n");
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
};
mesRoot.addValueEventListener(mValueEventListener);
}
//close app (delete all data)
@Override
protected void onStop() {
super.onStop();
if (mValueEventListener != null) {
mesRoot.removeEventListener(mValueEventListener);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.realTimeDTB:
startActivity(new Intent(MainActivity.this, MainActivity.class));
return true;
case R.id.login:
startActivity(new Intent(MainActivity.this, LoginActivity.class));
return true;
default:
}
return super.onOptionsItemSelected(item);
}
}
| true |
abf73f02075d6a4b7470d362c4477ae9fe947c5b | Java | TicTicBoooom-Mods/SlashMod | /src/main/java/live/ticticboooom/mods/mmo/screen/modules/player/startscreen/SidePanelModule.java | UTF-8 | 952 | 2.078125 | 2 | [] | no_license | package live.ticticboooom.mods.mmo.screen.modules.player.startscreen;
import com.mojang.blaze3d.matrix.MatrixStack;
import live.ticticboooom.mods.mmo.ModIds;
import live.ticticboooom.mods.mmo.api.client.gui.AbstractGuiModule;
import live.ticticboooom.mods.mmo.screen.player.startscreen.PlayerStartSelectorScreen;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.screen.inventory.ContainerScreen;
import java.util.function.Supplier;
public class SidePanelModule extends AbstractGuiModule {
public SidePanelModule(Supplier<Integer> x, Supplier<Integer> y, ContainerScreen<?> screen) {
super(x, y, screen);
}
@Override
public void drawGuiContainerBackgroundLayer(MatrixStack matrixStack, float partialTicks, int mouseX, int mouseY) {
Minecraft.getInstance().textureManager.bindTexture(ModIds.GUI_PARTS_TEXTURE_ID);
this.screen.blit(matrixStack, x.get(), y.get(), 0, 0, 103, 223);
}
}
| true |
151dc7401874aa9702026a362ce6ed7b45e93efc | Java | guo522593280/weal-parent | /weal-collect/src/main/java/com/weal/collect/init/InitJob.java | UTF-8 | 2,264 | 2.125 | 2 | [] | no_license | package com.weal.collect.init;
import com.weal.collect.feign.FeignClient;
import com.weal.collect.feign.JobActionService;
import com.weal.storage.entity.JobInfo;
import com.weal.storage.repository.JobInfoMapper;
import com.xxl.job.core.biz.model.ReturnT;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import java.util.Date;
import java.util.List;
/**
* @program: boms-parent
* @description:
* @author: chenshanlin
* @create: 2018-08-08 16:15
**/
@Component
@Slf4j
public class InitJob implements CommandLineRunner {
@Autowired
private JobInfoMapper jobInfoMapper;
@Autowired
private FeignClient feignClient;
@Override
public void run(String... args) throws Exception {
List<JobInfo> jobInfos = jobInfoMapper.selectAll();
for (JobInfo jobInfo : jobInfos) {
//如果没有初始化job,则初始化job
if (jobInfo.getInit() != JobInitEnum.YES.getInit()) {
jobInfo = addJob(jobInfo);
jobInfoMapper.updateByPrimaryKeySelective(jobInfo);
}
}
}
private JobInfo addJob(JobInfo jobInfo) {
JobActionService jobActionService = feignClient.getJobActionService();
try {
ReturnT returnT = jobActionService.jobInfoAdd(jobInfo);
if (isSucsess(returnT)) {
jobInfo.setInit(JobInitEnum.YES.getInit());
log.debug("初始化job成功,jobInfo ID [{}]", jobInfo.getPkid());
} else {
jobInfo.setInit(JobInitEnum.ERROR.getInit());
log.error("初始化job失败,jobInfo ID [{}]", jobInfo.getPkid());
}
} catch (Exception e) {
jobInfo.setInit(JobInitEnum.ERROR.getInit());
log.error("初始化job异常,异常信息[{}]", e);
}
jobInfo.setUpdateTime(new Date());
return jobInfo;
}
private boolean isSucsess(ReturnT returnT) {
if (returnT.getCode() != 200) {
log.error("初始化job失败,错误信息[{}]", returnT.getMsg());
return false;
}
return true;
}
}
| true |
912c26186299938ee824a6ab16e4080d4dcaf850 | Java | DhrumilShah26/Group-Formation-Tool | /src/main/java/CSCI5308/GroupFormationTool/Courses/StudentCSVImport.java | UTF-8 | 2,328 | 2.734375 | 3 | [] | no_license | package CSCI5308.GroupFormationTool.Courses;
import java.util.ArrayList;
import java.util.List;
import CSCI5308.GroupFormationTool.IGlobalFactoryProvider;
import CSCI5308.GroupFormationTool.AccessControl.*;
import CSCI5308.GroupFormationTool.Security.IPasswordEncryption;
import org.springframework.web.multipart.MultipartFile;
public class StudentCSVImport implements IStudentCsvImport
{
private final List<String> successResults;
private final List<String> failureResults;
private final IPasswordEncryption passwordEncryption;
public StudentCSVImport(IGlobalFactoryProvider provider)
{
successResults = new ArrayList<>();
failureResults = new ArrayList<>();
passwordEncryption = provider.getSecurityFactory().getPasswordEncryption();
}
public void enrollStudentFromRecord(Course course, MultipartFile file, AbstractCourseDependencyFactory factory,
AbstractAclDependencyFactory aclDependencyFactory)
{
List<User> studentList = factory.getStudentCSVParser().parseCSVFile(file, failureResults);
for(User u : studentList)
{
String bannerID = u.getBanner();
String firstName = u.getFirstName();
String lastName = u.getLastName();
String email = u.getEmail();
String userDetails = bannerID + " " + firstName + " " + lastName +" " + email;
User user = new User();
aclDependencyFactory.getUserPersistence().loadUserByBannerID(bannerID, user);
if (user.isValidUser() == false)
{
user.setBannerID(bannerID);
user.setFirstName(firstName);
user.setLastName(lastName);
user.setEmail(email);
if (user.createUser(aclDependencyFactory.getUserPersistence(), passwordEncryption, null))
{
successResults.add("Created: " + userDetails);
aclDependencyFactory.getUserPersistence().loadUserByBannerID(bannerID, user);
}
else
{
failureResults.add("Unable to save this user to DB: " + userDetails);
return;
}
}
if (course.enrollUserInCourse(Role.STUDENT, user, factory.getCourseUserRelationship()))
{
successResults.add("User enrolled in course: " + userDetails);
}else
{
failureResults.add("Unable to enroll user in course: " + userDetails);
}
}
}
public List<String> getSuccessResults()
{
return successResults;
}
public List<String> getFailureResults()
{
return failureResults;
}
}
| true |
5a4bf5fce11540ec293282e701077623e5d9cbd8 | Java | SmileLSJ/IJava | /src/main/java/InnerClass/Test.java | UTF-8 | 248 | 1.8125 | 2 | [] | no_license | package InnerClass;
/**
* Created by Gxy on 2019/3/27.
*/
public class Test {
public static void main(String[] args) {
Tree.Node node = new Tree().new Node();
StaticTree.StaticNode sn = new StaticTree.StaticNode();
}
}
| true |
17304af70151a16f14b8d60edee9ed527137af85 | Java | renguzi/Practice | /src/main/java/ThinkingInJavaPractice/Polymorphism/shape/RandomShapeGenerator.java | UTF-8 | 557 | 3.296875 | 3 | [] | no_license | package ThinkingInJavaPractice.Polymorphism.shape;
import java.util.Random;
/**
* @Author:asher
* @Date:2021/3/14 12:12
* @Description:ThinkingInJavaPractice.Polymorphism.shape
* @Version:1.0
*/
public class RandomShapeGenerator {
private Random random = new Random(47);
public Shape next() {
switch (random.nextInt(3)) {
default:
case 0:
return new Circle();
case 1:
return new Square();
case 2:
return new Triangle();
}
}
}
| true |
f42cb7d49b03ad8ff037279efeb8bb68a02f4c0a | Java | mmmika/alpaca-java | /src/main/java/io/github/mainstringargs/polygon/properties/PolygonProperties.java | UTF-8 | 2,535 | 2.46875 | 2 | [
"MIT"
] | permissive | package io.github.mainstringargs.polygon.properties;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import io.github.mainstringargs.alpaca.properties.AlpacaProperties;
/**
* The Class AlpacaProperties.
*/
public class PolygonProperties {
/** The property file. */
private static Properties propertyFile;
static {
InputStream is = PolygonProperties.class.getResourceAsStream("/polygon.properties");
propertyFile = new Properties();
try {
propertyFile.load(is);
} catch (IOException e) {
e.printStackTrace();
}
}
/** The Constant KEY_ID_KEY. */
private static final String KEY_ID_KEY = "key_id";
/** The Constant BASE_DATA_URL_KEY. */
private static final String BASE_DATA_URL_KEY = "base_data_url";
/** The Constant USER_AGENT_KEY. */
private static final String USER_AGENT_KEY = "user_agent";
/** The Constant DEFAULT_USER_AGENT. */
private static final String DEFAULT_USER_AGENT =
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36";
/** The Constant DEFAULT_DATA_URL. */
private static final String DEFAULT_DATA_URL = "https://api.polygon.io";
/** The Constant INVALID_VALUE. */
public static final String INVALID_VALUE = "INVALID";
/** The Constant KEY_ID_VALUE. */
public static final String KEY_ID_VALUE = getProperty(KEY_ID_KEY, AlpacaProperties.KEY_ID_VALUE);
/** The base data url value. */
public static String BASE_DATA_URL_VALUE = getProperty(BASE_DATA_URL_KEY, DEFAULT_DATA_URL);
/** The polygon nats servers key. */
private static String POLYGON_NATS_SERVERS_KEY = "nats_urls";
/** The default polygon nats servers. */
private static String DEFAULT_POLYGON_NATS_SERVERS =
"nats1.polygon.io:31101,nats2.polygon.io:31102,nats3.polygon.io:31103";
/** The polygon nats servers value. */
public static String[] POLYGON_NATS_SERVERS_VALUE =
getProperty(POLYGON_NATS_SERVERS_KEY, DEFAULT_POLYGON_NATS_SERVERS).split(",");
/** The Constant USER_AGENT_VALUE. */
public static final String USER_AGENT_VALUE = getProperty(USER_AGENT_KEY, DEFAULT_USER_AGENT);
/**
* Gets the property.
*
* @param key the key
* @param defaultValue the default value
* @return the property
*/
public static String getProperty(String key, String defaultValue) {
return propertyFile.getProperty(key, defaultValue).trim();
}
}
| true |
840e028513d4b3590c0b96bfa9a8ad4e3ebf6eb4 | Java | skosko00/seongmin | /KH-WEB-Project-v2-master/src/jsp/board/controller/NoticeCommentServlet.java | UTF-8 | 2,194 | 2.328125 | 2 | [] | no_license | package jsp.board.controller;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import jsp.board.model.service.BoardService;
import jsp.board.model.vo.Comment;
import jsp.member.model.vo.MemberVo;
/**
* Servlet implementation class NoticeCommentServlet
*/
@WebServlet(name = "NoticeComment", urlPatterns = { "/noticeComment" })
public class NoticeCommentServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public NoticeCommentServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.인코딩
request.setCharacterEncoding("utf-8");
//2. 변수값 저장(내용, 게시물 번호)
String CM_CONTENTS = request.getParameter("CM_CONTENTS");
int BD_NO = Integer.parseInt(request.getParameter("bdNo"));
HttpSession session = request.getSession(false);
if(session.getAttribute("member")!=null) { //로그인이 된 상태라면
Comment c = new Comment();
c.setCmBdNo(BD_NO);
c.setCmContents(CM_CONTENTS);
c.setCmWriter(((MemberVo)session.getAttribute("member")).getMbId());
int result = new BoardService().insertComment(c);
if(result>0) {//댓글내용이 들어오면
response.sendRedirect("/reviewSelect?bdNo="+BD_NO);
}else {//내용이 안들어오면
response.sendRedirect("/View/error/error.jsp");
}
}else {
response.sendRedirect("/View/error/error.jsp");
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
| true |
e7ca3005991c3b13417b953aa630398aaaeb86d9 | Java | zilanghuo/project-summary | /src/main/java/com/zilanghuo/controller/DepositController.java | UTF-8 | 4,687 | 2.0625 | 2 | [] | no_license | package com.zilanghuo.controller;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.zilanghuo.third.fuyou.dto.req.RechargeReqDTO;
import com.zilanghuo.third.fuyou.dto.req.RegisterReqDTO;
import com.zilanghuo.third.fuyou.dto.req.WithdrawReqDTO;
import com.zilanghuo.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;
/**
* @author lwf
* @date 2018/7/24
* use:
*/
@Controller
@RequestMapping(value = "/deposit")
@Slf4j
public class DepositController {
@RequestMapping(value = "/home")
public String home(ModelMap model) {
log.info("-----------home");
return "/deposit/home";
}
@RequestMapping(value = "/register")
public String register(ModelMap model) {
RegisterReqDTO registerDTO = new RegisterReqDTO();
registerDTO.setMchnt_txn_ssn(DateUtil.format(new Date(), DatePattern.PURE_DATETIME_MS_PATTERN));
registerDTO.setUsr_attr("1");
registerDTO.setMobile_no("18525863602");
registerDTO.setCust_nm("秦海贤");
registerDTO.setCertif_id("360822198609284091");
registerDTO.setEmail("lll@qq.com");
registerDTO.setSignature(SecurityUtils.signByBean(registerDTO));
getModelMap(registerDTO, model);
return "/deposit/register";
}
@RequestMapping(value = "/recharge")
public String recharge(HttpServletRequest request, ModelMap model) {
log.info("recharge");
RechargeReqDTO rechargeDTO = new RechargeReqDTO();
rechargeDTO.setAmt(Integer.parseInt(request.getParameter("amt")));
rechargeDTO.setLogin_id(request.getParameter("login_id"));
rechargeDTO.setSignature(SecurityUtils.signByBean(rechargeDTO));
getModelMap(rechargeDTO, model);
return "/deposit/recharge";
}
@RequestMapping(value = "/rechargeInternet")
public String rechargeInternet(HttpServletRequest request, ModelMap model) {
log.info("rechargeInternet");
RechargeReqDTO rechargeDTO = new RechargeReqDTO();
rechargeDTO.setCode(null);
rechargeDTO.setClient_tp(null);
rechargeDTO.setVer(null);
rechargeDTO.setAmt(Integer.parseInt(request.getParameter("amt")));
rechargeDTO.setLogin_id(request.getParameter("login_id"));
rechargeDTO.setSignature(SecurityUtils.signByBean(rechargeDTO));
getModelMap(rechargeDTO, model);
return "/deposit/rechargeInternet";
}
@RequestMapping(value = "/rechargeInternetBank")
public String rechargeInternetBank(HttpServletRequest request, ModelMap model) {
log.info("rechargeInternetBank");
RechargeReqDTO rechargeDTO = new RechargeReqDTO();
rechargeDTO.setCode(null);
rechargeDTO.setClient_tp(null);
rechargeDTO.setVer(null);
rechargeDTO.setIss_ins_cd("0803080000");
rechargeDTO.setAmt(Integer.parseInt(request.getParameter("amt")));
rechargeDTO.setLogin_id(request.getParameter("login_id"));
rechargeDTO.setOrder_pay_type("B2C");
rechargeDTO.setSignature(SecurityUtils.signByBean(rechargeDTO));
getModelMap(rechargeDTO, model);
return "/deposit/rechargeInternetBank";
}
@RequestMapping(value = "/withdraw")
public String withdraw(HttpServletRequest request, ModelMap model) {
log.info("withdraw");
WithdrawReqDTO withdrawDTO = new WithdrawReqDTO();
withdrawDTO.setAmt(Integer.parseInt(request.getParameter("amt")));
withdrawDTO.setLogin_id(request.getParameter("login_id"));
withdrawDTO.setSignature(SecurityUtils.signByBean(withdrawDTO));
getModelMap(withdrawDTO, model);
return "/deposit/withdraw";
}
@RequestMapping(value = "registerPage")
public String registerPage() {
log.info("enter registerPage");
return "deposit/registerBack";
}
/**
* 对象转model
*
* @param bean
* @param modelMap
* @return
*/
public ModelMap getModelMap(Object bean, ModelMap modelMap) {
Map<String, Object> beanToMap = BeanUtil.beanToMap(bean);
Iterator<Map.Entry<String, Object>> iterator = beanToMap.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, Object> next = iterator.next();
modelMap.put(next.getKey(), next.getValue());
}
return modelMap;
}
}
| true |