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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
c6febd68741ba1ec168111367b6c6bf35d6e786e | Java | dashayushman/HashCode | /src/com/hashcode/bolbhum/beans/Drone.java | UTF-8 | 1,073 | 2.25 | 2 | [] | no_license | package com.hashcode.bolbhum.beans;
public class Drone {
private Integer droneId;
private Integer totalWeight;
private Location location;
private Integer startTime;
private Integer endTime;
public Location getLocation() {
return location;
}
public void setLocation(Location location) {
this.location = location;
}
public Integer getStartTime() {
return startTime;
}
public void setStartTime(Integer startTime) {
this.startTime = startTime;
}
public Integer getEndTime() {
return endTime;
}
public void setEndTime(Integer endTime) {
this.endTime = endTime;
}
private Integer currentOrderId;
public Integer getDroneId() {
return droneId;
}
public void setDroneId(Integer droneId) {
this.droneId = droneId;
}
public Integer getTotalWeight() {
return this.totalWeight;
}
public void setTotalWeight(Integer totalWeight) {
this.totalWeight = totalWeight;
}
public void setcurrentOrderId(Integer OrderId) {
this.currentOrderId = OrderId;
}
public Integer getcurrentOrderId() {
return this.currentOrderId;
}
}
| true |
0779e2d4989a8a2451c90be9fb2b1916f5e10ea3 | Java | MrLetsplay2003/MrCore | /MrCore-Bukkit/src/main/java/me/mrletsplay/mrcore/bukkitimpl/multiblock/MultiBlockStructure.java | UTF-8 | 4,859 | 2.578125 | 3 | [
"MIT"
] | permissive | package me.mrletsplay.mrcore.bukkitimpl.multiblock;
import java.util.ArrayList;
import java.util.Collections;
import java.util.EnumSet;
import java.util.List;
import java.util.Set;
import java.util.function.Consumer;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.NamespacedKey;
import org.bukkit.block.BlockFace;
import org.bukkit.util.Vector;
public class MultiBlockStructure {
public static final Set<BlockFace> ALL_DIRECTIONS = Collections.unmodifiableSet(EnumSet.of(BlockFace.NORTH, BlockFace.WEST, BlockFace.SOUTH, BlockFace.EAST));
private NamespacedKey key;
private List<MultiBlockLayer> layers;
public MultiBlockStructure(NamespacedKey key) {
this.key = key;
this.layers = new ArrayList<>();
}
public MultiBlockStructure addLayer(MultiBlockLayer layer) {
this.layers.add(layer);
return this;
}
public NamespacedKey getKey() {
return key;
}
public List<MultiBlockLayer> getLayers() {
return layers;
}
public BuiltMultiBlockStructure checkAt(Location loc) {
return checkAt(loc, ALL_DIRECTIONS);
}
public List<Vector> getBlockOffsets() {
List<Vector> offs = new ArrayList<>();
for(int h = 0; h < layers.size(); h++) {
MultiBlockLayer layer = layers.get(h);
for(int x = 0; x < layer.getWidth(); x++) {
for(int y = 0; y < layer.getHeight(); y++) {
Character key = layer.getKeyAt(x, y);
if(key == null) continue;
Material mapping = layer.getTypeMappings().get(key);
if(mapping == null) continue; // No mapping => placeholder, any block
offs.add(new Vector(x, h, y));
}
}
}
return offs;
}
public BuiltMultiBlockStructure checkAt(Location loc, Set<BlockFace> possibleDirections) {
Location cLoc = loc.clone();
for(int h = 0; h < layers.size(); h++) {
MultiBlockLayer layer = layers.get(h);
for(int x = 0; x < layer.getWidth(); x++) {
for(int y = 0; y < layer.getHeight(); y++) {
Character key = layer.getKeyAt(x, y);
if(key == null) continue;
Material mapping = layer.getTypeMappings().get(key);
if(mapping == null) continue; // No mapping => placeholder, any block
if(mapping.equals(loc.getBlock().getType())) {
for(BlockFace dir : possibleDirections) {
Location originLoc = offsetLoc(loc, cLoc, -x, -h, -y, dir);
BuiltMultiBlockStructure built = checkOriginAt(originLoc, Collections.singleton(dir));
if(built != null) return built;
}
}
}
}
}
return null;
}
public BuiltMultiBlockStructure checkOriginAt(Location loc) {
return checkOriginAt(loc, ALL_DIRECTIONS);
}
public BuiltMultiBlockStructure checkOriginAt(Location loc, Set<BlockFace> possibleDirections) {
if(!isValid()) throw new IllegalStateException("Multiblock structure is invalid");
Location cLoc = loc.clone();
dl: for(BlockFace dir : possibleDirections) {
for(int h = 0; h < layers.size(); h++) {
MultiBlockLayer layer = layers.get(h);
for(int x = 0; x < layer.getWidth(); x++) {
for(int y = 0; y < layer.getHeight(); y++) {
Character key = layer.getKeyAt(x, y);
if(key == null) continue;
Material mapping = layer.getTypeMappings().get(key);
if(mapping == null) continue; // No mapping => placeholder, any block
Location chLoc = offsetLoc(loc, cLoc, x, h, y, dir);
if(!chLoc.getBlock().getType().equals(mapping)) {
continue dl;
}
}
}
}
return new BuiltMultiBlockStructure(this, loc, dir);
}
return null;
}
public boolean isValid() {
return !layers.isEmpty() && layers.stream().allMatch(MultiBlockLayer::isValid);
}
public MultiBlockStructure addBuiltListener(Consumer<MultiBlockStructureCreatedEvent> listener) {
MultiBlockStructureListener.addCreatedListener(this, listener);
return this;
}
public MultiBlockStructure addBrokenListener(Consumer<MultiBlockStructureBrokenEvent> listener) {
MultiBlockStructureListener.addBrokenListener(this, listener);
return this;
}
public static Location offsetLoc(Location originalLoc, Location newLoc, double xOff, double yOff, double zOff, BlockFace direction) {
double
x = originalLoc.getBlockX(),
y = originalLoc.getBlockY() + yOff,
z = originalLoc.getBlockZ();
switch(direction) {
case NORTH:
x += xOff;
z += zOff;
break;
case SOUTH:
x -= xOff;
z -= zOff;
break;
case WEST:
x += xOff;
z -= zOff;
break;
case EAST:
x -= xOff;
z += zOff;
break;
default:
throw new IllegalArgumentException("Unsupported direction " + direction + ", must be one of NORTH, WEST, SOUTH or EAST");
}
newLoc.setX(x);
newLoc.setY(y);
newLoc.setZ(z);
return newLoc;
}
@Override
public boolean equals(Object obj) {
if(!(obj instanceof MultiBlockStructure)) return false;
return key.equals(((MultiBlockStructure) obj).getKey());
}
}
| true |
d7fcb3231a1ca15254ce9cb491823f362e013fb3 | Java | chendongjing/gulf-web-architecture-demo | /gulf-parent/gulf-service/src/main/java/cn/chmobile/ai/modules/base/dao/IUserDao.java | UTF-8 | 153 | 1.539063 | 2 | [] | no_license | package cn.chmobile.ai.modules.base.dao;
import cn.chmobile.ai.util.PageData;
public interface IUserDao {
PageData selectByPrimaryKey(Integer id);
} | true |
105368784aa1d9641d94869cccf6039593d5eace | Java | RG2N/Spigot-BT | /Bukkit/src/main/java/org/bukkit/util/VoxelShape.java | UTF-8 | 880 | 3.078125 | 3 | [
"GPL-3.0-only",
"Apache-2.0"
] | permissive | package org.bukkit.util;
import java.util.Collection;
import org.jetbrains.annotations.NotNull;
/**
* A shape made out of voxels.
*
* For example, used to represent the detailed collision shape of blocks.
*/
public interface VoxelShape {
/**
* Converts this shape into a collection of {@link BoundingBox} equivalent
* to the shape: a bounding box intersects with this block shape if it
* intersects with any of the shape's bounding boxes.
*
* @return shape converted to bounding boxes
*/
@NotNull
public Collection<BoundingBox> getBoundingBoxes();
/**
* Checks if the given bounding box intersects this block shape.
*
* @param other bounding box to test
* @return true if other overlaps this, false otherwise
*/
public boolean overlaps(@NotNull BoundingBox other);
}
| true |
bcbabf3a2b14d013c0de3e883b45fc1b1de7c3e5 | Java | DanieldelRioJ/covid-app | /backend/src/main/java/dh/covid/api/services/CountryServiceImpl.java | UTF-8 | 1,862 | 2.34375 | 2 | [] | no_license | package dh.covid.api.services;
import dh.covid.api.mappers.CountryMapper;
import dh.covid.api.models.internal.dto.CountryDTO;
import dh.covid.api.models.internal.vo.Country;
import dh.covid.api.repositories.CountryRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class CountryServiceImpl implements CountryService {
@Autowired
CountryRepository countryRepository;
@Autowired
private CountryMapper countryMapper;
public CountryServiceImpl(){
}
@Override
public Page<Country> getCountries(Pageable pageable){
Page<Country> countries = countryRepository.findAll(pageable);
return countries;
}
@Override
public Page<Country> getTopCountries(Integer top, Pageable pageable) {
Page<Country> countries = countryRepository.findTopCountries(top, pageable);
return countries;
}
@Override
public Country getCountryById(Integer id) {
Country country = countryRepository.findById(id).orElse(null);
return country;
}
@Override
public void save(CountryDTO country) {
this.countryRepository.save(countryMapper.toCountry(country));
}
@Override
public List<CountryDTO> saveAll(List<CountryDTO> country) {
List<Country> countryList = countryMapper.toCountry(country);
countryList = this.countryRepository.saveAll(countryList);
return countryMapper.toCountryDTO(countryList);
}
@Override
public void deleteAll() {
this.countryRepository.deleteAll();
}
@Override
public Country getCountryByName(String name) {
return countryRepository.findByName(name);
}
}
| true |
f6a357a2beb76e79c7b7cd02e928e62828dd3d3e | Java | arjunpat/adv-comp-sci | /labs/sem1/iterators/ScreenManager.java | UTF-8 | 832 | 2.609375 | 3 | [] | no_license | import resume.Resume;
import javax.swing.*;
import java.util.*;
public class ScreenManager {
private JFrame jFrame;
private Resume resume;
public ScreenManager(JFrame jFrame) {
this.jFrame = jFrame;
resume = new Resume();
this.showBasicInformationView();
}
private void updateScreen(View view) {
jFrame.setContentPane(view);
jFrame.pack();
jFrame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
jFrame.setVisible(true);
}
public void showBasicInformationView() {
this.updateScreen(new BasicInformationView(this, resume));
}
public void showEducationView() {
this.updateScreen(new EducationView(this, resume));
}
public void showJobView() {
this.updateScreen(new JobView(this, resume));
}
public void showResume() {
this.updateScreen(new DisplayResumeView(this, resume));
}
} | true |
dd9f312671b264ddfe693a8fccf5f67965704122 | Java | nightwolf93/Wakxy-Core-Decompiled | /1_39_120042/com/ankamagames/framework/sound/stream/AudioStreamProvider.java | UTF-8 | 615 | 2.390625 | 2 | [] | no_license | package com.ankamagames.framework.sound.stream;
import java.io.*;
public interface AudioStreamProvider
{
void openStream() throws IOException;
void reset() throws IOException;
void close() throws IOException;
boolean isSeekable();
void seek(long p0) throws IOException;
long length() throws IOException;
long tell() throws IOException;
String getDescription();
String getFileId();
int read() throws IOException;
int read(byte[] p0) throws IOException;
int read(byte[] p0, int p1, int p2) throws IOException;
}
| true |
1edfa1e57f9e08a8cc761b9a23cf8b288817e0fb | Java | ShabinaTaj/ALM21101-SHABINA-TAJ-SHAIK | /lab_01/AreaofCircle.java | UTF-8 | 356 | 3.515625 | 4 | [] | no_license | package lab_01;
import java.util.Scanner;
public class AreaofCircle {
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
System.out.println("Enter the Radius of the circle: ");
double r= scanner.nextDouble();
double area= Math.PI*(r*r);
System.out.println("The Area of the circle is: "+area);
}
}
| true |
b95e5731a95132e02c4bcee9ee3ced021a8788d9 | Java | priyamaurya08/Assignment | /app/src/main/java/m/com/assigment/MainActivity.java | UTF-8 | 4,618 | 2.078125 | 2 | [] | no_license | package m.com.assigment;
import android.content.Intent;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.google.gson.Gson;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
public class MainActivity extends AppCompatActivity {
private Button add;
private RecyclerView recyclerView;
private TextView totalCount;
private LinearLayoutManager linearLayoutManager;
private InputModel inoutMode;
private ReportsRecyclerViewAdapter reportsRecycerViewAdapter;
private ArrayList<Result> list=new ArrayList<>();
private Result result;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
add=findViewById(R.id.add_button);
recyclerView=findViewById(R.id.recycler_view);
totalCount=findViewById(R.id.total_reports_count);
linearLayoutManager=new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false);
reportsRecycerViewAdapter=new ReportsRecyclerViewAdapter(list);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setAdapter(reportsRecycerViewAdapter);
add.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String json= loadJSONFromAsset();
inoutMode=new Gson().fromJson(json, InputModel.class);
Intent i=new Intent(MainActivity.this,DynamicUIActivity.class);
i.putExtra("json",inoutMode);
startActivityForResult(i,1);
}
});
}
public String loadJSONFromAsset() {
String json = null;
try {
InputStream is = getAssets().open("inut_json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode==RESULT_OK){
if(requestCode==1){
String json=data.getStringExtra("json");
Log.v("TAG",json);
try {
JSONObject jsonObject=new JSONObject(json);
Iterator<String> keys= jsonObject.keys();
result=new Result();
int count=0;
while (keys.hasNext()) {
String keyValue = (String) keys.next();
count++;
if (count == 1) {
ResultModel resultMode = new ResultModel();
if (!TextUtils.isEmpty(jsonObject.getString(String.valueOf(jsonObject.names().get(0))))) {
resultMode.setValue(jsonObject.getString(String.valueOf(jsonObject.names().get(0))));
resultMode.setKey(keyValue);
}
result.setField1(resultMode);
} else if (count == 2) {
ResultModel field2 = new ResultModel();
if (!TextUtils.isEmpty(jsonObject.getString(String.valueOf(jsonObject.names().get(1))))) {
field2.setValue(jsonObject.getString(String.valueOf(jsonObject.names().get(1))));
field2.setKey(keyValue);
}
result.setField2(field2);
} else
break;
}
list.add(result);
totalCount.setText(""+list.size());
reportsRecycerViewAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
}
| true |
aaad2c99bfd96f3661d30db242f97bc41e13fa7a | Java | xrealm/tiktok-src | /sources/com/p280ss/android/ugc/aweme/p313im/sdk/chat/model/SystemContent.java | UTF-8 | 2,777 | 1.757813 | 2 | [] | no_license | package com.p280ss.android.ugc.aweme.p313im.sdk.chat.model;
import android.text.TextUtils;
import com.google.gson.p276a.C6593c;
import java.util.Map;
/* renamed from: com.ss.android.ugc.aweme.im.sdk.chat.model.SystemContent */
public class SystemContent extends BaseContent {
@C6593c(mo15949a = "group_tips")
String groupNoticeTips;
@C6593c(mo15949a = "template")
Key[] template;
@C6593c(mo15949a = "tips")
String tips;
/* renamed from: com.ss.android.ugc.aweme.im.sdk.chat.model.SystemContent$Key */
public static class Key {
@C6593c(mo15949a = "action")
int action;
@C6593c(mo15949a = "extra")
Map<String, String> extra;
@C6593c(mo15949a = "key")
String key;
@C6593c(mo15949a = "link")
String link;
@C6593c(mo15949a = "name")
String name;
public int getAction() {
return this.action;
}
public Map<String, String> getExtra() {
return this.extra;
}
public String getKey() {
return this.key;
}
public String getLink() {
return this.link;
}
public String getName() {
return this.name;
}
public void setAction(int i) {
this.action = i;
}
public void setExtra(Map<String, String> map) {
this.extra = map;
}
public void setKey(String str) {
this.key = str;
}
public void setLink(String str) {
this.link = str;
}
public void setName(String str) {
this.name = str;
}
}
/* renamed from: com.ss.android.ugc.aweme.im.sdk.chat.model.SystemContent$LinkTypeExtra */
public static class LinkTypeExtra {
public static boolean isSafeWarningLink(Key key) {
if (key != null) {
try {
if (key.getExtra() != null) {
return TextUtils.equals((String) key.extra.get("link_type"), "safe_warning");
}
} catch (Exception unused) {
return false;
}
}
return false;
}
}
public String getGroupNoticeTips() {
return this.groupNoticeTips;
}
public Key[] getTemplate() {
return this.template;
}
public String getTips() {
return this.tips;
}
public String getMsgHint() {
return getTips();
}
public void setGroupNoticeTips(String str) {
this.groupNoticeTips = str;
}
public void setTemplate(Key[] keyArr) {
this.template = keyArr;
}
public void setTips(String str) {
this.tips = str;
}
}
| true |
6729c946f65f98129f5ab122a32435958989434f | Java | focframework/framework | /foc/src/com/foc/dataSource/IFocDataUtil.java | UTF-8 | 683 | 1.851563 | 2 | [
"Apache-2.0"
] | permissive | package com.foc.dataSource;
import com.foc.desc.FocDesc;
public interface IFocDataUtil {
public void dbUtil_RemoveAllIndexesForTable_ExceptRef(FocDesc focDesc);
public void dbUtil_UpdateFieldEqualToAnother(String tableName, String tarField, String srcField);
public void dbUtil_DuplicateTable(String previousName, String newName);
public void dbUtil_RenameTable(String previousName, String newName);
public void dbUtil_RenameColumnsText(String table, String srcCol, String tarCol, int size);
public void dbUtil_RenameColumnsInteger(String table, String srcCol, String tarCol);
public void dbUtil_RenameColumnsDate(String table, String srcCol, String tarCol);
}
| true |
0df28d9c86a519c408f6c416e8131d1ca8cf43de | Java | gopinaghr/demo | /sa.elm.ob.scm/src/sa/elm/ob/scm/actionHandler/IRComplete.java | UTF-8 | 32,224 | 1.515625 | 2 | [] | no_license | package sa.elm.ob.scm.actionHandler;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.log4j.Logger;
import org.openbravo.base.exception.OBException;
import org.openbravo.base.provider.OBProvider;
import org.openbravo.base.secureApp.VariablesSecureApp;
import org.openbravo.client.kernel.RequestContext;
import org.openbravo.dal.core.OBContext;
import org.openbravo.dal.service.OBDal;
import org.openbravo.dal.service.OBQuery;
import org.openbravo.database.ConnectionProvider;
import org.openbravo.erpCommon.utility.OBError;
import org.openbravo.erpCommon.utility.OBErrorBuilder;
import org.openbravo.erpCommon.utility.OBMessageUtils;
import org.openbravo.erpCommon.utility.SequenceIdData;
import org.openbravo.exception.NoConnectionAvailableException;
import org.openbravo.model.ad.access.User;
import org.openbravo.model.common.enterprise.Locator;
import org.openbravo.model.common.plm.Product;
import org.openbravo.model.common.uom.UOM;
import org.openbravo.model.materialmgmt.transaction.MaterialTransaction;
import org.openbravo.model.materialmgmt.transaction.ShipmentInOut;
import org.openbravo.model.materialmgmt.transaction.ShipmentInOutLine;
import org.openbravo.scheduling.Process;
import org.openbravo.scheduling.ProcessBundle;
import org.openbravo.service.db.DbUtility;
import sa.elm.ob.scm.EscmInitialReceipt;
import sa.elm.ob.utility.util.Utility;
public class IRComplete implements Process {
private final OBError obError = new OBError();
private static Logger log4j = Logger.getLogger(IRComplete.class);
@Override
public void execute(ProcessBundle bundle) throws Exception {
// TODO Auto-generated method stub
Connection connection = null;
Connection conn = null;
try {
ConnectionProvider provider = bundle.getConnection();
connection = provider.getConnection();
conn = OBDal.getInstance().getConnection();
} catch (NoConnectionAvailableException e) {
log4j.error("No Database Connection Available.Exception:" + e);
throw new RuntimeException(e);
}
HttpServletRequest request = RequestContext.get().getRequest();
VariablesSecureApp vars = new VariablesSecureApp(request);
final String receiptId = (String) bundle.getParams().get("M_InOut_ID").toString();
final String clientId = (String) bundle.getContext().getClient();
final String userId = (String) bundle.getContext().getUser();
final String orgId = (String) bundle.getContext().getOrganization();
log4j.debug("receiptId:" + receiptId);
ShipmentInOutLine inoutline = null;
String p_instance_id = null, sql = null, sql1 = null;
PreparedStatement ps = null, ps1 = null, ps2 = null;
ResultSet rs = null, rs1 = null;
boolean delflag = true;
int count = 0;
try {
OBContext.setAdminMode(true);
OBQuery<EscmInitialReceipt> Ir = OBDal.getInstance().createQuery(EscmInitialReceipt.class,
"goodsShipment.id='" + receiptId + "'");
if (Ir.list() == null || Ir.list().size() < 1) {
obError.setType("Error");
obError.setTitle("Error");
obError.setMessage(OBMessageUtils.messageBD("Escm_No_IR"));
bundle.setResult(obError);
return;
}
ShipmentInOut header = OBDal.getInstance().get(ShipmentInOut.class, receiptId);
// Check the period control is opened (only if it is legal entity with accounting)
// Gets the BU or LE of the document
sql = " SELECT AD_GET_DOC_LE_BU('M_INOUT', '" + receiptId
+ "', 'M_INOUT_ID', 'LE') as org_blue_id FROM DUAL ";
ps = conn.prepareStatement(sql);
log4j.debug("ps:" + ps.toString());
rs = ps.executeQuery();
if (rs.next()) {
sql = " SELECT AD_OrgType.IsAcctLegalEntity as isacctle FROM AD_OrgType, AD_Org "
+ " WHERE AD_Org.AD_OrgType_ID = AD_OrgType.AD_OrgType_ID "
+ " AND AD_Org.AD_Org_ID=? ";
ps1 = conn.prepareStatement(sql);
ps1.setString(1, rs.getString("org_blue_id"));
log4j.debug("ps:" + ps1.toString());
rs1 = ps1.executeQuery();
if (rs1.next()) {
if (rs1.getString("isacctle").equals("Y")) {
sql1 = " SELECT C_CHK_OPEN_PERIOD( '" + header.getOrganization().getId() + "', '"
+ header.getAccountingDate() + "', NULL, '" + header.getDocumentType().getId()
+ "') as avialbleperiod FROM DUAL ";
ps2 = conn.prepareStatement(sql1);
log4j.debug("ps:" + ps2.toString());
rs = ps2.executeQuery();
if (rs.next()) {
if (rs.getInt("avialbleperiod") != 1) {
throw new OBException("@PeriodNotAvailable@");
}
}
}
}
}
OBQuery<EscmInitialReceipt> receipt = OBDal.getInstance().createQuery(
EscmInitialReceipt.class, "goodsShipment.id='" + receiptId + "'");
List<EscmInitialReceipt> receiptList = new ArrayList<EscmInitialReceipt>();
receiptList = receipt.list();
if (header.getEscmReceivingtype().equals("SR")) {
for (EscmInitialReceipt ir : receiptList) {
ir.setDeliveredQty(ir.getQuantity());
OBDal.getInstance().save(ir);
}
} else if (header.getEscmReceivingtype().equals("IR")) {
for (EscmInitialReceipt ir : receiptList) {
if (ir.getProduct().isStocked()) {
if (ir.getProduct().isEscmNoinspection()) {
ir.setAcceptedQty(ir.getQuantity());
}
} else {
ir.setDeliveredQty(ir.getQuantity());
}
OBDal.getInstance().save(ir);
}
} else if (header.getEscmReceivingtype().equals("INS")) {
int inscount = updateInitialRecipt(connection, header.getClient().getId(), header
.getOrganization().getId(), header);
log4j.debug("count:" + inscount);
if (inscount == 2) {
OBError result = OBErrorBuilder.buildMessage(null, "error",
"@ESCM_ProcessFailed(Reason)@");
bundle.setResult(result);
return;
} else if (inscount == 1) {
OBError result = OBErrorBuilder.buildMessage(null, "success",
"@Escm_Ir_complete_success@");
bundle.setResult(result);
header.setEscmDocstatus("CO");
header.setDocumentStatus("CO");
header.setProcessed(true);
header.setDocumentAction("--");
OBDal.getInstance().save(header);
OBDal.getInstance().flush();
return;
} else {
OBError result = OBErrorBuilder.buildMessage(null, "error", "@ESCM_ProcessFailed@");
bundle.setResult(result);
return;
}
} else if (header.getEscmReceivingtype().equals("DEL")) {
sql = " select coalesce(sum(mr.accepted_qty),0) as accqty,coalesce(sum(ur.deliveredqty),0) as deliveredqty, "
+ " coalesce(sum(cr.crqty),0) as crqty ,cr.source_ref from escm_initialreceipt mr "
+ " left join (select source_ref,sum(quantity)as deliveredqty from escm_initialreceipt ur join m_inout io on io.m_inout_id=ur.m_inout_id "
+ " where io.em_escm_receivingtype ='DEL' and io.em_escm_docstatus='CO' group by source_ref ) as ur on ur.source_ref=mr.escm_initialreceipt_id "
+ " left join (select sum(quantity) as crqty,source_ref from escm_initialreceipt where m_inout_id='"
+ header.getId()
+ "' group by source_ref) as cr on cr.source_ref=mr.escm_initialreceipt_id "
+ " where mr.escm_initialreceipt_id in (select distinct source_ref from escm_initialreceipt where m_inout_id='"
+ header.getId()
+ "' ) group by cr.source_ref having (coalesce(sum(cr.crqty),0)) > coalesce(sum(mr.accepted_qty),0) ";
ps = conn.prepareStatement(sql);
log4j.debug("ps:" + ps.toString());
rs = ps.executeQuery();
while (rs.next()) {
OBQuery<EscmInitialReceipt> erroreceiptQry = OBDal.getInstance().createQuery(
EscmInitialReceipt.class,
"as e where e.sourceRef.id='" + rs.getString("source_ref")
+ "' and e.goodsShipment.id='" + header.getId() + "'");
if (erroreceiptQry.list().size() > 0) {
for (EscmInitialReceipt lineObject : erroreceiptQry.list()) {
lineObject.setFailurereason("Quantity Exceed,Availabe Quantity to Delivery:'"
+ rs.getInt("accqty") + "'");
OBDal.getInstance().save(lineObject);
}
}
delflag = false;
}
log4j.debug("count:" + count);
if (delflag) {
for (EscmInitialReceipt initial : header.getEscmInitialReceiptList()) {
inoutline = OBProvider.getInstance().get(ShipmentInOutLine.class);
inoutline.setClient(header.getClient());
inoutline.setOrganization(header.getOrganization());
inoutline.setCreationDate(new java.util.Date());
inoutline.setCreatedBy(OBDal.getInstance().get(User.class, userId));
inoutline.setUpdated(new java.util.Date());
inoutline.setUpdatedBy(OBDal.getInstance().get(User.class, userId));
inoutline.setActive(true);
inoutline.setShipmentReceipt(header);
inoutline.setLineNo(initial.getLineNo());
inoutline.setProduct(initial.getProduct());
inoutline.setEscmUnitprice(initial.getUnitprice());
inoutline.setUOM(initial.getUOM());
inoutline.setDescription(initial.getDescription());
inoutline.setMovementQuantity(initial.getQuantity());
inoutline.setEscmCustodyItem(initial.isCustodyItem());
inoutline.setEscmTransaction("A");
OBQuery<Locator> locator = OBDal.getInstance().createQuery(
Locator.class,
" as e where e.warehouse.id='" + header.getWarehouse().getId()
+ "' and e.default='Y' ");
locator.setMaxResult(1);
if (locator.list().size() > 0) {
inoutline.setStorageBin(locator.list().get(0));
log4j.debug("getStorageBin:" + inoutline.getStorageBin());
} else
inoutline.setStorageBin(null);
inoutline.setEscmInitialreceipt(initial);
OBDal.getInstance().save(inoutline);
OBDal.getInstance().flush();
EscmInitialReceipt updinitial = OBDal.getInstance().get(EscmInitialReceipt.class,
initial.getSourceRef().getId());
// update the initial accept qty
updinitial.setAcceptedQty(updinitial.getAcceptedQty().subtract(
inoutline.getMovementQuantity()));
updinitial.setDeliveredQty(updinitial.getDeliveredQty().add(
inoutline.getMovementQuantity()));
log4j.debug("getAcceptedQty:" + updinitial.getAcceptedQty());
log4j.debug("getDeliveredQty:" + updinitial.getDeliveredQty());
OBDal.getInstance().save(updinitial);
}
if (inoutline.getId() != null) {
log4j.debug("entering into instance Id:");
p_instance_id = SequenceIdData.getUUID();
String error = "", s = "";
log4j.debug("p_instance_id:" + p_instance_id);
sql = " INSERT INTO ad_pinstance (ad_pinstance_id, ad_process_id, record_id, isactive, ad_user_id, ad_client_id, ad_org_id, created, createdby, updated, updatedby,isprocessing) "
+ " VALUES ('"
+ p_instance_id
+ "', '708D305269134EBF8A92E107D7EB6443','"
+ header.getId()
+ "', 'Y','"
+ userId
+ "','"
+ clientId
+ "','"
+ orgId
+ "', now(),'" + userId + "', now(),'" + userId + "','Y')";
ps = conn.prepareStatement(sql);
log4j.debug("ps:" + ps.toString());
count = ps.executeUpdate();
log4j.debug("count:" + count);
String instanceqry = "select ad_pinstance_id from ad_pinstance where ad_pinstance_id=?";
PreparedStatement pr = conn.prepareStatement(instanceqry);
pr.setString(1, p_instance_id);
ResultSet set = pr.executeQuery();
if (set.next()) {
sql = " select * from m_inout_post(?,?)";
ps = conn.prepareStatement(sql);
ps.setString(1, p_instance_id);
ps.setString(2, header.getId());
// ps.setString(2, invoice.getId());
ps.executeQuery();
log4j.debug("count12:" + set.getString("ad_pinstance_id"));
sql = " select result, errormsg from ad_pinstance where ad_pinstance_id='"
+ p_instance_id + "'";
ps = conn.prepareStatement(sql);
log4j.debug("ps12:" + ps.toString());
rs = ps.executeQuery();
if (rs.next()) {
log4j.debug("result:" + rs.getString("result"));
if (rs.getString("result").equals("0")) {
error = rs.getString("errormsg").replace("@ERROR=", "");
log4j.debug("error:" + error);
s = error;
/*
* int start = s.indexOf("@"); int end = s.lastIndexOf("@");
*
* if (log4j.isDebugEnabled()) { log4j.debug("start:" + start); log4j.debug("end:"
* + end); }
*
* if (end != 0) { sql = " select msgtext from ad_message where value ='" +
* s.substring(start + 1, end) + "'"; ps = conn.prepareStatement(sql);
* log4j.debug("ps12:" + ps.toString()); rs = ps.executeQuery(); if (rs.next()) {
* if (rs.getString("msgtext") != null) throw new OBException(error); } }
*/
String[] errMsgArray = s.split(" ");
StringBuilder errorBuilder = new StringBuilder();
int i = 0;
for (String str : errMsgArray) {
if (str.startsWith("@") && str.endsWith("@")) {
sql = " select msgtext from ad_message where value ='"
+ errMsgArray[i].substring(1, errMsgArray[i].length() - 1) + "'";
ps = conn.prepareStatement(sql);
log4j.debug("ps12:" + ps.toString());
rs = ps.executeQuery();
if (rs.next()) {
if (rs.getString("msgtext") != null)
str = rs.getString("msgtext");
}
}
errorBuilder.append(" ").append(str);
i++;
}
throw new OBException(errorBuilder.toString());
} else if (rs.getString("result").equals("1")) {
for (ShipmentInOutLine line : header.getMaterialMgmtShipmentInOutLineList()) {
OBQuery<MaterialTransaction> transaction = OBDal.getInstance().createQuery(
MaterialTransaction.class, " goodsShipmentLine.id='" + line.getId() + "'");
if (transaction.list().size() > 0) {
MaterialTransaction trans = transaction.list().get(0);
trans.setEscmTransactiontype("RDR");
trans.setEscmInitialreceipt(line.getEscmInitialreceipt());
OBDal.getInstance().save(trans);
OBDal.getInstance().flush();
}
}
}
}
}
}
log4j.debug("inoutline:" + inoutline.getMovementQuantity());
} else {
OBError result = OBErrorBuilder.buildMessage(null, "error",
"@ESCM_ProcessFailed(Reason)@");
bundle.setResult(result);
return;
}
} else if (header.getEscmReceivingtype().equals("RET")) {
OBQuery<EscmInitialReceipt> IR = OBDal.getInstance().createQuery(EscmInitialReceipt.class,
"goodsShipment.id ='" + header.getId() + "'");
Boolean ErrorFlag = false;
String defaultBin = "";
Date currentDate = new Date();
List<EscmInitialReceipt> returnvendor = new ArrayList<EscmInitialReceipt>();
List<EscmInitialReceipt> errorlist = new ArrayList<EscmInitialReceipt>();
List<EscmInitialReceipt> successlist = new ArrayList<EscmInitialReceipt>();
returnvendor = IR.list();
for (EscmInitialReceipt ret : returnvendor) {
EscmInitialReceipt initial = OBDal.getInstance().get(EscmInitialReceipt.class,
ret.getSourceRef().getId());
if (ret.getAlertStatus().equals("I")) {
// validaiton
if ((initial.getQuantity().subtract(initial.getReturnQuantity())).compareTo(ret
.getQuantity()) < 0) {
errorlist.add(ret);
ErrorFlag = true;
} else {
successlist.add(ret);
}
} else if (ret.getAlertStatus().equals("A")) {
// validaiton
if (initial.getAcceptedQty().compareTo(ret.getQuantity()) < 0) {
errorlist.add(ret);
ErrorFlag = true;
} else {
successlist.add(ret);
}
} else if (ret.getAlertStatus().equals("R")) {
// validaiton
if (initial.getRejectedQty().compareTo(ret.getQuantity()) < 0) {
errorlist.add(ret);
ErrorFlag = true;
} else {
successlist.add(ret);
}
} else if (ret.getAlertStatus().equals("D")) {
// validaiton
if (initial.getDeliveredQty().compareTo(ret.getQuantity()) < 0) {
errorlist.add(ret);
ErrorFlag = true;
} else {
successlist.add(ret);
}
}
}
if (ErrorFlag) {
for (EscmInitialReceipt ret : errorlist) {
if (ret.getAlertStatus().equals("I")) {
ret.setFailurereason(OBMessageUtils.messageBD("Escm_Qty_available").replace("xxx",
"Initial receipt"));
} else if (ret.getAlertStatus().equals("A")) {
ret.setFailurereason(OBMessageUtils.messageBD("Escm_Qty_available").replace("xxx",
"Accepted"));
} else if (ret.getAlertStatus().equals("R")) {
ret.setFailurereason(OBMessageUtils.messageBD("Escm_Qty_available").replace("xxx",
"Rejected"));
} else if (ret.getAlertStatus().equals("D")) {
ret.setFailurereason(OBMessageUtils.messageBD("Escm_Qty_available").replace("xxx",
"Delivered"));
}
OBDal.getInstance().save(ret);
}
OBDal.getInstance().flush();
OBError result = OBErrorBuilder.buildMessage(null, "error",
"@ESCM_ProcessFailed(Reason)@");
bundle.setResult(result);
return;
} else {
for (EscmInitialReceipt ret : successlist) {
EscmInitialReceipt initial = OBDal.getInstance().get(EscmInitialReceipt.class,
ret.getSourceRef().getId());
if (ret.getAlertStatus().equals("I")) {
initial.setReturnQuantity((initial.getReturnQuantity().add(ret.getQuantity())));
// initial.setAcceptedQty(initial.getAcceptedQty().subtract(ret.getQuantity()));
} else if (ret.getAlertStatus().equals("A")) {
initial.setReturnQty((initial.getReturnQty().add(ret.getQuantity())));
initial.setAcceptedQty(initial.getAcceptedQty().subtract(ret.getQuantity()));
} else if (ret.getAlertStatus().equals("R")) {
initial.setReturnQty((initial.getReturnQty().add(ret.getQuantity())));
initial.setRejectedQty(initial.getRejectedQty().subtract(ret.getQuantity()));
} else if (ret.getAlertStatus().equals("D")) {
if (initial.getGoodsShipment().getEscmReceivingtype().equals("SR")) {
initial.setReturnQty((initial.getReturnQty().add(ret.getQuantity())));
initial.setDeliveredQty(initial.getDeliveredQty().subtract(ret.getQuantity()));
} else {
initial.setReturnQty((initial.getReturnQty().add(ret.getQuantity())));
initial.setDeliveredQty(initial.getDeliveredQty().subtract(ret.getQuantity()));
Product product = OBDal.getInstance().get(Product.class,
initial.getProduct().getId());
if (product.isStocked()) {
// checking the stock of product.
ps = conn.prepareStatement(" select * from M_Check_Stock(?,?,?)");
ps.setString(1, product.getId());
ps.setString(2, initial.getClient().getId());
ps.setString(3, initial.getOrganization().getId());
rs = ps.executeQuery();
if (rs.next()) {
if (rs.getInt("p_result") == 0) {
String errormsg = rs.getString("p_message") + " "
+ OBMessageUtils.messageBD("@line@") + " "
+ initial.getSourceRef().getLineNo() + " " + product.getName();
OBError result = OBErrorBuilder.buildMessage(null, "error", errormsg);
bundle.setResult(result);
OBDal.getInstance().rollbackAndClose();
return;
}
}
// doubt to reduce qunts in ir or return data.
OBQuery<ShipmentInOutLine> finalreceipt = OBDal.getInstance().createQuery(
ShipmentInOutLine.class,
"shipmentReceipt.id='" + initial.getGoodsShipment().getId() + "'");
// insert into m_inoutline
ShipmentInOutLine sline = OBProvider.getInstance().get(ShipmentInOutLine.class);
sline.setClient(ret.getClient());
sline.setLineNo(ret.getLineNo());
sline.setOrganization(ret.getOrganization());
sline.setCreationDate(new java.util.Date());
sline.setCreatedBy(OBDal.getInstance().get(User.class, vars.getUser()));
sline.setUpdated(new java.util.Date());
sline.setUpdatedBy(OBDal.getInstance().get(User.class, vars.getUser()));
sline.setActive(true);
sline.setShipmentReceipt(header);
sline.setUOM(ret.getUOM());
sline.setProduct(ret.getProduct());
sline.setMovementQuantity(ret.getQuantity());
sline.setEscmInitialreceipt(ret);
OBDal.getInstance().save(sline);
OBDal.getInstance().flush();
// insert in product transaction to update storage details
MaterialTransaction trans = OBProvider.getInstance().get(
MaterialTransaction.class);
trans.setOrganization(ret.getOrganization());
trans.setClient(ret.getClient());
trans.setCreatedBy(OBDal.getInstance().get(User.class, vars.getUser()));
trans.setUpdatedBy(OBDal.getInstance().get(User.class, vars.getUser()));
trans.setCreationDate(new java.util.Date());
trans.setUpdated(new java.util.Date());
trans.setMovementType("V-");
trans.setEscmTransactiontype("RER");
trans.setEscmInitialreceipt(ret);
defaultBin = Utility.GetDefaultBin(header.getWarehouse().getId());
if (defaultBin.equals("")) {
OBError result = OBErrorBuilder.buildMessage(null, "error",
"@Escm_No_DefaultBin@");
bundle.setResult(result);
OBDal.getInstance().rollbackAndClose();
return;
} else {
Locator locator = OBDal.getInstance().get(Locator.class, defaultBin);
trans.setStorageBin(locator);
}
/*
* OBQuery<Locator> locator = OBDal.getInstance().createQuery( Locator.class,
* " as e where e.warehouse.id='" + header.getWarehouse().getId() +
* "' and e.default='Y' "); locator.setMaxResult(1); if (locator.list().size() >
* 0) { trans.setStorageBin(locator.list().get(0)); log4j.debug("getStorageBin:" +
* trans.getStorageBin()); } else { OBError result =
* OBErrorBuilder.buildMessage(null, "error", "@Escm_No_DefaultBin@");
* bundle.setResult(result); OBDal.getInstance().rollbackAndClose(); return; }
*/
int chkqty = Utility.ChkStoragedetOnhandQtyNeg(initial.getProduct().getId(),
defaultBin, ret.getQuantity(), ret.getClient().getId());
log4j.debug("chkqty:" + chkqty);
if (chkqty == -1) {
OBError result = OBErrorBuilder.buildMessage(null, "error",
"@ESCM_StorageDetail_QtyonHand@");
bundle.setResult(result);
OBDal.getInstance().rollbackAndClose();
String msg = OBMessageUtils.messageBD("ESCM_AvaQtyZero");
log4j.debug("msg:" + msg);
ret.setFailurereason(msg);
OBDal.getInstance().save(ret);
OBDal.getInstance().flush();
return;
}
trans.setProduct(initial.getProduct());
trans.setMovementDate(header.getMovementDate());
trans.setMovementQuantity(ret.getQuantity().negate());
// insert in m_inoutline and use refernece here
trans.setGoodsShipmentLine(sline);
trans.setUOM(OBDal.getInstance().get(UOM.class, initial.getUOM().getId()));
OBDal.getInstance().save(trans);
OBDal.getInstance().flush();
}
}
}
OBDal.getInstance().save(initial);
}
OBDal.getInstance().flush();
}
}
log4j.debug("header:" + header);
header.setEscmDocstatus("CO");
header.setDocumentStatus("CO");
header.setProcessed(true);
header.setDocumentAction("--");
OBDal.getInstance().save(header);
OBDal.getInstance().flush();
obError.setType("Success");
obError.setTitle("Success");
obError.setMessage(OBMessageUtils.messageBD("Escm_Ir_complete_success"));
bundle.setResult(obError);
OBDal.getInstance().commitAndClose();
return;
} catch (Exception e) {
e.printStackTrace();
log4j.debug("Exeception in Requisition Submit:" + e);
Throwable t = DbUtility.getUnderlyingSQLException(e);
final OBError error = OBMessageUtils.translateError(bundle.getConnection(), vars,
vars.getLanguage(), t.getMessage());
bundle.setResult(error);
OBDal.getInstance().rollbackAndClose();
} finally {
OBContext.restorePreviousMode();
}
}
public static int updateInitialRecipt(Connection con, String clientId, String orgId,
ShipmentInOut objInout) {
String objId = objInout.getId();
int count = 1;
String query = "", query1 = "", query2 = "";
PreparedStatement ps1 = null, ps = null, ps2 = null;
Boolean isProceed = true;
ResultSet rs = null, rs1 = null, rs2 = null;
try {
OBContext.setAdminMode(true);
query = " select coalesce((sum(mr.quantity)-sum(mr.ir_return_qty)-sum(mr.return_qty)),0) as irqty, coalesce(sum(mr.accepted_qty),0)+coalesce(sum(mr.rejected_qty),0) as insqty ,"
+ " coalesce(sum(ur.insqty),0) as inspecedqty, "
+ " coalesce(sum(cr.crqty),0) as crqty ,cr.source_ref from escm_initialreceipt mr "
+ " left join (select source_ref,sum(quantity) as insqty "
+ " from escm_initialreceipt ur join m_inout io on io.m_inout_id=ur.m_inout_id "
+ " where io.em_escm_receivingtype ='INS' and io.em_escm_docstatus='CO' "
+ " group by source_ref) as ur on ur.source_ref=mr.escm_initialreceipt_id "
+ " left join (select sum(quantity) as crqty,source_ref from escm_initialreceipt "
+ " where m_inout_id='"
+ objId
+ "' group by source_ref) as cr on cr.source_ref=mr.escm_initialreceipt_id "
+ " where mr.escm_initialreceipt_id in (select distinct source_ref from escm_initialreceipt "
+ " where m_inout_id='"
+ objId
+ "') group by cr.source_ref "
+ " having (coalesce((sum(mr.quantity)-sum(mr.ir_return_qty)-sum(mr.return_qty)),0) ) < (coalesce(sum(mr.accepted_qty),0)+coalesce(sum(mr.rejected_qty),0) +coalesce(sum(cr.crqty),0))";
ps = con.prepareStatement(query);
log4j.debug("QtyCheck:" + ps.toString());
rs = ps.executeQuery();
while (rs.next()) {
OBQuery<EscmInitialReceipt> erroreceiptQry = OBDal.getInstance().createQuery(
EscmInitialReceipt.class,
"as e where e.sourceRef.id='" + rs.getString("source_ref")
+ "' and e.goodsShipment.id='" + objId + "'");
if (erroreceiptQry.list().size() > 0) {
for (EscmInitialReceipt lineObject : erroreceiptQry.list()) {
lineObject.setFailurereason("Quantity Exceed,Availabe Quantity to inspect:'"
+ (rs.getInt("irqty") - rs.getInt("insqty")) + "'");
OBDal.getInstance().save(lineObject);
}
}
isProceed = false;
count = 2;
}
OBDal.getInstance().flush();
if (isProceed) {
// update AcceptQty in Initial receipt
query1 = " select sum(quantity) as qty,source_ref from escm_initialreceipt where m_inout_id='"
+ objId + "' " + " and status='A' group by source_ref ";
ps1 = con.prepareStatement(query1);
rs1 = ps1.executeQuery();
while (rs1.next()) {
EscmInitialReceipt objIrReceipt = OBDal.getInstance().get(EscmInitialReceipt.class,
rs1.getString("source_ref"));
objIrReceipt
.setAcceptedQty(objIrReceipt.getAcceptedQty().add((rs1.getBigDecimal("qty"))));
OBDal.getInstance().save(objIrReceipt);
}
// update RejectQty in Initial Receipt
query2 = " select sum(quantity) as qty,source_ref from escm_initialreceipt where m_inout_id='"
+ objId + "' " + " and status='R' group by source_ref ";
ps2 = con.prepareStatement(query2);
rs2 = ps2.executeQuery();
while (rs2.next()) {
EscmInitialReceipt objIrReceipt = OBDal.getInstance().get(EscmInitialReceipt.class,
rs2.getString("source_ref"));
objIrReceipt
.setRejectedQty(objIrReceipt.getRejectedQty().add((rs2.getBigDecimal("qty"))));
OBDal.getInstance().save(objIrReceipt);
}
count = 1;
// update failure reason as empty once success
OBDal
.getInstance()
.getConnection()
.prepareStatement(
"update escm_initialreceipt set failurereason='' where m_inout_id='" + objId + "'")
.executeUpdate();
}
} catch (Exception e) {
count = 0;
log4j.error("Exception in updateInitialRecipt: ", e);
OBDal.getInstance().rollbackAndClose();
} finally {
OBContext.restorePreviousMode();
}
return count;
}
}
| true |
617ce021f4526b02d74080e7a2648dfa203d6b3d | Java | zachaxy/SafeDefender | /app/src/main/java/com/zachaxy/safedefender/receiver/SmsReceiver.java | UTF-8 | 4,283 | 1.859375 | 2 | [] | no_license | package com.zachaxy.safedefender.receiver;
import android.Manifest;
import android.app.admin.DevicePolicyManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.telephony.SmsMessage;
import android.widget.Toast;
import com.zachaxy.safedefender.R;
import com.zachaxy.safedefender.service.LocationService;
/**
* Created by zhangxin on 2016/7/6.
*/
public class SmsReceiver extends BroadcastReceiver {
private DevicePolicyManager mDPM;
private ComponentName mDeviceAdminSample;
@Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
Object[] pdus = (Object[]) bundle.get("pdus");//提取短信消息
SmsMessage[] messages = new SmsMessage[pdus.length];
for (int i = 0; i < pdus.length; i++) {
messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
}
String from = messages[0].getOriginatingAddress();//获取对方手机号码
String content = ""; //获取短信内容
for (SmsMessage msg : messages) {
content += msg.getMessageBody();
}
/*if ("#*location*#".equals(content)) {
}
if ("#*alarm*#".equals(content)) {
}
if ("#*wipedata*#".equals(content)) {
}
if ("#*lockscreen*#".equals(content)) {
}*/
switch (content) {
case "#*location*#":
//开启定位的服务
context.startService(new Intent(context, LocationService.class));
abortBroadcast();
break;
case "#*alarm*#":
MediaPlayer player = MediaPlayer.create(context, R.raw.ylzs);
player.setVolume(1f, 1f); //左右声道最大声
player.setLooping(true); //单曲循环
player.start(); //开始播放
abortBroadcast();
break;
case "#*wipedata*#":
mDPM = (DevicePolicyManager) context.getSystemService(Context.DEVICE_POLICY_SERVICE);
mDeviceAdminSample = new ComponentName(context, AdminReceiver.class);
//首先判断设别管理器是否已经激活,如果未激活,那么程序会直接崩溃
if (!mDPM.isAdminActive(mDeviceAdminSample)) {
//进入激活设备的向导
activeDevice(context);
}
mDPM.wipeData(0);//清除数据,恢复出厂设置
abortBroadcast();
break;
case "#*lockscreen*#":
mDPM = (DevicePolicyManager) context.getSystemService(Context.DEVICE_POLICY_SERVICE);
mDeviceAdminSample = new ComponentName(context, AdminReceiver.class);
//首先判断设别管理器是否已经激活,如果未激活,那么程序会直接崩溃
if (!mDPM.isAdminActive(mDeviceAdminSample)) {
//进入激活设备的向导
activeDevice(context);
}
mDPM.lockNow();
mDPM.resetPassword("123456", 0); //重置锁屏密码.并且不让其他设备重复设置密码,进一步加强设备安全性
abortBroadcast();
break;
default:
break;
}
}
private void activeDevice(Context context) {
//进入激活设备的向导
Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
mDeviceAdminSample = new ComponentName(context, AdminReceiver.class);
intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, mDeviceAdminSample);
intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION,
context.getString(R.string.add_admin_extra_app_text));
context.startActivity(intent);
}
}
| true |
dbc3548d2b269cecf0c28dcaaae57a7d2a358b29 | Java | shreekalloji/CentralVarsity | /app/src/main/java/com/iprismtech/studentvarsity/adapters/ExpandableListViewAdapter.java | UTF-8 | 5,800 | 2.078125 | 2 | [] | no_license | package com.iprismtech.studentvarsity.adapters;
import android.content.Context;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.TextView;
import com.iprismtech.studentvarsity.R;
import com.iprismtech.studentvarsity.network.listener.ChildClickListener;
import com.iprismtech.studentvarsity.pojos.ChaptersPojo;
import java.util.HashMap;
import java.util.List;
public class ExpandableListViewAdapter extends BaseExpandableListAdapter {
private Context context;
ChildClickListener childClickListener;
private List<String> parentDataSource;
private HashMap<String, List<String>> childDataSource;
private ChaptersPojo chaptersPojo;
public ExpandableListViewAdapter(ChaptersPojo chaptersPojo, List<String> parentHeaderInformation, HashMap<String, List<String>> allChildItems, Context context) {
this.context = context;
this.parentDataSource = parentHeaderInformation;
// this.childClickListener = ;
this.childDataSource = allChildItems;
this.chaptersPojo = chaptersPojo;
}
private OnitemClickListener mListner;
public void setOnItemClickListener(OnitemClickListener onitemClickListener) {
mListner = onitemClickListener;
}
public interface OnitemClickListener {
void onItemClick(View view, int group_position, int child_position);
}
@Override
public int getGroupCount() {
return parentDataSource.size();
}
@Override
public int getChildrenCount(int groupPosition) {
//return childDataSource.get(this.parentDataSource.get(groupPosition)).size();
//return this.childDataSource.get(this.parentDataSource.get(groupPosition)).size();
if (this.childDataSource.get(this.parentDataSource.get(groupPosition)) == null) {
return 0;
} else {
return this.childDataSource.get(this.parentDataSource.get(groupPosition)).size();
}
}
@Override
public Object getGroup(int groupPosition) {
return parentDataSource.get(groupPosition);
}
@Override
public Object getChild(int groupPosition, int childPosition) {
String bjs = "";
// return childDataSource.get(parentDataSource.get(groupPosition)).get(childPosition);
if (childDataSource != null) {
if (parentDataSource != null) {
String patext = parentDataSource.get(groupPosition);
if (patext != null) {
if (childDataSource.get(patext) != null) {
String chailsourcetext = childDataSource.get(patext).get(childPosition);
if (chailsourcetext != null) {
bjs = this.childDataSource.get(parentDataSource.get(groupPosition)).get(childPosition);
}
}
}
}
return bjs;
}
return bjs;
}
@Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
@Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
@Override
public boolean hasStableIds() {
return false;
}
@Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
// View view = convertView;
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.parent_layout, parent, false);
String parentHeader = (String) getGroup(groupPosition);
TextView parentItem = (TextView) convertView.findViewById(R.id.parent_text);
parentItem.setText(parentHeader);
return convertView;
}
@Override
public View getChildView(final int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
// View view = convertView;
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.child_layout, parent, false);
String childName = (String) getChild(groupPosition, childPosition);
TextView childItem = (TextView) convertView.findViewById(R.id.child_text);
childItem.setText(Html.fromHtml(childName));
// childItem.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View view) {
//
// if (mListner != null) {
// mListner.onItemClick(view, groupPosition, childPosition);
// }
//
//
//// String category_id= String.valueOf(departmentCategoryPOJO.getResponse().get(groupPosition).getCategory_id());
//// String sub_category_id= String.valueOf(departmentCategoryPOJO.getResponse().get(groupPosition).getSubcategory().get(childPosition).getId());
//// Toast.makeText(context, category_id+" \n "+sub_category_id, Toast.LENGTH_SHORT).show();
//
// //Sending Bundle object to T-Shirt Fragment
//// Bundle b=new Bundle();
//// b.putString("category_id", "1");
//// b.putString("sub_category_id","2");
//// b.putString("tag","Tag");
//// ApplicationController.getInstance().handleEvent(AppConstants.EventIds.LAUNCH_HOME_SCREEN,b); Bundle b=new Bundle();
//
//
// }
// });
return convertView;
}
@Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
| true |
58bad6106816d719e4980a1a7999b04516915022 | Java | Mats-SX/personal_repo | /java_workspace/Network_Programming/src/lab1/NetworkClient.java | UTF-8 | 1,331 | 3.296875 | 3 | [] | no_license | package lab1;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
public class NetworkClient {
public static void main(String[] args) {
if (args.length != 3) {
System.err.println("Incorrect command line. Need three arguments: machine, port, command");
}
InetAddress address = null;
try {
address = InetAddress.getByName(args[0]);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int port = Integer.parseInt(args[1]);
String command = args[2];
byte[] data = command.getBytes();
byte[] responseData = new byte[65000];
DatagramPacket request = new DatagramPacket(data, data.length, address, 30001);
DatagramPacket response = new DatagramPacket(responseData, responseData.length);
DatagramSocket socket = null;
try {
socket = new DatagramSocket(port);
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
socket.send(request);
socket.receive(response);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Response:");
System.out.println(new String(response.getData()));
}
}
| true |
ed1fad665390d37661358db53826393664471368 | Java | Yufan341955/FulLiCenter | /app/src/main/java/ucai/cn/fulicenter/activity/GoodsDetailsActivity.java | UTF-8 | 9,407 | 1.726563 | 2 | [] | no_license | package ucai.cn.fulicenter.activity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;
import ucai.cn.fulicenter.FuLiCenterApplication;
import ucai.cn.fulicenter.I;
import ucai.cn.fulicenter.R;
import ucai.cn.fulicenter.bean.AlbumsBean;
import ucai.cn.fulicenter.bean.GoodsDetailsBean;
import ucai.cn.fulicenter.bean.MessageBean;
import ucai.cn.fulicenter.bean.UserAvatar;
import ucai.cn.fulicenter.utils.CommonUtils;
import ucai.cn.fulicenter.utils.L;
import ucai.cn.fulicenter.utils.MFGT;
import ucai.cn.fulicenter.utils.NetDao;
import ucai.cn.fulicenter.utils.OkHttpUtils;
import ucai.cn.fulicenter.views.FlowIndicator;
import ucai.cn.fulicenter.views.SlideAutoLoopView;
public class GoodsDetailsActivity extends AppCompatActivity {
@Bind(R.id.backAuto)
LinearLayout backAuto;
@Bind(R.id.tvEnglishName)
TextView tvEnglishName;
@Bind(R.id.tvName)
TextView tvName;
@Bind(R.id.tvPericeCurrent)
TextView tvPericeCurrent;
@Bind(R.id.tvPericeShop)
TextView tvPericeShop;
@Bind(R.id.Sav)
SlideAutoLoopView Sav;
@Bind(R.id.flow)
FlowIndicator flow;
@Bind(R.id.wv_goods_brief)
WebView wvGoodsBrief;
int goodsId;
@Bind(R.id.collect_in)
ImageView collectIn;
@Bind(R.id.share)
ImageView share;
UserAvatar user;
boolean isCollect=false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_goods_details);
ButterKnife.bind(this);
goodsId = getIntent().getIntExtra("goodsId", 0);
L.e("details", goodsId + "");
if (goodsId == 0) {
finish();
}
user= FuLiCenterApplication.getUser();
initView();
initData();
setListener();
}
private void setListener() {
}
private void initData() {
downloadGoodsDetails();
if(user!=null) {
isCollect(goodsId,user.getMuserName());
}
}
private void isCollect(int goodsId,String username) {
NetDao.isCollect(this, goodsId, username, new OkHttpUtils.OnCompleteListener<MessageBean>() {
@Override
public void onSuccess(MessageBean result) {
if(result!=null){
isCollect=result.isSuccess();
setCollectImage();
}
}
@Override
public void onError(String error) {
}
});
}
private void downloadGoodsDetails() {
NetDao.downlodaGoodsDetails(this, goodsId, new OkHttpUtils.OnCompleteListener<GoodsDetailsBean>() {
@Override
public void onSuccess(GoodsDetailsBean result) {
L.i("details.result=", result.toString());
if (result == null) {
finish();
} else {
showGoodsDetails(result);
}
}
@Override
public void onError(String error) {
finish();
L.e("details.error=", error);
Toast.makeText(GoodsDetailsActivity.this, error, Toast.LENGTH_SHORT).show();
}
});
}
private void showGoodsDetails(GoodsDetailsBean details) {
tvEnglishName.setText(details.getGoodsEnglishName());
tvName.setText(details.getGoodsName());
tvPericeCurrent.setText(details.getCurrencyPrice());
tvPericeShop.setText(details.getShopPrice());
Sav.startPlayLoop(flow, getAlbumsImgUrl(details), getAlbumsImgCount(details));
wvGoodsBrief.loadDataWithBaseURL(null, details.getGoodsBrief(), I.TEXT_HTML, I.UTF_8, null);
}
private int getAlbumsImgCount(GoodsDetailsBean details) {
if (details.getProperties() != null && details.getProperties().length > 0) {
return details.getProperties()[0].getAlbums().length;
}
return 0;
}
private String[] getAlbumsImgUrl(GoodsDetailsBean details) {
String[] urls = new String[]{};
if (details.getProperties() != null && details.getProperties().length > 0) {
AlbumsBean[] albums = details.getProperties()[0].getAlbums();
urls = new String[albums.length];
for (int i = 0; i < albums.length; i++) {
urls[i] = albums[0].getImgUrl();
}
}
return urls;
}
private void initView() {
}
@OnClick(R.id.backAuto)
public void onClick() {
MFGT.finish(this);
}
@Override
public void onBackPressed() {
MFGT.finish(this);
}
@OnClick({R.id.collect_in, R.id.share,R.id.cart})
public void onClick(View view) {
switch (view.getId()) {
case R.id.collect_in:
if(user!=null){
if(isCollect){
delteCollect();
}else {
addCollect(goodsId, user.getMuserName());
}
}else {
CommonUtils.showLongToast("请先登录");
}
break;
case R.id.share:
showShare();
break;
case R.id.cart:
if(user!=null) {
addIntoCart();
}else {
CommonUtils.showLongToast("请先登录");
}
break;
}
}
private void addIntoCart() {
NetDao.addCart(this, goodsId, user.getMuserName(), new OkHttpUtils.OnCompleteListener<MessageBean>() {
@Override
public void onSuccess(MessageBean result) {
if(result!=null){
if(result.isSuccess()){
CommonUtils.showLongToast("商品添加到购物车");
}else {
CommonUtils.showLongToast(result.getMsg());
}
}
}
@Override
public void onError(String error) {
}
});
}
private void delteCollect() {
NetDao.deleteCollect(this, goodsId, user.getMuserName(), new OkHttpUtils.OnCompleteListener<MessageBean>() {
@Override
public void onSuccess(MessageBean result) {
if(result!=null){
isCollect=!result.isSuccess();
setCollectImage();
//CommonUtils.showLongToast(result.getMsg());
}
}
@Override
public void onError(String error) {
}
});
}
private void addCollect(int goodsId, String muserName) {
NetDao.addCollect(this, goodsId, muserName, new OkHttpUtils.OnCompleteListener<MessageBean>() {
@Override
public void onSuccess(MessageBean result) {
if(result!=null){
isCollect=result.isSuccess();
setCollectImage();
CommonUtils.showLongToast(result.getMsg());
}
}
@Override
public void onError(String error) {
}
});
}
private void setCollectImage() {
if(isCollect){
collectIn.setImageResource(R.mipmap.bg_collect_out);
}else{
collectIn.setImageResource(R.mipmap.bg_collect_in);
}
}
public void showShare(){
ShareSDK.initSDK(this);
OnekeyShare oks = new OnekeyShare();
//关闭sso授权
oks.disableSSOWhenAuthorize();
// 分享时Notification的图标和文字 2.5.9以后的版本不调用此方法
//oks.setNotification(R.drawable.ic_launcher, getString(R.string.app_name));
// title标题,印象笔记、邮箱、信息、微信、人人网和QQ空间使用
oks.setTitle("标题");
// titleUrl是标题的网络链接,仅在人人网和QQ空间使用
oks.setTitleUrl("http://sharesdk.cn");
// text是分享文本,所有平台都需要这个字段
oks.setText("我是分享文本");
//分享网络图片,新浪微博分享网络图片需要通过审核后申请高级写入接口,否则请注释掉测试新浪微博
oks.setImageUrl("http://f1.sharesdk.cn/imgs/2014/02/26/owWpLZo_638x960.jpg");
// imagePath是图片的本地路径,Linked-In以外的平台都支持此参数
//oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片
// url仅在微信(包括好友和朋友圈)中使用
oks.setUrl("http://sharesdk.cn");
// comment是我对这条分享的评论,仅在人人网和QQ空间使用
oks.setComment("我是测试评论文本");
// site是分享此内容的网站名称,仅在QQ空间使用
oks.setSite("ShareSDK");
// siteUrl是分享此内容的网站地址,仅在QQ空间使用
oks.setSiteUrl("http://sharesdk.cn");
// 启动分享GUI
oks.show(this);
}
}
| true |
78dfcdf962317c1eaa37013a3b9e5820be1ed38f | Java | zhouxin1008/LeetcodeEveryDay | /Java/No141LinkedListCycle.java | UTF-8 | 648 | 3.078125 | 3 | [] | no_license |
/*
* @lc app=leetcode id=141 lang=java
*
* [141] Linked List Cycle
*/
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class No141LinkedListCycle {
public boolean hasCycle(ListNode head) {
if(head==null || head.next==null) return false;
ListNode p1 = head.next;
ListNode p2 = head;
while(p1!=null && p1!=p2){
p1 = p1.next==null ? null : p1.next.next;
p2 = p2.next;
}
if(p1==p2) return true;
return false;
}
}
| true |
370cb45a339f1e81e5a0596bb55e5b52c5172769 | Java | bszymkowiak/PokerTexas | /src/klasy/menu/panelKoncowy/PanelKoncowy.java | UTF-8 | 1,164 | 2.65625 | 3 | [] | no_license | package klasy.menu.panelKoncowy;
import klasy.Rozgrywka;
import klasy.menu.PanelStolik;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
public class PanelKoncowy extends JPanel {
private PanelKoncowy me;
private PanelStolik panelStolik;
private Rozgrywka rozgrywka;
private JFrame window;
public PanelKoncowy(PanelStolik panelStolik) {
this.panelStolik = panelStolik;
setRozgrywka(panelStolik.getRozgrywka());
me = this;
dodajTlo();
}
private void dodajTlo() {
window = new JFrame("Poker Texas");
window.setVisible(true);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setPreferredSize(new Dimension(1920, 1080));
window.add(new KlasyfikacjaKoncowa(me));
window.pack();
}
public Rozgrywka getRozgrywka() {
return rozgrywka;
}
public void setRozgrywka(Rozgrywka rozgrywka) {
this.rozgrywka = rozgrywka;
}
@Override
protected void paintComponent(Graphics g) {
}
}
| true |
53dd4dbe921d75b2811cc976a88edbf429b2bffd | Java | github-changhyeon/my-own-map | /backend/myOwnMap/src/main/java/com/ssafy/mom/firebase/NotificationType.java | UTF-8 | 916 | 2.390625 | 2 | [] | no_license | package com.ssafy.mom.firebase;
import com.ssafy.mom.model.UserDto;
public enum NotificationType {
LIKE_RECEIVED(((sender, receiver)
-> sender.getUsername() + "님이 " + receiver.getUsername() + "님의 글을 찜하였습니다.")),
COMMENT_RECEIVED(((sender, receiver)
-> sender.getUsername() + "님이 " + receiver.getUsername() + "님에게 댓글을 달았습니다.")),
FOLLOW_RECEIVED(((sender, receiver)
-> sender.getUsername() + "님이 " + receiver.getUsername() + "님을 팔로우했습니다."));
private NotificationMessageGenerator notificationMessageGenerator;
NotificationType(NotificationMessageGenerator notificationMessageGenerator) {
this.notificationMessageGenerator = notificationMessageGenerator;
}
public String generateNotificationMessage(UserDto sender, UserDto receiver) {
return notificationMessageGenerator.generateNotificationMessage(sender, receiver);
}
}
| true |
33e610d4db8d46f2090b603317af67f50ca4fea1 | Java | TonyChinwe/cqrs-demo-two | /src/main/java/com/bridgingcode/bankaccountscqrsdemo/command/aggregate/Book.java | UTF-8 | 1,096 | 2.453125 | 2 | [] | no_license | package com.bridgingcode.bankaccountscqrsdemo.command.aggregate;
import com.bridgingcode.bankaccountscqrsdemo.command.command.AddBookCommand;
import com.bridgingcode.bankaccountscqrsdemo.events.BookAddedEvent;
import lombok.extern.slf4j.Slf4j;
import org.axonframework.commandhandling.CommandHandler;
import org.axonframework.eventsourcing.EventSourcingHandler;
import org.axonframework.modelling.command.AggregateIdentifier;
import org.axonframework.modelling.command.AggregateLifecycle;
import org.axonframework.spring.stereotype.Aggregate;
@Slf4j
public class Book {
private Integer bookId;
private String name;
private String isbn;
public Book() {
}
// @CommandHandler
// public Book(AddBookCommand cmd){
// AggregateLifecycle.apply(new BookAddedEvent(cmd.getBookId(),cmd.getName(),cmd.getIsbn()));
//
// }
//
// @EventSourcingHandler
// public void on(BookAddedEvent event){
// log.info("In the book added event ");
// this.bookId=event.getBookId();
// this.name=event.getName();
// this.isbn=event.getIsbn();
// }
}
| true |
467c2b3980650c6b6662b421c498ca1fed4351f5 | Java | nami/datastructures_algorithmsmaven | /src/test/java/data_structures/LinkedListTest.java | UTF-8 | 971 | 3.109375 | 3 | [] | no_license | package data_structures;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
public class LinkedListTest {
LinkedList linkedListTest = new LinkedList();
@Before
public void setUp() throws Exception {
linkedListTest.append("Pikachu");
linkedListTest.append("Charmander");
linkedListTest.append("Bulbasaur");
linkedListTest.append("Squirtle");
linkedListTest.prepend("Mew");
}
@Test
public void append() {
linkedListTest.append("Vulpix");
assertNotNull(linkedListTest.find("Vulpix"));
}
@Test
public void prepend() {
linkedListTest.prepend("Snorlax");
assertNotNull(linkedListTest.find("Snorlax"));
}
@Test
public void delete() {
linkedListTest.delete("Mew");
assertNull(linkedListTest.find("Mew"));
}
@Test
public void find() {
assertNotNull(linkedListTest.find("Charmander"));
}
} | true |
1fafd3603499583dee85b27696f2edcadbb31c15 | Java | bilalwahla/product-selection | /customer-location-service/src/main/java/com/df/location/model/CustomerLocation.java | UTF-8 | 746 | 2.34375 | 2 | [] | no_license | package com.df.location.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* Customer location model.
*
* @author bilalwahla
*/
@Entity
@Table(name = "customer_location")
public class CustomerLocation {
@Id
@Column(name = "customer_id", nullable = false)
private String customerId;
@Column(name = "location", nullable = false)
private String location;
public String getCustomerId() {
return customerId;
}
public void setCustomerId(String customerId) {
this.customerId = customerId;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
}
| true |
0fe83ab0d6fe411b8e2d1ac9b40e6aae0bdb02c2 | Java | 275618939/narutov1 | /src/com/movie/adapter/SignInAdapter.java | UTF-8 | 3,338 | 2.203125 | 2 | [] | no_license | package com.movie.adapter;
import java.util.List;
import java.util.Map;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.movie.R;
import com.movie.client.bean.Miss;
import com.movie.client.bean.User;
import com.movie.client.service.CommentService;
public class SignInAdapter extends BaseAdapter {
List<Map<Integer,Integer>> signInList;
int sex;
User user;
boolean showCount;
Context context;
LayoutInflater inflater;
CommentService commentService;
Handler handler;
public SignInAdapter(Context context,List<Map<Integer,Integer>> signInList) {
this.context = context;
this.signInList = signInList;
inflater = LayoutInflater.from(context);
}
public SignInAdapter(Context context,Handler handler,List<Map<Integer,Integer>> signInList) {
this.context = context;
this.signInList = signInList;
this.handler=handler;
inflater = LayoutInflater.from(context);
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return signInList == null ? 0 : signInList.size();
}
@Override
public Map<Integer,Integer> getItem(int position) {
// TODO Auto-generated method stub
if (signInList != null && signInList.size() != 0) {
return signInList.get(position);
}
return null;
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder mHolder;
View view = convertView;
if (view == null) {
view = inflater.inflate(R.layout.signin_item, null);
mHolder = new ViewHolder();
mHolder.linearLayout= (LinearLayout)view.findViewById(R.id.comment_view);
mHolder.reward = (TextView)view.findViewById(R.id.reward);
mHolder.signIn = (TextView)view.findViewById(R.id.signInBtn);
view.setTag(mHolder);
} else {
mHolder = (ViewHolder) view.getTag();
}
//获取position对应的数据
Map<Integer,Integer> signs = getItem(position);
for (Map.Entry<Integer, Integer> entry : signs.entrySet()) {
mHolder.reward.setText("奖励"+String.valueOf(entry.getKey())+"影币");
}
return view;
}
class ViewHolder {
LinearLayout linearLayout;
//签到奖励
TextView reward;
//签到
TextView signIn;
}
protected class UserSelectAction implements OnClickListener {
int position;
public UserSelectAction(int position) {
this.position = position;
}
@Override
public void onClick(final View v) {
switch (v.getId()) {
case R.id.comment:
Message message = new Message();
message.what = Miss.EVLATOIN_USER;
Bundle bundle = new Bundle();
bundle.putSerializable("user", user);
message.setData(bundle);
handler.sendMessage(message);
break;
default:
break;
}
}
}
public void updateData(List<Map<Integer,Integer>> signInList) {
this.signInList=signInList;
this.notifyDataSetChanged();
}
public void setUser(User user) {
this.user = user;
}
}
| true |
18e61ad40ad1498cdc0c3a2952ce43e1a3548ec2 | Java | bellmit/vst_order | /src/main/java/com/lvmama/vst/order/constant/config/DynConfigProp.java | UTF-8 | 6,379 | 2.046875 | 2 | [] | no_license | package com.lvmama.vst.order.constant.config;
import java.net.URL;
import java.util.List;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import com.lvmama.config.common.ZooKeeperConfigProperties;
import com.lvmama.vst.comm.utils.StringUtil;
import com.lvmama.vst.comm.vo.Constant;
/**
* 动态配置属性
* <p>
* 1、优先从sweet获取配置属性值, 且sweet属性的配置修改实时生效。
* SWEET(ZK)动态配置属性修改实时生效, 须配置(zookeeper.config.watcher.enabled=true)
* 2、若sweet未获取相应的属性值, 则从当前应用的const.properties文件中获取。
* </p>
*
* @version 1.0
*/
public class DynConfigProp {
private static final Logger LOG = LoggerFactory.getLogger(DynConfigProp.class);
private static final String ER_UNPROVIDERIDS = "expiredRefund.unproviderids";
private static final String ER_DISTCHNL = "expiredRefund.distchnl";
private static final String ER_DISTCODE = "expiredRefund.distcode";
private static final String ER_DISTCHNLCODES = "expiredRefund.distchnlcodes";
private static final String ER_DISTCHNL_VALS = "expiredRefund.distchnlvals";
private static final String ER_PAGE_REFRESH_TIME = "expiredRefund.page.refresh.time";
private static final String ER_ROWNUM_MAX = "expiredRefund.rownum.max";
private static List<Long> erUnprovideridsList;
private static boolean erDistchnl = false;
private static boolean erDistcode = false;
private static List<String> erDistchnlcodesList;
private static List<Long> erDistchnlvalsList;
private static int erPageRefreshTime = 60 * 60;
private static int erRownumMax = Constant.ROWNUM_MAX;
private static Properties props = new Properties();
private static DynConfigProp dynConfigProp = new DynConfigProp();
public DynConfigProp() {
try {
URL url = DynConfigProp.class.getResource("/const.properties");
if (url == null) {
LOG.info("DynConfigProp: const.properties may not exist, Please check sweet-config!");
return;
}
props.load(DynConfigProp.class.getResourceAsStream("/const.properties"));
String erUnprovideridsProp = props.getProperty(ER_UNPROVIDERIDS);
if (!StringUtils.isEmpty(erUnprovideridsProp)) {
erUnprovideridsList = StringUtil.str2listOflong(erUnprovideridsProp);
}
String erDistchnlProp = props.getProperty(ER_DISTCHNL);
if (!StringUtils.isEmpty(erDistchnlProp)) {
erDistchnl = Boolean.valueOf(erDistchnlProp);
}
String erDistchnlcodesProp = props.getProperty(ER_DISTCHNLCODES);
if (!StringUtils.isEmpty(erDistchnlcodesProp)) {
erDistchnlcodesList = StringUtil.str2list(erDistchnlcodesProp);
}
String erDistchnlvalsProp = props.getProperty(ER_DISTCHNL_VALS);
if (!StringUtils.isEmpty(erDistchnlvalsProp)) {
erDistchnlvalsList = StringUtil.str2listOflong(erDistchnlvalsProp);
}
String erPageRefreshTimeProp = props.getProperty(ER_PAGE_REFRESH_TIME);
if (!StringUtils.isEmpty(erPageRefreshTimeProp)) {
erPageRefreshTime = Integer.valueOf(erPageRefreshTimeProp);
}
String erRownumMaxProp = props.getProperty(ER_ROWNUM_MAX);
if (!StringUtils.isEmpty(erRownumMaxProp)) {
erRownumMax = Integer.valueOf(erRownumMaxProp);
}
} catch (Exception e) {
LOG.error("DynConfigProp: Init is error!", e);
}
}
/**
* 门票过期退: 独立申码中不处理的服务商
*
* @return List<Long>
*/
public List<Long> getErUnProviderIds() {
String sweetValue = ZooKeeperConfigProperties.getProperties(ER_UNPROVIDERIDS);
if (!StringUtils.isEmpty(sweetValue)) {
return StringUtil.str2listOflong(sweetValue);
}
if (erUnprovideridsList != null) {
return erUnprovideridsList;
}
LOG.info("DynConfigProp: erUnProviderIds is not config, use the default value!");
return Constant.UNPROVIDERIDS;
}
/**
* 门票过期退: 无线渠道开关
*
* @return boolean
*/
public boolean getErDistChnl() {
String sweetValue = ZooKeeperConfigProperties.getProperties(ER_DISTCHNL);
if (!StringUtils.isEmpty(sweetValue)) {
return Boolean.valueOf(sweetValue);
}
return erDistchnl;
}
/**
* 门票过期退: 分销渠道开关
*
* @return boolean
*/
public boolean getErDistCode() {
String sweetValue = ZooKeeperConfigProperties.getProperties(ER_DISTCODE);
if (!StringUtils.isEmpty(sweetValue)) {
return Boolean.valueOf(sweetValue);
}
return erDistcode;
}
/**
* 门票过期退: 分销渠道CODE
*
* @return List<String>
*/
public List<String> getErDistChnlCodes() {
String sweetValue = ZooKeeperConfigProperties.getProperties(ER_DISTCHNLCODES);
if (!StringUtils.isEmpty(sweetValue)) {
return StringUtil.str2list(sweetValue);
}
if (erDistchnlcodesList != null) {
return erDistchnlcodesList;
}
LOG.info("DynConfigProp: erDistChnlCodes is not config, use the default value!");
return Constant.DIST_CHNL_CODES;
}
/**
* 门票过期退: 无线渠道
*
* @return List<Long>
*/
public List<Long> getErDistChnlVals() {
String sweetValue = ZooKeeperConfigProperties.getProperties(ER_DISTCHNL_VALS);
if (!StringUtils.isEmpty(sweetValue)) {
return StringUtil.str2listOflong(sweetValue);
}
if (erDistchnlvalsList != null) {
return erDistchnlvalsList;
}
LOG.info("DynConfigProp: erDistChnlVals is not config, use the default value!");
return Constant.DIST_CHNL_VALS;
}
/**
* 过期退页面刷新时间
*
* @return int
*/
public int getErPageRefreshTime() {
String sweetValue = ZooKeeperConfigProperties.getProperties(ER_PAGE_REFRESH_TIME);
if (!StringUtils.isEmpty(sweetValue)) {
return Integer.valueOf(sweetValue);
}
return erPageRefreshTime;
}
/**
* 数据列表最大ROWNUM
*
* @return int
*/
public int getErRownumMax() {
String sweetValue = ZooKeeperConfigProperties.getProperties(ER_ROWNUM_MAX);
if (!StringUtils.isEmpty(sweetValue)) {
return Integer.valueOf(sweetValue);
}
return erRownumMax;
}
public static DynConfigProp getInstance() {
return dynConfigProp;
}
}
| true |
67ae3b01660d73989038e15df73de7338788c584 | Java | qatestuser2019/Fieldbook | /src/main/java/com/efficio/fieldbook/util/labelprinting/CSVLabelGenerator.java | UTF-8 | 6,091 | 1.929688 | 2 | [] | no_license | package com.efficio.fieldbook.util.labelprinting;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.generationcp.commons.pojo.ExportColumnHeader;
import org.generationcp.commons.pojo.ExportRow;
import org.generationcp.commons.service.GermplasmExportService;
import org.generationcp.middleware.domain.fieldbook.FieldMapLabel;
import org.generationcp.middleware.domain.fieldbook.FieldMapTrialInstanceInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import com.efficio.fieldbook.service.LabelPrintingServiceImpl;
import com.efficio.fieldbook.web.common.exception.LabelPrintingException;
import com.efficio.fieldbook.web.label.printing.bean.StudyTrialInstanceInfo;
import com.efficio.fieldbook.web.label.printing.bean.UserLabelPrinting;
import com.efficio.fieldbook.web.util.SettingsUtil;
@Component
public class CSVLabelGenerator implements LabelGenerator {
private static final Logger LOG = LoggerFactory.getLogger(CSVLabelGenerator.class);
@Resource
private GermplasmExportService germplasmExportService;
@Resource
private LabelPrintingUtil labelPrintingUtil;
@Override
public String generateLabels(final List<StudyTrialInstanceInfo> trialInstances, final UserLabelPrinting userLabelPrinting) throws LabelPrintingException {
final String fileName = userLabelPrinting.getFilenameDLLocation();
String mainSelectedFields = userLabelPrinting.getMainSelectedLabelFields();
final boolean includeHeader =
LabelPrintingServiceImpl.INCLUDE_NON_PDF_HEADERS.equalsIgnoreCase(userLabelPrinting.getIncludeColumnHeadinginNonPdf());
final boolean isBarcodeNeeded = LabelPrintingServiceImpl.BARCODE_NEEDED.equalsIgnoreCase(userLabelPrinting.getBarcodeNeeded());
mainSelectedFields = this.labelPrintingUtil.appendBarcode(isBarcodeNeeded, mainSelectedFields);
final List<Integer> selectedFieldIDs = SettingsUtil.parseFieldListAndConvertToListOfIDs(mainSelectedFields);
final List<ExportColumnHeader> exportColumnHeaders =
this.generateColumnHeaders(selectedFieldIDs, this.labelPrintingUtil.getLabelHeadersFromTrialInstances(trialInstances));
final List<ExportRow> exportRows =
this.generateRows(trialInstances, selectedFieldIDs, userLabelPrinting);
try {
this.germplasmExportService.generateCSVFile(exportRows, exportColumnHeaders, fileName, includeHeader);
} catch (final IOException e) {
throw new LabelPrintingException(e);
}
return fileName;
}
private List<ExportRow> generateRows(final List<StudyTrialInstanceInfo> trialInstances, final List<Integer> selectedFieldIDs,
final UserLabelPrinting userLabelPrinting) {
final List<ExportRow> exportRows = new ArrayList<>();
final String firstBarcodeField = userLabelPrinting.getFirstBarcodeField();
final String secondBarcodeField = userLabelPrinting.getSecondBarcodeField();
final String thirdBarcodeField = userLabelPrinting.getThirdBarcodeField();
final boolean generateAutomatically = (userLabelPrinting.getBarcodeGeneratedAutomatically()
.equalsIgnoreCase(LabelPrintingServiceImpl.BARCODE_GENERATED_AUTOMATICALLY)) ? true : false;
// we populate the info now
for (final StudyTrialInstanceInfo trialInstance : trialInstances) {
final FieldMapTrialInstanceInfo fieldMapTrialInstanceInfo = trialInstance.getTrialInstance();
final Map<String, String> moreFieldInfo = this.labelPrintingUtil.generateAddedInformationField(fieldMapTrialInstanceInfo, trialInstance, "");
for (final FieldMapLabel fieldMapLabel : fieldMapTrialInstanceInfo.getFieldMapLabels()) {
final String barcodeLabelForCode;
if (!generateAutomatically ) {
barcodeLabelForCode = this.labelPrintingUtil
.generateBarcodeField(moreFieldInfo, fieldMapLabel, firstBarcodeField, secondBarcodeField, thirdBarcodeField,
fieldMapTrialInstanceInfo.getLabelHeaders(), false);
} else {
barcodeLabelForCode = fieldMapLabel.getObsUnitId();
}
moreFieldInfo.put(LabelPrintingServiceImpl.BARCODE, barcodeLabelForCode);
final ExportRow row =
this.generateExportRow(fieldMapTrialInstanceInfo.getLabelHeaders(), selectedFieldIDs, moreFieldInfo, fieldMapLabel);
exportRows.add(row);
}
}
return exportRows;
}
private List<ExportColumnHeader> generateColumnHeaders(final List<Integer> selectedFieldIDs, final Map<Integer, String> labelHeaders) {
final List<ExportColumnHeader> columnHeaders = new ArrayList<>();
for (final Integer selectedFieldID : selectedFieldIDs) {
final String headerName = this.labelPrintingUtil.getColumnHeader(selectedFieldID, labelHeaders);
final ExportColumnHeader columnHeader = new ExportColumnHeader(selectedFieldID, headerName, true);
columnHeaders.add(columnHeader);
}
return columnHeaders;
}
private ExportRow generateExportRow(final Map<Integer, String> labelHeaders, final List<Integer> selectedFieldIDs,
final Map<String, String> moreFieldInfo, final FieldMapLabel fieldMapLabel) {
final ExportRow exportRow = new ExportRow();
for (final Integer selectedFieldID : selectedFieldIDs) {
try {
final String value = this.labelPrintingUtil.getValueFromSpecifiedColumn(moreFieldInfo, fieldMapLabel, selectedFieldID, labelHeaders, false);
exportRow.addColumnValue(selectedFieldID, value);
} catch (final NumberFormatException e) {
CSVLabelGenerator.LOG.error(e.getMessage(), e);
}
}
return exportRow;
}
}
| true |
2d8ac18dd869f91b164c49cfe4430125c878d9fb | Java | League-level3-student/level3-module1-cheetah676 | /src/_03_IntroToStacks/_03_TestMatchingBrackets.java | UTF-8 | 1,416 | 3.515625 | 4 | [] | no_license | package _03_IntroToStacks;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.util.Stack;
import org.junit.Test;
public class _03_TestMatchingBrackets {
@Test
public void testMatchingBrackets() {
assertTrue(doBracketsMatch("{}"));
assertTrue(doBracketsMatch("{{}}"));
assertTrue(doBracketsMatch("{}{}{{}}"));
assertFalse(doBracketsMatch("{{}"));
assertFalse(doBracketsMatch("}{"));
}
// USE A STACK TO COMPLETE THE METHOD FOR CHECKING IF EVERY OPENING BRACKET HAS
// A MATCHING CLOSING BRACKET
private boolean doBracketsMatch(String b) {
boolean matchingBrackets = false;
Stack<Character> brackets = new Stack<Character>();
Stack<Character> check = new Stack<Character>();
for (int i = 0; i < b.length(); i++) {
char letter = b.charAt(i);
brackets.push(letter);
}
for (int i = 0; i < b.length(); i++) {
if (!brackets.isEmpty()) {
Character newBracket = brackets.pop();
if (newBracket == '}') {
check.push(newBracket);
} else if (!check.isEmpty() && newBracket == '{') {
check.pop();
} else if (check.isEmpty() && newBracket == '{') {
matchingBrackets = false;
check.push(newBracket);
break;
}
}
}
if (check.isEmpty()) {
matchingBrackets = true;
}
System.out.println(matchingBrackets);
return matchingBrackets;
}
} | true |
f24a48362035e3dd9ee6ced7f04783be0d593a5d | Java | zhoujun0920/leetcode_java | /76_minimum_window_substring.java | UTF-8 | 2,039 | 2.9375 | 3 | [] | no_license | class Solution {
public String minWindow(String s, String t) {
Map<Character, Integer> window = new HashMap<>();
Map<Character, Integer> remains = new HashMap<>();
int m = Integer.MAX_VALUE;
int maxStart = 0;
int maxEnd = 0;
char[] sArray = s.toCharArray();
for (Character c : t.toCharArray()) {
if (window.containsKey(c)) {
window.put(c, window.get(c) + 1);
} else {
window.put(c, 1);
remains.put(c, 1);
}
}
int startIndex = 0;
while (startIndex < sArray.length) {
char c = sArray[startIndex];
if (window.containsKey(c)) {
break;
}
startIndex++;
}
for (int i = startIndex; i < sArray.length; i++) {
char c = sArray[i];
if (window.containsKey(c)) {
int res = window.get(c) - 1;
window.put(c, res);
if (res <= 0) {
remains.remove(c);
} else {
remains.put(c, 1);
}
if (remains.keySet().size() == 0) {
if (i - startIndex < m) {
maxStart = startIndex;
maxEnd = i;
}
char sa = sArray[startIndex++];
int res2 = window.get(sa) + 1;
window.put(sa, res2);
if (res2 > 0) {
remains.put(sa, 1);
}
while (startIndex <= i) {
char ss = sArray[startIndex];
if (window.containsKey(ss)) {
if (window.get(ss) == 0) {
if (remains.keySet().size() == 0) {
if (i - startIndex < m) {
maxStart = startIndex;
maxEnd = i;
}
}
break;
} else {
window.put(ss, window.get(ss) + 1);
}
}
startIndex++;
}
}
}
}
return s.substring(maxStart, maxEnd + 1);
}
}
| true |
3c5434874b893730b212c03100134265715bbfe5 | Java | sameersyd/Spark | /app/src/main/java/com/haze/android/spark/HomeCustomAdapter.java | UTF-8 | 4,336 | 2.328125 | 2 | [] | no_license | package com.haze.android.spark;
import android.content.Context;
import android.support.design.widget.FloatingActionButton;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
public class HomeCustomAdapter extends BaseAdapter {
Context c;
HomeActivity delegate;
ArrayList<HomeSpacecraft> spacecrafts = new ArrayList<>();
ArrayList<HomeSpacecraft> originalList = new ArrayList<>();
public HomeCustomAdapter(Context c) {
this.c = c;
}
@Override
public int getCount() {
return spacecrafts.size();
}
@Override
public Object getItem(int position) {
return spacecrafts.get(spacecrafts.size() - position - 1); // Existing Code Modified To Display Recent Top
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
if(convertView==null)
{
convertView= LayoutInflater.from(c).inflate(R.layout.home_display,parent,false);
}
TextView tvName = (TextView)convertView.findViewById(R.id.home_name);
TextView tvAge = (TextView)convertView.findViewById(R.id.home_age);
TextView tvPhn = (TextView)convertView.findViewById(R.id.home_phn);
TextView status = (TextView)convertView.findViewById(R.id.home_status);
TextView fbLink = (TextView)convertView.findViewById(R.id.home_fbLink);
TextView instaLink = (TextView)convertView.findViewById(R.id.home_instaLink);
TextView snapLink = (TextView)convertView.findViewById(R.id.home_snapLink);
TextView email = (TextView)convertView.findViewById(R.id.home_email);
TextView city = (TextView)convertView.findViewById(R.id.home_city);
TextView country = (TextView)convertView.findViewById(R.id.home_country);
TextView uid = (TextView)convertView.findViewById(R.id.home_uid);
ImageView imgProfile = (ImageView)convertView.findViewById(R.id.home_profile_pic);
//FloatingActionButton viewFab = (FloatingActionButton)convertView.findViewById(R.id.home_view_fab);
HomeSpacecraft s = (HomeSpacecraft) this.getItem(position);
tvName.setText(s.getName());
tvAge.setText(s.getAge());
tvPhn.setText(s.getPhn());
status.setText(s.getStatus());
fbLink.setText(s.getFbLink());
instaLink.setText(s.getInstaLink());
snapLink.setText(s.getSnapLink());
email.setText(s.getEmail());
city.setText(s.getCity());
country.setText(s.getCountry());
uid.setText(s.getUid());
Glide.with(c).load(s.getProfile_pic()).into(imgProfile);
// viewFab.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View view) {
//
// }
// });
//ONITECLICK
imgProfile.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int pos = position;
delegate.displayUser(pos);
}
});
convertView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});
return convertView;
}
public ArrayList<HomeSpacecraft> sortByVotes(ArrayList<HomeSpacecraft> list){
Collections.sort(list,ageComparator);
return list;
}
public static Comparator<HomeSpacecraft> ageComparator = new Comparator<HomeSpacecraft>() {
@Override
public int compare(HomeSpacecraft user1, HomeSpacecraft user2) {
return (Integer.parseInt(user2.getAge()) < Integer.parseInt(user1.getAge()) ? -1 :
(Integer.parseInt(user2.getAge()) == Integer.parseInt(user1.getAge()) ? 0 : 1));
}
};
public void update(ArrayList<HomeSpacecraft> list){
originalList = spacecrafts;
spacecrafts.clear();
spacecrafts.addAll(sortByVotes(list));
notifyDataSetChanged();
}
}
| true |
a89400906d1a17020fc0b14547f573b3d491132d | Java | Zenika/wicket-validation | /src/test/java/com/zenika/wicket/contrib/test/bean/SuperBeanObject.java | UTF-8 | 1,220 | 2.671875 | 3 | [] | no_license | package com.zenika.wicket.contrib.test.bean;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
/**
* @author ophelie (zenika)
*
*/
public abstract class SuperBeanObject {
@NotNull(groups = ValidationGroup.class)
@Size(groups = ValidationGroup.class, max = 5)
private String string;
/**
* {@inheritDoc}
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!(obj instanceof SuperBeanObject))
return false;
SuperBeanObject other = (SuperBeanObject) obj;
if (string == null) {
if (other.string != null)
return false;
} else if (!string.equals(other.string))
return false;
return true;
}
/**
* @return string
*/
public String getString() {
return string;
}
/**
* {@inheritDoc}
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((string == null) ? 0 : string.hashCode());
return result;
}
/**
* @param string
* , string
*/
public void setString(String string) {
this.string = string;
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
return "SuperBeanObject [string=" + string + "]";
}
}
| true |
ceca9d712b3538fc433cb40b8e29b908f2a4e770 | Java | JackChan1999/boohee_v5.6 | /src/main/java/com/xiaomi/push/service/ai.java | UTF-8 | 398 | 1.65625 | 2 | [
"Apache-2.0"
] | permissive | package com.xiaomi.push.service;
import com.xiaomi.push.service.XMPushService.e;
class ai extends e {
final /* synthetic */ XMPushService a;
ai(XMPushService xMPushService, int i) {
this.a = xMPushService;
super(i);
}
public void a() {
this.a.a(18, null);
}
public String b() {
return "disconnect because of connecting timeout";
}
}
| true |
71605c9985b10471808614bc11c480a1217541b4 | Java | Lenny-Zh/AlgorithmsADay | /ZCYAlgo/src/main/java/cp1_StkAndQue/q2_queueby2stk/Test.java | UTF-8 | 1,056 | 3.46875 | 3 | [] | no_license | package cp1_StkAndQue.q2_queueby2stk;
/**
* 编写一个类,用两个栈实现队列,支持队列的基本操作(add、poll、peek)。
* <p>
* 难度 : 尉 2
*/
public class Test {
public static void main(String[] args) {
CQueue03 queue01 = new CQueue03();
int total = 20;
int cnt = 5;
while (cnt-- > 0) {
int num = Long.valueOf(Math.round(Math.random() * total)).intValue();
System.out.println("in: " + num);
queue01.appendTail(num);
}
cnt = 2;
while (cnt-- > 0) {
int num = queue01.deleteHead();
System.out.println("out: " + num);
}
cnt = 3;
while (cnt-- > 0) {
int num = Long.valueOf(Math.round(Math.random() * total)).intValue();
System.out.println("in: " + num);
queue01.appendTail(num);
}
cnt = 5;
while (cnt-- > 0) {
int num = queue01.deleteHead();
System.out.println("out: " + num);
}
}
}
| true |
350a2e2a4d01e0c455c36ff6b110057f2cc139fb | Java | malex20d/pecl_final | /PECL_Final/src/pecl_final/Tobogan.java | UTF-8 | 2,654 | 2.890625 | 3 | [] | no_license | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package pecl_final;
import java.util.ArrayList;
/**
*
* @author alex
*/
public class Tobogan {
private ArrayList<Ninno> ninnosEsperando = new ArrayList<>();
private boolean ocupado = false;
private ParqueInfantil parque;
private int edadTobogan;
private boolean expulsar = false;
public Tobogan(ParqueInfantil parqueInfantil) {
parque = parqueInfantil;
}
public synchronized void entrarTobogan(Ninno ninno) throws InterruptedException {
while (ocupado) {
System.out.println(ninno.getName()+" esperando para entrar al tobogan");
ninnosEsperando.add(ninno);
parque.getjTextColaTobogan().setText(ArrayListToString(ninnosEsperando));
wait();
}
if(ninnosEsperando.contains(ninno)) {
ninnosEsperando.remove(ninno);
parque.getjTextColaTobogan().setText(ArrayListToString(ninnosEsperando));
}
ocupado = true;
edadTobogan = ninno.getEdad();
parque.getjTextNinnoMontadoTobogan().setText(ninno.getName());
parque.getjTextEdadNinnoMontadoTobogan().setText(String.valueOf(ninno.getEdad()));
System.out.println(ninno.getName()+"esta subiendo al tobogan");
Thread.sleep(1200);
}
public void montarEnTobogan(Ninno ninno) throws InterruptedException{
System.out.println(ninno.getName()+" montando en tobogan");
if (!(expulsar && ninno.getEdad()>7)) {
Thread.sleep(500);
}
expulsar = false;
}
public synchronized void salirTobogan(Ninno ninno) {
System.out.println(ninno.getName()+" sale del tobogan");
ocupado = false;
parque.getjTextEdadNinnoMontadoTobogan().setText("");
parque.getjTextNinnoMontadoTobogan().setText("");
notify();
}
public String ArrayListToString (ArrayList<Ninno> ninnos) {
String s = "";
for (int i = 0; i < ninnos.size(); i++) {
if (i==0) {
s= s+ninnos.get(i).getName();
} else {
s = s+", "+ninnos.get(i).getName();
}
}
return s;
}
public int getEdadTobogan() {
return edadTobogan;
}
public void setExpulsar(boolean expulsar) {
this.expulsar = expulsar;
}
public ArrayList<Ninno> getNinnosEsperando() {
return ninnosEsperando;
}
}
| true |
a8055b40d7cc3af467c287dd4e457d57f8aff356 | Java | zhengqun1029/personal-base | /common/src/main/java/com/personal/common/base/exception/BusinessException.java | UTF-8 | 1,364 | 2.28125 | 2 | [] | no_license | package com.personal.common.base.exception;
import com.personal.common.base.enums.ReturnCodeEnum;
/**
* @Title: BusinessException.class
* @Package: com.pay.fee.org.ssm.zhb.common.basic.exception
* @Descriptiom: 业务处理异常
* @author: zhenghanbin
* @date 2018/1/31 11:07
*/
public class BusinessException extends BaseException {
public BusinessException(int errorCode, String errorMsg) {
super(errorCode, errorMsg);
}
public BusinessException(ReturnCodeEnum returnCode, String errorMsg) {
super(returnCode.getKey(), errorMsg);
}
public BusinessException(int errorCode) {
super(errorCode);
}
public BusinessException(ReturnCodeEnum returnCode) {
super(returnCode.getKey(), returnCode.getRemark());
}
public BusinessException(String errorMsg) {
super(errorMsg);
}
public BusinessException(Throwable cause, int errorCode, String errorMsg,
String traceId) {
super(cause, errorCode, errorMsg, traceId);
}
public BusinessException(Throwable cause, int errorCode, String errorMsg) {
super(cause, errorCode, errorMsg);
}
public BusinessException(Throwable cause, String errorMsg) {
super(cause, errorMsg);
}
public BusinessException(Throwable cause) {
super(cause);
}
}
| true |
bccba13fcba5d4cfbe7fe5d0a17296811de037f6 | Java | the-lazy-val/leetcode-premium | /google-frequency/trie/720_longest_word_in_dict.java | UTF-8 | 1,659 | 3.671875 | 4 | [] | no_license | /**
My solution:
Sort array and then Trie
keep count of incremental chars while filling words
*/
class Solution {
class TrieNode{
boolean isWord;
TrieNode[] children;
public TrieNode(){
children = new TrieNode[26];
}
}
public Pair<Integer, String> addWord(TrieNode root, String word){
int count=1;
for(int i=0; i<word.length(); i++){
char c = word.charAt(i);
if(root.children[c-'a']==null){
TrieNode temp = new TrieNode();
if(i==word.length()-1) temp.isWord=true;
root.children[c-'a'] = temp;
}else if(root.children[c-'a'].isWord){
count++;
}
root=root.children[c-'a'];
}
// System.out.println("Word: "+word+" , count:"+count);
if(count!=word.length()) count=0;
return new Pair(count, word);
}
public String longestWord(String[] words) {
int max = 0;
String maxString = "";
Arrays.sort(words);
TrieNode root = new TrieNode();
for(String w : words){
TrieNode temp = root;
Pair<Integer, String> pair = addWord(temp, w);
if(pair.getKey() == max){
if(maxString.compareTo(pair.getValue()) > 0){
maxString=pair.getValue();
}
}
if(pair.getKey() > max){
max=pair.getKey();
maxString=pair.getValue();
}
}
return maxString;
}
}
| true |
a52f7b975deb2991ea24777f6a4eb81c80251522 | Java | SunJunipero/JavaSE | /generics/init/src/main/java/GenericClassExample.java | UTF-8 | 1,451 | 4.0625 | 4 | [] | no_license | import java.util.*;
public class GenericClassExample {
public static void main(String[] args) {
Example<String> stringExample = new Example<String>("string");
Example<Integer> integerExample = new Example<Integer>(42);
System.out.println("stringExample - " + stringExample.getT());
System.out.println("integerExample - " + integerExample.getT());
System.out.println(" \n\t\tArrayList<Example<String>>");
ArrayList<Example<String>> examples = new ArrayList<>();
examples.add(new Example<>("Alex"));
examples.add(new Example<>("Jamie"));
examples.add(new Example<>("Miles"));
examples.add(new Example<>("Math"));
examples.get(0).Sett("Alex Turner");
for (Example<String> example : examples) {
System.out.println(example.getT());
}
/**
* If we type this - "Example stringExample1 = new Example<String>() "
* Return type of example will be object
*/
System.out.println(" \n\t\tExample stringExample1 = new Example<String>()");
Example stringExample1 = new Example<String>();
stringExample1.Sett(12222);
System.out.println(stringExample1.getT());
}
}
class Example <T>{
private T t;
Example(){
}
Example (T t){
this.t = t;
}
public void Sett(T t){
this.t = t;
}
public T getT(){
return t;
}
}
| true |
d9d392171127cf39476afcdd4671006113cb72df | Java | peiyuxin/common-libs | /src/main/java/com/sm/common/libs/pool/BatchBuffer.java | UTF-8 | 2,512 | 2.625 | 3 | [
"Apache-2.0"
] | permissive | /**
*
*/
package com.sm.common.libs.pool;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
/**
* 批量的缓冲池
*
* @author <a href="chenxu.xc@alibaba-inc.com">xc</a>
* @version create on 2016年11月17日 下午1:45:04
* @param <T>
*/
public class BatchBuffer<T extends Keyable<String>> implements Buffer<T> {
/**
* 缓冲池集
*/
private List<Buffer<T>> buffers = new ArrayList<>();
/**
* 缓冲池映射表
*/
private final Map<String, Buffer<T>> bufferMap = new HashMap<>();
/**
* 缓冲池名称
*/
private String name;
/**
* 是否激活
*/
private boolean active;
public BatchBuffer() {
this.name = this.getClass().getSimpleName();
}
public BatchBuffer(String name) {
this.name = name;
}
@Override
public void start() throws Exception {
for (Buffer<T> buffer : buffers) {
buffer.start();
}
active = true;
}
@Override
public void stop() throws Exception {
for (Buffer<T> buffer : buffers) {
buffer.stop();
}
active = false;
}
/**
* 添加缓冲池 @see Buffer
*
* @param buffer 缓冲池
*/
public void add(Buffer<T> buffer) {
buffers.add(buffer);
bufferMap.put(buffer.getName(), buffer);
}
@Override
public boolean add(T record) {
Buffer<T> buffer = bufferMap.get(record.getId());
return (buffer == null) ? false : buffer.add(record);
}
@Override
public boolean add(T record, long timeout, TimeUnit unit) {
Buffer<T> buffer = bufferMap.get(record.getId());
return (buffer == null) ? false : buffer.add(record, timeout, unit);
}
/**
* 清理
*/
public void clean() {
buffers.clear();
bufferMap.clear();
}
/**
* 移除缓冲池
*
* @param key 缓冲池的Key
*/
public void remove(String key) {
Buffer<T> buffer = bufferMap.remove(key);
if (buffer != null) {
buffers.remove(buffer);
}
}
/**
* 移除缓冲池
*
* @param buffer 缓冲池 @see Buffer
*/
public void remove(Buffer<T> buffer) {
buffers.remove(buffer);
bufferMap.remove(buffer.getName());
}
@Override
public String getName() {
return name;
}
public void setBuffers(List<Buffer<T>> buffers) {
this.buffers = buffers;
for (Buffer<T> buffer : buffers) {
bufferMap.put(buffer.getName(), buffer);
}
}
@Override
public boolean isActive() {
return active;
}
}
| true |
dd0b3e8a42d085a6a10c915038998a5f860616fe | Java | dechengyang/ydc_java_shop | /ydc_java_shop/app/src/main/java/com/ydcjavashop/shop/account/model/LoginAbstractModel.java | UTF-8 | 541 | 1.96875 | 2 | [] | no_license | package com.ydcjavashop.shop.account.model;
import com.ydc.mvp.model.BaseMvpModel;
import com.ydc.networkservice.bean.Feed;
import com.ydcjavashop.shop.account.bean.TokenBean;
import java.util.Map;
import rx.Observable;
/**
* ydc 获取数据的逻辑模块协议,也可以是接口,提供给P调用,在callback中更新V
* Created by Administrator on 2017/7/6.
*/
public abstract class LoginAbstractModel extends BaseMvpModel {
public abstract Observable<Feed<TokenBean>> login(String url, Map<String, String> params);
}
| true |
cc4f25306db06cda7a750b3285127a57fea992d3 | Java | abhisheknn/click-game | /game/src/main/java/com/micro/game/rest/UserControllerImpl.java | UTF-8 | 854 | 1.835938 | 2 | [] | no_license | package com.micro.game.rest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
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.RestController;
import com.micro.game.pojo.User;
import com.micro.game.service.UserService;
@RestController
@RequestMapping("/users")
public class UserControllerImpl implements UserController {
@Override
public void send(String topic, User user) {
// TODO Auto-generated method stub
}
@Override
public void recive(String policy) {
// TODO Auto-generated method stub
}
}
| true |
27c60da8bafd6e5e20f18104cdc09b897cb6c21b | Java | ukman/DataGrig | /src/main/java/com/datagrig/AppConfig.java | UTF-8 | 692 | 1.625 | 2 | [] | no_license | package com.datagrig;
import java.io.File;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import lombok.experimental.FieldNameConstants;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import com.datagrig.cache.CacheConfig;
import lombok.Data;
@ConfigurationProperties("datagrig")
@Data
@Component
@EnableWebMvc
@FieldNameConstants
public class AppConfig {
private File folder;
private String rebootPassword;
private String[] labelColumnNames;
}
| true |
29da9002d0a921dfb08fb4d37d4f2b730539e09b | Java | Marvel-cx/SchoolServer | /src/com/example/daoImpl/handleDaoImpl.java | UTF-8 | 9,880 | 2.15625 | 2 | [] | no_license | package com.example.daoImpl;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import com.example.dao.handleDao;
import com.example.db.DBConnection;
import com.example.vo.AlarmInfo;
import com.example.vo.CustomerVo;
import com.example.vo.PageVo;
import com.example.vo.TempData;
public class handleDaoImpl implements handleDao{
private Connection conn;
private PreparedStatement pst;
private ResultSet res;
public int saveCustomer(CustomerVo vo) throws Exception {
String sql="insert into student values(?,?,?,?,?,?)";
DBConnection db=new DBConnection();
conn=db.getConnection();
pst=conn.prepareStatement(sql);
pst.setInt(1,vo.getCusno());
pst.setString(2,vo.getCusName());
pst.setInt(3,vo.getAge());
pst.setDate(4,vo.getBirthday());
pst.setInt(5,vo.getSal());
pst.setString(6,vo.getAddress());
int i=pst.executeUpdate();
conn.close();
return i;
}
public int saveAlrmInfo(String recordNo, String result) throws Exception {
// TODO Auto-generated method stub
String sql="update alarminfo set handleSta='已处理',result='"+result+"' where recordNo='"+recordNo+"'";
DBConnection db=new DBConnection();
conn=db.getConnection();
pst=conn.prepareStatement(sql);
int i=pst.executeUpdate();
conn.close();
return i;
}
//delete
public int DeleteCustomer(Integer cusno) throws Exception {
String sql="delete from student where cusno=?";
DBConnection db=new DBConnection();
conn=db.getConnection();
pst=conn.prepareStatement(sql);
pst.setInt(1,cusno);
int i=pst.executeUpdate();
conn.close();
return i;
}
//update
public int updataCustomer(CustomerVo vo) throws Exception {
String sql="update student set cusName=?,age=?,birthday=?,sal=?,address=?where cusno=?";
DBConnection db=new DBConnection();
conn=db.getConnection();
pst=conn.prepareStatement(sql);
pst.setString(1,vo.getCusName());
pst.setInt(2,vo.getAge());
pst.setDate(3,vo.getBirthday());
pst.setInt(4,vo.getSal());
pst.setString(5,vo.getAddress());
pst.setInt(6,vo.getCusno());
int i=pst.executeUpdate();
conn.close();
return i;
}
//select
public CustomerVo selectByCusNo(int cusno) throws Exception {
String sql="select cusno,cusName,age,birthday,sal,address from student where cusno=?";
DBConnection db=new DBConnection();
conn=db.getConnection();
pst=conn.prepareStatement(sql);
pst.setInt(1,cusno);
res=pst.executeQuery();
CustomerVo cus=null;
if(res.next()){
cus=new CustomerVo();
cus.setCusno(res.getInt(1));
cus.setCusName(res.getString(2));
cus.setAge(res.getInt(3));
cus.setBirthday(res.getDate(4));
cus.setSal(res.getInt(5));
cus.setAddress(res.getString(6));
}
conn.close();
return cus;
}
//selectAll
public List<AlarmInfo> selectAll() throws Exception {
List<AlarmInfo> list=new ArrayList<AlarmInfo>();
String sql="select a.recordNo,a.alarmTime,a.infraredSta,a.smokeSta,a.occupySta,a.tempSta,a.handleSta,a.result,f.school,f.detailBuilding,f.detailFloor,f.gender,f.siteNum,f.securityNo from alarminfo a,fenbuinfo f where a.device_id=f.deviceID order by a.alarmTime desc limit 0,10;";
DBConnection db=new DBConnection();
conn=db.getConnection();
pst=conn.prepareStatement(sql);
res=pst.executeQuery();
while(res.next()){
AlarmInfo alarmInfo=new AlarmInfo();
alarmInfo.setRecordNo(res.getString(1));
alarmInfo.setAlarmTime(res.getString(2));
alarmInfo.setInfraredSta(res.getString(3));
alarmInfo.setSmokeSta(res.getString(4));
alarmInfo.setOccupySta(res.getString(5));
alarmInfo.setTempSta(res.getString(6));
alarmInfo.setHandleSta(res.getString(7));
alarmInfo.setResult(res.getString(8));
alarmInfo.setSchool(res.getString(9));
alarmInfo.setDetailBuilding(res.getString(10));
alarmInfo.setDetailFloor(res.getString(11));
alarmInfo.setGender(res.getString(12));
alarmInfo.setSiteNum(res.getString(13));
alarmInfo.setSecurityNo(res.getString(14));
list.add(alarmInfo);
}
conn.close();
return list;
}
//根据时间查询
public List<AlarmInfo> selectByTime(String date) throws Exception {
// TODO Auto-generated method stub
List<AlarmInfo> list=new ArrayList<AlarmInfo>();
String sql="select a.recordNo,a.alarmTime,a.infraredSta,a.smokeSta,a.occupySta,a.tempSta,a.handleSta,a.result,f.school,f.detailBuilding,f.detailFloor,f.gender,f.siteNum,f.securityNo from alarminfo a,fenbuinfo f where a.device_id=f.deviceID and substring(a.alarmTime,1,10)='"+date+"' order by alarmTime desc;";
DBConnection db=new DBConnection();
conn=db.getConnection();
pst=conn.prepareStatement(sql);
res=pst.executeQuery();
if(res.next()){
res.previous();
while(res.next()){
AlarmInfo alarmInfo=new AlarmInfo();
alarmInfo.setRecordNo(res.getString(1));
alarmInfo.setAlarmTime(res.getString(2));
alarmInfo.setInfraredSta(res.getString(3));
alarmInfo.setSmokeSta(res.getString(4));
alarmInfo.setOccupySta(res.getString(5));
alarmInfo.setTempSta(res.getString(6));
alarmInfo.setHandleSta(res.getString(7));
alarmInfo.setResult(res.getString(8));
alarmInfo.setSchool(res.getString(9));
alarmInfo.setDetailBuilding(res.getString(10));
alarmInfo.setDetailFloor(res.getString(11));
alarmInfo.setGender(res.getString(12));
alarmInfo.setSiteNum(res.getString(13));
alarmInfo.setSecurityNo(res.getString(14));
list.add(alarmInfo);
}
}else{
list=null;
}
conn.close();
return list;
}
public List<CustomerVo> FenYeSelect(PageVo vo) throws Exception {
String sql="select cusno,cusName,age,birthday,sal,address from student limit ?,?";
DBConnection db=new DBConnection();
conn=db.getConnection();
pst=conn.prepareStatement(sql);
pst.setInt(1,vo.getOffset());
pst.setInt(2,vo.getPageSize());
res=pst.executeQuery();
List<CustomerVo> list=new ArrayList<CustomerVo>();
while(res.next()){
CustomerVo cus=new CustomerVo();
cus.setCusno(res.getInt(1));
cus.setCusName(res.getString(2));
cus.setAge(res.getInt(3));
cus.setBirthday(res.getDate(4));
cus.setSal(res.getInt(5));
cus.setAddress(res.getString(6));
list.add(cus);
}
conn.close();
return list;
}
public int selectTotal() throws Exception {
String sql="select count(*) as count from student";
DBConnection db=new DBConnection();
conn=db.getConnection();
pst=conn.prepareStatement(sql);
res=pst.executeQuery();
int total=0;
if(res.next()){
total=res.getInt("count");
}
return total;
}
public List<TempData> selectData() throws Exception {
List<TempData> list=new ArrayList<TempData>();
String sql="select * from school.temp_data order by temp_data_id desc limit 1;";
DBConnection db=new DBConnection();
conn=db.getConnection();
pst=conn.prepareStatement(sql);
res=pst.executeQuery();
while(res.next()){
TempData tempData=new TempData();
tempData.setTemp_id(res.getString(1));
tempData.setDevice_id(res.getString(2));
tempData.setTl(res.getString(3));
tempData.setTh1(res.getString(4));
tempData.setVer(res.getString(5));
tempData.setTvoc(res.getString(6));
tempData.setDb(res.getString(7));
tempData.setD1_1(res.getString(8));
tempData.setD1_2(res.getString(9));
tempData.setD1_3(res.getString(10));
tempData.setD1_4(res.getString(11));
tempData.setD1_5(res.getString(12));
tempData.setD1_6(res.getString(13));
tempData.setD1_7(res.getString(14));
tempData.setD1_8(res.getString(15));
tempData.setD2_1(res.getString(16));
tempData.setD2_2(res.getString(17));
tempData.setD2_3(res.getString(18));
tempData.setD2_4(res.getString(19));
tempData.setD2_5(res.getString(20));
tempData.setD2_6(res.getString(21));
tempData.setD2_7(res.getString(22));
tempData.setD2_8(res.getString(23));
tempData.setD3_1(res.getString(24));
tempData.setD3_2(res.getString(25));
tempData.setD3_3(res.getString(26));
tempData.setD3_4(res.getString(27));
tempData.setD3_5(res.getString(28));
tempData.setD3_6(res.getString(29));
tempData.setD3_7(res.getString(30));
tempData.setD3_8(res.getString(31));
tempData.setD4_1(res.getString(32));
tempData.setD4_2(res.getString(33));
tempData.setD4_3(res.getString(34));
tempData.setD4_4(res.getString(35));
tempData.setD4_5(res.getString(36));
tempData.setD4_6(res.getString(37));
tempData.setD4_7(res.getString(38));
tempData.setD4_8(res.getString(39));
tempData.setD5_1(res.getString(40));
tempData.setD5_2(res.getString(41));
tempData.setD5_3(res.getString(42));
tempData.setD5_4(res.getString(43));
tempData.setD5_5(res.getString(44));
tempData.setD5_6(res.getString(45));
tempData.setD5_7(res.getString(46));
tempData.setD5_8(res.getString(47));
tempData.setD6_1(res.getString(48));
tempData.setD6_2(res.getString(49));
tempData.setD6_3(res.getString(50));
tempData.setD6_4(res.getString(51));
tempData.setD6_5(res.getString(52));
tempData.setD6_6(res.getString(53));
tempData.setD6_7(res.getString(54));
tempData.setD6_8(res.getString(55));
tempData.setD7_1(res.getString(56));
tempData.setD7_2(res.getString(57));
tempData.setD7_3(res.getString(58));
tempData.setD7_4(res.getString(59));
tempData.setD7_5(res.getString(60));
tempData.setD7_6(res.getString(61));
tempData.setD7_7(res.getString(62));
tempData.setD7_8(res.getString(63));
tempData.setD8_1(res.getString(64));
tempData.setD8_2(res.getString(65));
tempData.setD8_3(res.getString(66));
tempData.setD8_4(res.getString(67));
tempData.setD8_5(res.getString(68));
tempData.setD8_6(res.getString(69));
tempData.setD8_7(res.getString(70));
tempData.setD8_8(res.getString(71));
list.add(tempData);
}
conn.close();
return list;
}
}
| true |
2d6211dae997ae9287d0f24e68dd27eaa39e95ea | Java | javafunk/referee | /src/main/java/org/javafunk/referee/conversion/Coercion.java | UTF-8 | 170 | 1.570313 | 2 | [
"BSD-3-Clause",
"BSD-2-Clause"
] | permissive | package org.javafunk.referee.conversion;
import org.javafunk.funk.functors.functions.UnaryFunction;
public interface Coercion extends UnaryFunction<Object, Object> { }
| true |
a5d52c0de048ce6e4c343c8c7e7a61a1028c9071 | Java | dbwuc/desktop | /device_docking/src/main/java/com/hedian/entity/ElectricalProducCheck.java | UTF-8 | 1,903 | 2.046875 | 2 | [] | no_license | package com.hedian.entity;
import java.util.Date;
import com.baomidou.mybatisplus.annotations.TableField;
import com.baomidou.mybatisplus.activerecord.Model;
import com.baomidou.mybatisplus.annotations.TableName;
import java.io.Serializable;
import com.baomidou.mybatisplus.annotations.Version;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
/**
* <p>
* 特种设备机电检验表
* </p>
*
* @author HC
* @since 2021-02-07
*/
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@TableName("flow_nv_special_equipment_electrical_produc_check")
public class ElectricalProducCheck extends Model<ElectricalProducCheck> {
private static final long serialVersionUID = 1L;
/**
* id
*/
private String id;
/**
* 企业id
*/
@TableField("department_id")
private String departmentId;
/**
* 关联机电类id
*/
@TableField("electrical_id")
private String electricalId;
/**
* 检验日期
*/
@TableField("JYRQ")
private Date jyrq;
/**
* 下检日期
*/
@TableField("XJRQ")
private Date xjrq;
/**
* 是否可以删除标记:0 不能删除, 1可以删除, 默认 1
*/
@TableField("del_flag")
private Integer delFlag;
/**
* 使用标记:1 使用 0 不使用
*/
@TableField("use_flag")
private Integer useFlag;
/**
* 创建人ID
*/
@TableField("create_id")
private String createId;
/**
* 创建时间
*/
@TableField("create_time")
private Date createTime;
/**
* 修改人ID
*/
@TableField("modified_id")
private String modifiedId;
/**
* 修改时间
*/
@TableField("modified_time")
private Date modifiedTime;
@Override
protected Serializable pkVal() {
return this.id;
}
}
| true |
95724c7ba242717b306ed940803520f9d7888fc7 | Java | Angry-Pixel/The-Betweenlands | /src/main/java/thebetweenlands/api/sky/IRiftSkyRenderer.java | UTF-8 | 910 | 2.421875 | 2 | [] | no_license | package thebetweenlands.api.sky;
import net.minecraft.client.Minecraft;
import net.minecraft.client.multiplayer.WorldClient;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
public interface IRiftSkyRenderer {
/**
* Sets the sky's clear color
* @param partialTicks
* @param world
* @param mc
*/
@SideOnly(Side.CLIENT)
public void setClearColor(float partialTicks, WorldClient world, Minecraft mc);
/**
* Renders the sky inside the rift
* @param partialTicks
* @param world
* @param mc
*/
@SideOnly(Side.CLIENT)
public void render(float partialTicks, WorldClient world, Minecraft mc);
/**
* Returns the sky's relative brightness between 0 and 1
* @param partialTicks
* @param world
* @param mc
* @return
*/
@SideOnly(Side.CLIENT)
public float getSkyBrightness(float partialTicks, WorldClient world, Minecraft mc);
}
| true |
214646580a6210db4f05aa7ac853c13405d49b03 | Java | akskos/dvidder | /src/main/java/com/dvidder/validation/PostForm.java | UTF-8 | 853 | 2.140625 | 2 | [] | no_license | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.dvidder.validation;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotEmpty;
/**
*
* @author akseli
*/
public class PostForm {
@NotEmpty
@Length(min=1, max=666)
private String content;
private String tags;
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getTags() {
return tags;
}
public void setTags(String tags) {
this.tags = tags;
}
}
| true |
7c57dbfe3b1f65da306aa428b431b234f7bba024 | Java | adriano282/java_se8_hands_on_code | /Reference Static Method/TestClass.java | UTF-8 | 471 | 3.421875 | 3 | [] | no_license | interface A {
public static void print() {
System.out.println("From interface A");
}
}
abstract class B {
public static void print() {
System.out.println("From abstract class B");
}
}
class C extends B implements A{
public static void print() {
System.out.println("From concrete class C");
}
}
public class TestClass {
public static void main(String...args) {
A a = new C();
B b = new C();
C c = new C();
A.print();
b.print();
c.print();
}
}
| true |
fa86d5792259d010461b2803cc6a51d3ddd8c19c | Java | tanghomvee/slst | /slst-common/src/main/java/com/slst/common/service/AreaCodeService.java | UTF-8 | 243 | 1.601563 | 2 | [] | no_license | package com.slst.common.service;
import com.slst.common.dao.model.AreaCode;
public interface AreaCodeService extends BaseService<AreaCode, Long> {
AreaCode findByCity(String city);
AreaCode save(AreaCode areaCode);
}
| true |
82e7fa35f2a0714b14709f8584eba7453747215b | Java | RuslanHassonov/Helpdesk_RHV | /src/com/helpdesk/user_interface/windows/NewEmployeeWin.java | UTF-8 | 2,719 | 2.671875 | 3 | [] | no_license | package com.helpdesk.user_interface.windows;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
import javax.swing.*;
import static com.helpdesk.service.employee.CreateEmployee.createNewEmployee;
public class NewEmployeeWin {
@FXML
private TextField tf_NewEmpFirstName;
@FXML
private TextField tf_NewEmpLastName;
@FXML
private TextField tf_NewEmpPhone;
@FXML
private TextField tf_NewEmpEmail;
@FXML
private Button btn_NewEmpConfirm;
@FXML
private Button btn_NewEmpCancel;
@FXML
private ComboBox cb_empRole;
@FXML
private void initialize() {
cb_empRole.getItems().addAll(
"Manager",
"Technician",
"Dispatcher"
);
}
@FXML
private void cancelButtonPressed() {
btn_NewEmpCancel.cancelButtonProperty();
Stage stage = (Stage) btn_NewEmpCancel.getScene().getWindow();
stage.close();
}
@FXML
private void confirmButtonPressed() {
try {
validateInputField();
String fName = tf_NewEmpFirstName.getText();
String lName = tf_NewEmpLastName.getText();
String phone = tf_NewEmpPhone.getText();
String email = tf_NewEmpEmail.getText();
String role = cb_empRole.getValue().toString();
createNewEmployee(fName, lName, phone, email, role);
//createNewCustomer();
JOptionPane.showMessageDialog(new JFrame(), "New employee succesfully created");
clearInputFields();
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
JOptionPane.showMessageDialog(new JFrame(), e.getMessage(), "Warning", JOptionPane.WARNING_MESSAGE);
} catch (Exception e) {
e.printStackTrace();
}
}
@FXML
private void validateInputField() {
if ((tf_NewEmpFirstName.getText() == null) ||
(tf_NewEmpLastName.getText() == null) ||
(tf_NewEmpPhone.getText() == null) ||
(tf_NewEmpEmail.getText() == null)) {
throw new IllegalArgumentException("All fields must be filled in correctly.");
}
if (cb_empRole.getValue().toString().isEmpty()) {
throw new IllegalArgumentException("Please choose a role.");
}
}
@FXML
private void clearInputFields() {
tf_NewEmpEmail.clear();
tf_NewEmpPhone.clear();
tf_NewEmpLastName.clear();
tf_NewEmpFirstName.clear();
cb_empRole.setValue(null);
}
}
| true |
af2b8f97a707e281e86bf3adf96c10ed60f2bba4 | Java | Ulez/EbbinghausMemory | /memory/src/main/java/fun/learnlife/memory/MemActivity.java | UTF-8 | 7,110 | 1.953125 | 2 | [] | no_license | package fun.learnlife.memory;
import android.app.Activity;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.InputType;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.alibaba.android.arouter.facade.annotation.Route;
import java.util.Date;
import java.util.List;
import fun.learnlife.base.beans.RecordInfo;
import fun.learnlife.base.beans.TaskContent;
import fun.learnlife.base.dao.RecordDao;
import fun.learnlife.base.dao.TaskDao;
import fun.learnlife.base.utils.CalculateUtil;
@Route(path = "/account/time")
public class MemActivity extends AppCompatActivity implements TasksFragment.OnListFragmentInteractionListener{
private static final String TAG = "MemActivity";
private FragmentManager fManager;
private FloatingActionButton fab;
private TasksFragment tasksFragment;
private Activity activity;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mem);
ActionBar actionBar = getSupportActionBar();
actionBar.setTitle("记忆组件");
activity = this;
fManager = getSupportFragmentManager();
fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
new MaterialDialog.Builder(activity)
.title(R.string.title)
.inputType(InputType.TYPE_CLASS_TEXT)
.input(R.string.input_hint, R.string.input_prefill, new MaterialDialog.InputCallback() {
@Override
public void onInput(MaterialDialog dialog, CharSequence input) {
if (!TextUtils.isEmpty(input.toString())) {
TaskContent.oldTask(input.toString(), MemActivity.this);
tasksFragment.notifyDataSetChanged();
}
}
}).show();
}
});
tasksFragment = TasksFragment.newInstance(10);
fManager.beginTransaction().replace(R.id.content_frame, tasksFragment).commit();
}
@Override
protected void onDestroy() {
super.onDestroy();
}
@Override
public void onLongClick(final List<RecordInfo> records, final int position) {
final int taskId = records.get(position).getTask().getId();
new MaterialDialog.Builder(this)
.title(R.string.delete)
.positiveText(R.string.allow)
.negativeText(R.string.deny)
.onNegative(new MaterialDialog.SingleButtonCallback() {
@Override
public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
Snackbar.make(fab, "已取消!ヾ(◍°∇°◍)ノ゙ ", Snackbar.LENGTH_SHORT)
.setAction("Action", null).show();
}
})
.onPositive(new MaterialDialog.SingleButtonCallback() {
@Override
public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
new TaskDao(MemApp.getContext()).delete(records.get(position).getTask());
Snackbar.make(fab, "已删除!୧(๑•̀◡•́๑)૭ ", Snackbar.LENGTH_SHORT)
.setAction("Action", null).show();
tasksFragment.notifyDataSetChanged();
}
})
.show();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_today) {
tasksFragment.setShowDays(1);
tasksFragment.notifyDataSetChanged();
return true;
}
if (id == R.id.action_3days) {
tasksFragment.setShowDays(3);
tasksFragment.notifyDataSetChanged();
return true;
}
if (id == R.id.action_7days) {
tasksFragment.setShowDays(7);
tasksFragment.notifyDataSetChanged();
return true;
}
if (id == R.id.action_all) {
tasksFragment.setShowDays(-1);
tasksFragment.notifyDataSetChanged();
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onClick(final List<RecordInfo> records, final int position) {
final int taskId = records.get(position).getTask().getId();
new MaterialDialog.Builder(this)
.title(R.string.confirm)
.positiveText(R.string.allow)
.negativeText(R.string.deny)
.onNegative(new MaterialDialog.SingleButtonCallback() {
@Override
public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
Snackbar.make(fab, "继续加油!ヾ(◍°∇°◍)ノ゙ ", Snackbar.LENGTH_SHORT)
.setAction("Action", null).show();
}
})
.onPositive(new MaterialDialog.SingleButtonCallback() {
@Override
public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
CalculateUtil calculateUtil = new CalculateUtil(new Date().getTime());
for (int i = position; i < records.size(); i++) {
RecordInfo item = records.get(i);
if (item.getTask().getId() == taskId) {
if (i == position) item.setDone(true);
item.setPlandate(calculateUtil.getDate(item.getNo(), records.get(position).getNo()));
new RecordDao(MemApp.getContext()).update(item);
}
}
Snackbar.make(fab, "୧(๑•̀◡•́๑)૭ ", Snackbar.LENGTH_SHORT)
.setAction("Action", null).show();
tasksFragment.notifyDataSetChanged();
}
})
.show();
}
}
| true |
8336e3dd99873101b1d084dc48d49d2200b297d0 | Java | projectomakase/omakase | /omakase/src/main/java/org/projectomakase/omakase/broker/Capacity.java | UTF-8 | 1,598 | 2.359375 | 2 | [
"Apache-2.0",
"GPL-2.0-only",
"LicenseRef-scancode-public-domain",
"WTFPL",
"CDDL-1.0",
"MIT",
"LicenseRef-scancode-warranty-disclaimer",
"LGPL-2.0-or-later",
"GPL-3.0-only",
"LGPL-2.1-or-later",
"EPL-1.0",
"BSD-3-Clause",
"Classpath-exception-2.0",
"LicenseRef-scancode-unknown-license-ref... | permissive | /*
* #%L
* omakase
* %%
* Copyright (C) 2015 Project Omakase LLC
* %%
* 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.
* #L%
*/
package org.projectomakase.omakase.broker;
/**
* The capacity available for a specific worker
*
* @author Richard Lucas
*/
public class Capacity {
private final String type;
private final int availability;
/**
* Capacity
*
* @param type
* the task type that the worker has capacity for.
* @param availability
* the available capacity for the task type
*/
public Capacity(String type, int availability) {
this.type = type;
this.availability = availability;
}
/**
* Gets the task type that the worker has capacity for.
*
* @return the task type that the worker has capacity for.
*/
public String getType() {
return type;
}
/**
* Gets the available capacity for the task type
*
* @return the available capacity for the task type
*/
public int getAvailability() {
return availability;
}
}
| true |
190793b00fff9db659d65d56f40e61ab6e906ff6 | Java | lixianglei/People_Blood | /app/src/main/java/com/example/admin/people_blood/view/activity/Activity_MessageFanKui.java | UTF-8 | 2,322 | 1.90625 | 2 | [] | no_license | package com.example.admin.people_blood.view.activity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import com.example.admin.people_blood.R;
import com.example.admin.people_blood.base.BaseActivity;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
/**
* Created by d on 2017/6/12.
*/
public class Activity_MessageFanKui extends BaseActivity {
@Bind(R.id.left_image)
ImageView leftImage;
@Bind(R.id.left_layout)
RelativeLayout leftLayout;
@Bind(R.id.custom_edit)
AnFQNumEditText customEdit;
// @Bind(R.id.Yijian_FanKui)
// TextView YijianFanKui;
// @Bind(R.id.Message_fasong)
// TextView MessageFasong;
// @Bind(R.id.Medit)
// EditText Medit;
@Override
protected int layoutId() {
return R.layout.yijianfankui_activity;
}
@Override
protected void initView() {
customEdit = (AnFQNumEditText) findViewById(R.id.custom_edit);
customEdit.setEtHint("内容")//设置提示文字
.setEtMinHeight(200)//设置最小高度,单位px
.setLength(100 / 1)//设置总字数
.setType(AnFQNumEditText.PERCENTAGE) //TextView显示类型(SINGULAR单数类型)(PERCENTAGE百分比类型)
// .setLineColor("#3F51B5")//设置横线颜色
.show();
}
@Override
protected void loadData() {
}
@Override
protected void listener() {
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// TODO: add setContentView(...) invocation
ButterKnife.bind(this);
}
@OnClick({R.id.left_image, R.id.Message_fasong})
public void onViewClicked(View view) {
switch (view.getId()) {
case R.id.left_image:
finish();
break;
case R.id.Message_fasong:
// if (customEdit.getText().toString().isEmpty()) {
// Toast.makeText(this, "内容不能为空", Toast.LENGTH_SHORT).show();
// } else {
// Toast.makeText(this, "发送成功", Toast.LENGTH_SHORT).show();
// }
break;
}
}
}
| true |
1fde41aca4c3de3c2b43fe5553ea0af8f90ca445 | Java | Leventseleveil/algorithm | /JAVA/HuarongRoad/HuarongRoad.java | GB18030 | 7,956 | 2.421875 | 2 | [
"Apache-2.0"
] | permissive | package HuarongRoad;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.SplashScreen;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.image.BufferedImage;
import java.util.Random;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.border.EmptyBorder;
import com.sun.corba.se.spi.orbutil.fsm.Action;
import HuarongRoad.Person;
public class HuarongRoad extends JFrame implements MouseListener,KeyListener,ActionListener{
@Override//
public void setTitle(String title) {
super.setTitle(title);
}
private JPanel contentPane, panel;
Person person[] = new Person[10]; //found persons
JButton left, right , above , below,belowx;
JButton restart,undo;// ʼ
JLabel label,label2;
JTextArea count;//
static int number = 0;
static int X[] = new int[500]; // ¼ ÿ һ
static int Y[] = new int[500];
Person p[] = new Person[500];
public HuarongRoad() { // ʼ
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(null);
setContentPane(contentPane);
panel = new JPanel();
panel.setBackground(new Color(218, 165, 32));
panel.setBounds(10, 10, 420, 520);
panel.setLayout(null);
contentPane.add(panel);
init();
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setBounds(25, 25, 500, 650);
setVisible(true);
}
public void init() { // ʼ
label = new JLabel(" ");
label2 = new JLabel("");
count = new JTextArea();
count.setEditable(false);
contentPane.add(label);
contentPane.add(label2);
contentPane.add(count);
label.setFont(new Font("",Font.BOLD,30));
label.setBounds(150, 535, 150, 35);
label2.setFont(new Font("",Font.BOLD,30));
label2.setBounds(310, 535, 100, 35);
count.setFont(new Font("",Font.BOLD,35));
count.setBounds(390, 535, 60, 35);
count.setText(number + "");
undo = new JButton("");
restart = new JButton("¿ʼ");
belowx = new JButton("");
contentPane.add(undo);
contentPane.add(restart);//init restart
undo.setBounds(10, 570, 80, 40);
undo.addActionListener(new unDo());
restart.setBounds(95, 570, 100, 40);
restart.addActionListener(this);
left = new JButton();//init wall
right = new JButton();
above = new JButton();
below = new JButton();
belowx = new JButton();
panel.add(left);
panel.add(right);
panel.add(above);
panel.add(belowx);
panel.add(below);
left.setBounds(0, 0, 10, 520);
right.setBounds(410, 0, 10, 520);
above.setBounds(10, 0, 400, 10);
below.setBounds(10, 510, 400, 10);
belowx.setBounds(110, 510, 200, 10);
belowx.setBackground(new Color(218, 165, 32));
String name[] = {"", "", "", "", "", "", "", "", "", ""};//init persons
for(int k = 0;k < name.length; k++) {
person[k] = new Person(k,name[k]);
person[k].addMouseListener(this);
person[k].addKeyListener(this);
panel.add(person[k]);
}
person[0].setBounds(110, 10, 200, 200);
person[0].setForeground(Color.PINK);
setIcon("src/HuarongRoad/ܲ.png",person[0]);
person[1].setBounds(110, 210, 200, 100);
setIcon("src/HuarongRoad/.png",person[1]);
person[2].setBounds(10, 210, 100, 200);
setIcon("src/HuarongRoad/.png",person[2]);
person[3].setBounds(310, 210, 100, 200);
setIcon("src/HuarongRoad/ŷ.png",person[3]);
person[4].setBounds(10, 10, 100, 200);
setIcon("src/HuarongRoad/.png",person[4]);
person[5].setBounds(310, 10, 100, 200);
setIcon("src/HuarongRoad/.png",person[5]);
person[6].setBounds(110, 310, 100, 100);
setIcon("src/HuarongRoad/.png",person[6]);
person[7].setBounds(210, 310, 100, 100);
setIcon("src/HuarongRoad/.png",person[7]);
person[8].setBounds(10,410,100,100);
setIcon("src/HuarongRoad/.png",person[8]);
person[9].setBounds(310,410,100,100);
setIcon("src/HuarongRoad/.png",person[9]);
person[9].requestFocus();
}
@Override
public void keyPressed(KeyEvent e) { //µĴжܷƶ
Person man = (Person) e.getSource(); //ȡ¼õĶãѡǸbutton
if(e.getKeyCode() == KeyEvent.VK_DOWN)
move(man, below);
if(e.getKeyCode() == KeyEvent.VK_UP)
move(man, above);
if(e.getKeyCode() == KeyEvent.VK_LEFT)
move(man, left);
if(e.getKeyCode() == KeyEvent.VK_RIGHT)
move(man, right);
}
public boolean move(Person personX, JButton wall) {
boolean isMove = true;
Rectangle personXRect = personX.getBounds();
int x = personX.getX();
int x1 = x;
int y = personX.getY();
int y1 = y;
if(wall == below) y += 100;
else if(wall == above) y -= 100;
else if(wall == right) x += 100;
else if(wall == left) x -= 100;
personXRect.setLocation(x, y);//Ҫƶλ
Rectangle thisIsWall= wall.getBounds();
if(personXRect.intersects(thisIsWall)) isMove = false;// personX ǽ
for (int k = 0; k < this.person.length; k++) {// personX
Rectangle personRect = person[k].getBounds();
if ((personXRect.intersects(personRect))&&(personX.number != k)) isMove = false;
}
if(isMove == true) {// ¼ + 1
personX.setLocation(x, y);
p[number] = personX;
X[number] = x1;
Y[number] = y1;
number++;
count.setText(number + "");
}
return isMove;
}
public boolean getRandom() {
boolean m = true;
double random = Math.random();
if(random >= 0.5) return m;
else {
m = false;
return m;
}
}
@Override
public void actionPerformed(ActionEvent e) {//restart
dispose();
number = 0;
p = null;
new HuarongRoad().setTitle("仪ݵ");
}
class unDo implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
if(number > 0) {
int x1 = X[number-1];
int y1 = Y[number-1];
p[number-1].setLocation(x1, y1);
number--;
count.setText(number + "");
}
}
}
class Count implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
number++;
}
}
public void setIcon(String file, JButton iconButton) {//ͼ Ƭ Ӧ
ImageIcon icon = new ImageIcon(file);
Image temp = icon.getImage().getScaledInstance(iconButton.getWidth(),
iconButton.getHeight(), icon.getImage().SCALE_DEFAULT);
icon = new ImageIcon(temp);
iconButton.setIcon(icon);
}
public void keyTyped(KeyEvent e){}
public void keyReleased(KeyEvent e){}
public void mouseClicked(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public static void main(String[] args) {
new HuarongRoad().setTitle("仪ݵ");
}
}
| true |
c626bbe1c8a397af18eacaa1a4e4e482040c28aa | Java | ForZeWolfzy/inleiding-java | /src/h05/javatekenen.java | UTF-8 | 1,372 | 3.421875 | 3 | [] | no_license | package h05;
import java.awt.*;
import java.applet.*;
public class javatekenen extends Applet {
// VARIABLEN DECLAREREN
int gewichtValerie;
int hoogteXas;
int gewichtHans;
int gewichtJeroen;
public void init() {
setSize(400,400);
hoogteXas = 350;
gewichtValerie = 40;
gewichtHans = 80;
gewichtJeroen = 100;
}
public void paint(Graphics g) {
// Verticale as
g.drawLine(50,50,50,hoogteXas);
// Horizontale as
g.drawLine(50,hoogteXas,hoogteXas,hoogteXas);
// Tekenen van de staven
// 1. Valerie
g.setColor(Color.blue);
g.fillRect(50,hoogteXas - gewichtValerie,80, gewichtValerie);
// 2. Hans
g.setColor(Color.red);
g.fillRect(150,hoogteXas - gewichtHans,80, gewichtHans);
// 3. Jeroen
g.setColor(Color.yellow);
g.fillRect(250,hoogteXas - gewichtJeroen,80, gewichtJeroen);
// Text
g.setColor(Color.black);
g.drawString("Valerie",50,360);
g.drawString("Hans",150,360);
g.drawString("Jeroen",250,360);
g.drawString("0",20,350);
g.drawString("20",20,330);
g.drawString("40",20,310);
g.drawString("60",20,290);
g.drawString("80",20,270);
g.drawString("100",20,250);
}
} | true |
4d6ff5296b54d01fc34527efff68c50c5e867697 | Java | rahamihi/RadioGroupButtonExample | /app/src/main/java/com/example/mamun/radiogroupbuttonexample/MainActivity.java | UTF-8 | 1,252 | 2.078125 | 2 | [] | no_license | package com.example.mamun.radiogroupbuttonexample;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TabHost;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private RadioGroup radiogp1;
private RadioButton cameleyatea,blackcoffee,greentea,chinaspecialtea,selectedButton;
private Button submit;
private int getSelected;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
radiogp1 = (RadioGroup) findViewById(R.id.radiogp1);
submit = (Button) findViewById(R.id.submit);
submit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getSelected = radiogp1.getCheckedRadioButtonId();
selectedButton = (RadioButton) findViewById(getSelected);
Toast.makeText(getApplicationContext(),selectedButton.getText().toString(), Toast.LENGTH_LONG).show();
}
});
}
}
| true |
d7ceac4ceb8852eeed5cf30db78d5c0cb7143c2d | Java | Natoto/PENGVideo | /server/PureData.java | UTF-8 | 1,130 | 2.640625 | 3 | [] | no_license | package sfc.network.req;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.util.Arrays;
import sfc.network.Req;
public class PureData implements Req {
public static final int ProtocolId = 0x1008;
private byte[] data;
public byte[] getData() {
return data;
}
public void setData(byte[] data) {
this.data = data;
}
@Override
public int getProtocolId() {
return ProtocolId;
}
@Override
public void fromDis(DataInputStream dis) {
try {
int len = dis.readInt();
data = new byte[len];
dis.read(data);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public byte[] toByteArray() {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(baos);
try{
dos.writeInt(data.length);
dos.write(data);
}catch(Exception e){
e.printStackTrace();
}
return baos.toByteArray();
}
@Override
public String toString() {
String dataDec = (data==null||data.length<2)?"TooShort":data[0]+"-"+data[data.length-1];
return "PureData [data=" + dataDec + "]";
}
}
| true |
16e2962f87ba7d24d7f09ebb477f85911158df25 | Java | Pedrog38/javatos | /JAVATOS_GARAGE/src/main/java/com/poe/ServletInitializer.java | UTF-8 | 473 | 1.742188 | 2 | [] | no_license | package com.poe;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
/**
* Créer par l'assistant Spring Initializer
* @author chris
*
*/
public class ServletInitializer extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Javatos03Application.class);
}
}
| true |
a51cda929c4d0a9a65e8d65f4808104fa3109c55 | Java | yx9009/PROJECT | /PersonalPage/src/com/DAO/GetDatabaseConnection.java | UTF-8 | 964 | 2.8125 | 3 | [] | no_license | package com.DAO;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class GetDatabaseConnection {
public static Connection getConnection() throws SQLException, ClassNotFoundException{
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/my";
String user = "root";
String password = "yinxiang";
Connection con = DriverManager.getConnection(url,user,password);
return con;
}
public static void main(String[] args){
try {
Connection con = getConnection();
Statement statement = con.createStatement();
String sql = "select * from user;";
ResultSet rs = statement.executeQuery(sql);
while (rs.next()) {
System.out.println(rs.getString(1));
System.out.println(rs.getString(2));
}
} catch (Exception e) {
// TODO: handle exception
}
}
}
| true |
f3a677e2353b92bc6728821dfd8534c425b5c9ba | Java | FrankGreen19/RIP | /src/main/java/Lab4/task3/UserHttpRequestWrapper.java | UTF-8 | 1,188 | 2.609375 | 3 | [] | no_license | package Lab4.task3;
import Lab4.task2.UserDAO;
import Lab4.task2.UserDTO;
import javax.servlet.ServletRequest;
import javax.servlet.ServletRequestWrapper;
import java.sql.SQLException;
public class UserHttpRequestWrapper extends ServletRequestWrapper {
public UserHttpRequestWrapper(ServletRequest request) {
super(request);
}
public static void main(String[] args) throws SQLException {
UserDTO userDTO = UserDAO.findByLogin("alice@gmail.com");
System.out.println(userDTO.getRole_id());
System.out.println(userDTO.getPassword());
}
@Override
public Object getAttribute(String login) {
try {
return UserDAO.findByLogin(login);
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return null;
}
@Override
public void setAttribute(String login, Object o) {
super.setAttribute(login, o);
}
}
class Main {
public static void main(String[] args) throws SQLException {
UserDTO userDTO = UserDAO.findByLogin("alice@gmail.com");
System.out.println(userDTO.getRole_id());
System.out.println(userDTO.getPassword());
}
}
| true |
d1710d099e5258b88510387fd02574f2b1fcf7fa | Java | 425732441/pyg | /pyg-manager-web/src/main/java/com/zhl/pyg/controller/TbPayLogController.java | UTF-8 | 3,907 | 2.296875 | 2 | [] | no_license | package com.zhl.pyg.controller;
import lombok.extern.slf4j.Slf4j;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.zhl.pyg.response.PageResult;
import com.zhl.pyg.response.Result;
import com.zhl.pyg.response.StatusCode;
import com.zhl.pyg.entity.TbPayLog;
import com.zhl.pyg.service.TbPayLogService;
import org.springframework.web.bind.annotation.*;
import org.springframework.util.CollectionUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import java.util.List;
import java.util.Objects;
/**
* (TbPayLog)控制层
*
* @author protagonist
* @since 2021-03-03 16:41:27
*/
@RestController
@Slf4j
@RequestMapping("/tbPayLog")
public class TbPayLogController {
/**
* 服务对象
*/
@DubboReference
private TbPayLogService tbPayLogServiceImpl;
/**
* 通过主键查询单条数据
*
* @param outTradeNo 主键
* @return 单条数据
*/
@GetMapping(value = "/get/{outTradeNo}")
public Result selectOne(@PathVariable("outTradeNo") String outTradeNo) {
TbPayLog result = tbPayLogServiceImpl.selectById(outTradeNo);
if (Objects.nonNull(result)) {
return new Result<>(true, StatusCode.OK, "查询成功", result);
}
return new Result<>(true, StatusCode.ERROR, "查询失败");
}
/**
* 新增一条数据
*
* @param tbPayLog 实体类
* @return Result对象
*/
@PostMapping(value = "/insert")
public Result insert(@RequestBody TbPayLog tbPayLog) {
int result = tbPayLogServiceImpl.insert(tbPayLog);
if (result > 0) {
return new Result<>(true, StatusCode.OK, "新增成功", result);
}
return new Result<>(true, StatusCode.ERROR, "新增失败");
}
/**
* 修改一条数据
*
* @param tbPayLog 实体类
* @return Result对象
*/
@PutMapping(value = "/update")
public Result update(@RequestBody TbPayLog tbPayLog) {
TbPayLog result = tbPayLogServiceImpl.update(tbPayLog);
if (Objects.nonNull(result)) {
return new Result<>(true, StatusCode.OK, "修改成功", result);
}
return new Result<>(true, StatusCode.ERROR, "修改失败");
}
/**
* 删除一条数据
*
* @param outTradeNo 主键
* @return Result对象
*/
@DeleteMapping(value = "/delete/{outTradeNo}")
public Result delete(@PathVariable("outTradeNo") String outTradeNo) {
int result = tbPayLogServiceImpl.deleteById(outTradeNo);
if (result > 0) {
return new Result<>(true, StatusCode.OK, "删除成功", result);
}
return new Result<>(true, StatusCode.ERROR, "删除失败");
}
/**
* 查询全部
*
* @return Result对象
*/
@GetMapping(value = "/selectAll")
public Result<List<TbPayLog>> selectAll() {
List<TbPayLog> tbPayLogs = tbPayLogServiceImpl.selectAll();
if (CollectionUtils.isEmpty(tbPayLogs)) {
return new Result<>(true, StatusCode.ERROR, "查询全部数据失败");
}
return new Result<>(true, StatusCode.OK, "查询全部数据成功", tbPayLogs);
}
/**
* 分页查询
*
* @param current 当前页 第零页和第一页的数据是一样
* @param size 每一页的数据条数
* @return Result对象
*/
@GetMapping(value = "/selectPage/{current}/{size}")
public Result selectPage(@PathVariable("current") Integer current, @PathVariable("size") Integer size) {
IPage<TbPayLog> page = tbPayLogServiceImpl.selectPage(current, size);
if (Objects.nonNull(page)) {
return new Result<>(true, StatusCode.OK, "分页条件查询成功", new PageResult<>(page.getTotal(), page.getRecords()));
}
return new Result<>(true, StatusCode.ERROR, "分页查询数据失败");
}
}
| true |
310f9be31d495ede5b3e502085dc780010957989 | Java | LounesBrahimi/Web-App-response-with-Json | /java-servlet-json/src/main/java/com/lounes/servlet/UserServlet.java | UTF-8 | 1,347 | 2.4375 | 2 | [] | no_license | package com.lounes.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
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 com.google.gson.Gson;
import com.lounes.beans.User;
import com.lounes.data.UserService;
@WebServlet(urlPatterns = {"/users"}, name="UserServlet", description="UserServlet returns json" )
public class UserServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private UserService service = new UserService();
public UserServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<User> users = new ArrayList<User>();
users = service.getUsers();
Gson gson = new Gson();
String userJson = gson.toJson(users);
PrintWriter out = response.getWriter();
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
out.write(userJson);
out.close();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
| true |
96f6e5be89f606f65f3ee7dacc26062456359ecd | Java | ahinshapiro/LeetCode-Solutions | /Integer to English Words.java | UTF-8 | 4,561 | 3.3125 | 3 | [] | no_license | /*
Convert a non-negative integer num to its English words representation.
Example 1:
Input: num = 123
Output: "One Hundred Twenty Three"
Example 2:
Input: num = 12345
Output: "Twelve Thousand Three Hundred Forty Five"
Example 3:
Input: num = 1234567
Output: "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"
Example 4:
Input: num = 1234567891
Output: "One Billion Two Hundred Thirty Four Million Five Hundred Sixty Seven Thousand Eight Hundred Ninety One"
Constraints:
0 <= num <= 231 - 1
*/
class Solution {
Map<Integer,String> mpSingle = new HashMap<Integer,String>(){{
put(1,"One") ;
put(2,"Two") ;
put(3,"Three") ;
put(4,"Four") ;
put(5,"Five") ;
put(6,"Six") ;
put(7,"Seven") ;
put(8,"Eight") ;
put(9,"Nine") ;
}};
Map<Integer,String> mpTens = new HashMap<Integer,String>(){{
put(10,"Ten") ;
put(20,"Twenty") ;
put(30,"Thirty") ;
put(40,"Forty") ;
put(50,"Fifty") ;
put(60,"Sixty") ;
put(70,"Seventy") ;
put(80,"Eighty") ;
put(90,"Ninety") ;
}};
Map<Integer,String> mpTwenties = new HashMap<Integer,String>(){{
put(11,"Eleven") ;
put(12,"Twelve") ;
put(13,"Thirteen") ;
put(14,"Fourteen") ;
put(15,"Fifteen") ;
put(16,"Sixteen") ;
put(17,"Seventeen") ;
put(18,"Eighteen") ;
put(19,"Nineteen") ;
}};
Map<Integer,String> mpTotal = new HashMap<Integer,String>(){{
put(6,"Million") ;
put(3,"Thousand") ;
put(9,"Billion") ;
put(2,"Hundred") ;
}};
List<Integer> arr = new ArrayList<Integer>();
public String numberToWords(int num)
{
if(num == 0){
return "Zero";
}
Set<Integer> set = mpTotal.keySet();
for(Integer key : set){
arr.add(key);
}
Collections.sort(arr,Collections.reverseOrder());
return nTW(String.valueOf(num),true);
}
private String nTW(String n, boolean switchValues)
{
if(n.equals("")){
return n;
}
if( mpTwenties.get(Integer.parseInt(n)) != null ){
return mpTwenties.get(Integer.parseInt(n))+"";
}
else if(mpTens.get(Integer.parseInt(n)) != null ){
return mpTens.get(Integer.parseInt(n))+"";
}
else if(mpSingle.get(Integer.parseInt(n)) != null ){
return mpSingle.get(Integer.parseInt(n));
}
n = String.valueOf(Integer.parseInt(n));
int totalLength = n.length();
if(totalLength > 0){
String leadingZeros = "";
Integer fPos = Integer.parseInt(n.charAt(0)+"");
String front = n;
if(switchValues){
for(int i = 0 ; i < totalLength-1 ; i++){
leadingZeros+="0";
}
front = n.charAt(0)+leadingZeros;
}
StringBuilder sb = new StringBuilder();
String word = "";
if(mpTotal.get(leadingZeros.length()) != null ){
sb.append(mpSingle.get(fPos) + " " + mpTotal.get(leadingZeros.length()));
if(!front.equals(n)){
sb.append(" ");
}
}
else if( mpTwenties.get(Integer.parseInt(front)) != null ){
sb.append(mpTwenties.get(Integer.parseInt(front))+" ");
}
else if(mpTens.get(Integer.parseInt(front)) != null ){
sb.append(mpTens.get(Integer.parseInt(front))+" ");
}
else if(mpSingle.get(Integer.parseInt(front)) != null ){
sb.append(mpSingle.get(Integer.parseInt(front)));
}
else{
for(int i = 0 ; i<arr.size() ; i++){
if(arr.get(i) < n.length())
{
String balance = n.substring(0,n.length()-arr.get(i));
String rest = n.substring(n.length()-arr.get(i),n.length());
if(Integer.parseInt(rest) == 0){
return nTW(balance,true) +" "+mpTotal.get(arr.get(i));
}else{
return nTW(balance,true) +" "+mpTotal.get(arr.get(i))+" "+ nTW(rest,true);
}
}
}
}
return sb.append(nTW(n.substring(1,n.length()),true)).toString();
}
return "";
}
}
| true |
c5fb6d326e4b8c1ad4939144fafecb041775c002 | Java | phsantiago/garagem_app | /public/app/src/main/java/com/garagem/nupark/dto/GaragemDto.java | UTF-8 | 1,558 | 2.1875 | 2 | [] | no_license | package com.garagem.nupark.dto;
import java.util.Date;
public class GaragemDto {
private int id_garagem;
private long dt_registro;
private long dt_delete;
private boolean deleted;
private double latitude;
private double longitude;
private String titulo;
private String descricao;
private int id_usuario_dono;
public GaragemDto(){
}
public int getId_garagem() {
return id_garagem;
}
public void setId_garagem(int id_garagem) {
this.id_garagem = id_garagem;
}
public boolean isDeleted() {
return deleted;
}
public void setDeleted(boolean deleted) {
this.deleted = deleted;
}
public double getLatitude() {
return latitude;
}
public void setLatitude(double latitude) {
this.latitude = latitude;
}
public double getLongitude() {
return longitude;
}
public void setLongitude(double longitude) {
this.longitude = longitude;
}
public String getTitulo() {
return titulo;
}
public void setTitulo(String titulo) {
this.titulo = titulo;
}
public String getDescricao() {
return descricao;
}
public void setDescricao(String descricao) {
this.descricao = descricao;
}
public int getId_usuario_dono() {
return id_usuario_dono;
}
public void setId_usuario_dono(int id_usuario_dono) {
this.id_usuario_dono = id_usuario_dono;
}
public long getDt_registro() {
return dt_registro;
}
public void setDt_registro(long dt_registro) {
this.dt_registro = dt_registro;
}
public long getDt_delete() {
return dt_delete;
}
public void setDt_delete(long dt_delete) {
this.dt_delete = dt_delete;
}
} | true |
119f6e19e22802e72b23aecf3240ffd6fe555072 | Java | chenzhiwei152/LifeHelp | /app/src/main/java/com/bozhengjianshe/shenghuobang/ui/bean/ShoppingAddressListItemBean.java | UTF-8 | 1,133 | 1.984375 | 2 | [] | no_license | package com.bozhengjianshe.shenghuobang.ui.bean;
import java.io.Serializable;
/**
* Created by chen.zhiwei on 2017-6-23.
*/
public class ShoppingAddressListItemBean implements Serializable {
/**
* lxdz : 噢噢噢哦哦默默噢噢噢哦哦
* lxdh : 13686958558
* lxr : 考虑考虑
* lxxq : 咯哦哦噢噢噢哦哦魔女UPSppsspp
* id : 4
*/
private String lxdz;
private String lxdh;
private String lxr;
private String lxxq;
private int id;
public String getLxdz() {
return lxdz;
}
public void setLxdz(String lxdz) {
this.lxdz = lxdz;
}
public String getLxdh() {
return lxdh;
}
public void setLxdh(String lxdh) {
this.lxdh = lxdh;
}
public String getLxr() {
return lxr;
}
public void setLxr(String lxr) {
this.lxr = lxr;
}
public String getLxxq() {
return lxxq;
}
public void setLxxq(String lxxq) {
this.lxxq = lxxq;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
| true |
0dd488325597ed813af1baf88f489fef03764267 | Java | sebastian-porling/notice-board | /src/main/java/se/experis/academy/session/util/SessionKeeper.java | UTF-8 | 1,412 | 3.1875 | 3 | [] | no_license | package se.experis.academy.session.util;
import java.util.HashMap;
/**
* Takes care of all the sessions
*/
public class SessionKeeper {
private static SessionKeeper sessionKeeperInstance = null;
private HashMap<String, Long> validSessions = new HashMap<>();
/**
* Checks if the session exists
* @param session session
* @return true if it exists
*/
public boolean CheckSession(String session) { return validSessions.containsKey(session); }
/**
* Gets the user id from the session
* @param session session
* @return user id
*/
public Long getSessionValue(String session) { return validSessions.get(session); }
/**
* Adds a session to the list
* @param session session
* @param id user id
*/
public void AddSession(String session, Long id){ validSessions.put(session, id); }
/**
* Removes a session
* @param session session
*/
public void RemoveSession(String session){
if(getInstance().CheckSession(session)) validSessions.remove(session);
}
/**
* Returns the singleton instance
* @return singleton instance of SessionKeeper
*/
public static SessionKeeper getInstance(){
if (sessionKeeperInstance == null) sessionKeeperInstance = new SessionKeeper();
return sessionKeeperInstance;
}
}
| true |
06ba26a49409681a7ec46a67d1e79efe826f4d79 | Java | joan-pons/Banc | /Banco/src/es/bancodehierro/banco/menu/MenuSucursal.java | UTF-8 | 10,256 | 2.59375 | 3 | [] | no_license | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package es.bancodehierro.banco.menu;
import es.bancodehierro.banco.central.Banco;
import es.bancodehierro.banco.conexion.Conexion;
import es.bancodehierro.banco.excepciones.SucursalException;
import es.bancodehierro.banco.sucursal.Sucursal;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
* Classe que contiene lo referente a las acciones sobre sucursales se
* ejecutaran en este menu.
*
* @author Guillem Arrom, Guillem Rotger, Pedro Lladó, François
*/
public abstract class MenuSucursal {
private static final int MENU_SUCURSAL_PREFIX = 70000;
private static final int MENU_SUCURSAL_CREAR = 70000;
private static final int MENU_SUCURSAL_LISTAR = 70001;
private static final int MENU_SUCURSAL_MODIFICAR = 70002;
private static final int MENU_SUCURSAL_ELIMINAR = 70003;
private static final int MENU_SUCURSAL_LISTARTOT = 70004;
private static final int MENU_SUCURSAL_VOLVER = 70005;
/**
* Hace los pasos necesarios y pide la informacion necesaria para dar de
* alta una sucursal y pasar la informacion a un metodo de banco que la
* inserte en la bdd.
*
* @throws SQLException Cuando ha ocurrido un error inesperado de SQL
*/
private static void crearSucursal() throws SQLException, SucursalException {
Sucursal central;
String poblacio = GestionaMenu.llegirCadena("Mete poblacion ");
String direccio = GestionaMenu.llegirCadena("Mete direccion ");
String telefono = GestionaMenu.llegirCadena("Inserte telefono ");
int codiPostal;
while (true) {
codiPostal = GestionaMenu.llegirSencer("Mete el codigo postal (xxxxx)");
if (codiPostal < 99999) {
break;
}
System.out.println("Codigo postal incorrecto (xxxxx");
}
boolean flagCentral = true;
do {
if (GestionaMenu.menuSiNo("", "Tiene central?")) {
int codiSuc = GestionaMenu.llegirSencer("Cual es el codigo de sucursal?");
central = Banco.devuelveSucursal(codiSuc);
} else {
flagCentral = false;
central = null;
}
} while (flagCentral);
Sucursal sucursal = new Sucursal(poblacio, direccio, 0, codiPostal, central, telefono);
try {
System.out.println("El codigo de la sucursal inserida ha sido " + Banco.insertaSucursal(sucursal));
} catch (SucursalException ex) {
System.out.println(ex.getMessage());
}
}
/**
*
* Te pide el codigo de sucursal y te devuelve la sucursal del codigo que
* has pedido
*
* @return La sucursal solicitada
* @throws SQLException Cuando la sentencia SQL ha fallado inesperadamente
*/
private static Sucursal seleccionaSucrusal() throws SQLException {
Sucursal sucursal;
boolean flag = true;
do {
int codiSuc = GestionaMenu.llegirSencer("Cual es el codigo de sucursal?");
try {
sucursal = Banco.devuelveSucursal(codiSuc);
flag = false;
} catch (SucursalException ex) {
sucursal = null;
flag = true;
System.out.println("Sucursal no encontrada");
}
} while (flag);
return sucursal;
}
/**
* Enseña toda la informacion de la sucursal
*
* @param sucursal El objeto sucursal de donde cogera la informacion
* @throws SucursalException Si la sucursal es null
*/
private static void mostrarSucursal(Sucursal sucursal) throws SucursalException {
if (sucursal != null) {
System.out.println("El codigo es: " + sucursal.getCodi());
System.out.println("---");
System.out.println("La direccion es: " + sucursal.getDireccio() + " poblacion " + sucursal.getPoblacio() + " CP: " + sucursal.getCodiPostal());
System.out.println("---");
if (sucursal.getCentral() != null) {
System.out.println("La central de la sucursal tiene el codigo " + sucursal.getCentral().getCodi());
} else {
System.out.println("No tiene central");
}
System.out.println("---");
} else {
throw new SucursalException("La sucursal que se ha querido mostrar fue null");
}
}
/**
* Pide todo lo necesario para modificar sucursal y la modifica
*
* @throws SucursalException Cuando hay errores con sucursales
* @throws SQLException Cuando hay errores SQL
*/
private static void modificarSucursal() throws SucursalException, SQLException {
Sucursal sucursal;
int codiSuc = GestionaMenu.llegirSencer("Cual es el codigo de sucursal que quieres modificar?");
sucursal = Banco.devuelveSucursal(codiSuc);
System.out.println("Tu sucursal es");
mostrarSucursal(sucursal);
boolean seguir = true;
String[] menu = {"Modificar poblacion", " Modificar direccion", "Modificar codigo postal", "Modificar central", "Modificar telefono ", "Nada mas"};
while (seguir) {
switch (GestionaMenu.gestionarMenu("Que quieres modificar?", menu, "", 0)) {
case 0:
String poblacion = GestionaMenu.llegirCadena("Inserta poblacion: ");
sucursal.setPoblacio(poblacion);
break;
case 1:
String direccion = GestionaMenu.llegirCadena("Inserta direccion: ");
sucursal.setDireccio(direccion);
break;
case 2:
int cp = GestionaMenu.llegirSencer("Inserte el nuevo CP: ");
sucursal.setCodiPostal(cp);
break;
case 3:
Sucursal central = seleccionaSucrusal();
sucursal.setCentral(central);
break;
case 4:
String telefono = GestionaMenu.llegirCadena("Inserte telefono");
sucursal.setTelefono(telefono);
break;
case 5:
seguir = false;
break;
}
}
Banco.modificarSucursal(sucursal);
}
/**
*
* Pide que sucursal eliminar y la elimina
*
* @throws SucursalException Si no existe la sucursal
* @throws SQLException Si hay un error de bdd
*/
private static void eliminarSucursal() throws SucursalException, SQLException {
Sucursal sucursal;
int codiSuc = GestionaMenu.llegirSencer("Cual es el codigo de sucursal que quieres borrar?");
sucursal = Banco.devuelveSucursal(codiSuc);
if (GestionaMenu.menuSiNo("", "Seguro que quereis borrar la sucursal " + codiSuc)) {
if (Banco.eliminarSucursal(sucursal)) {
System.out.println("Sucursal borrada");
} else {
throw new SucursalException("Error al borrar la sucursal.");
}
} else {
System.out.println("cancelant borrada...");
}
}
/**
* Genera el menu principal
*/
public static void menu() {
try {
String[] menu = {"Crear sucursal", "listar sucursal", "Modificar sucursal", "Eliminar sucursal", "Mostrar todas", "Atrás..."};
switch (GestionaMenu.gestionarMenu("Menu sucursal", menu, "", MENU_SUCURSAL_PREFIX)) {
case MENU_SUCURSAL_CREAR:
crearSucursal();
break;
case MENU_SUCURSAL_LISTAR:
Sucursal sucursal;
sucursal = seleccionaSucrusal();
mostrarSucursal(sucursal);
break;
case MENU_SUCURSAL_MODIFICAR:
modificarSucursal();
break;
case MENU_SUCURSAL_ELIMINAR:
eliminarSucursal();
break;
case MENU_SUCURSAL_LISTARTOT:
mostrarTodas();
break;
case MENU_SUCURSAL_VOLVER:
break;
default:
break;
}
} catch (SucursalException ex) {
System.err.println(ex.getMessage());
} catch (SQLException ex) {
System.err.println(ex.getMessage());
}
}
/**
*
* Muestra todas las sucursales de la bdd
* @throws SQLException cuando hay un error inesperado de bdd
*/
private static void mostrarTodas() throws SQLException {
Connection conexion = Conexion.conectar();
Statement st = conexion.createStatement();
ResultSet rs = st.executeQuery("SELECT MAX(CODIGO_SUCURSAL) FROM SUCURSAL");
rs.next();
int maxSuc = rs.getInt(1);
st.close();
rs.close();
Sucursal sucursal;
if (maxSuc != 0) {
for (int index = 1; index <= maxSuc; index++) {
boolean existente = true;
try {
existente = Banco.comprobarSucursal(index);
} catch (SucursalException ex) {
existente = false;
}
if (existente) {
try {
sucursal = Banco.devuelveSucursal(index);
System.out.println("|||||||||||||||||||||||||||||||||||||||||||||");
mostrarSucursal(sucursal);
System.out.println("|||||||||||||||||||||||||||||||||||||||||||||");
} catch (SucursalException ex) {
System.out.println("Se ha borrado una sucursal mientras se estaba intentando listar.");
}
}
}
} else {
System.out.println("No hay ninguna sucursal!4");
}
}
}
| true |
76f19bd98b9062dca2225886b3800b27d8cd2e70 | Java | gotenigatien/PubRoad | /AndroidApp/src/com/Object/PubRoadObject.java | UTF-8 | 1,889 | 2.453125 | 2 | [] | no_license | package com.Object;
import android.annotation.SuppressLint;
public class PubRoadObject implements Comparable<PubRoadObject> {
private int ID;
private String Nom;
private String Tel;
private String Email;
private String SiteWeb;
private String Entreprise;
private String Adresse;
private int Distance;
private int Occurance;
private Boolean IsParticulier;
public int getID() {
return ID;
}
public void setID(int NvID) {
this.ID=NvID;
}
public String getNom() {
return Nom;
}
public void setNom(String nvNom) {
this.Nom=nvNom;
}
public String getTel() {
return Tel;
}
public void setTel(String nvTel) {
this.Tel=nvTel;
}
public String getEmail() {
return Email;
}
public void setEmail(String nvEmail) {
this.Email= nvEmail;
}
public String getSiteWeb() {
return SiteWeb;
}
public void setSiteWeb(String nvSiteWeb) {
this.SiteWeb=nvSiteWeb;
}
public String getEntreprise() {
return Entreprise;
}
public void setEntreprise(String nvEntreprise) {
this.Entreprise= nvEntreprise;
}
public String getAdresse() {
return Adresse;
}
public void setAdresse(String nvAdresse) {
this.Adresse= nvAdresse;
}
public int getDistance() {
return Distance;
}
public void setDistance(int nvDistance) {
this.Distance= nvDistance;
}
public int getOccurance() {
return Occurance;
}
public void setOccurance(int nvOccurance) {
this.Occurance= nvOccurance;
}
public Boolean getIsParticulier() {
return IsParticulier;
}
public void setIsParticulier(Boolean nvIsParticulier) {
this.IsParticulier =nvIsParticulier;
}
@SuppressLint("UseValueOf")
@Override
public int compareTo(PubRoadObject another) {
Integer myDistance = new Integer(Distance);
Integer myDistance2 = new Integer(another.Distance);
return myDistance.compareTo(myDistance2);
}
}
| true |
c1e3beb5cb7f670ac55df69af867ab023c77452c | Java | paolo-itp/SnakeFromScratch | /CampoDiGioco.java | UTF-8 | 780 | 2.96875 | 3 | [] | no_license | import javax.swing.JPanel;
import java.awt.GridLayout;
public class CampoDiGioco extends JPanel
{
private Quadratino[][] matrice = new Quadratino [20][20];
public CampoDiGioco ( )
{
super(new GridLayout (20,20) );
for (int r =0 ; r<20; r++ )
for (int c = 0 ; c<20; c++ )
{
matrice[r][c]= new Quadratino( ) ;
this.add(matrice[r][c]).setLocation(r, c) ;
} ;
}
public void inizializzaTuttoPrato()
{
for (int r =0 ; r<20; r++ )
for (int c = 0 ; c<20; c++ )
{
matrice[r][c].setToPrato();
} ;
} ;
public Quadratino getQuadratino( PuntoDelCampo punto )
{
return (matrice[punto.getR()][punto.getC()]) ;
}
public Quadratino getQuadratino( int r, int c )
{
return (matrice[r][c]) ;
}
}
| true |
b5b0d59af5b1e6f4648a41d07ac519323df82fe5 | Java | mcollison/PiJ-sample-code | /SumPowers.java | UTF-8 | 368 | 3.171875 | 3 | [] | no_license | public class SumPowers{
public static void main(String[] args){
if( args.length == 2){
int terms = Integer.parseInt(args[0]);
int power = Integer.parseInt(args[1]);
int total = 0;
for(int i=1; i<=terms;i++){
total += Math.pow(i,power);
//System.out.println( total );
}
System.out.println( total );
}
}
}
| true |
1056a2d5c7dc953441ede8e36f428858ba8d00b8 | Java | Yumm1021/2020_classA_JavaDev_Java | /first/src/com/koreait/first/inter/InterGrand.java | UTF-8 | 118 | 1.890625 | 2 | [] | no_license | package com.koreait.first.inter;
public interface InterGrand {
final int MAX = 10;
void print();
void print2();
}
| true |
b7ab152279fbd45d38837495621e54f3f405390b | Java | wsgan001/RuleMining | /src/edu/cwru/eecs/statianalysis/dao/springimpl/ViolationDaoSpringImpl.java | UTF-8 | 8,806 | 2.15625 | 2 | [] | no_license | package edu.cwru.eecs.statianalysis.dao.springimpl;
import edu.cwru.eecs.statianalysis.data.PatternViolationKeyPair;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.sql.DataSource;
import org.springframework.jdbc.core.simple.ParameterizedBeanPropertyRowMapper;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
import edu.cwru.eecs.statianalysis.dao.ViolationDao;
import edu.cwru.eecs.statianalysis.dao.springimpl.rowmapper.InstanceVertexMapper;
import edu.cwru.eecs.statianalysis.dao.springimpl.rowmapper.PatternViolationKeyPairRowMapper;
import edu.cwru.eecs.statianalysis.dao.springimpl.rowmapper.VertexRowMapper;
import edu.cwru.eecs.statianalysis.dao.springimpl.rowmapper.ViolationRowMapper;
import edu.cwru.eecs.statianalysis.data.Edge;
import edu.cwru.eecs.statianalysis.data.Vertex;
import edu.cwru.eecs.statianalysis.pattern.Rule;
import edu.cwru.eecs.statianalysis.pattern.Violation;
import edu.cwru.eecs.statianalysis.to.EdgesPo;
public class ViolationDaoSpringImpl <V extends Vertex, E extends Edge<V>, Vio extends Violation<V, E>, M extends Map<Integer, V>> implements ViolationDao <V, E, Vio, M>{
private SimpleJdbcTemplate template;
public ViolationDaoSpringImpl(DataSource dataSource) {
this.template = new SimpleJdbcTemplate(dataSource);
}
@Override
public Vio getViolation(int violationKey) {
String sql = "select pattern_key, violation_key, vertex_key, lost_nodes, lost_edges, confirm, comments from violations where violation_key = ?";
return this.template.queryForObject(sql, new ViolationRowMapper<Vio>(), violationKey);
}
@Override
public List<V> getVertices(int violationKey) {
String sql = "select distinct v.VERTEX_KEY, v.vertex_label, v.vertex_kind_id, v.startline, v.endline, v.vertex_characters, v.pdg_id, v.vertex_ast from violation_node_info vni, vertex v\n"+
"where vni.violation_key = ?\n"+
"and vni.vertex_key = v.vertex_key\n";
//"order by node_index";
return template.query(sql, new VertexRowMapper<V>(), violationKey);
}
@Override
public List<EdgesPo> getEdges(int violationKey) {
String sql = "select src_vertex_key, tar_vertex_key, edge_type from pattern_violation_edges where violation_key = ?";
return template.query(sql, ParameterizedBeanPropertyRowMapper
.newInstance(EdgesPo.class), violationKey);
}
@Override
public List<V> getDeltaVertices(int patternKey, int violationKey) {
String sql = "select pni.node_index, v.vertex_label, v.vertex_kind_id, v.startline, v.endline, v.vertex_characters, v.pdg_id\n"+
"from vertex v, pattern_node_info pni\n"+
"where v.vertex_key = pni.vertex_key\n"+
"and pni.pattern_key = ? and pni.pattern_instance=0\n"+
"and pni.node_index in\n"+
"(\n"+
"select node_index from pattern_node_info where pattern_key = ? and pattern_instance=0\n"+
"minus\n"+
"select node_index from violation_node_info where violation_key = ?\n"+
")";
return template.query(sql, new VertexRowMapper<V>(), patternKey, patternKey, violationKey);
}
@Override
public List<EdgesPo> getDeltaEdges(int patternKey, int violationKey) {
String sql = "(\n"+
"select pni_src.node_index as src_vertex_key, pni_tar.node_index as tar_vertex_key, pi.edge_type\n"+
"from pattern_instance pi, pattern_node_info pni_src, pattern_node_info pni_tar\n"+
"where pi.PATTERN_KEY=? and pni_src.PATTERN_KEY=? and pni_tar.PATTERN_KEY=?\n"+
"and pi.graph_id=0 and pni_src.pattern_instance =0 and pni_tar.PATTERN_INSTANCE = 0\n"+
"and pi.src_vertex_key = pni_src.VERTEX_KEY\n"+
"and pi.tar_vertex_key = pni_tar.vertex_key\n"+
")\n"+
"minus\n"+
"(\n"+
"select vni_src.node_index, vni_tar.node_index, pve.edge_type\n"+
"from pattern_violation_edges pve, violation_node_info vni_src, violation_node_info vni_tar\n"+
"where pve.violation_key = ? and vni_src.violation_key = ? and vni_tar.violation_key = ?\n"+
"and pve.src_vertex_key = vni_src.vertex_key\n"+
"and pve.tar_vertex_key = vni_tar.vertex_key\n"+
")";
return template.query(sql, ParameterizedBeanPropertyRowMapper
.newInstance(EdgesPo.class),patternKey, patternKey, patternKey, violationKey, violationKey, violationKey);
}
@Override
public List<V> getVerticesForDeltaGraph(int patternKey, int violationKey) {
//This function get all the vertices appeared in the delta edges
List<EdgesPo> edgesPoList = this.getDeltaEdges(patternKey, violationKey);
Set<Integer> deltaVertexKeySet = new HashSet<Integer>();
for(int i=0; i<edgesPoList.size();i++)
{
EdgesPo edgesPo = edgesPoList.get(i);
if(!deltaVertexKeySet.contains(edgesPo.getSrcVertexKey()))
deltaVertexKeySet.add(edgesPo.getSrcVertexKey());
if(!deltaVertexKeySet.contains(edgesPo.getTarVertexKey()))
deltaVertexKeySet.add(edgesPo.getTarVertexKey());
}
String vertexKeys = "";
Iterator<Integer> iterator = deltaVertexKeySet.iterator();
while(iterator.hasNext())
{
vertexKeys = vertexKeys+iterator.next()+",";
}
/**
* BUGFIX: missing condition
*/
if(vertexKeys == "")
return null;
String sql = "select distinct pni.node_index, v.vertex_label, v.vertex_kind_id, v.startline, v.endline, v.vertex_characters, v.pdg_id, v.vertex_ast\n"+
"from vertex v, pattern_node_info pni\n"+
"where v.vertex_key = pni.vertex_key\n"+
"and pni.pattern_key = ? and pni.pattern_instance=0\n"+
"and pni.node_index in (\n"+
vertexKeys.substring(0, vertexKeys.length()-1)+
")";
return template.query(sql, new VertexRowMapper<V>(), patternKey);
}
@Override
public List<EdgesPo> getEdgesForDeltaGraph(int patternKey, int violationKey) {
return this.getDeltaEdges(patternKey, violationKey);
}
@Override
public List<M> getVertexIndexMaps(int violationKey) {
String sql = "select distinct vni.NODE_INDEX, v.VERTEX_KEY, v.vertex_label, v.vertex_kind_id, v.startline, v.endline, v.vertex_characters, v.pdg_id, v.vertex_ast\n"+
"from violation_node_info vni, vertex v\n"+
"where vni.violation_key = ?\n"+
"and vni.vertex_key = v.vertex_key\n"+
"order by vni.node_index";
return template.query(sql,new InstanceVertexMapper<V,M>(),violationKey);
}
@Override
public int getNumFunctionsCrossed(int violationKey) {
String sql = "select count(distinct v.pdg_id)\n"+
"from violation_node_info vni, vertex v\n"+
"where vni.violation_key = ?\n"+
"and vni.vertex_key = v.vertex_key";
return this.template.queryForInt(sql, violationKey);
}
@Override
public List<PatternViolationKeyPair> getTruePatternViolationKeyPairs() {
/**
* TODO: change back
*/
String sql = "select pattern_key, violation_key from violations where pattern_key > 0 and not (lost_edges = 0 and lost_edges = 0) and confirm = 'Y'\n" +
"order by violation_key";
return this.template.query(sql, new PatternViolationKeyPairRowMapper());
}
@Override
public List<PatternViolationKeyPair> getFalsePatternViolationKeyPairs() {
/**
* TODO: change back
*/
String sql = "select pattern_key, violation_key from violations where pattern_key > 0 and not (lost_edges = 0 and lost_edges = 0) and confirm = 'F'\n" +
"order by violation_key";
return this.template.query(sql, new PatternViolationKeyPairRowMapper());
}
@Override
public List<PatternViolationKeyPair> getAllPatternViolationKeyPairs() {
/**
* TODO: change back
*/
String sql = "select pattern_key, violation_key from violations where pattern_key > 0 and not (lost_edges = 0 and lost_edges = 0) and confirm in ('Y','F')\n" +
"order by violation_key";
return this.template.query(sql, new PatternViolationKeyPairRowMapper());
}
@Override
public List<Map<String, Object>> getViolationsForPattern(int patternKey,
String confirm) {
String sql = "select violation_key from violations where pattern_key = ? and confirm = ? and not(lost_nodes = 0 and lost_edges=0)";
return this.template.queryForList(sql, patternKey, confirm);
}
}
| true |
f362c3bf3fbd259a7afdf49727222a0bef545002 | Java | Carterin/yijiabao | /src/com/yijiabao/activitys/DaohangActivity.java | GB18030 | 6,914 | 1.8125 | 2 | [] | no_license | package com.yijiabao.activitys;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.search.sug.OnGetSuggestionResultListener;
import com.baidu.mapapi.search.sug.SuggestionResult;
import com.baidu.mapapi.search.sug.SuggestionSearch;
import com.baidu.mapapi.search.sug.SuggestionSearchOption;
import com.yijiabao.R;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
public class DaohangActivity extends Activity implements OnGetSuggestionResultListener {
private Button turn;
private Button search;
private AutoCompleteTextView qidian;
private AutoCompleteTextView zhongdian;
private String qidiantext;
private String zhongdiantext;
private String city;
private LocationClient locationClient;
private SuggestionSearch msuggestionSearch;
private ArrayAdapter<String> adapter;
public BDLocationListener myListener = new BDLocationListener() {
@Override
public void onReceiveLocation(BDLocation location) {
// TODO Auto-generated method stub
city = location.getCity();
}
@Override
public void onConnectHotSpotMessage(String arg0, int arg1) {
// TODO Auto-generated method stub
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
//ʹSDK֮ǰʼcontextϢApplicationContext
//ע÷ҪsetContentView֮ǰʵ
SDKInitializer.initialize(getApplicationContext());
setContentView(R.layout.activity_daohang);
//ؼʼ
turn = (Button) findViewById(R.id.bt_turn);
search = (Button) findViewById(R.id.bt_search);
qidian = (AutoCompleteTextView) findViewById(R.id.autoTV_qidian);
zhongdian = (AutoCompleteTextView) findViewById(R.id.autoTV_zhongdian);
//ֶԵť
turn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
qidiantext = qidian.getText().toString().trim();
zhongdiantext = zhongdian.getText().toString().trim();
qidian.setText(zhongdiantext);
zhongdian.setText(qidiantext);
}
});
//ť
search.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(getApplicationContext(), Search_MapActivity.class);
qidiantext = qidian.getText().toString().trim();
zhongdiantext = zhongdian.getText().toString().trim();
Bundle bundle = new Bundle();
bundle.putString("qidian", qidiantext);
bundle.putString("zhongdian", zhongdiantext);
intent.putExtras(bundle);
startActivity(intent);
}
});
//ʵLocationClient
locationClient = new LocationClient(getApplicationContext());
//ע
locationClient.registerLocationListener(myListener);
//öλ
this.setLocationOption();
//ʼλ
locationClient.start();
//mpoiSearch = PoiSearch.newInstance();
// mpoiSearch.setOnGetPoiSearchResultListener(this);
msuggestionSearch = SuggestionSearch.newInstance();
msuggestionSearch.setOnGetSuggestionResultListener(this);
adapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.autocompletetextview);
zhongdian.setAdapter(adapter);
qidian.setAdapter(adapter);
//ַ仯ʱ̬б
qidian.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
if (s.length()<=0) {
return;
}
msuggestionSearch.requestSuggestion((new SuggestionSearchOption()).keyword(s.toString()).city(city));
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
/*if (s.length()<=0) {
return;
}
msuggestionSearch.requestSuggestion((new SuggestionSearchOption()).keyword(s.toString()).city(city));
*/}
});
//ַ仯ʱ̬б
zhongdian.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
if (s.length()<=0) {
return;
}
msuggestionSearch.requestSuggestion((new SuggestionSearchOption()).keyword(s.toString()).city(city));
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
/*if (s.length()<=0) {
return;
}
msuggestionSearch.requestSuggestion((new SuggestionSearchOption()).keyword(s.toString()).city(city));
*/}
});
}//onCreateλ
//λ
private void setLocationOption() {
// TODO Auto-generated method stub
LocationClientOption option = new LocationClientOption();
option.setOpenGps(true);//GPS
option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);//öλģʽ߾ȷ
option.setCoorType("bd09ll");//صĶλǰٶȾγȣĬΪgcj02
option.setScanSpan(5000);//÷λļʱΪ5000ms
option.setIsNeedAddress(true);//صĶλַϢ
option.setNeedDeviceDirect(true);//صĶλϢֻͷķ
locationClient.setLocOption(option);
}
@Override
protected void onDestroy() {
// ͷԴ
locationClient.stop();
super.onDestroy();
}
@Override
public void onGetSuggestionResult(SuggestionResult arg0) {
// TODO Auto-generated method stub
if (arg0==null||arg0.getAllSuggestions()==null) {
return;
}
//adapter.clear();
for (SuggestionResult.SuggestionInfo info : arg0.getAllSuggestions()) {
if (info.key!=null) {
adapter.add(info.key);
}
}
adapter.notifyDataSetChanged();
}
}
| true |
0c3c25582b4b73c24c25564d22d26f05584cb4f7 | Java | java-projects-kenanhancer/enum-usage | /src/com/extuni/program3/Main.java | UTF-8 | 454 | 3.546875 | 4 | [] | no_license | package com.extuni.program3;
enum Color {
RED, GREEN, BLUE;
private Color() {
System.out.println("Constructor called for : " + this.toString());
}
public void colorInfo() {
System.out.println("Universal Color");
}
}
public class Main {
public static void main(String[] args) {
Color color = Color.BLUE;
System.out.println(color);
color.colorInfo();
}
}
| true |
2a17a5a0dfcfe08cbd610a4bf882720a360ba6d0 | Java | ReteganCatalin/ISS | /src/main/java/ro/ubb/iss/CMS/Services/ConferenceService.java | UTF-8 | 675 | 2.15625 | 2 | [] | no_license | package ro.ubb.iss.CMS.Services;
import ro.ubb.iss.CMS.domain.Conference;
import java.util.Date;
import java.util.List;
import java.util.Optional;
public interface ConferenceService {
Optional<Conference> findConference(int conferenceID);
List<Conference> findAll();
Conference updateConference(
int conferenceID,
String name,
Date startDate,
Date endDate,
Date proposalDeadline,
Date paperDeadline,
Date reviewDeadline);
Conference saveConference(
String name, Date startDate, Date endDate, Date proposalDeadline, Date paperDeadline,Date reviewDeadline,int chair);
void deleteConference(int conferenceID);
}
| true |
d92729d62b91f69d749c90126da55d87f0381706 | Java | lukehuang/design-patterns | /design-patterns/src/main/java/pattern/structural/proxy/b/MainB.java | UTF-8 | 620 | 2.875 | 3 | [
"MIT"
] | permissive | package pattern.structural.proxy.b;
import java.lang.reflect.Proxy;
/**
*
* @author leishiguang
* date 2018/10/4 11:19
* @version v1.0
*/
public class MainB {
static void customer(ProxyInterface pi) {
pi.say();
}
public static void main(String[] args) {
RealObject real = new RealObject();
ProxyInterface proxy = (ProxyInterface)
Proxy.newProxyInstance(
ProxyInterface.class.getClassLoader(),
new Class[]{ProxyInterface.class},
new ProxyObject(real));
customer(proxy);
}
}
| true |
7846e78c4b4bd19b1bf2ee2cf93cdddf5f49a102 | Java | VinyarionHyarmendacil/Fukkit | /src/main/java/vinyarion/fukkit/rpg/palantir/FFakeNetworkManager.java | UTF-8 | 463 | 1.835938 | 2 | [] | no_license | package vinyarion.fukkit.rpg.palantir;
import io.netty.util.concurrent.GenericFutureListener;
import net.minecraft.network.NetworkManager;
import net.minecraft.network.Packet;
public class FFakeNetworkManager extends NetworkManager {
public FFakeNetworkManager() {
super(false);
}
@Override
public void scheduleOutboundPacket(Packet p_150725_1_, GenericFutureListener... p_150725_2_) {
}
@Override
public void processReceivedPackets() {
}
}
| true |
24274606d51b99c230e7db84ab54b00c7e252ef5 | Java | netzu/stock-exchange | /stock-exchange-commons/src/test/java/data/collector/EODTickHistoryTest.java | UTF-8 | 6,997 | 2.453125 | 2 | [] | no_license | package data.collector;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import org.joda.time.DateTime;
import org.junit.Test;
import utils.MockForCommonsTest;
import configuration.Share;
public class EODTickHistoryTest {
MockForCommonsTest mock = new MockForCommonsTest();
@Test
public void setStockTickerDataListTest() throws ParseException{
StockTickerHistory tickerCollection = mock.readStockTickerHistory("data/collector/tickerHistory/setStockTickerDataListTest");
List<EODTick> EODTickDataList = new ArrayList<EODTick>();
tickerCollection.setEODTickDataList(EODTickDataList);
assertTrue(EODTickDataList.equals(tickerCollection.getEODTickDataList()));
}
@Test
public void subListOfCollectionException() throws ParseException{
StockTickerHistory tickerCollection = mock.readStockTickerHistory("data/collector/tickerHistory/setStockTickerDataListTest");
try{
List<EODTick> EODTickDataList = tickerCollection.subListOfCollection(4, 2);
fail("Exception not found when expected");
}catch(StockExchangeIllegalStateException ex){
String expectedErrorMessage = "Cannot create sublist when FROM is greather or equal TO";
assertTrue(ex.getMessage().equals(expectedErrorMessage));
}
}
@Test
public void subListOfCollectionTest() throws ParseException{
StockTickerHistory tickerCollection = mock.readStockTickerHistory("data/collector/tickerHistory/subListOfCollectionTest_Input");
try{
List<EODTick> currentResults = tickerCollection.subListOfCollection(2, 6);
List<EODTick> expectedResults = mock.readStockTickerHistory("data/collector/tickerHistory/subListOfCollectionTest_Expected").getEODTickDataList();
assertTrue(currentResults.equals(expectedResults));
}catch(Exception ex){
fail("Exception when not expected");
}
}
@Test
public void findStockByDateEmptyTicker(){
StockTickerHistory tickerCollection = new StockTickerHistory();
DateTime date = Share.COMMON_FORMATTER.parseDateTime(("20120319"));
try{
tickerCollection.findStockByDate(date);
fail("Exception not found when expected");
}catch(StockExchangeIllegalStateException ex){
String expectedErrorMessage = "Cannot find stock by date if ticker's collection is empty";
assertTrue(ex.getMessage().equals(expectedErrorMessage));
}
}
@Test
public void findStockByDateWhenNullDate() throws ParseException{
StockTickerHistory tickerCollection = new StockTickerHistory();
tickerCollection.setEODTickDataList(mock.readStockTickerHistory("data/collector/tickerHistory/findStockByDateNotFound").getEODTickDataList());
try{
tickerCollection.findStockByDate(null);
fail("Exception not found when expected");
}catch(StockExchangeIllegalStateException ex){
String expectedErrorMessage = "Cannot find ticker by date if date is null";
assertTrue(ex.getMessage().equals(expectedErrorMessage));
}
}
@Test
public void findStockByDateNotFound() throws ParseException{
StockTickerHistory tickerCollection = new StockTickerHistory();
tickerCollection.setEODTickDataList(mock.readStockTickerHistory("data/collector/tickerHistory/findStockByDateNotFound").getEODTickDataList());
DateTime date = Share.COMMON_FORMATTER.parseDateTime(("20100417"));
try{
tickerCollection.findStockByDate(date);
fail("Exception not found when expected");
}catch(StockExchangeIllegalStateException ex){
String expectedErrorMessage = "Could not find a stock in given day";
assertTrue(ex.getMessage().equals(expectedErrorMessage));
}
}
@Test
public void findStockByDateFound() throws ParseException{
StockTickerHistory tickerCollection = new StockTickerHistory();
tickerCollection.setEODTickDataList(mock.readStockTickerHistory("data/collector/tickerHistory/findStockByDateNotFound").getEODTickDataList());
DateTime date = Share.COMMON_FORMATTER.parseDateTime(("20100412"));
EODTick currentResult = tickerCollection.findStockByDate(date);
assertTrue("Diffrent StockName than expected", currentResult.getStockName().equals("Test"));
assertTrue("Diffrent Date than expected", currentResult.getDate().equals(date));
assertTrue("Diffrent Open than expected", currentResult.getOpen() == 1.23);
assertTrue("Diffrent High than expected", currentResult.getHigh() == 2.92);
assertTrue("Diffrent Low than expected", currentResult.getLow() == 0.23);
assertTrue("Diffrent Close than expected", currentResult.getClose() == 3.58);
assertTrue("Diffrent Volumen than expected", currentResult.getVolumen() == 1232);
}
@Test
public void findStockIndexByDateTickerEmpty(){
StockTickerHistory tickerCollection = new StockTickerHistory();
DateTime date = Share.COMMON_FORMATTER.parseDateTime(("20120319"));
try{
tickerCollection.findStockIndexByDate(date);
fail("Exception not found when expected");
}catch(StockExchangeIllegalStateException ex){
String expectedErrorMessage = "Cannot find index for a ticker with given date for an empty ticker collection";
assertTrue(ex.getMessage().equals(expectedErrorMessage));
}
}
@Test
public void findStockIndexByDateIsNull() throws ParseException{
StockTickerHistory tickerCollection = new StockTickerHistory();
tickerCollection.setEODTickDataList(mock.readStockTickerHistory("data/collector/tickerHistory/findStockByDateNotFound").getEODTickDataList());
try{
tickerCollection.findStockIndexByDate(null);
fail("Exception not found when expected");
}catch(StockExchangeIllegalStateException ex){
String expectedErrorMessage = "Cannot find index for a ticker when date is null";
assertTrue(ex.getMessage().equals(expectedErrorMessage));
}
}
// @Test
// public void findStockIndexByDateFound() throws ParseException{
// StockTickerHistory tickerCollection = new StockTickerHistory();
// tickerCollection.setEODTickDataList(mock.readStockTickerHistory("data/collector/tickerHistory/findStockByDateNotFound").getEODTickDataList());
// DateTime date = dateFormater.parseDateTime(("20120319"));
//
// int expectedResult = 6;
//
// try{
// int currentResult = tickerCollection.findStockIndexByDate(date);
// assertTrue(currentResult == expectedResult);
// }catch(Exception ex){
// fail("Exception when not expected");
// }
// }
@Test
public void findStockIndexByDateNotFound() throws ParseException{
StockTickerHistory tickerCollection = new StockTickerHistory();
tickerCollection.setEODTickDataList(mock.readStockTickerHistory("data/collector/tickerHistory/findStockByDateNotFound").getEODTickDataList());
DateTime date = Share.COMMON_FORMATTER.parseDateTime(("20120317"));
try{
tickerCollection.findStockIndexByDate(date);
fail("Exception not found when expected");
}catch(StockExchangeIllegalStateException ex){
String expectedErrorMessage = "Could not find it";
assertTrue(ex.getMessage().equals(expectedErrorMessage));
}
}
}
| true |
245b66ee3eb2c9037393cfaa7634b09f763b5bb2 | Java | charlietran714/CSC250_HW13_Template2 | /app/src/main/java/com/example/awesomefat/csc250_hw13_template/Core.java | UTF-8 | 204 | 1.757813 | 2 | [] | no_license | package com.example.awesomefat.csc250_hw13_template;
/**
* Created by awesomefat on 11/9/17.
*/
public class Core
{
public static String myName = "N/A";
public static MyObject myObj = null;
}
| true |
a7cc34fe0e53e876f04559a7910873160cc23bc0 | Java | bnzonlia/8INF872 | /B-For/app/src/main/java/bfor8inf972/b_for/view/HomeActivity.java | UTF-8 | 7,419 | 1.8125 | 2 | [] | no_license | package bfor8inf972.b_for.view;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import com.facebook.login.widget.ProfilePictureView;
import bfor8inf972.b_for.R;
import bfor8inf972.b_for.representation.User;
import bfor8inf972.b_for.view.Fragments.CreateEventFragment;
import bfor8inf972.b_for.view.Fragments.FindEventFragment;
import bfor8inf972.b_for.view.Fragments.ManageEvents;
import bfor8inf972.b_for.view.Fragments.OverviewFragment;
import bfor8inf972.b_for.view.Fragments.ProfilFragment;
import bfor8inf972.b_for.view.Fragments.SettingsFragment;
import bfor8inf972.b_for.view.Fragments.TermOfUseFragment;
public class HomeActivity extends AppCompatActivity
implements ProfilFragment.OnFragmentInteractionListener,
CreateEventFragment.OnFragmentInteractionListener,
FindEventFragment.OnFragmentInteractionListener,
TermOfUseFragment.OnFragmentInteractionListener,
SettingsFragment.OnFragmentInteractionListener,
ManageEvents.OnFragmentInteractionListener,
OverviewFragment.OnFragmentInteractionListener,
NavigationView.OnNavigationItemSelectedListener {
private ManageEvents manageEventsFragment;
private FindEventFragment findEventFragment;
private ProfilFragment profilFragment;
private SettingsFragment settingFragment;
private TermOfUseFragment termOfUseFragment;
private OverviewFragment overviewFragment;
private User user;
private String currentFragmentName;
private int currentFragmentID;
public HomeActivity() {
manageEventsFragment = new ManageEvents();
findEventFragment = new FindEventFragment();
profilFragment = new ProfilFragment();
settingFragment = new SettingsFragment();
termOfUseFragment = new TermOfUseFragment();
overviewFragment = new OverviewFragment();
currentFragmentID = -1;
currentFragmentName = null;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
user = (User) getIntent().getSerializableExtra("User");
setContentView(R.layout.activity_home);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
InitialiseUserInfo(navigationView.getHeaderView(0));
//replace fragment only if it's first time on activity
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction().
replace(R.id.FragmentContainer, overviewFragment)
.commit();
currentFragmentName = getResources().getString(R.string.overview_title);
currentFragmentID = R.id.nav_overview;
}
//get restored data
if (savedInstanceState != null) {
currentFragmentName = savedInstanceState.getString("currentFragmentName");
}
}
private void InitialiseUserInfo(View v) {
TextView firstName = (TextView) v.findViewById(R.id.first_name);
TextView lastName = (TextView) v.findViewById(R.id.last_name);
ProfilePictureView profilePictureView = (ProfilePictureView) v.findViewById(R.id.picture_profile);
if (user != null) {
firstName.setText(user.getFirstName());
lastName.setText(user.getLastName());
profilePictureView.setProfileId(user.getId());
}
}
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putString("currentFragmentName", currentFragmentName);
super.onSaveInstanceState(savedInstanceState);
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id != currentFragmentID) {
currentFragmentID = id;
if (id == R.id.nav_profil) {
getSupportFragmentManager().beginTransaction().
replace(R.id.FragmentContainer, profilFragment).addToBackStack(currentFragmentName)
.commit();
currentFragmentName = getResources().getString(R.string.profil_title);
} else if (id == R.id.nav_termOfUse) {
getSupportFragmentManager().beginTransaction().
replace(R.id.FragmentContainer, termOfUseFragment).addToBackStack(currentFragmentName)
.commit();
currentFragmentName = getResources().getString(R.string.termOfUse_title);
} else if (id == R.id.nav_manageEvent) {
getSupportFragmentManager().beginTransaction().
replace(R.id.FragmentContainer, manageEventsFragment).addToBackStack(currentFragmentName)
.commit();
currentFragmentName = getResources().getString(R.string.manageEvent_title);
} else if (id == R.id.nav_settings) {
getSupportFragmentManager().beginTransaction().
replace(R.id.FragmentContainer, settingFragment).addToBackStack(currentFragmentName)
.commit();
currentFragmentName = getResources().getString(R.string.settings_title);
} else if (id == R.id.nav_findEvent) {
getSupportFragmentManager().beginTransaction().
replace(R.id.FragmentContainer, findEventFragment).addToBackStack(currentFragmentName)
.commit();
currentFragmentName = getResources().getString(R.string.findEvent_title);
} else if (id == R.id.nav_overview) {
getSupportFragmentManager().beginTransaction().
replace(R.id.FragmentContainer, overviewFragment).addToBackStack(currentFragmentName)
.commit();
currentFragmentName = getResources().getString(R.string.overview_title);
}
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
@Override
public void onFragmentInteraction(Uri uri) {
}
}
| true |
7ab47cddd275f2c91c512e77553eed20d6d86632 | Java | chugunov-v/refactoring | /src/main/java/edu/refactor/demo/core/customer/CustomerDAO.java | UTF-8 | 523 | 1.953125 | 2 | [] | no_license | package edu.refactor.demo.core.customer;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import edu.refactor.demo.entities.Customer;
import java.util.List;
import java.util.Optional;
@Repository
public interface CustomerDAO extends CrudRepository<Customer, Long> {
List<Customer> loadNotDeletedCustomers();
boolean existsByLoginAndEmail(String login, String email);
Optional<Customer> loadCustomerByLoginAndEmail(String login, String email);
} | true |
f2f2f0058a0f53405fd00794378d184bf8455da1 | Java | Zhaoxianxv/zhao_sheng_old_one | /zhao_sheng/build/generated/source/apt/debug/com/yfy/app/duty/DutyDateActivity$$ViewBinder.java | UTF-8 | 843 | 1.820313 | 2 | [] | no_license | // Generated code from Butter Knife. Do not modify!
package com.yfy.app.duty;
import android.view.View;
import butterknife.ButterKnife.Finder;
public class DutyDateActivity$$ViewBinder<T extends com.yfy.app.duty.DutyDateActivity> extends com.yfy.base.activity.BaseActivity$$ViewBinder<T> {
@Override public void bind(final Finder finder, final T target, Object source) {
super.bind(finder, target, source);
View view;
view = finder.findRequiredView(source, 2131297658, "field 'top_layout'");
target.top_layout = view;
view = finder.findRequiredView(source, 2131297289, "field 'parent_name'");
target.parent_name = finder.castView(view, 2131297289, "field 'parent_name'");
}
@Override public void unbind(T target) {
super.unbind(target);
target.top_layout = null;
target.parent_name = null;
}
}
| true |
1acb9b57bd04eb360f795bcc7de0063a830c24cd | Java | shine-spike/Restaurant-App | /phase1/src/model/EmployeeController.java | UTF-8 | 810 | 3.5 | 4 | [] | no_license | package model;
import java.util.ArrayList;
/**
* Controls all aspects of employees in the restaurant.
*/
public class EmployeeController {
// List of employees indexed by employee number
private final ArrayList<String> employees;
/**
* Creates an EmployeeController with no employees
*/
EmployeeController() {
employees = new ArrayList<>();
}
/**
* Adds an Employee to this EmployeeController
*
* @param name the first and last name of the Employee to be added
*/
public void addEmployee(String name) {
employees.add(name);
}
/**
* Gets the name of an Employee from the Employee's id
*
* @param id the id of the desired Employee
* @return the name of Employee id
*/
public String getEmployeeName(int id) {
return employees.get(id);
}
}
| true |
9d4ec8cfef590c5bed459a69d207d26b68e1b4ee | Java | xuechaoke/DesignpPatterns | /src/TheFactoryPattern/Factory.java | UTF-8 | 138 | 2.359375 | 2 | [] | no_license | package TheFactoryPattern;
/**
* Created by Administrator on 2018/6/28/028.
*/
public interface Factory {
Animal createAnimal();
}
| true |
729410fcf76c62a46073ad1c21e792b2213886dc | Java | Zer0XoL/Shadow | /Shadow/src/Shadow/Util/Math/Point.java | UTF-8 | 672 | 3.375 | 3 | [] | no_license | package Shadow.Util.Math;
/*
* A generalized functional structure for a point in 1, 2, 3 or EVEN 4 if you're nuts enough.
*/
public class Point {
public double x, y, z, w;
public Point(double x, double y) {
set(x, y);
}
public Point(double x, double y, double z) {
set(x, y, z);
}
public Point(double x, double y, double z, double w) {
set(x, y, z, w);
}
public void set(double x, double y, double z, double w) {
this.x = x;
this.y = y;
this.z = z;
this.w = w;
}
public void set(double x, double y, double z) {
set(x, y, z, 0);
}
public void set(double x, double y) {
set(x, y, 0, 0);
}
}
| true |
0fb8a8beb9b9e37b96427b404db25e3cce73b861 | Java | Hjordrup/Variabler_Opgave_Fra_Klassen | /src/Variabler.java | UTF-8 | 703 | 2.546875 | 3 | [] | no_license | public class Variabler {
public static void main(String[] args) {
byte etTal = 126;
short etKortTal = 31000;
int etHelTal = 10;
long etLangtTal = 1000l;
float etTalMedFlyvendeDecimal = 9.55445f;
double etStortTal = 5656556;
boolean jaEllerNej = true;
char etBokstav = 'a';
System.out.println(etTal);
System.out.println(etKortTal);
System.out.println(etHelTal);
System.out.println(etLangtTal);
System.out.println(etTalMedFlyvendeDecimal);
System.out.println(etStortTal);
System.out.println(jaEllerNej);
System.out.println(etBokstav);
}
}
| true |
114f5d3df491f87d4209c5f3038460ef294c9a92 | Java | DAMLuis/Adivinador_LuisMonge | /app/src/main/java/com/example/pdmm_luismonge/adivinador_luismonge/Info_Jugador.java | UTF-8 | 636 | 1.859375 | 2 | [] | no_license | package com.example.pdmm_luismonge.adivinador_luismonge;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ListView;
public class Info_Jugador extends AppCompatActivity {
ListView listView;
Info_JugadorAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.esqueleto_info_jugador);
adapter = new Info_JugadorAdapter(this, JugarActivity.info);
listView = (ListView) findViewById(R.id.mListView);
listView.setAdapter(adapter);
}
}
| true |
89d3a7894490d0b201eae220431d8f62d8e3ca26 | Java | nls-jajuko/citygml4j | /src-gen/main/java/net/opengis/gml/OperationMethodType.java | UTF-8 | 7,895 | 1.945313 | 2 | [
"LGPL-3.0-only",
"Apache-2.0"
] | permissive | //
// Diese Datei wurde mit der JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.3.2 generiert
// Siehe <a href="https://javaee.github.io/jaxb-v2/">https://javaee.github.io/jaxb-v2/</a>
// Änderungen an dieser Datei gehen bei einer Neukompilierung des Quellschemas verloren.
// Generiert: 2019.02.03 um 11:14:53 PM CET
//
package net.opengis.gml;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
/**
* Definition of an algorithm used to perform a coordinate operation. Most operation methods use a number of operation parameters, although some coordinate conversions use none. Each coordinate operation using the method assigns values to these parameters.
*
* <p>Java-Klasse für OperationMethodType complex type.
*
* <p>Das folgende Schemafragment gibt den erwarteten Content an, der in dieser Klasse enthalten ist.
*
* <pre>
* <complexType name="OperationMethodType">
* <complexContent>
* <extension base="{http://www.opengis.net/gml}OperationMethodBaseType">
* <sequence>
* <element ref="{http://www.opengis.net/gml}methodID" maxOccurs="unbounded" minOccurs="0"/>
* <element ref="{http://www.opengis.net/gml}remarks" minOccurs="0"/>
* <element ref="{http://www.opengis.net/gml}methodFormula"/>
* <element ref="{http://www.opengis.net/gml}sourceDimensions"/>
* <element ref="{http://www.opengis.net/gml}targetDimensions"/>
* <element ref="{http://www.opengis.net/gml}usesParameter" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "OperationMethodType", propOrder = {
"methodID",
"remarks",
"methodFormula",
"sourceDimensions",
"targetDimensions",
"usesParameter"
})
public class OperationMethodType
extends OperationMethodBaseType
{
protected List<IdentifierType> methodID;
protected StringOrRefType remarks;
@XmlElement(required = true)
protected CodeType methodFormula;
@XmlElement(required = true)
@XmlSchemaType(name = "positiveInteger")
protected BigInteger sourceDimensions;
@XmlElement(required = true)
@XmlSchemaType(name = "positiveInteger")
protected BigInteger targetDimensions;
protected List<AbstractGeneralOperationParameterRefType> usesParameter;
/**
* Set of alternative identifications of this operation method. The first methodID, if any, is normally the primary identification code, and any others are aliases. Gets the value of the methodID property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the methodID property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getMethodID().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link IdentifierType }
*
*
*/
public List<IdentifierType> getMethodID() {
if (methodID == null) {
methodID = new ArrayList<IdentifierType>();
}
return this.methodID;
}
public boolean isSetMethodID() {
return ((this.methodID!= null)&&(!this.methodID.isEmpty()));
}
public void unsetMethodID() {
this.methodID = null;
}
/**
* Comments on or information about this operation method, including source information.
*
* @return
* possible object is
* {@link StringOrRefType }
*
*/
public StringOrRefType getRemarks() {
return remarks;
}
/**
* Legt den Wert der remarks-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link StringOrRefType }
*
*/
public void setRemarks(StringOrRefType value) {
this.remarks = value;
}
public boolean isSetRemarks() {
return (this.remarks!= null);
}
/**
* Ruft den Wert der methodFormula-Eigenschaft ab.
*
* @return
* possible object is
* {@link CodeType }
*
*/
public CodeType getMethodFormula() {
return methodFormula;
}
/**
* Legt den Wert der methodFormula-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link CodeType }
*
*/
public void setMethodFormula(CodeType value) {
this.methodFormula = value;
}
public boolean isSetMethodFormula() {
return (this.methodFormula!= null);
}
/**
* Ruft den Wert der sourceDimensions-Eigenschaft ab.
*
* @return
* possible object is
* {@link BigInteger }
*
*/
public BigInteger getSourceDimensions() {
return sourceDimensions;
}
/**
* Legt den Wert der sourceDimensions-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link BigInteger }
*
*/
public void setSourceDimensions(BigInteger value) {
this.sourceDimensions = value;
}
public boolean isSetSourceDimensions() {
return (this.sourceDimensions!= null);
}
/**
* Ruft den Wert der targetDimensions-Eigenschaft ab.
*
* @return
* possible object is
* {@link BigInteger }
*
*/
public BigInteger getTargetDimensions() {
return targetDimensions;
}
/**
* Legt den Wert der targetDimensions-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link BigInteger }
*
*/
public void setTargetDimensions(BigInteger value) {
this.targetDimensions = value;
}
public boolean isSetTargetDimensions() {
return (this.targetDimensions!= null);
}
/**
* Unordered list of associations to the set of operation parameters and parameter groups used by this operation method. Gets the value of the usesParameter property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the usesParameter property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getUsesParameter().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link AbstractGeneralOperationParameterRefType }
*
*
*/
public List<AbstractGeneralOperationParameterRefType> getUsesParameter() {
if (usesParameter == null) {
usesParameter = new ArrayList<AbstractGeneralOperationParameterRefType>();
}
return this.usesParameter;
}
public boolean isSetUsesParameter() {
return ((this.usesParameter!= null)&&(!this.usesParameter.isEmpty()));
}
public void unsetUsesParameter() {
this.usesParameter = null;
}
public void setMethodID(List<IdentifierType> value) {
this.methodID = value;
}
public void setUsesParameter(List<AbstractGeneralOperationParameterRefType> value) {
this.usesParameter = value;
}
}
| true |
f377689a6c710caeb6364b9b7372077f7e526f5d | Java | matteomannavola/TheHeist | /adventure/src/main/java/TheHeist/GraphicUserInterface/HeistGameFrame.java | UTF-8 | 48,991 | 2.1875 | 2 | [] | no_license | package TheHeist.GraphicUserInterface;
import TheHeist.HeistGame;
import TheHeist.ItalianCharacterParameters;
import TheHeist.ItalianCommandNames;
import TheHeist.ItalianEnemyParameters;
import TheHeist.ItalianObjectParameters;
import Adventure.Parser.Parser;
import Adventure.Parser.ParserOutput;
import Adventure.Type.AdvObject;
import Adventure.Type.CommandType;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.Timer;
public class HeistGameFrame extends javax.swing.JFrame {
private HeistGame game;
private final Parser parser = new Parser();
private boolean saved = true;
private boolean fast = false;
private Timer tm;
private StringBuilder s=new StringBuilder();
private int counter = 0;
private AudioInputStream ais;
private Clip clip;
private boolean music=true;
public HeistGameFrame() {
initComponents();
init();
ActionListener taskPerformer = (ActionEvent evt) -> {
enableElements(false);
counter++;
if(counter >= s.length())
{
counter = 0;
tm.stop();
enableElements(true);
}else{
StringBuilder supp=new StringBuilder();
supp.append(s.toString().charAt(counter));
GameTextArea.append(supp.toString());
supp=new StringBuilder();
}
};
int delay = 10;
tm = new Timer(delay, taskPerformer);
tm.start();
playMusic();
}
private void playMusic(){
try {
ais = AudioSystem.getAudioInputStream(new File("music/Payday 2 Official Soundtrack - AndNowWeWait.wav"));
clip = AudioSystem.getClip();
clip.open(ais);
startMusic();
} catch (Exception exc) {
JOptionPane.showMessageDialog(this, "Errore nella riproduzione della musica", "Errore" ,JOptionPane.ERROR_MESSAGE);
}
}
private void startMusic(){
clip.start();
clip.loop(Clip.LOOP_CONTINUOUSLY);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jScrollPane2 = new javax.swing.JScrollPane();
GameTextArea = new javax.swing.JTextArea();
GameCommandField = new javax.swing.JTextField();
EnterButton = new javax.swing.JButton();
WestButton = new javax.swing.JButton();
NorthButton = new javax.swing.JButton();
SouthButton = new javax.swing.JButton();
TitleLabel = new javax.swing.JLabel();
LoadButton = new javax.swing.JButton();
SaveButton = new javax.swing.JButton();
jScrollPane3 = new javax.swing.JScrollPane();
InventoryTextArea = new javax.swing.JTextArea();
InventoryLabel = new javax.swing.JLabel();
CurrentRoomTitleLabel = new javax.swing.JLabel();
CurrentRoomLabel = new javax.swing.JLabel();
LookButton = new javax.swing.JButton();
EastButton = new javax.swing.JButton();
HealthTitleLabel = new javax.swing.JLabel();
HealthLabel = new javax.swing.JLabel();
MenuBar = new javax.swing.JMenuBar();
FileMenu = new javax.swing.JMenu();
NewMenuItem = new javax.swing.JMenuItem();
jSeparator2 = new javax.swing.JPopupMenu.Separator();
LoadMenuItem = new javax.swing.JMenuItem();
SaveMenuItem = new javax.swing.JMenuItem();
jSeparator1 = new javax.swing.JPopupMenu.Separator();
ExitMenuItem = new javax.swing.JMenuItem();
Options = new javax.swing.JMenu();
FastText = new javax.swing.JCheckBoxMenuItem();
Music = new javax.swing.JCheckBoxMenuItem();
AboutMenu = new javax.swing.JMenu();
AboutMenuItem = new javax.swing.JMenuItem();
HelpMenu = new javax.swing.JMenu();
HelpMenu_HeistItem = new javax.swing.JMenuItem();
HelpMenu_CommandsItem = new javax.swing.JMenuItem();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("The Heist");
setIconImage((new ImageIcon("img/diamond.gif")).getImage());
setResizable(false);
jPanel1.setBackground(new java.awt.Color(153, 102, 255));
jScrollPane2.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
jScrollPane2.setAutoscrolls(true);
GameTextArea.setEditable(false);
GameTextArea.setBackground(new java.awt.Color(204, 204, 255));
GameTextArea.setColumns(20);
GameTextArea.setRows(5);
jScrollPane2.setViewportView(GameTextArea);
GameCommandField.setToolTipText("Inserisci comando...");
GameCommandField.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
GameCommandFieldKeyReleased(evt);
}
});
EnterButton.setBackground(new java.awt.Color(102, 0, 204));
EnterButton.setForeground(new java.awt.Color(255, 255, 255));
EnterButton.setText("INVIO");
EnterButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
EnterButtonActionPerformed(evt);
}
});
WestButton.setBackground(new java.awt.Color(102, 0, 204));
WestButton.setForeground(new java.awt.Color(255, 255, 255));
WestButton.setText("Ovest");
WestButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
WestButtonActionPerformed(evt);
}
});
NorthButton.setBackground(new java.awt.Color(102, 0, 204));
NorthButton.setForeground(new java.awt.Color(255, 255, 255));
NorthButton.setText("Nord");
NorthButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
NorthButtonActionPerformed(evt);
}
});
SouthButton.setBackground(new java.awt.Color(102, 0, 204));
SouthButton.setForeground(new java.awt.Color(255, 255, 255));
SouthButton.setText("Sud");
SouthButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
SouthButtonActionPerformed(evt);
}
});
TitleLabel.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
TitleLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
TitleLabel.setText("--- THE HEIST ---");
LoadButton.setBackground(new java.awt.Color(102, 0, 204));
LoadButton.setForeground(new java.awt.Color(255, 255, 255));
LoadButton.setText("CARICA");
LoadButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
LoadButtonActionPerformed(evt);
}
});
SaveButton.setBackground(new java.awt.Color(102, 0, 204));
SaveButton.setForeground(new java.awt.Color(255, 255, 255));
SaveButton.setText("SALVA");
SaveButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
SaveButtonActionPerformed(evt);
}
});
InventoryTextArea.setEditable(false);
InventoryTextArea.setColumns(20);
InventoryTextArea.setRows(5);
jScrollPane3.setViewportView(InventoryTextArea);
InventoryLabel.setFont(new java.awt.Font("Tahoma", 1, 10)); // NOI18N
InventoryLabel.setForeground(new java.awt.Color(255, 255, 255));
InventoryLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
InventoryLabel.setText("--- Inventario ---");
CurrentRoomTitleLabel.setFont(new java.awt.Font("Tahoma", 1, 10)); // NOI18N
CurrentRoomTitleLabel.setForeground(new java.awt.Color(255, 255, 255));
CurrentRoomTitleLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
CurrentRoomTitleLabel.setText("Stanza corrente:");
CurrentRoomLabel.setForeground(new java.awt.Color(255, 255, 255));
CurrentRoomLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
CurrentRoomLabel.setText("*DEFAULT*");
LookButton.setBackground(new java.awt.Color(102, 0, 204));
LookButton.setForeground(new java.awt.Color(255, 255, 255));
LookButton.setText("OSSERVA");
LookButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
LookButtonActionPerformed(evt);
}
});
EastButton.setBackground(new java.awt.Color(102, 0, 204));
EastButton.setForeground(new java.awt.Color(255, 255, 255));
EastButton.setText("Est");
EastButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
EastButtonActionPerformed(evt);
}
});
HealthTitleLabel.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
HealthTitleLabel.setForeground(new java.awt.Color(255, 255, 255));
HealthTitleLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
HealthTitleLabel.setText("Salute:");
HealthLabel.setFont(new java.awt.Font("Tahoma", 0, 36)); // NOI18N
HealthLabel.setForeground(new java.awt.Color(153, 0, 0));
HealthLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(GameCommandField)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(EnterButton))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 624, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 5, Short.MAX_VALUE)))
.addGap(18, 18, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(TitleLabel, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(HealthTitleLabel, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(CurrentRoomLabel, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(CurrentRoomTitleLabel, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(InventoryLabel, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(LookButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
.addComponent(LoadButton, javax.swing.GroupLayout.PREFERRED_SIZE, 77, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(SaveButton, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jScrollPane3, javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(HealthLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(12, 12, 12)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(NorthButton, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(WestButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(SouthButton, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(EastButton, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(20, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(TitleLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(SaveButton, javax.swing.GroupLayout.DEFAULT_SIZE, 34, Short.MAX_VALUE)
.addComponent(LoadButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(InventoryLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(CurrentRoomTitleLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(2, 2, 2)
.addComponent(CurrentRoomLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(HealthTitleLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 21, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(HealthLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(LookButton, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(NorthButton, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(WestButton, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(SouthButton, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(EastButton, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jScrollPane2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(GameCommandField, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(EnterButton, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addContainerGap())
);
GameCommandField.getAccessibleContext().setAccessibleName("");
GameCommandField.getAccessibleContext().setAccessibleDescription(".");
FileMenu.setText("File");
NewMenuItem.setText("Nuova Partita");
NewMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
NewMenuItemActionPerformed(evt);
}
});
FileMenu.add(NewMenuItem);
FileMenu.add(jSeparator2);
LoadMenuItem.setText("Carica");
LoadMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
LoadMenuItemActionPerformed(evt);
}
});
FileMenu.add(LoadMenuItem);
SaveMenuItem.setText("Salva");
SaveMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
SaveMenuItemActionPerformed(evt);
}
});
FileMenu.add(SaveMenuItem);
FileMenu.add(jSeparator1);
ExitMenuItem.setText("Esci");
ExitMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ExitMenuItemActionPerformed(evt);
}
});
FileMenu.add(ExitMenuItem);
MenuBar.add(FileMenu);
Options.setText("Options");
FastText.setText("Fast Text");
FastText.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
FastTextActionPerformed(evt);
}
});
Options.add(FastText);
Music.setSelected(true);
Music.setText("Music");
Music.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
MusicActionPerformed(evt);
}
});
Options.add(Music);
MenuBar.add(Options);
AboutMenu.setText("About");
AboutMenuItem.setText("About");
AboutMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
AboutMenuItemActionPerformed(evt);
}
});
AboutMenu.add(AboutMenuItem);
MenuBar.add(AboutMenu);
HelpMenu.setText("?");
HelpMenu_HeistItem.setText("The Heist");
HelpMenu_HeistItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
HelpMenu_HeistItemActionPerformed(evt);
}
});
HelpMenu.add(HelpMenu_HeistItem);
HelpMenu_CommandsItem.setText("Lista comandi");
HelpMenu_CommandsItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
HelpMenu_CommandsItemActionPerformed(evt);
}
});
HelpMenu.add(HelpMenu_CommandsItem);
MenuBar.add(HelpMenu);
setJMenuBar(MenuBar);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void EnterButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_EnterButtonActionPerformed
sendCommand();
checkEnd();
}//GEN-LAST:event_EnterButtonActionPerformed
private void WestButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_WestButtonActionPerformed
ParserOutput p = parser.parse("ovest", game.getCommands(), game.getCurrentRoom().getObjects(), game.getInventory(), game.getCurrentRoom().getNPCs());
GameCommandField.setText("");
tm.start();
s=new StringBuilder("\n");
GameTextArea.append("\n>> ovest\n");
GameTextArea.setCaretPosition(0);
GameTextArea.setCaretPosition(GameTextArea.getDocument().getLength());
if (fast) {
GameTextArea.append(game.nextMove(p));
} else s.append(game.nextMove(p));
GameTextArea.setCaretPosition(GameTextArea.getDocument().getLength());
CurrentRoomLabel.setText(game.getCurrentRoom().getName());
updateInventory();
updateHealth();
saved = false;
checkEnd();
}//GEN-LAST:event_WestButtonActionPerformed
private void EastButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_EastButtonActionPerformed
ParserOutput p = parser.parse("est", game.getCommands(), game.getCurrentRoom().getObjects(), game.getInventory(), game.getCurrentRoom().getNPCs());
GameCommandField.setText("");
tm.start();
s=new StringBuilder("\n");
GameTextArea.append("\n>> est\n");
GameTextArea.setCaretPosition(0);
GameTextArea.setCaretPosition(GameTextArea.getDocument().getLength());
if (fast) {
GameTextArea.append(game.nextMove(p));
} else s.append(game.nextMove(p));
GameTextArea.setCaretPosition(GameTextArea.getDocument().getLength());
CurrentRoomLabel.setText(game.getCurrentRoom().getName());
updateInventory();
updateHealth();
saved = false;
checkEnd();
}//GEN-LAST:event_EastButtonActionPerformed
private void NorthButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_NorthButtonActionPerformed
ParserOutput p = parser.parse("nord", game.getCommands(), game.getCurrentRoom().getObjects(), game.getInventory(), game.getCurrentRoom().getNPCs());
GameCommandField.setText("");
tm.start();
s=new StringBuilder("\n");
GameTextArea.append("\n>> nord\n");
GameTextArea.setCaretPosition(0);
GameTextArea.setCaretPosition(GameTextArea.getDocument().getLength());
if (fast) {
GameTextArea.append(game.nextMove(p));
} else s.append(game.nextMove(p));
GameTextArea.setCaretPosition(GameTextArea.getDocument().getLength());
CurrentRoomLabel.setText(game.getCurrentRoom().getName());
updateInventory();
updateHealth();
saved = false;
checkEnd();
}//GEN-LAST:event_NorthButtonActionPerformed
private void SouthButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SouthButtonActionPerformed
ParserOutput p = parser.parse("sud", game.getCommands(), game.getCurrentRoom().getObjects(), game.getInventory(), game.getCurrentRoom().getNPCs());
GameCommandField.setText("");
tm.start();
s=new StringBuilder("\n");
GameTextArea.append("\n>> sud\n");
GameTextArea.setCaretPosition(0);
GameTextArea.setCaretPosition(GameTextArea.getDocument().getLength());
if (fast) {
GameTextArea.append(game.nextMove(p));
} else s.append(game.nextMove(p));
GameTextArea.setCaretPosition(GameTextArea.getDocument().getLength());
CurrentRoomLabel.setText(game.getCurrentRoom().getName());
updateInventory();
updateHealth();
saved = false;
checkEnd();
}//GEN-LAST:event_SouthButtonActionPerformed
private void LookButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_LookButtonActionPerformed
ParserOutput p = parser.parse("osserva", game.getCommands(), game.getCurrentRoom().getObjects(), game.getInventory(), game.getCurrentRoom().getNPCs());
GameCommandField.setText("");
tm.start();
s=new StringBuilder("\n");
GameTextArea.append("\n>> osserva\n");
GameTextArea.setCaretPosition(0);
GameTextArea.setCaretPosition(GameTextArea.getDocument().getLength());
if (fast) {
GameTextArea.append(game.nextMove(p));
} else s.append(game.nextMove(p));
GameTextArea.setCaretPosition(GameTextArea.getDocument().getLength());
updateHealth();
saved = false;
checkEnd();
}//GEN-LAST:event_LookButtonActionPerformed
private void SaveMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SaveMenuItemActionPerformed
saveFile();
checkEnd();
}//GEN-LAST:event_SaveMenuItemActionPerformed
private void NewMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_NewMenuItemActionPerformed
if (!saved && !game.isEnd()) {
int option = JOptionPane.showConfirmDialog(null, "Ci sono modifiche non salvate. Sicuro di voler cominciare una nuova partita?", "Nuova partita", JOptionPane.YES_NO_CANCEL_OPTION);
if (option == JOptionPane.YES_OPTION) {
init();
saved = true;
} else if (option == JOptionPane.NO_OPTION) {
saveFile();
} else if (option == JOptionPane.CANCEL_OPTION) {
return;
}
} else {
init();
saved = true;
}
}//GEN-LAST:event_NewMenuItemActionPerformed
private void GameCommandFieldKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_GameCommandFieldKeyReleased
if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
sendCommand();
}
}//GEN-LAST:event_GameCommandFieldKeyReleased
private void LoadButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_LoadButtonActionPerformed
if (!saved && !game.isEnd()) {
int option = JOptionPane.showConfirmDialog(null, "Ci sono modifiche non salvate. Sicuro di voler caricare una nuova partita?", "Caricamento file", JOptionPane.YES_NO_CANCEL_OPTION);
if (option == JOptionPane.YES_OPTION) {
loadFile();
saved = true;
} else if (option == JOptionPane.NO_OPTION) {
saveFile();
} else if (option == JOptionPane.CANCEL_OPTION) {
return;
}
} else {
loadFile();
saved = true;
}
}//GEN-LAST:event_LoadButtonActionPerformed
private void SaveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SaveButtonActionPerformed
saveFile();
checkEnd();
}//GEN-LAST:event_SaveButtonActionPerformed
private void LoadMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_LoadMenuItemActionPerformed
if (!saved && !game.isEnd()) {
int option = JOptionPane.showConfirmDialog(null, "Ci sono modifiche non salvate. Sicuro di voler caricare una nuova partita?", "Caricamento file", JOptionPane.YES_NO_CANCEL_OPTION);
if (option == JOptionPane.YES_OPTION) {
loadFile();
saved = true;
} else if (option == JOptionPane.NO_OPTION) {
saveFile();
} else if (option == JOptionPane.CANCEL_OPTION) {
return;
}
} else {
loadFile();
saved = true;
}
}//GEN-LAST:event_LoadMenuItemActionPerformed
private void ExitMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ExitMenuItemActionPerformed
if (!saved && !game.isEnd()) {
int option = JOptionPane.showConfirmDialog(null, "Ci sono modifiche non salvate. Sicuro di voler chiudere il gioco?", "Chiusura gioco", JOptionPane.YES_NO_CANCEL_OPTION);
if (option == JOptionPane.YES_OPTION) {
System.exit(0);
} else if (option == JOptionPane.NO_OPTION) {
saveFile();
} else if (option == JOptionPane.CANCEL_OPTION) {
return;
}
} else {
System.exit(0);
}
}//GEN-LAST:event_ExitMenuItemActionPerformed
private void AboutMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AboutMenuItemActionPerformed
JOptionPane.showMessageDialog(this, "-The Heist - Ver. 1.0.0\n"
+ "Authors: Matteo Mannavola, Roberta Sallustio, Gianluca \"Roger\" Sonnante\n"
+ "Diamond Games, Inc.", "The Heist", JOptionPane.INFORMATION_MESSAGE, new ImageIcon("img/diamond.gif"));
}//GEN-LAST:event_AboutMenuItemActionPerformed
private void HelpMenu_HeistItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_HelpMenu_HeistItemActionPerformed
JOptionPane.showMessageDialog(this, "The Heist e' un gioco d'avventura testuale nel quale l'utente\n"
+ "scrive dei comandi in una riga di testo per avanzare e \n"
+ "risolvere degli enigmi, utilizzando l'astuzia e gli strumenti\n"
+ "che puo' trovare in giro.\n"
+ "\n"
+ "Vesti i panni di un rapinatore seriale, che dopo anni di carriera,\n"
+ "si concede un'ultimo colpo: l'assalto alla gioielleria che custodisce\n"
+ "il diamante piu' prezioso al mondo! Riuscirai a farla franca?", "The Heist", JOptionPane.PLAIN_MESSAGE);
}//GEN-LAST:event_HelpMenu_HeistItemActionPerformed
private void HelpMenu_CommandsItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_HelpMenu_CommandsItemActionPerformed
JOptionPane.showMessageDialog(this, "E' possibile usare questi comandi testuali anche senza premere i relativi pulsanti:\n"
+ "\n"
+ ">> nord - Spostati in direzione nord\n"
+ ">> est - Spostati in direzione est\n"
+ ">> ovest - Spostati in direzione ovest\n"
+ ">> sud - Spostati in direzione sud\n"
+ ">> osserva - permette di guardarti intorno ed esaminare l'ambiente circostante\n"
+ ">> carica - carica un salvataggio\n"
+ ">> salva - salva la partita corrente\n"
+ "\n"
+ "Qualche altro comando:\n"
+ "\n"
+ ">> esamina [qualcosa] - esamina qualcosa presente nella stanza\n"
+ ">> inventario - visualizza l'inventario\n"
+ ">> equipaggia [oggetto] - equipaggia un oggetto dell'inventario (massimo 2 alla volta!)\n"
+ ">> togli [oggetto] - disequipaggia un oggetto\n"
+ ">> apri [oggetto] - apri un oggetto specifico\n"
+ ">> chiudi [oggetto] - chiudi un oggetto specifico\n"
+ ">> lascia [oggetto] - lascia un oggetto in una stanza\n"
+ ">> metti [oggetto] in [oggetto contenitore] - metti un oggetto in un contenitore valido\n"
+ ">> prendi [oggetto] - prendi un oggetto nella stanza\n"
+ ">> parla a [personaggio] - parla ad un personaggio nella stanza\n"
+ ">> dai [oggetto] a [persona] - dai un oggetto nel tuo inventario ad un personaggio\n"
+ "\nPer il resto... usa la fantasia!", "Lista comandi", JOptionPane.PLAIN_MESSAGE);
}//GEN-LAST:event_HelpMenu_CommandsItemActionPerformed
private void FastTextActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_FastTextActionPerformed
fast = !fast;
}//GEN-LAST:event_FastTextActionPerformed
private void MusicActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_MusicActionPerformed
// TODO add your handling code here:
music=!music;
if(!music){
clip.stop();
}else{
startMusic();
}
}//GEN-LAST:event_MusicActionPerformed
private void init() {
game = new HeistGame(new ItalianCommandNames(), new ItalianObjectParameters(), new ItalianCharacterParameters(), new ItalianEnemyParameters());
try {
this.game.init();
} catch (Exception ex) {
JOptionPane.showMessageDialog(this, ex.getMessage(), "Errore" ,JOptionPane.ERROR_MESSAGE);
}
GameCommandField.setEditable(true);
NorthButton.setEnabled(true);
SouthButton.setEnabled(true);
EastButton.setEnabled(true);
WestButton.setEnabled(true);
LookButton.setEnabled(true);
SaveButton.setEnabled(true);
SaveMenuItem.setEnabled(true);
GameTextArea.setText("");
GameTextArea.append("//// " + game.getCurrentRoom().getName() + " ////");
GameTextArea.setCaretPosition(GameTextArea.getDocument().getLength());
GameTextArea.append("\n" + game.getCurrentRoom().getFirstDescription());
GameTextArea.setCaretPosition(0);
GameTextArea.setCaretPosition(GameTextArea.getDocument().getLength());
game.getCurrentRoom().setVisited(true);
CurrentRoomLabel.setText(game.getCurrentRoom().getName());
updateInventory();
updateHealth();
}
private void enableElements(boolean enable) {
if (!game.isEnd()) {
GameCommandField.setEditable(enable);
NorthButton.setEnabled(enable);
SouthButton.setEnabled(enable);
EastButton.setEnabled(enable);
WestButton.setEnabled(enable);
LookButton.setEnabled(enable);
SaveButton.setEnabled(enable);
LoadButton.setEnabled(enable);
SaveMenuItem.setEnabled(enable);
NewMenuItem.setEnabled(enable);
LoadMenuItem.setEnabled(enable);
ExitMenuItem.setEnabled(enable);
}
}
private void checkEnd() {
if (game.isEnd()) {
GameCommandField.setEditable(false);
NorthButton.setEnabled(false);
SouthButton.setEnabled(false);
EastButton.setEnabled(false);
WestButton.setEnabled(false);
LookButton.setEnabled(false);
SaveButton.setEnabled(false);
SaveMenuItem.setEnabled(false);
}
}
private void sendCommand() {
if (GameCommandField.getText().length() > 0) {
String command = GameCommandField.getText();
ParserOutput p = parser.parse(command, game.getCommands(), game.getCurrentRoom().getObjects(), game.getInventory(), game.getCurrentRoom().getNPCs());
GameCommandField.setText("");
tm.start();
s = new StringBuilder("\n");
if (p.getCommand() != null && p.getCommand().getType() == CommandType.END) {
if (p.getObject1() != null || p.getInvObject1() != null || p.getCharacter1() != null || p.getEnemy1() != null || p.hasExtraWords()) {
GameTextArea.append("\nForse intendevi: esci");
GameTextArea.setCaretPosition(GameTextArea.getDocument().getLength());
} else {
GameTextArea.append("\nAddio!");
GameTextArea.setCaretPosition(GameTextArea.getDocument().getLength());
System.exit(0);
}
} else if (p.getCommand() != null && p.getCommand().getType() == CommandType.SAVE) {
if (p.getObject1() != null || p.getInvObject1() != null || p.getCharacter1() != null || p.getEnemy1() != null || p.hasExtraWords()) {
GameTextArea.append("\n\nForse intendevi: salva");
GameTextArea.setCaretPosition(GameTextArea.getDocument().getLength());
} else {
saveFile();
checkEnd();
}
} else if (p.getCommand() != null && p.getCommand().getType() == CommandType.LOAD) {
if (p.getObject1() != null || p.getInvObject1() != null || p.getCharacter1() != null || p.getEnemy1() != null || p.hasExtraWords()) {
GameTextArea.append("\n\nForse intendevi: carica");
GameTextArea.setCaretPosition(GameTextArea.getDocument().getLength());
} else {
if (!saved) {
int option = JOptionPane.showConfirmDialog(null, "Ci sono modifiche non salvate. Sicuro di voler caricare una nuova partita?", "Caricamento file", JOptionPane.YES_NO_CANCEL_OPTION);
if (option == JOptionPane.YES_OPTION) {
loadFile();
saved = true;
} else if (option == JOptionPane.NO_OPTION) {
saveFile();
} else if (option == JOptionPane.CANCEL_OPTION) {
return;
}
} else {
loadFile();
saved = true;
}
}
} else {
GameTextArea.append("\n>> " + command + "\n");
GameTextArea.setCaretPosition(0);
GameTextArea.setCaretPosition(GameTextArea.getDocument().getLength());
if (fast) {
GameTextArea.append(game.nextMove(p));
} else s.append(game.nextMove(p));
GameTextArea.setCaretPosition(GameTextArea.getDocument().getLength());
CurrentRoomLabel.setText(game.getCurrentRoom().getName());
updateInventory();
updateHealth();
saved = false;
checkEnd();
}
}
}
private void updateInventory() {
InventoryTextArea.setText("");
for (AdvObject o : game.getInventory()) {
if (o.getContained() == -1 && !o.isEquipped()) {
InventoryTextArea.append("- " + o.getName());
if (o.isOpen()) {
InventoryTextArea.append(" (aperto)");
}
InventoryTextArea.append("\n");
}
}
InventoryTextArea.append("-------------------------------------------------");
InventoryTextArea.append("\nOggetti equipaggiati:\n");
for (AdvObject o : game.getInventory()) {
if (o.isEquipped()) {
InventoryTextArea.append("- " + o.getName());
if (o.isOpen()) {
InventoryTextArea.append(" (aperto)");
}
InventoryTextArea.append("\n");
}
}
}
private void updateHealth() {
HealthLabel.setText("");
switch (game.getHealth()) {
case 1:
HealthLabel.setText("♥");
break;
case 2:
HealthLabel.setText("♥♥");
break;
case 3:
HealthLabel.setText("♥♥♥");
break;
case 4:
HealthLabel.setText("♥♥♥♥");
break;
case 5:
HealthLabel.setText("♥♥♥♥♥");
break;
}
}
private void loadFile() {
JFileChooser fc = new JFileChooser();
fc.setMultiSelectionEnabled(false);
fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
if (fc.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
try {
ObjectInputStream in = new ObjectInputStream(new FileInputStream(file));
this.game = (HeistGame)in.readObject();
in.close();
GameTextArea.append("\n\nCaricamento partita completato.");
GameTextArea.setCaretPosition(GameTextArea.getDocument().getLength());
CurrentRoomLabel.setText(game.getCurrentRoom().getName());
updateInventory();
updateHealth();
GameCommandField.setEditable(true);
NorthButton.setEnabled(true);
SouthButton.setEnabled(true);
EastButton.setEnabled(true);
WestButton.setEnabled(true);
LookButton.setEnabled(true);
SaveButton.setEnabled(true);
SaveMenuItem.setEnabled(true);
} catch (IOException | ClassNotFoundException ex) {
JOptionPane.showMessageDialog(this, "Il file selezionato e' incompatibile con questo gioco!", "Errore nel caricamento", JOptionPane.ERROR_MESSAGE);
}
}
}
private void saveFile() {
JFileChooser fc = new JFileChooser();
fc.setMultiSelectionEnabled(false);
fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
if (fc.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
try {
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(file));
out.writeObject(this.game);
out.close();
saved = true;
GameTextArea.append("\n\nSalvataggio partita completato.");
GameTextArea.setCaretPosition(GameTextArea.getDocument().getLength());
} catch (IOException ex) {
JOptionPane.showMessageDialog(this, "Errore nel salvataggio!", "Errore", JOptionPane.ERROR_MESSAGE);
}
}
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(HeistGameFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(HeistGameFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(HeistGameFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(HeistGameFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new HeistGameFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JMenu AboutMenu;
private javax.swing.JMenuItem AboutMenuItem;
private javax.swing.JLabel CurrentRoomLabel;
private javax.swing.JLabel CurrentRoomTitleLabel;
private javax.swing.JButton EastButton;
private javax.swing.JButton EnterButton;
private javax.swing.JMenuItem ExitMenuItem;
private javax.swing.JCheckBoxMenuItem FastText;
private javax.swing.JMenu FileMenu;
private javax.swing.JTextField GameCommandField;
private javax.swing.JTextArea GameTextArea;
private javax.swing.JLabel HealthLabel;
private javax.swing.JLabel HealthTitleLabel;
private javax.swing.JMenu HelpMenu;
private javax.swing.JMenuItem HelpMenu_CommandsItem;
private javax.swing.JMenuItem HelpMenu_HeistItem;
private javax.swing.JLabel InventoryLabel;
private javax.swing.JTextArea InventoryTextArea;
private javax.swing.JButton LoadButton;
private javax.swing.JMenuItem LoadMenuItem;
private javax.swing.JButton LookButton;
private javax.swing.JMenuBar MenuBar;
private javax.swing.JCheckBoxMenuItem Music;
private javax.swing.JMenuItem NewMenuItem;
private javax.swing.JButton NorthButton;
private javax.swing.JMenu Options;
private javax.swing.JButton SaveButton;
private javax.swing.JMenuItem SaveMenuItem;
private javax.swing.JButton SouthButton;
private javax.swing.JLabel TitleLabel;
private javax.swing.JButton WestButton;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JScrollPane jScrollPane3;
private javax.swing.JPopupMenu.Separator jSeparator1;
private javax.swing.JPopupMenu.Separator jSeparator2;
// End of variables declaration//GEN-END:variables
}
| true |
47456a141996a9a352a4bb85a95aed900a8dda45 | Java | SonaliOberoi/TargetInterview | /src/com/practice/arrays/MinMeetingRooms.java | UTF-8 | 721 | 3.1875 | 3 | [] | no_license | package com.practice.arrays;
import java.util.*;
//https://leetcode.com/problems/meeting-rooms-ii/
public class MinMeetingRooms {
public int minMeetingRooms(int[][] intervals) {
if(intervals == null) {
return 0;
}
Arrays.sort(intervals, (a, b) -> a[0] - b[0]);
Queue<int[]> queue = new PriorityQueue<>((a, b) -> {
return a[1] - b[1];});
for(int[] current: intervals) {
if (queue.isEmpty()) {
queue.add(current);
continue;
}
if(queue.peek()[1] <= current[0]) {
queue.poll();
}
queue.add(current);
}
return queue.size();
}
}
| true |
5f884e01323777c130a3960b91d8d777295b2679 | Java | bahrmichael/brave-bucks | /src/main/java/com/bravebucks/eve/web/rest/SolarSystemResource.java | UTF-8 | 7,088 | 2.140625 | 2 | [
"MIT"
] | permissive | package com.bravebucks.eve.web.rest;
import com.bravebucks.eve.domain.enumeration.Region;
import com.bravebucks.eve.security.AuthoritiesConstants;
import com.bravebucks.eve.service.JsonRequestService;
import com.bravebucks.eve.domain.SolarSystem;
import com.bravebucks.eve.repository.SolarSystemRepository;
import com.bravebucks.eve.web.rest.util.HeaderUtil;
import com.bravebucks.eve.web.rest.util.PaginationUtil;
import com.codahale.metrics.annotation.Timed;
import com.mashape.unirest.http.JsonNode;
import io.github.jhipster.web.util.ResponseUtil;
import io.swagger.annotations.ApiParam;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.annotation.Secured;
import org.springframework.web.bind.annotation.*;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Optional;
/**
* REST controller for managing SolarSystem.
*/
@RestController
@RequestMapping("/api")
public class SolarSystemResource {
private final Logger log = LoggerFactory.getLogger(SolarSystemResource.class);
private static final String ENTITY_NAME = "solarSystem";
private final SolarSystemRepository solarSystemRepository;
private final JsonRequestService jsonRequestService;
public SolarSystemResource(SolarSystemRepository solarSystemRepository,
final JsonRequestService jsonRequestService) {
this.solarSystemRepository = solarSystemRepository;
this.jsonRequestService = jsonRequestService;
}
/**
* POST /solar-systems : Create a new solarSystem.
*
* @param solarSystem the solarSystem to create
* @return the ResponseEntity with status 201 (Created) and with body the new solarSystem, or with status 400 (Bad Request) if the solarSystem has already an ID
* @throws URISyntaxException if the Location URI syntax is incorrect
*/
@Secured(AuthoritiesConstants.MANAGER)
@PostMapping("/solar-systems")
public ResponseEntity<SolarSystem> createSolarSystem(@RequestBody SolarSystem solarSystem) throws URISyntaxException {
log.debug("REST request to save SolarSystem : {}", solarSystem);
if (solarSystem.getId() != null) {
return ResponseEntity.badRequest().headers(HeaderUtil.createFailureAlert(ENTITY_NAME, "idexists", "A new solarSystem cannot already have an ID")).body(null);
}
solarSystem.setSystemName(solarSystem.getSystemName().toUpperCase());
Optional<JsonNode> optional = jsonRequestService.searchSolarSystem(solarSystem.getSystemName());
if (optional.isPresent()) {
JSONObject object = optional.get().getObject();
if (object.has("solar_system")) {
long systemId = object.getJSONArray("solar_system").getLong(0);
solarSystem.setSystemId(systemId);
SolarSystem result = solarSystemRepository.save(solarSystem);
return ResponseEntity.created(new URI("/api/solar-systems/" + result.getId()))
.headers(HeaderUtil.createEntityCreationAlert(ENTITY_NAME, result.getId().toString()))
.body(result);
}
}
return ResponseEntity.badRequest().headers(HeaderUtil.createFailureAlert(ENTITY_NAME, "notresolved",
"The system could not be found. Is there a typo?")).body(null);
}
/**
* PUT /solar-systems : Updates an existing solarSystem.
*
* @param solarSystem the solarSystem to update
* @return the ResponseEntity with status 200 (OK) and with body the updated solarSystem,
* or with status 400 (Bad Request) if the solarSystem is not valid,
* or with status 500 (Internal Server Error) if the solarSystem couldn't be updated
* @throws URISyntaxException if the Location URI syntax is incorrect
*/
@Secured(AuthoritiesConstants.MANAGER)
@PutMapping("/solar-systems")
public ResponseEntity<SolarSystem> updateSolarSystem(@RequestBody SolarSystem solarSystem) throws URISyntaxException {
log.debug("REST request to update SolarSystem : {}", solarSystem);
if (solarSystem.getId() == null) {
return createSolarSystem(solarSystem);
}
SolarSystem result = solarSystemRepository.save(solarSystem);
return ResponseEntity.ok()
.headers(HeaderUtil.createEntityUpdateAlert(ENTITY_NAME, solarSystem.getId()))
.body(result);
}
@Secured(AuthoritiesConstants.USER)
@GetMapping("/solar-systems/region/{region}")
public ResponseEntity<List<SolarSystem>> getSystems(@PathVariable("region") final Region region) {
return ResponseEntity.ok(solarSystemRepository.findByRegion(region));
}
/**
* GET /solar-systems : get all the solarSystems.
*
* @param pageable the pagination information
* @return the ResponseEntity with status 200 (OK) and the list of solarSystems in body
*/
@Secured(AuthoritiesConstants.MANAGER)
@GetMapping("/solar-systems")
public ResponseEntity<List<SolarSystem>> getAllSolarSystems(@ApiParam Pageable pageable) {
log.debug("REST request to get a page of SolarSystems");
Page<SolarSystem> page = solarSystemRepository.findAll(pageable);
HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/solar-systems");
return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
}
/**
* GET /solar-systems/:id : get the "id" solarSystem.
*
* @param id the id of the solarSystem to retrieve
* @return the ResponseEntity with status 200 (OK) and with body the solarSystem, or with status 404 (Not Found)
*/
@Secured(AuthoritiesConstants.MANAGER)
@GetMapping("/solar-systems/{id}")
public ResponseEntity<SolarSystem> getSolarSystem(@PathVariable String id) {
log.debug("REST request to get SolarSystem : {}", id);
SolarSystem solarSystem = solarSystemRepository.findOne(id);
return ResponseUtil.wrapOrNotFound(Optional.ofNullable(solarSystem));
}
/**
* DELETE /solar-systems/:id : delete the "id" solarSystem.
*
* @param id the id of the solarSystem to delete
* @return the ResponseEntity with status 200 (OK)
*/
@Secured(AuthoritiesConstants.MANAGER)
@DeleteMapping("/solar-systems/{id}")
public ResponseEntity<Void> deleteSolarSystem(@PathVariable String id) {
log.debug("REST request to delete SolarSystem : {}", id);
solarSystemRepository.delete(id);
return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert(ENTITY_NAME, id)).build();
}
}
| true |
42f2d4de13bfbbf148cd4dbb64337333643aaf40 | Java | hqottsz/MXI | /am-query-test/src/main/java/com/mxi/am/api/resource/sys/refterm/taskpriority/TaskPriorityResourceBeanTest.java | UTF-8 | 5,369 | 1.796875 | 2 | [] | no_license | package com.mxi.am.api.resource.sys.refterm.taskpriority;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.security.Principal;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.EJBContext;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;
import com.google.inject.AbstractModule;
import com.google.inject.Inject;
import com.mxi.am.api.annotation.CSIContractTest;
import com.mxi.am.api.annotation.CSIContractTest.Project;
import com.mxi.am.api.exception.AmApiResourceNotFoundException;
import com.mxi.am.api.resource.sys.refterm.taskpriority.impl.TaskPriorityResourceBean;
import com.mxi.mx.apiengine.security.Security;
import com.mxi.mx.common.exception.MxException;
import com.mxi.mx.common.inject.InjectorContainer;
import com.mxi.mx.common.table.InjectionOverrideRule;
import com.mxi.mx.core.apiengine.security.CoreSecurity;
import com.mxi.mx.testing.ResourceBeanTest;
/**
* Query test for Task Priority ResourceBean
*
*/
@RunWith( MockitoJUnitRunner.class )
public class TaskPriorityResourceBeanTest extends ResourceBeanTest {
private static final String TASK_PRIORITY_CODE = "LOW";
public static final String TASK_PRIORITY_NAME = "Low priority";
public static final String TASK_PRIORITY_DESCRIPTION = "Low priority";
public static final int TASK_PRIORITY_ORDER = 1;
private static final String TASK_PRIORITY_CODE2 = "HIGH";
public static final String TASK_PRIORITY_NAME2 = "High priority";
public static final String TASK_PRIORITY_DESCRIPTION2 = "High priority";
public static final int TASK_PRIORITY_ORDER2 = 2;
private static final int TASK_PRIORITY_RECORD_COUNT = 2;
private static final String NON_EXIST_TASK_PRIORITY_CODE = "XXX";
private static final String NULL_TASK_PRIORITY_CODE = null;
@Rule
public InjectionOverrideRule injectionOverrideRule =
new InjectionOverrideRule( new AbstractModule() {
@Override
protected void configure() {
bind( TaskPriorityResource.class ).to( TaskPriorityResourceBean.class );
bind( Security.class ).to( CoreSecurity.class );
bind( EJBContext.class ).toInstance( ejbContext );
}
} );
@Inject
private TaskPriorityResourceBean taskPriorityResourceBean;
@Mock
private Principal principal;
@Mock
private EJBContext ejbContext;
@Before
public void setUp() throws MxException {
// Guice injection to avoid permission checks
InjectorContainer.get().injectMembers( this );
taskPriorityResourceBean.setEJBContext( ejbContext );
setAuthorizedUser( AUTHORIZED );
setUnauthorizedUser( UNAUTHORIZED );
initializeTest();
Mockito.when( ejbContext.getCallerPrincipal() ).thenReturn( principal );
Mockito.when( principal.getName() ).thenReturn( AUTHORIZED );
}
@Test
@CSIContractTest( { Project.AFKLM_IMECH } )
public void testGetTaskPriorityByCodeSuccess200() throws AmApiResourceNotFoundException {
TaskPriority taskPriority = taskPriorityResourceBean.get( TASK_PRIORITY_CODE );
assertEquals( defaultTaskPriorityBuilder(), taskPriority );
}
@Test
@CSIContractTest( { Project.AFKLM_IMECH } )
public void testSearchAllTaskPrioritiesSuccess200() {
List<TaskPriority> taskPriorityList = taskPriorityResourceBean.search();
assertEquals( TASK_PRIORITY_RECORD_COUNT, taskPriorityList.size() );
assertTrue( taskPriorityList.containsAll( defaultTaskPriorityListBuilder() ) );
}
@Test( expected = AmApiResourceNotFoundException.class )
public void testGetTaskPriorityByNonExistCodeFailure404() throws AmApiResourceNotFoundException {
taskPriorityResourceBean.get( NON_EXIST_TASK_PRIORITY_CODE );
}
@Test( expected = AmApiResourceNotFoundException.class )
public void testGetTaskPriorityByNullCodeFailure404() throws AmApiResourceNotFoundException {
taskPriorityResourceBean.get( NULL_TASK_PRIORITY_CODE );
}
private TaskPriority defaultTaskPriorityBuilder() {
TaskPriority taskPriority = new TaskPriority();
taskPriority.setCode( TASK_PRIORITY_CODE );
taskPriority.setName( TASK_PRIORITY_NAME );
taskPriority.setDescription( TASK_PRIORITY_DESCRIPTION );
taskPriority.setOrder( TASK_PRIORITY_ORDER );
return taskPriority;
}
private List<TaskPriority> defaultTaskPriorityListBuilder() {
List<TaskPriority> taskPriorityList = new ArrayList<TaskPriority>();
TaskPriority taskPriority1 = new TaskPriority();
taskPriority1.setCode( TASK_PRIORITY_CODE );
taskPriority1.setName( TASK_PRIORITY_NAME );
taskPriority1.setDescription( TASK_PRIORITY_DESCRIPTION );
taskPriority1.setOrder( TASK_PRIORITY_ORDER );
TaskPriority taskPriority2 = new TaskPriority();
taskPriority2.setCode( TASK_PRIORITY_CODE2 );
taskPriority2.setName( TASK_PRIORITY_NAME2 );
taskPriority2.setDescription( TASK_PRIORITY_DESCRIPTION2 );
taskPriority2.setOrder( TASK_PRIORITY_ORDER2 );
taskPriorityList.add( taskPriority1 );
taskPriorityList.add( taskPriority2 );
return taskPriorityList;
}
}
| true |
f4a98698b0f09a51353ce6ebb1078c8baa798ae0 | Java | 3bdelrahmann/cafeteria-ordering-system | /src/cafeteria/ordering/system/Strategy/Payment.java | UTF-8 | 12,290 | 2.109375 | 2 | [] | no_license | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package cafeteria.ordering.system.Strategy;
import javax.swing.JFrame;
import java.io.Console;
import java.lang.System;
/**
*
* @author user
*/
public class Payment extends javax.swing.JFrame {
/**
* Creates new form Payment
*/
public Payment() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jButton_CANCEL = new javax.swing.JButton();
jButton_Confirm = new javax.swing.JButton();
jComboBox1 = new javax.swing.JComboBox<>();
jPanel5 = new javax.swing.JPanel();
jLabelMin4 = new javax.swing.JLabel();
jLabelClose4 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setUndecorated(true);
jPanel1.setBackground(new java.awt.Color(70, 109, 109));
jButton_CANCEL.setBackground(new java.awt.Color(242, 38, 19));
jButton_CANCEL.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
jButton_CANCEL.setForeground(new java.awt.Color(255, 255, 255));
jButton_CANCEL.setText("CANCEL");
jButton_CANCEL.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton_CANCELActionPerformed(evt);
}
});
jButton_Confirm.setBackground(new java.awt.Color(76, 175, 80));
jButton_Confirm.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
jButton_Confirm.setForeground(new java.awt.Color(255, 255, 255));
jButton_Confirm.setText("Confirm");
jButton_Confirm.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton_ConfirmActionPerformed(evt);
}
});
jComboBox1.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
jComboBox1.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Credit", "Paypal" }));
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jComboBox1, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jButton_CANCEL, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 130, Short.MAX_VALUE)
.addComponent(jButton_Confirm, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addGap(22, 22, 22)
.addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton_CANCEL, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton_Confirm, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(21, Short.MAX_VALUE))
);
jPanel5.setBackground(new java.awt.Color(255, 102, 0));
jLabelMin4.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
jLabelMin4.setForeground(new java.awt.Color(255, 255, 255));
jLabelMin4.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabelMin4.setText("-");
jLabelMin4.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
jLabelMin4.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabelMin4MouseClicked(evt);
}
});
jLabelClose4.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
jLabelClose4.setForeground(new java.awt.Color(255, 255, 255));
jLabelClose4.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabelClose4.setText("x");
jLabelClose4.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
jLabelClose4.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabelClose4MouseClicked(evt);
}
});
jLabel6.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
jLabel6.setForeground(new java.awt.Color(255, 255, 255));
jLabel6.setText("Payment");
javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5);
jPanel5.setLayout(jPanel5Layout);
jPanel5Layout.setHorizontalGroup(
jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel5Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel6)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabelMin4, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabelClose4, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(6, 6, 6))
);
jPanel5Layout.setVerticalGroup(
jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel5Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel6)
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabelClose4, javax.swing.GroupLayout.DEFAULT_SIZE, 28, Short.MAX_VALUE)
.addComponent(jLabelMin4)))
.addContainerGap())
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, 0)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jLabelMin4MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabelMin4MouseClicked
this.setState(JFrame.ICONIFIED);
}//GEN-LAST:event_jLabelMin4MouseClicked
private void jLabelClose4MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabelClose4MouseClicked
System.exit(0);
}//GEN-LAST:event_jLabelClose4MouseClicked
private void jButton_CANCELActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_CANCELActionPerformed
System.exit(0);
}//GEN-LAST:event_jButton_CANCELActionPerformed
private void jButton_ConfirmActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_ConfirmActionPerformed
String type = jComboBox1.getSelectedItem().toString();
if("Credit".equals(type)){
CreditCardJframe credit = new CreditCardJframe();
credit.setVisible(true);
credit.pack();
credit.setLocationRelativeTo(null);
credit.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.dispose();
} else {
PaypalJframe paypal = new PaypalJframe();
paypal.setVisible(true);
paypal.pack();
paypal.setLocationRelativeTo(null);
paypal.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); }
}//GEN-LAST:event_jButton_ConfirmActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Payment.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Payment.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Payment.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Payment.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Payment().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton_CANCEL;
private javax.swing.JButton jButton_Confirm;
private javax.swing.JComboBox<String> jComboBox1;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabelClose4;
private javax.swing.JLabel jLabelMin4;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel5;
// End of variables declaration//GEN-END:variables
}
| true |
f174e76b4599b440d584d15c5c2f5887393494fb | Java | matiw11/SI-lab | /zad2/back/src/main/java/com/wouek/back/parser/Parser.java | UTF-8 | 1,328 | 2.890625 | 3 | [] | no_license | package com.wouek.back.parser;
import com.wouek.back.entity.Sudoku;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Parser {
public Parser(){
}
public Sudoku loadSudoku(int sudokuId, boolean isSolution) throws IOException {
String[] data = getLine(sudokuId);
assert data != null;
String puzzle;
if(isSolution){
puzzle = data[3];
}
else {
puzzle = data[2];
}
Sudoku sudoku = new Sudoku();
int counter = 0;
for(int i=0; i<9; i++){
for (int j=0; j<9; j++){
sudoku.loadVariable(puzzle.toCharArray()[counter], i, j);
counter++;
}
}
return sudoku;
}
private String[] getLine(int sudokuId) throws IOException {
BufferedReader csvReader = new BufferedReader(new FileReader("src/main/resources/Sudoku.csv"));
String row;
String[] data;
csvReader.readLine();
while ((row = csvReader.readLine()) != null) {
data = row.split(";");
if(Integer.parseInt(data[0])==sudokuId) {
csvReader.close();
return data;
}
}
csvReader.close();
return null;
}
}
| true |
9c7a48ff8e9748dcd3a519fcaf9b4d11630bc73b | Java | wen-sr/jxxhwl | /src/com/jxxhwl/wx/service/impl/GetShouFaServiceImpl.java | GB18030 | 1,246 | 1.984375 | 2 | [] | no_license | package com.jxxhwl.wx.service.impl;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.jxxhwl.wx.dao.GetShouFaDao;
import com.jxxhwl.wx.entity.FaHuo;
import com.jxxhwl.wx.entity.QueryShouFa;
import com.jxxhwl.wx.entity.ShouHuo;
import com.jxxhwl.wx.entity.Storer;
import com.jxxhwl.wx.service.GetShouFaService;
@Transactional
@Service("getShouFaService")
public class GetShouFaServiceImpl implements GetShouFaService {
//עdao
@Resource
private GetShouFaDao getShouFaDao;
public void setGetShouFaDao(GetShouFaDao getShouFaDao) {
this.getShouFaDao = getShouFaDao;
}
/**
* ջ
*/
@Override
public List<ShouHuo> getshou(QueryShouFa queryShouFa) {
List<ShouHuo> list = getShouFaDao.getShou(queryShouFa);
return list;
}
/**
*
*/
@Override
public List<FaHuo> getfa(QueryShouFa queryShouFa) {
List<FaHuo> list = getShouFaDao.getFa(queryShouFa);
return list;
}
/**
* Ϣ
*/
@Override
public List<Storer> getStorer(String matchInfo) {
List<Storer> list = getShouFaDao.getStorer(matchInfo);
return list;
}
}
| true |
84eaa3091bd01be7298ac0f0f22713bab439e429 | Java | softinite/Algorithms | /src/main/java/com/softinite/algorithms/array/TapeEquilibrium.java | UTF-8 | 771 | 3.3125 | 3 | [] | no_license | package com.softinite.algorithms.array;
/**
* Created by Sergiu Ivasenco on 31/07/16.
*/
public class TapeEquilibrium {
public int solution(int[] A) {
if (A.length == 2) {
return Math.abs(A[0] - A[1]);
}
int left = A[0];
int right = sum(A, 1);
int minEq = Math.abs(left - right);
for(int i = 1; i < A.length - 1; i++) {
left += A[i];
right -= A[i];
int tmpSum = Math.abs(left - right);
if (tmpSum < minEq) {
minEq = tmpSum;
}
}
return minEq;
}
private int sum(int[] A, int idx) {
int sum = 0;
for(int i = idx; i < A.length; i++) {
sum += A[i];
}
return sum;
}
}
| true |
c61368f06a83362ba8475bf9fafd933ef42f5814 | Java | WangChen0328/kafka | /src/main/java/cn/kafka/TopicUtils.java | UTF-8 | 1,501 | 1.953125 | 2 | [] | no_license | package cn.kafka;
import kafka.admin.AdminUtils;
import kafka.admin.RackAwareMode;
import kafka.server.ConfigType;
import kafka.utils.ZKStringSerializer$;
import kafka.utils.ZkUtils;
import org.I0Itec.zkclient.ZkClient;
import org.apache.kafka.common.config.TopicConfig;
import org.apache.kafka.common.security.JaasUtils;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
/**
* @author wangchen
* @date 2018/8/14 16:01
*/
public class TopicUtils {
private static final Properties kafkaProp = new Properties();
public static void createTopic(String topicName) {
ZkClient zkClient = new ZkClient("192.168.31.106:2181", 30000, 30000, ZKStringSerializer$.MODULE$);;
ZkUtils zkUtils = ZkUtils.apply(zkClient, false);
if (!AdminUtils.topicExists(zkUtils, topicName)) {
AdminUtils.createTopic(zkUtils, topicName, 3, 2, kafkaProp, RackAwareMode.Enforced$.MODULE$);
}
}
public static Properties selectTopic(String topicName) {
ZkClient zkClient = new ZkClient("192.168.31.106:2181", 30000, 30000, ZKStringSerializer$.MODULE$);;
ZkUtils zkUtils = ZkUtils.apply(zkClient, false);
return AdminUtils.fetchEntityConfig(zkUtils, ConfigType.Topic(), topicName);
}
public static void main(String[] args){
createTopic("avro");
}
}
| true |
27006125c1747a132aafd3991d8b1438fe251bb7 | Java | xdtcssdi/sc_p | /amicool/app/src/main/java/com/example/amicool/bean/TcaseBean.java | UTF-8 | 5,506 | 1.695313 | 2 | [] | no_license | package com.example.amicool.bean;
public class TcaseBean {
private int id;
private String name;
private String thumb;
private String thumbsize;
private String description;
private Object ressrcid;
private Object ressrcname;
private Object srcsc;
private Object srcscsize;
private Object donesc;
private Object donescsize;
private String technoid;
private String technoname;
private String kcdm;
private Object kcmc;
private String sectionid;
private Object sectionname;
private Object specialid;
private Object specialname;
private Object author;
private String content;
private int userid;
private String hits;
private Object insert_time;
private String update_time;
private String check_userid;
private Object checktime;
private String checkstate;
private String listorder;
private String vstate;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getThumb() {
return thumb;
}
public void setThumb(String thumb) {
this.thumb = thumb;
}
public String getThumbsize() {
return thumbsize;
}
public void setThumbsize(String thumbsize) {
this.thumbsize = thumbsize;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Object getRessrcid() {
return ressrcid;
}
public void setRessrcid(Object ressrcid) {
this.ressrcid = ressrcid;
}
public Object getRessrcname() {
return ressrcname;
}
public void setRessrcname(Object ressrcname) {
this.ressrcname = ressrcname;
}
public Object getSrcsc() {
return srcsc;
}
public void setSrcsc(Object srcsc) {
this.srcsc = srcsc;
}
public Object getSrcscsize() {
return srcscsize;
}
public void setSrcscsize(Object srcscsize) {
this.srcscsize = srcscsize;
}
public Object getDonesc() {
return donesc;
}
public void setDonesc(Object donesc) {
this.donesc = donesc;
}
public Object getDonescsize() {
return donescsize;
}
public void setDonescsize(Object donescsize) {
this.donescsize = donescsize;
}
public String getTechnoid() {
return technoid;
}
public void setTechnoid(String technoid) {
this.technoid = technoid;
}
public String getTechnoname() {
return technoname;
}
public void setTechnoname(String technoname) {
this.technoname = technoname;
}
public String getKcdm() {
return kcdm;
}
public void setKcdm(String kcdm) {
this.kcdm = kcdm;
}
public Object getKcmc() {
return kcmc;
}
public void setKcmc(Object kcmc) {
this.kcmc = kcmc;
}
public String getSectionid() {
return sectionid;
}
public void setSectionid(String sectionid) {
this.sectionid = sectionid;
}
public Object getSectionname() {
return sectionname;
}
public void setSectionname(Object sectionname) {
this.sectionname = sectionname;
}
public Object getSpecialid() {
return specialid;
}
public void setSpecialid(Object specialid) {
this.specialid = specialid;
}
public Object getSpecialname() {
return specialname;
}
public void setSpecialname(Object specialname) {
this.specialname = specialname;
}
public Object getAuthor() {
return author;
}
public void setAuthor(Object author) {
this.author = author;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public int getUserid() {
return userid;
}
public void setUserid(int userid) {
this.userid = userid;
}
public String getHits() {
return hits;
}
public void setHits(String hits) {
this.hits = hits;
}
public Object getInsert_time() {
return insert_time;
}
public void setInsert_time(Object insert_time) {
this.insert_time = insert_time;
}
public String getUpdate_time() {
return update_time;
}
public void setUpdate_time(String update_time) {
this.update_time = update_time;
}
public String getCheck_userid() {
return check_userid;
}
public void setCheck_userid(String check_userid) {
this.check_userid = check_userid;
}
public Object getChecktime() {
return checktime;
}
public void setChecktime(Object checktime) {
this.checktime = checktime;
}
public String getCheckstate() {
return checkstate;
}
public void setCheckstate(String checkstate) {
this.checkstate = checkstate;
}
public String getListorder() {
return listorder;
}
public void setListorder(String listorder) {
this.listorder = listorder;
}
public String getVstate() {
return vstate;
}
public void setVstate(String vstate) {
this.vstate = vstate;
}
}
| true |
571e576d2167a10433c89718af7d1a08caafd387 | Java | wudizhangzhi/test | /weixin_android/src/com/example/demo/MainActivity.java | GB18030 | 15,418 | 1.585938 | 2 | [] | no_license | package com.example.demo;
import android.util.Log;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.example.demo.view.DrawView;
import com.tencent.mm.sdk.modelmsg.SendMessageToWX;
import com.tencent.mm.sdk.modelmsg.WXImageObject;
import com.tencent.mm.sdk.modelmsg.WXMediaMessage;
import com.tencent.mm.sdk.modelmsg.WXMusicObject;
import com.tencent.mm.sdk.modelmsg.WXTextObject;
import com.tencent.mm.sdk.modelmsg.WXWebpageObject;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import Decoder.BASE64Encoder;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Bitmap.Config;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import net.sf.json.JSON;
import uk.co.senab.photoview.PhotoView;
public class MainActivity extends Activity implements OnClickListener {
Button btn_sendToWx, btn_launch, btn_register, btn_sendimage, btn_sendmusic, btn_sendpage, btn_token, btn_sendall,
btn_sendimagemsg;
private static final String APP_ID = "wx9fa2a68da1eca278";
private IWXAPI api;
// ù˺
private static final String WX_APP_ID = "wxeebd32309ff9a187";
private static final String WX_APP_SECRET = "21c1a896b231f114738f7b04b95c1644";
private String Token;
// ҵĹ˺
// private static final String WX_APP_ID = "wxbacc90fe16af9648";
// private static final String WX_APP_SECRET ="a732faee5044729a316c4505e2c52b80";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// ȡwxʵ
api = WXAPIFactory.createWXAPI(this, APP_ID, false);
initView();
}
private void initView() {
btn_sendToWx = (Button) findViewById(R.id.btn_sendToWx);
btn_launch = (Button) findViewById(R.id.btn_launch);
btn_register = (Button) findViewById(R.id.btn_register);
btn_sendimage = (Button) findViewById(R.id.btn_sendimage);
btn_sendmusic = (Button) findViewById(R.id.btn_sendmusic);
btn_sendpage = (Button) findViewById(R.id.btn_sendpage);
btn_token = (Button) findViewById(R.id.btn_token);
btn_sendall = (Button) findViewById(R.id.btn_sendall);
btn_sendimagemsg = (Button) findViewById(R.id.btn_sendimagemsg);
btn_sendToWx.setOnClickListener(this);
btn_launch.setOnClickListener(this);
btn_register.setOnClickListener(this);
btn_sendimage.setOnClickListener(this);
btn_sendmusic.setOnClickListener(this);
btn_sendpage.setOnClickListener(this);
btn_token.setOnClickListener(this);
btn_sendall.setOnClickListener(this);
btn_sendimagemsg.setOnClickListener(this);
}
/**
* תļΪbase64ַ
*
* @param path
* @return
* @throws Exception
*/
public static String encodeBase64File(File file) throws Exception {
FileInputStream inputFile = new FileInputStream(file);
byte[] buffer = new byte[(int) file.length()];
inputFile.read(buffer);
inputFile.close();
return new BASE64Encoder().encode(buffer);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_register:
Toast.makeText(this, "ע" + api.registerApp(APP_ID), Toast.LENGTH_SHORT).show();
break;
case R.id.btn_sendToWx:// ı
// ʼһWXTextObject
WXTextObject textObj = new WXTextObject();
textObj.text = "ı";
// WXTextObjectʼһWXMediaMessage
WXMediaMessage msg = new WXMediaMessage();
msg.mediaObject = textObj;
// ı͵Ϣʱtitleֶβ
// msg.title = "Will be ignored";
msg.description = "ı";
// һReq
SendMessageToWX.Req req = new SendMessageToWX.Req();
req.transaction = buildTransaction("text"); // transactionֶΨһʶһ
req.message = msg;
// SendMessageToWX.Req.WXSceneTimeline;Ȧ
req.scene = SendMessageToWX.Req.WXSceneSession;//
// apiӿڷݵ
api.sendReq(req);
break;
case R.id.btn_launch:// ¼
api.openWXApp();
break;
case R.id.btn_sendimage:// ͼƬ
Toast.makeText(MainActivity.this, "ͼƬ", Toast.LENGTH_SHORT).show();
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
WXImageObject imageobj = new WXImageObject(bitmap);
Bitmap thumbBitmap = Bitmap.createScaledBitmap(bitmap, 150, 150, true);
WXMediaMessage imageMsg = new WXMediaMessage();
imageMsg.mediaObject = imageobj;
imageMsg.thumbData = BmpToByteArray(thumbBitmap, true);
SendMessageToWX.Req reqImage = new SendMessageToWX.Req();
reqImage.message = imageMsg;
reqImage.transaction = buildTransaction("img");
reqImage.scene = SendMessageToWX.Req.WXSceneSession;//
api.sendReq(reqImage);
break;
case R.id.btn_sendmusic://
WXMusicObject musicObj = new WXMusicObject();
musicObj.musicUrl = "http://staff2.ustc.edu.cn/~wdw/softdown/index.asp/0042515_05.ANDY.mp3";
WXMediaMessage musicMsg = new WXMediaMessage();
musicMsg.mediaObject = musicObj;
musicMsg.title = "ɵ棡ɵ棡ɵ棡";
musicMsg.description = "ɵ棡ɵ棡ɵ棡";
musicMsg.thumbData = BmpToByteArray(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher),
true);
SendMessageToWX.Req musicReq = new SendMessageToWX.Req();
musicReq.message = musicMsg;
musicReq.transaction = buildTransaction("music");
musicReq.scene = SendMessageToWX.Req.WXSceneSession;
api.sendReq(musicReq);
break;
case R.id.btn_sendpage:// ҳ
WXWebpageObject webObj = new WXWebpageObject();
webObj.webpageUrl = "http://user.qzone.qq.com/1079229086?ADUIN=554330595&ADSESSION=1442364949&ADTAG=CLIENT.QQ.5419_FriendInfo_PersonalInfo.0&ADPUBNO=26494&ptlang=2052";
WXMediaMessage webMsg = new WXMediaMessage(webObj);
webMsg.title = "Ƕ.com";
webMsg.description = "welcome to Ƕ.com";
webMsg.thumbData = BmpToByteArray(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher),
true);
SendMessageToWX.Req reqWeb = new SendMessageToWX.Req();
reqWeb.message = webMsg;
reqWeb.transaction = buildTransaction("webpage");
reqWeb.scene = SendMessageToWX.Req.WXSceneSession;
api.sendReq(reqWeb);
break;
case R.id.btn_token:
Thread r = new WXThread();
r.start();
break;
case R.id.btn_sendall:
Thread r2 = new WXsendTextThread();
r2.start();
break;
case R.id.btn_sendimagemsg:
WXsendImageMsg r3 = new WXsendImageMsg();
r3.start();
break;
default:
break;
}
}
private byte[] BmpToByteArray(Bitmap thumbBitmap, boolean NeedRecycle) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
thumbBitmap.compress(CompressFormat.PNG, 100, baos);
byte[] result = baos.toByteArray();
if (NeedRecycle) {
thumbBitmap.recycle();
}
try {
baos.close();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
private String buildTransaction(final String type) {
return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
}
/**
* ȡƾ֤
*
* @author Administrator
*
*/
class WXThread extends Thread {
@Override
public void run() {
super.run();
HttpClient httpclient = new DefaultHttpClient();
String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + WX_APP_ID
+ "&secret=" + WX_APP_SECRET;
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse response = httpclient.execute(httpGet);
if (response.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
JSONObject json = new JSONObject(reader.readLine());
Token = json.getString("access_token");
Log.i("token", Token);
}
} catch (ClientProtocolException e2) {
e2.printStackTrace();
} catch (IOException e2) {
e2.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
class WXsendTextThread extends Thread {
@Override
public void run() {
super.run();
try {
HttpClient httpclient = new DefaultHttpClient();
String url = "https://api.weixin.qq.com/cgi-bin/message/mass/sendall?access_token=" + Token;
HttpPost httpPost = new HttpPost(url);
// HttpParams params=new BasicHttpParams();
// params.setParameter("encoding", "utf-8");
// Ϣ
JSONObject jsonObj = new JSONObject();
JSONObject json1 = new JSONObject();
json1.put("is_to_all", true);
// Ϣ
String content = "Ⱥı";
JSONObject json2 = new JSONObject();
json2.put("content", content);
jsonObj.put("filter", json1);
jsonObj.put("text", json2);
jsonObj.put("msgtype", "text");
// ҪñΪutf-8
StringEntity jsonentity = new StringEntity(jsonObj.toString(), "utf-8");
httpPost.setEntity(jsonentity);
HttpResponse response = httpclient.execute(httpPost);
if (response.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
JSONObject json = new JSONObject(reader.readLine());
Log.i("", json.toString());
}
} catch (ClientProtocolException e2) {
e2.printStackTrace();
} catch (IOException e2) {
e2.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
class WXsendImageMsg extends Thread {
@Override
public void run() {
super.run();
try {
//ϴͼƬ
String fileurl = "";
HttpClient httpclient = new DefaultHttpClient();
String url = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=" + Token+"&type=thumb";
HttpPost httpPost = new HttpPost(url);
// HttpParams params=new BasicHttpParams();
// params.setParameter("encoding", "utf-8");
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "big.jpg");
FileBody f1 = new FileBody(file);
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("file", f1);
reqEntity.addPart("filename", new StringBody("big.jpg"));
httpPost.setEntity(reqEntity);
HttpResponse response = httpclient.execute(httpPost);
if (response.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
JSONObject json = new JSONObject(reader.readLine());
// String[] s = json.toString().split("\\\\/");
// Log.i("json",json.toString());
// fileurl = s[s.length - 2];
// Log.i("json", s[s.length - 2]);
fileurl=json.getString("thumb_media_id");
}
Log.i("ļַ", fileurl);
// ͼjson
String mediaUrl="";
JSONObject j1 = new JSONObject();
j1.put("thumb_media_id", fileurl);
j1.put("title", "tuwen title");
j1.put("content_source_url", "www.qq.com");
j1.put("content", "tuwen content");
j1.put("show_cover_pic", "1");
JSONArray array = new JSONArray();
array.put(j1);
array.put(j1);
JSONObject obj = new JSONObject();
obj.put("articles", array);
Log.i("͵json", obj.toString());
// ͼϢز
HttpPost httpPost2 = new HttpPost(
"https://api.weixin.qq.com/cgi-bin/media/uploadnews?access_token=" + Token);
httpPost2.setEntity(new StringEntity(obj.toString()));
HttpResponse response2 = httpclient.execute(httpPost2);
if (response2.getStatusLine().getStatusCode() == 200) {
HttpEntity entity2 = response2.getEntity();
InputStream is2 = entity2.getContent();
BufferedReader reader2 = new BufferedReader(new InputStreamReader(is2));
JSONObject json2 = new JSONObject(reader2.readLine());
// ȡurl
Log.i("", json2.toString());
mediaUrl=json2.getString("media_id");
}
//ͼϢ
JSONObject json1_1=new JSONObject();
json1_1.put("is_to_all", "true");
JSONObject json2_1=new JSONObject();
json2_1.put("media_id", mediaUrl);
JSONObject jsonAll=new JSONObject();
jsonAll.put("msgtype", "mpnews");
jsonAll.put("filter", json1_1);
jsonAll.put("mpnews", json2_1);
Log.i("ͼϢ", jsonAll.toString());
String sendUrl="https://api.weixin.qq.com/cgi-bin/message/mass/sendall?access_token="+Token;
HttpPost httpPost3=new HttpPost(sendUrl);
httpPost3.setEntity(new StringEntity(jsonAll.toString()));
HttpResponse res=httpclient.execute(httpPost3);
if (res.getStatusLine().getStatusCode()==200) {
HttpEntity e=res.getEntity();
InputStream is=e.getContent();
BufferedReader r=new BufferedReader(new InputStreamReader(is));
Log.i("ȺͼϢ", r.readLine());
}
} catch (ClientProtocolException e2) {
e2.printStackTrace();
} catch (IOException e2) {
e2.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
| true |
6042eb862a712834d3e65c78345a6b287180478a | Java | vladbortnik/Java | /project_2/TargetShootingGame/src/main/java/edu/cuny/brooklyn/cisc3120/project/game/TargetGame.java | UTF-8 | 2,053 | 3.1875 | 3 | [] | no_license | package edu.cuny.brooklyn.cisc3120.project.game;
import java.util.Random;
import java.util.Scanner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import edu.cuny.brooklyn.cisc3120.project.game.Weapon.Gun;
import edu.cuny.brooklyn.cisc3120.project.game.Weapon.Rifle;
public class TargetGame {
private static Logger logger = LoggerFactory.getLogger(TargetGame.class);
private final int GAME_TARGET_AREA_WIDTH = 80;
private final int GAME_TARGET_AREA_HEIGHT = 25;
private GameBoard gameBoard; // having its own dimension: cells
private GameDisplay gameDisplay; // having its own dimension: cells to characters
private Random rng;
private Scanner in;
private Gun weapon;
public TargetGame() {
gameBoard = new GameBoard(GAME_TARGET_AREA_HEIGHT, GAME_TARGET_AREA_WIDTH);
gameDisplay = new GameDisplay(gameBoard);
rng = new Random();
in = new Scanner(System.in);
in.useDelimiter("(\\p{javaWhitespace}|,)+");
weapon = new Rifle(gameBoard);
}
public void play() {
boolean won = false;
setTarget();
gameBoard.plotBorder();
gameBoard.writeText(0, GAME_TARGET_AREA_HEIGHT-1, "Enter your target position (x, y):");
while(!won) {
gameDisplay.draw();
int xGuess = in.nextInt();
int yGuess = in.nextInt();
logger.debug("Player guessed x = " + xGuess + ", y =" + yGuess + ".");
if (targetHit(xGuess, yGuess)) {
gameBoard.plotBorder();
gameBoard.writeText(0, GAME_TARGET_AREA_HEIGHT-1, "You won. Game over.");
won = true;
} else {
gameBoard.plotBorder();
gameBoard.writeText(0, GAME_TARGET_AREA_HEIGHT-1,"Try again. Enter your target position (x, y): ");
}
gameDisplay.draw();
}
}
private void setTarget() {
int x = rng.nextInt(GAME_TARGET_AREA_WIDTH);
int y = rng.nextInt(GAME_TARGET_AREA_HEIGHT);
gameBoard.setCell(x, y, 'X');
logger.debug("Target: " + x + "," + y);
}
private boolean targetHit(int xGuess, int yGuess) {
return weapon.withinShootingArea(); // TODO
}
}
| true |
f8961e9e169214b26875486dabf095292ab1dbc5 | Java | saleksandrov/mdm-universal-api | /src/main/java/com/asv/unapi/service/UniversalRepoServiceImpl.java | UTF-8 | 24,210 | 2 | 2 | [] | no_license | package com.asv.unapi.service;
import com.asv.unapi.service.model.HierarchyItem;
import com.sap.mdm.commands.CommandException;
import com.sap.mdm.data.MdmValueTypeException;
import com.sap.mdm.data.Record;
import com.sap.mdm.data.RecordFactory;
import com.sap.mdm.data.RecordResultSet;
import com.sap.mdm.extension.data.RecordEx;
import com.sap.mdm.ids.FieldId;
import com.sap.mdm.ids.RecordId;
import com.sap.mdm.ids.TableId;
import com.sap.mdm.internal.protocol.commands.mdspublic.RequestEventsOnRepositoryCommand;
import com.sap.mdm.net.ConnectionException;
import com.sap.mdm.schema.FieldProperties;
import com.sap.mdm.schema.RepositorySchema;
import com.sap.mdm.schema.TableSchema;
import com.sap.mdm.valuetypes.LookupValue;
import com.sap.mdm.valuetypes.MdmValue;
import com.sap.mdm.valuetypes.MultiTupleValue;
import com.sap.mdm.valuetypes.TupleValue;
import com.asv.unapi.dao.BaseMdmDAO;
import com.asv.unapi.service.model.Item;
import com.asv.unapi.service.model.ItemProducer;
import com.asv.unapi.service.util.Assert;
import com.asv.unapi.service.util.MdmTypesMapper;
import java.util.*;
/**
* Experimental API for Mdm To Bean mapping.
*
* @author alexandrov
* @since 24.03.2016
*/
public class UniversalRepoServiceImpl<T extends Item> implements UniversalRepoService<T> {
private final BaseMdmDAO baseDAO;
private final MdmTypesMapper mapper;
private final Class<T> typeParameterClass;
private final LookupCache lookupCache = new LookupCache();
private class LookupCache {
private final Map<String, Record> lookupCacheMap = new HashMap<String, Record>();
void put(String key, Record value) {
lookupCacheMap.put(key, value);
}
Record get(String key) {
return lookupCacheMap.get(key);
}
void clear() {
lookupCacheMap.clear();
}
}
public UniversalRepoServiceImpl(Class<T> typeParameterClass, BaseMdmDAO baseDAO, MdmTypesMapper mapper) {
this.baseDAO = baseDAO;
this.mapper = mapper;
this.typeParameterClass = typeParameterClass;
}
public T recordToGenericPosition(RecordEx record, String[] supportingTables) {
return recordToGenericPosition(record, supportingTables, 0, typeParameterClass);
}
@SuppressWarnings("unchecked")
protected T recordToGenericPosition(RecordEx record, String[] supportingTables, int lookupLevel, Class itemClass) {
Item item = getInstanceOfItem(itemClass);
Assert.notNull(item, String.format("Cannot instantiate class by class %s. Object is NULL. Check does is implement the base interface.", itemClass.getName()));
ItemProducer producer = ItemProducer.parse(item);
producer.setId(record.getId().getIdValue());
producer.setOriginalRecord(record);
FieldId[] fields = record.getFields();
for (FieldId field : fields) {
RepositorySchema schema = baseDAO.getSchema();
FieldProperties fp = schema.getField(record.getTable(), field);
MdmValue value = record.getFieldValue(field);
if (value.getType() != MdmValue.Type.NULL) {
if ((fp.isTaxonomyLookup() || fp.isLookup()) && record.containsField(fp.getCode())) {
Record[] lookupRecords = record.findLookupRecords(field);
if (lookupRecords.length > 0) {
// Now we look through all the lookup record besides
// main tables or the tables which are not in supporting
// table list
for (Record currentLookupRecord : lookupRecords) {
RecordEx lookupRecord = (RecordEx) currentLookupRecord;
Class<? extends Item> classForMdmCode = producer.getClassForMdmCode(fp.getCode());
if (classForMdmCode != null) {
Item position = recordToGenericPosition(lookupRecord, supportingTables, lookupLevel + 1, classForMdmCode);
producer.setItem(fp.getCode(), position);
}
}
}
} else if (fp.isTuple()) {
if (fp.isMultiValued()) {
MultiTupleValue mtv = (MultiTupleValue) record.getFieldValue(field);
MdmValue[] tupleValues = mtv.getValues();
for (MdmValue v : tupleValues) {
TupleValue tv = (TupleValue) v;
Class<? extends Item> classForMdmCode = producer.getClassForMdmCode(fp.getCode());
if (classForMdmCode != null) {
Item tupleItem = tupleToGenericPosition(tv, classForMdmCode);
producer.addItem(fp.getCode(), tupleItem);
}
}
} else {
TupleValue tv = (TupleValue) record.getFieldValue(field);
Class<? extends Item> classForMdmCode = producer.getClassForMdmCode(fp.getCode());
if (classForMdmCode != null) {
Item tupleItem = tupleToGenericPosition(tv, classForMdmCode);
producer.addItem(fp.getCode(), tupleItem);
}
}
} else {
Object convertedValue = mapper.mapMdmToBeanType(value);
producer.setValue(fp.getCode(), convertedValue);
}
}
}
return (T) item;
}
protected Item tupleToGenericPosition(TupleValue tv, Class<? extends Item> itemClass) {
Item tupleItem = getInstanceOfItem(itemClass);
if (tupleItem == null) {
return null;
}
ItemProducer tupleProducer = ItemProducer.parse(tupleItem);
FieldId[] tupleFieldIds = tv.getFields();
for (FieldId tupleField : tupleFieldIds) {
FieldProperties tupleProperties = tv.getMetadata().getField(tupleField);
MdmValue tupleValue = tv.getFieldValue(tupleField);
if (!tupleValue.isNull()) {
if (tupleProperties.isLookup()) {
Record[] tupleLookupRecords = tv.findLookupRecords(tupleField);
populateInnerLookup(tupleProducer, tupleProperties, tupleLookupRecords);
} else if (tupleProperties.isTuple()) {
if (!tupleProperties.isMultiValued()) {
Item position = tupleToGenericPosition((TupleValue) tupleValue, tupleProducer.getClassForMdmCode(tupleProperties.getCode()));
tupleProducer.addItem(tupleProperties.getCode(), position);
} else {
MultiTupleValue mtv = (MultiTupleValue) tupleValue;
MdmValue[] tupleValues = mtv.getValues();
for (MdmValue v : tupleValues) {
TupleValue innerTv = (TupleValue) v;
Item innerTgp = tupleToGenericPosition(innerTv, tupleProducer.getClassForMdmCode(tupleProperties.getCode()));
tupleProducer.addItem(tupleProperties.getCode(), innerTgp);
}
}
} else {
Object convertedValue = mapper.mapMdmToBeanType(tupleValue);
tupleProducer.setValue(tupleProperties.getCode(), convertedValue);
}
}
}
return tupleItem;
}
protected void populateInnerLookup(ItemProducer tupleProducer, FieldProperties tupleProperties, Record[] tupleLookupRecords) {
if (tupleLookupRecords != null && tupleLookupRecords.length > 0) {
Record tupleLookupRecord = tupleLookupRecords[0];
Class<? extends Item> classForMdmCode = tupleProducer.getClassForMdmCode(tupleProperties.getCode());
Item position = getInstanceOfItem(classForMdmCode);
if (position == null) {
return;
}
ItemProducer positionProducer = ItemProducer.parse(position);
FieldId[] fieldIds = tupleLookupRecord.getFields();
for (FieldId fieldId : fieldIds) {
MdmValue fieldValue = tupleLookupRecord.getFieldValue(fieldId);
TableSchema lookupMetadata = tupleLookupRecord.getMetadata();
FieldProperties lookupFieldProperties = lookupMetadata.getField(fieldId);
String code = lookupFieldProperties.getCode();
if (lookupFieldProperties.isLookup()) {
Record[] records = tupleLookupRecord.findLookupRecords(lookupFieldProperties.getId());
Item lookupPosition = getInstanceOfItem(positionProducer.getClassForMdmCode(lookupFieldProperties.getCode()));
if (lookupPosition == null) {
continue;
}
if (records.length > 0) {
populateInnerLookup(ItemProducer.parse(lookupPosition), lookupFieldProperties, records);
}
positionProducer.setValue(code, lookupPosition);
} else {
positionProducer.setValue(code, mapper.mapMdmToBeanType(fieldValue));
}
}
tupleProducer.setValue(tupleProperties.getCode(), position);
}
}
@Override
public T getBeanByInternalId(int internalId, String[] supportingTables, int resultDefinitionMode) {
String table = ItemProducer.getMdmTableFromAnnotation(typeParameterClass);
try {
TableId[] sTables = new TableId[supportingTables.length];
int i = 0;
for (String tbl : supportingTables) {
sTables[i++] = baseDAO.getSchema().getTableId(tbl);
}
TableId tableId = baseDAO.getSchema().getTableId(table);
RecordEx record = baseDAO.getRecordExById(tableId, new RecordId(internalId), sTables, resultDefinitionMode);
return recordToGenericPosition(record, supportingTables);
} catch (ConnectionException e) {
throw new RuntimeException(e);
}
}
@Override
public T getBeanByInternalId(int internalId, String[] supportingTables) {
return getBeanByInternalId(internalId, supportingTables, BaseMdmDAO.CREATE_RESULTDEF_MODE_ALLFIELDS);
}
@Override
@SuppressWarnings("unchecked")
public T getBeanByPK(String idFieldCode, Object idFieldValue, String[] supportingTables) {
String table = ItemProducer.getMdmTableFromAnnotation(typeParameterClass);
try {
TableId[] sTables = new TableId[supportingTables.length];
int i = 0;
for (String tbl : supportingTables) {
sTables[i++] = baseDAO.getSchema().getTableId(tbl);
}
Hashtable pkValueMap = new Hashtable();
FieldProperties idFieldProperties = baseDAO.getSchema().getField(table, idFieldCode);
pkValueMap.put(idFieldProperties, idFieldValue);
RecordEx record = baseDAO.getCheckoutVersionOfRecordByIdValue(table, pkValueMap, sTables);
return recordToGenericPosition(record, supportingTables);
} catch (ConnectionException e) {
throw new RuntimeException(e);
}
}
public void delete(T t) {
Assert.notNull(t.getOriginalRecord(), "Original record cannot be null");
try {
baseDAO.deleteRecord(t.getOriginalRecord());
} catch (ConnectionException e) {
throw new RuntimeException(e);
}
}
@Override
@SuppressWarnings("unchecked")
public void saveBean(T t) {
Record originalRecord = t.getOriginalRecord();
if (originalRecord == null) {
// we have to get Record by internal id field
try {
String table = ItemProducer.getMdmTableFromAnnotation(typeParameterClass);
TableId tableId = baseDAO.getSchema().getTableId(table);
originalRecord = baseDAO.getRecordExById(tableId, new RecordId(t.getId()), null, BaseMdmDAO.CREATE_RESULTDEF_MODE_ALLFIELDS);
} catch (ConnectionException e) {
throw new RuntimeException(e);
}
}
ItemProducer itemProducer = ItemProducer.parse(t);
itemProducer.setOriginalRecord(originalRecord);
Map<String, Object> simpleFieldValues = itemProducer.getSimpleFieldValues();
String rootTableName = itemProducer.getTableName();
// save simple fields
for (String mdmCode : simpleFieldValues.keySet()) {
FieldProperties fieldProperties = baseDAO.getField(rootTableName, mdmCode);
Object value = simpleFieldValues.get(mdmCode);
MdmValue mdmValue = mapper.mapBeanTypeToMdm(value);
try {
originalRecord.setFieldValue(fieldProperties.getId(), mdmValue);
} catch (MdmValueTypeException e) {
throw new RuntimeException(String.format("Cannot set value (%s) to field (%s) of the record ", mdmValue, mdmCode), e);
}
}
foundAndSetLookupRecord(originalRecord, itemProducer, false);
try {
baseDAO.updateRecord(originalRecord);
} catch (ConnectionException e) {
throw new RuntimeException("Cannot save record", e);
}
}
private void foundAndSetLookupRecord(Record originalRecord, ItemProducer itemProducer, boolean useCache) {
String rootTableName = itemProducer.getTableName();
Map<String, Map<String, Object>> lookupFieldValues = itemProducer.getLookupFieldValues();
// save lookup fields
// find new Lookup Record and add it to original Record
for (String tableName : lookupFieldValues.keySet()) {
Map<String, Object> simpleValuesOfLookup = lookupFieldValues.get(tableName);
if (useCache) {
// We know that lookups values are stored in LinkedHashMap
// That meas it support ORDER and we can use it in constructing cache key
String cacheKey = constructLookupCacheKey(tableName, simpleValuesOfLookup);
Record lookupRecord = this.lookupCache.get(cacheKey);
if (lookupRecord != null) {
FieldProperties fieldProperties = baseDAO.getField(rootTableName, itemProducer.getMdmCodeOfLookupByTablename(tableName));
try {
originalRecord.setFieldValue(fieldProperties.getId(), new LookupValue(lookupRecord.getId()));
continue;
} catch (MdmValueTypeException e) {
throw new RuntimeException(String.format("Cannot set Lookup record to record. Lookup table=%s", tableName), e);
}
}
}
// perform search for lookup
Hashtable data = new Hashtable();
for (String mdmCodeOfLookup : simpleValuesOfLookup.keySet()) {
FieldProperties fieldProperties = baseDAO.getField(tableName, mdmCodeOfLookup);
Object value = simpleValuesOfLookup.get(mdmCodeOfLookup);
if (value != null) data.put(fieldProperties, value);
}
try {
if (data.size() == 0) {
continue;
}
RecordResultSet recordsByFieldValue = baseDAO.getRecordsByFieldValue(tableName, data, false);
if (recordsByFieldValue.getRecords().length > 1) {
throw new RuntimeException(String.format("Found to many lookup records in table=%s by fields=%s", tableName, data));
} else if (recordsByFieldValue.getRecords().length == 0) {
// not found lookup
continue;
}
Record lookupRecord = recordsByFieldValue.getRecords()[0];
FieldProperties fieldProperties = baseDAO.getField(rootTableName, itemProducer.getMdmCodeOfLookupByTablename(tableName));
originalRecord.setFieldValue(fieldProperties.getId(), new LookupValue(lookupRecord.getId()));
if (useCache) {
String cacheKey = constructLookupCacheKey(tableName, simpleValuesOfLookup);
this.lookupCache.put(cacheKey, lookupRecord);
}
} catch (ConnectionException e) {
throw new RuntimeException(String.format("Cannot find Lookup record in table=%s by fields=%s", tableName, data), e);
} catch (MdmValueTypeException e) {
throw new RuntimeException(String.format("Cannot set Lookup record to record. Lookup table=%s", tableName), e);
}
}
}
private String constructLookupCacheKey(String tableName, Map<String, Object> simpleValuesOfLookup) {
return tableName + simpleValuesOfLookup;
}
public int create(List<T> items) {
int created = 0;
try {
for (T item : items) {
create(item, true);
created++;
}
} finally {
// empty cache
}
return created;
}
public void create(T t) {
create(t, false);
}
public void create(T t, boolean useCache) {
ItemProducer itemProducer = ItemProducer.parse(t);
String tableName = itemProducer.getTableName();
Record emptyRecord = RecordFactory.createEmptyRecord(baseDAO.getSchema().getTableId(tableName));
Map<String, Object> simpleFieldValues = itemProducer.getSimpleFieldValues(true);
for (String key : simpleFieldValues.keySet()) {
FieldProperties field = baseDAO.getField(tableName, key);
Object value = simpleFieldValues.get(key);
try {
emptyRecord.setFieldValue(field.getId(), mapper.mapBeanTypeToMdm(value));
} catch (MdmValueTypeException e) {
throw new RuntimeException(String.format("Cannot map bean value to mdm type value = %s", value), e);
}
}
// lookup fields
foundAndSetLookupRecord(emptyRecord, itemProducer, useCache);
try {
Record parentRecord = null;
// два сопсоба указанаия парента через поле parendId и через иерархию
// второй способ будет работать быстрее при массовой вставке, т.к. он предполагает что Record у рута уже получен
if (itemProducer.hasParent()) {
String keyCode = itemProducer.getParentKeyCode();
Object value = itemProducer.getParentValue();
if (value != null) {
RecordResultSet recordResultSet = baseDAO.getRecordsByFieldValue(tableName, keyCode, value);
if (recordResultSet.getRecords().length > 1) {
throw new RuntimeException(String.format("Found to many records in table=%s by keyCode=%s value=%s", tableName, keyCode, value));
}
parentRecord = recordResultSet.getRecord(0);
}
} else if (t instanceof HierarchyItem) {
HierarchyItem hi = (HierarchyItem) t;
Item parent = hi.getParent();
if (parent != null) {
parentRecord = parent.getOriginalRecord();
if (parentRecord == null) {
throw new RuntimeException("Original record of parent cannot be null");
}
}
}
Record record = baseDAO.createRecord(emptyRecord, parentRecord != null ? parentRecord.getId() : null);
itemProducer.setOriginalRecord(record);
} catch (Exception e) {
throw new RuntimeException("Cannot create record", e);
}
}
@Override
@SuppressWarnings("unchecked")
public List<T> searchBeansByFilter(Map<String, Object> searchData, String[] supportingTables) {
String table = ItemProducer.getMdmTableFromAnnotation(typeParameterClass);
// needed for old code
Hashtable data = new Hashtable();
for (String key : searchData.keySet()) {
FieldProperties field = baseDAO.getField(table, key);
data.put(field, searchData.get(key));
}
return searchRecordsByParameters(supportingTables, data);
}
private List<T> searchRecordsByParameters(String[] supportingTables, Map<FieldProperties, Object> data) {
TableId[] sTables = new TableId[supportingTables.length];
int i = 0;
for (String tbl : supportingTables) {
sTables[i++] = baseDAO.getSchema().getTableId(tbl);
}
List<T> result = new ArrayList<T>();
try {
RecordResultSet recordsByFieldValue = baseDAO.getRecordsByMapValue(data, sTables, false);
int count = recordsByFieldValue.getCount();
while (--count >= 0) {
RecordEx record = (RecordEx) recordsByFieldValue.getRecord(count);
T t = recordToGenericPosition(record, supportingTables);
result.add(t);
}
} catch (ConnectionException e) {
throw new RuntimeException(String.format("Cannot perform search by data=%s", data), e);
}
return result;
}
@Override
@SuppressWarnings("unchecked")
public List<T> searchBeanByPattern(T pattern, String[] supportingTables) {
ItemProducer itemProducer = ItemProducer.parse(pattern);
String rootTableName = itemProducer.getTableName();
Map<String, Object> simpleFieldValues = itemProducer.getSimpleFieldValues(true);
Map<FieldProperties, Object> searchData = new HashMap<FieldProperties, Object>();
for (String key : simpleFieldValues.keySet()) {
FieldProperties field = baseDAO.getField(rootTableName, key);
searchData.put(field, simpleFieldValues.get(key));
}
Map<String, Map<String, Object>> lookupFieldValues = itemProducer.getLookupFieldValues(true);
// add all lookup values to search params
for (String tableName : lookupFieldValues.keySet()) {
Map<String, Object> simpleValuesOfLookup = lookupFieldValues.get(tableName);
// perform search for lookup
Hashtable lookupData = new Hashtable();
for (String mdmCodeOfLookup : simpleValuesOfLookup.keySet()) {
FieldProperties fieldProperties = baseDAO.getField(tableName, mdmCodeOfLookup);
lookupData.put(fieldProperties, simpleValuesOfLookup.get(mdmCodeOfLookup));
}
try {
RecordResultSet recordsByFieldValue = baseDAO.getRecordsByFieldValue(tableName, lookupData, false);
if (recordsByFieldValue.getRecords().length > 1) {
throw new RuntimeException(String.format("Found to many lookup records in table=%s by fields=%s", tableName, lookupData));
}
Record lookupRecord = recordsByFieldValue.getRecords()[0];
FieldProperties fieldProperties = baseDAO.getField(rootTableName, itemProducer.getMdmCodeOfLookupByTablename(tableName));
searchData.put(fieldProperties, new LookupValue(lookupRecord.getId()));
} catch (ConnectionException e) {
throw new RuntimeException(String.format("Cannot find Lookup record in table=%s by fields=%s", tableName, lookupData), e);
}
}
return searchRecordsByParameters(supportingTables, searchData);
}
private Item getInstanceOfItem(Class<? extends Item> type) {
try {
return type.newInstance();
} catch (Exception e) {
return null;
}
}
}
| true |
2fbfbd9833b046f44d5e76f9a799f64eccba48c6 | Java | shaukhk01/JavaExample | /BoxDemo18.java | UTF-8 | 549 | 2.71875 | 3 | [] | no_license | class File_Terminal
{
int outer_x = 100;
public void Write_File()
{
for(int i=0;i<10;i++)
{
class Open_Tab
{
public void read_file()
{
System.out.println("outer_class file: " + outer_x);
}
}
Open_Tab ob = new Open_Tab();
ob.read_file();
}
}
}
public class BoxDemo18
{
public static void main(String[]args)
{
File_Terminal TF = new File_Terminal();
TF.Write_File();
}
}
| true |
1026760d08e7af1eee67e7fc38bdac5e21dba51a | Java | livyk/oop-4 | /Laba2/src/Main.java | UTF-8 | 309 | 2.53125 | 3 | [
"MIT"
] | permissive | import rect.Rectangle;
public class Main {
public static void main(String[] args) {
Rectangle r1 = new Rectangle(5, 5);
System.out.println(r1);
r1.move(2, 3);
System.out.println(r1);
Rectangle r2 = new Rectangle(5, 5);
Rectangle r3 = r2.Union(r1);
System.out.println(r3);
}
}
| true |