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
6df49c7cd5976d4574351f9ec163b82b11f35ac6
Java
Chrisxavix/JavaJDK15
/src/UniversityJava/topics/herency/Test.java
UTF-8
713
3.40625
3
[]
no_license
package UniversityJava.topics.herency; import java.util.Date; public class Test { public static void main(String[] args) { Empleado test = new Empleado("Juan", 5000); Cliente test1 = new Cliente(new Date(), false, "Chris", 'm', 12, "M4"); /* Creado objetos desde persona con los constructores definidos */ Persona sobrecargaVacio = new Persona(); Persona sobrecargaConUnParametro = new Persona("Chris"); Persona sobrecargaConvariosParametros = new Persona("Chris", 'm', 12, "M4"); System.out.println("Empleado: Información de clase hija y padre: " + test); System.out.println("Cliente: Información de clase hija y padre: " + test1); } }
true
dc7b9c64157cf9df682b3ace92dcfe58e288a1bf
Java
mklucz/stapi
/server/src/main/java/com/cezarykluczynski/stapi/server/trading_card/reader/TradingCardSoapReader.java
UTF-8
3,103
2.109375
2
[ "MIT" ]
permissive
package com.cezarykluczynski.stapi.server.trading_card.reader; import com.cezarykluczynski.stapi.client.v1.soap.TradingCardBaseRequest; import com.cezarykluczynski.stapi.client.v1.soap.TradingCardBaseResponse; import com.cezarykluczynski.stapi.client.v1.soap.TradingCardFullRequest; import com.cezarykluczynski.stapi.client.v1.soap.TradingCardFullResponse; import com.cezarykluczynski.stapi.model.trading_card.entity.TradingCard; import com.cezarykluczynski.stapi.server.common.mapper.PageMapper; import com.cezarykluczynski.stapi.server.common.mapper.SortMapper; import com.cezarykluczynski.stapi.server.common.reader.BaseReader; import com.cezarykluczynski.stapi.server.common.reader.FullReader; import com.cezarykluczynski.stapi.server.common.validator.StaticValidator; import com.cezarykluczynski.stapi.server.trading_card.mapper.TradingCardBaseSoapMapper; import com.cezarykluczynski.stapi.server.trading_card.mapper.TradingCardFullSoapMapper; import com.cezarykluczynski.stapi.server.trading_card.query.TradingCardSoapQuery; import com.google.common.collect.Iterables; import org.springframework.data.domain.Page; import org.springframework.stereotype.Service; @Service public class TradingCardSoapReader implements BaseReader<TradingCardBaseRequest, TradingCardBaseResponse>, FullReader<TradingCardFullRequest, TradingCardFullResponse> { private final TradingCardSoapQuery tradingCardSoapQuery; private final TradingCardBaseSoapMapper tradingCardBaseSoapMapper; private final TradingCardFullSoapMapper tradingCardFullSoapMapper; private final PageMapper pageMapper; private final SortMapper sortMapper; public TradingCardSoapReader(TradingCardSoapQuery tradingCardSoapQuery, TradingCardBaseSoapMapper tradingCardBaseSoapMapper, TradingCardFullSoapMapper tradingCardFullSoapMapper, PageMapper pageMapper, SortMapper sortMapper) { this.tradingCardSoapQuery = tradingCardSoapQuery; this.tradingCardBaseSoapMapper = tradingCardBaseSoapMapper; this.tradingCardFullSoapMapper = tradingCardFullSoapMapper; this.pageMapper = pageMapper; this.sortMapper = sortMapper; } @Override public TradingCardBaseResponse readBase(TradingCardBaseRequest input) { Page<TradingCard> tradingCardPage = tradingCardSoapQuery.query(input); TradingCardBaseResponse tradingCardResponse = new TradingCardBaseResponse(); tradingCardResponse.setPage(pageMapper.fromPageToSoapResponsePage(tradingCardPage)); tradingCardResponse.setSort(sortMapper.map(input.getSort())); tradingCardResponse.getTradingCards().addAll(tradingCardBaseSoapMapper.mapBase(tradingCardPage.getContent())); return tradingCardResponse; } @Override public TradingCardFullResponse readFull(TradingCardFullRequest input) { StaticValidator.requireUid(input.getUid()); Page<TradingCard> tradingCardPage = tradingCardSoapQuery.query(input); TradingCardFullResponse tradingCardFullResponse = new TradingCardFullResponse(); tradingCardFullResponse.setTradingCard(tradingCardFullSoapMapper .mapFull(Iterables.getOnlyElement(tradingCardPage.getContent(), null))); return tradingCardFullResponse; } }
true
63f3a00c8feabba7638ec12feca8880f3ea09b7a
Java
sekys/ivda
/src/sk/stuba/fiit/perconik/ivda/activity/dto/SystemEventDto.java
UTF-8
343
1.875
2
[ "MIT" ]
permissive
package sk.stuba.fiit.perconik.ivda.activity.dto; import javax.ws.rs.core.UriBuilder; public class SystemEventDto extends EventDto { private static final long serialVersionUID = -2196950013163342189L; @Override protected UriBuilder getDefaultEventTypeUri() { return super.getDefaultEventTypeUri().path("system"); } }
true
f159276dc98a3bbe51b5f7acda02534956a44e10
Java
terakael/sandbox2
/src/main/java/responses/AssembleResponse.java
UTF-8
2,253
2.265625
2
[]
no_license
package responses; import database.dao.ConstructableDao; import database.dao.ItemDao; import database.dao.PlayerStorageDao; import database.dao.SceneryDao; import processing.PathFinder; import processing.attackable.Player; import processing.attackable.Player.PlayerState; import processing.managers.FightManager; import requests.AssembleRequest; import requests.Request; import types.StorageTypes; public class AssembleResponse extends Response { @Override public void process(Request req, Player player, ResponseMaps responseMaps) { // if (FightManager.fightWithFighterExists(player)) { // setRecoAndResponseText(0, "you can't do that during combat."); // responseMaps.addClientOnlyResponse(player, this); // return; // } final int slot = ((AssembleRequest)req).getSlot(); final int itemId = PlayerStorageDao.getItemIdInSlot(player.getId(), StorageTypes.INVENTORY, slot); if (ConstructableDao.getConstructableByFlatpackItemId(itemId) == null) return; int existingSceneryId = SceneryDao.getSceneryIdByTileId(player.getFloor(), req.getTileId()); if (existingSceneryId != -1) { setRecoAndResponseText(0, "you can't build that here."); responseMaps.addClientOnlyResponse(player, this); return; } int newTileId = ConstructionResponse.findDestinationTileId(player.getFloor(), player.getTileId()); if (newTileId == player.getTileId()) { // somehow no tiles are free? are you inside a tree or something? setRecoAndResponseText(0, "you can't build that here."); responseMaps.addClientOnlyResponse(player, this); return; } // move the player to the side so the constructable doesn't appear on top of the player PlayerUpdateResponse playerUpdate = new PlayerUpdateResponse(); playerUpdate.setId(player.getId()); playerUpdate.setTileId(newTileId); playerUpdate.setFaceDirection(PathFinder.getDirection(newTileId, player.getTileId())); responseMaps.addLocalResponse(player.getFloor(), newTileId, playerUpdate); player.setTileId(newTileId); player.setState(PlayerState.assembling); player.setSavedRequest(req); player.setTickCounter(3); responseMaps.addLocalResponse(player.getFloor(), player.getTileId(), new ActionBubbleResponse(player, ItemDao.getItem(itemId))); } }
true
e8127bed6e3a5bfac60160b0acb541a90eaecdba
Java
Unity3DMobileAlbatron/DATAUNITY3D
/Servercode/gsd/src/lx/matcher/gs/activity/huiwu/msg/SPreselectionKickout.java
UTF-8
1,349
1.890625
2
[]
no_license
package lx.gs.activity.huiwu.msg; import com.goldhuman.Common.Marshal.OctetsStream; import com.goldhuman.Common.Marshal.MarshalException; // {{{ RPCGEN_IMPORT_BEGIN // {{{ DO NOT EDIT THIS abstract class __SPreselectionKickout__ extends xio.Protocol { } // DO NOT EDIT THIS }}} // RPCGEN_IMPORT_END }}} public class SPreselectionKickout extends __SPreselectionKickout__ { @Override protected void process() { // protocol handle } // {{{ RPCGEN_DEFINE_BEGIN // {{{ DO NOT EDIT THIS public static final int PROTOCOL_TYPE = 6579458; public int getType() { return 6579458; } public SPreselectionKickout() { } public final boolean _validator_() { return true; } public OctetsStream marshal(OctetsStream _os_) { return _os_; } public OctetsStream unmarshal(OctetsStream _os_) throws MarshalException { return _os_; } public boolean equals(Object _o1_) { if (_o1_ == this) return true; return _o1_ instanceof SPreselectionKickout; } public int hashCode() { int _h_ = 0; return _h_; } public String toString() { StringBuilder _sb_ = new StringBuilder(); _sb_.append("("); _sb_.append(")"); return _sb_.toString(); } public int compareTo(SPreselectionKickout _o_) { if (_o_ == this) return 0; int _c_ = 0; return _c_; } // DO NOT EDIT THIS }}} // RPCGEN_DEFINE_END }}} }
true
726523c798ac5d877bca6cdddf3fb77812b94390
Java
moutainhigh/acc2
/src/com/sinosoft/picc/schema/AccRemarkManageSchema.java
GB18030
10,881
2.4375
2
[]
no_license
/** * Copyright (c) 2002 sinosoft Co. Ltd. * All right reserved. */ package com.sinosoft.picc.schema; import java.sql.*; import java.io.*; import java.util.Date; import com.sinosoft.picc.pubfun.*; import com.sinosoft.utility.*; import com.sinosoft.picc.db.AccRemarkManageDB; /* * <p>ClassName: AccRemarkManageSchema </p> * <p>Description: DB Schema ļ </p> * <p>Copyright: Copyright (c) 2002</p> * <p>Company: sinosoft </p> * @Database: PhysicalDataModel_1 * @CreateDate2006-07-20 */ public class AccRemarkManageSchema implements Schema, Cloneable { // @Field /** 㵥λ */ private String CenterCode; /** ժҪ */ private String RemarkCode; /** ƾ֤ժҪ */ private String RemarkName; /** */ private String Flag; public static final int FIELDNUM = 4; // ݿֶθ private static String[] PK; // public CErrors mErrors; // Ϣ // @Constructor public AccRemarkManageSchema() { mErrors = new CErrors(); String[] pk = new String[2]; pk[0] = "CenterCode"; pk[1] = "RemarkCode"; PK = pk; } /** * Schema¡ * @return Object * @throws CloneNotSupportedException */ public Object clone() throws CloneNotSupportedException { AccRemarkManageSchema cloned = (AccRemarkManageSchema)super.clone(); cloned.mErrors = (CErrors) mErrors.clone(); return cloned; } // @Method public String[] getPK() { return PK; } public String getCenterCode() { return CenterCode; } public void setCenterCode(String aCenterCode) { CenterCode = aCenterCode; } public String getRemarkCode() { return RemarkCode; } public void setRemarkCode(String aRemarkCode) { RemarkCode = aRemarkCode; } public String getRemarkName() { return RemarkName; } public void setRemarkName(String aRemarkName) { RemarkName = aRemarkName; } public String getFlag() { return Flag; } public void setFlag(String aFlag) { Flag = aFlag; } /** * ʹһ AccRemarkManageSchema Schema ֵ * @param: aAccRemarkManageSchema AccRemarkManageSchema **/ public void setSchema(AccRemarkManageSchema aAccRemarkManageSchema) { this.CenterCode = aAccRemarkManageSchema.getCenterCode(); this.RemarkCode = aAccRemarkManageSchema.getRemarkCode(); this.RemarkName = aAccRemarkManageSchema.getRemarkName(); this.Flag = aAccRemarkManageSchema.getFlag(); } /** * ʹ ResultSet еĵ i и Schema ֵ * @param: rs ResultSet * @param: i int * @return: boolean **/ public boolean setSchema(ResultSet rs,int i) { try { //rs.absolute(i); // ǹα if( rs.getString(1) == null ) this.CenterCode = null; else this.CenterCode = rs.getString(1).trim(); if( rs.getString(2) == null ) this.RemarkCode = null; else this.RemarkCode = rs.getString(2).trim(); if( rs.getString(3) == null ) this.RemarkName = null; else this.RemarkName = rs.getString(3).trim(); if( rs.getString(4) == null ) this.Flag = null; else this.Flag = rs.getString(4).trim(); } catch(SQLException sqle) { System.out.println("ݿбAccRemarkManageֶθSchemaеֶθһ£ִdb.executeQueryѯʱδʹselect * from tables"); // @@ CError tError = new CError(); tError.moduleName = "AccRemarkManageSchema"; tError.functionName = "setSchema"; tError.errorMessage = sqle.toString(); this.mErrors .addOneError(tError); return false; } return true; } public AccRemarkManageSchema getSchema() { AccRemarkManageSchema aAccRemarkManageSchema = new AccRemarkManageSchema(); aAccRemarkManageSchema.setSchema(this); return aAccRemarkManageSchema; } public AccRemarkManageDB getDB() { AccRemarkManageDB aDBOper = new AccRemarkManageDB(); aDBOper.setSchema(this); return aDBOper; } /** * ݴ XML ʽ˳μ<A href ={@docRoot}/dataStructure/tb.html#PrpAccRemarkManage/A>ֶ * @return: String شַ **/ public String encode() { StringBuffer strReturn = new StringBuffer(256); strReturn.append(StrTool.cTrim(CenterCode)); strReturn.append(SysConst.PACKAGESPILTER); strReturn.append(StrTool.cTrim(RemarkCode)); strReturn.append(SysConst.PACKAGESPILTER); strReturn.append(StrTool.cTrim(RemarkName)); strReturn.append(SysConst.PACKAGESPILTER); strReturn.append(StrTool.cTrim(Flag)); return strReturn.toString(); } /** * ݽ˳μ<A href ={@docRoot}/dataStructure/tb.html#PrpAccRemarkManage>ʷƾ֤Ϣ</A>ֶ * @param: strMessage String һ¼ݵַ * @return: boolean **/ public boolean decode(String strMessage) { try { CenterCode = StrTool.getStr(StrTool.GBKToUnicode(strMessage), 1, SysConst.PACKAGESPILTER ); RemarkCode = StrTool.getStr(StrTool.GBKToUnicode(strMessage), 2, SysConst.PACKAGESPILTER ); RemarkName = StrTool.getStr(StrTool.GBKToUnicode(strMessage), 3, SysConst.PACKAGESPILTER ); Flag = StrTool.getStr(StrTool.GBKToUnicode(strMessage), 4, SysConst.PACKAGESPILTER ); } catch(NumberFormatException ex) { // @@ CError tError = new CError(); tError.moduleName = "AccRemarkManageSchema"; tError.functionName = "decode"; tError.errorMessage = ex.toString(); this.mErrors .addOneError(tError); return false; } return true; } /** * ȡöӦStringʽֵֶ * @param: FCode String ϣȡõֶ * @return: String * ûжӦֶΣ"" * ֵֶΪգ"null" **/ public String getV(String FCode) { String strReturn = ""; if (FCode.equals("CenterCode")) { strReturn = StrTool.GBKToUnicode(String.valueOf(CenterCode)); } if (FCode.equals("RemarkCode")) { strReturn = StrTool.GBKToUnicode(String.valueOf(RemarkCode)); } if (FCode.equals("RemarkName")) { strReturn = StrTool.GBKToUnicode(String.valueOf(RemarkName)); } if (FCode.equals("Flag")) { strReturn = StrTool.GBKToUnicode(String.valueOf(Flag)); } if (strReturn.equals("")) { strReturn = "null"; } return strReturn; } /** * ȡSchemaֵָӦֵֶ * @param: nFieldIndex int ֵֶָ * @return: String * ûжӦֶΣ"" * ֵֶΪգ"null" **/ public String getV(int nFieldIndex) { String strFieldValue = ""; switch(nFieldIndex) { case 0: strFieldValue = StrTool.GBKToUnicode(CenterCode); break; case 1: strFieldValue = StrTool.GBKToUnicode(RemarkCode); break; case 2: strFieldValue = StrTool.GBKToUnicode(RemarkName); break; case 3: strFieldValue = StrTool.GBKToUnicode(Flag); break; default: strFieldValue = ""; }; if( strFieldValue.equals("") ) { strFieldValue = "null"; } return strFieldValue; } /** * öӦStringʽֵֶ * @param: FCode String ҪֵĶ * @param: FValue String Ҫֵ * @return: boolean **/ public boolean setV(String FCode ,String FValue) { if( StrTool.cTrim( FCode ).equals( "" )) return false; if (FCode.equalsIgnoreCase("CenterCode")) { if( FValue != null && !FValue.equals("")) { CenterCode = FValue.trim(); } else CenterCode = null; } if (FCode.equalsIgnoreCase("RemarkCode")) { if( FValue != null && !FValue.equals("")) { RemarkCode = FValue.trim(); } else RemarkCode = null; } if (FCode.equalsIgnoreCase("RemarkName")) { if( FValue != null && !FValue.equals("")) { RemarkName = FValue.trim(); } else RemarkName = null; } if (FCode.equalsIgnoreCase("Flag")) { if( FValue != null && !FValue.equals("")) { Flag = FValue.trim(); } else Flag = null; } return true; } public boolean equals(Object otherObject) { if (this == otherObject) return true; if (otherObject == null) return false; if (getClass() != otherObject.getClass()) return false; AccRemarkManageSchema other = (AccRemarkManageSchema)otherObject; return CenterCode.equals(other.getCenterCode()) && RemarkCode.equals(other.getRemarkCode()) && RemarkName.equals(other.getRemarkName()) && Flag.equals(other.getFlag()); } /** * ȡSchemaӵֶε * @return: int **/ public int getFieldCount() { return FIELDNUM; } /** * ȡSchemaֶָӦֵ * ûжӦֶΣ-1 * @param: strFieldName String * @return: int **/ public int getFieldIndex(String strFieldName) { if( strFieldName.equals("CenterCode") ) { return 0; } if( strFieldName.equals("RemarkCode") ) { return 1; } if( strFieldName.equals("RemarkName") ) { return 2; } if( strFieldName.equals("Flag") ) { return 3; } return -1; } /** * ȡSchemaֵָӦֶ * ûжӦֶΣ"" * @param: nFieldIndex int * @return: String **/ public String getFieldName(int nFieldIndex) { String strFieldName = ""; switch(nFieldIndex) { case 0: strFieldName = "CenterCode"; break; case 1: strFieldName = "RemarkCode"; break; case 2: strFieldName = "RemarkName"; break; case 3: strFieldName = "Flag"; break; default: strFieldName = ""; }; return strFieldName; } /** * ȡSchemaֶָӦֶ * ûжӦֶΣSchema.TYPE_NOFOUND * @param: strFieldName String * @return: int **/ public int getFieldType(String strFieldName) { if( strFieldName.equals("CenterCode") ) { return Schema.TYPE_STRING; } if( strFieldName.equals("RemarkCode") ) { return Schema.TYPE_STRING; } if( strFieldName.equals("RemarkName") ) { return Schema.TYPE_STRING; } if( strFieldName.equals("Flag") ) { return Schema.TYPE_STRING; } return Schema.TYPE_NOFOUND; } /** * ȡSchemaֵָӦֶ * ûжӦֶΣSchema.TYPE_NOFOUND * @param: nFieldIndex int * @return: int **/ public int getFieldType(int nFieldIndex) { int nFieldType = Schema.TYPE_NOFOUND; switch(nFieldIndex) { case 0: nFieldType = Schema.TYPE_STRING; break; case 1: nFieldType = Schema.TYPE_STRING; break; case 2: nFieldType = Schema.TYPE_STRING; break; case 3: nFieldType = Schema.TYPE_STRING; break; default: nFieldType = Schema.TYPE_NOFOUND; }; return nFieldType; } }
true
88635e2582d13507d67af3cab0634cfe244b9d97
Java
oshhh/PlantsVsZombies
/src/Controller/RegularAction.java
UTF-8
3,408
2.6875
3
[]
no_license
package Controller; import javafx.application.Platform; import java.util.*; import java.io.*; public class RegularAction extends Thread { private static int ZOMBIE_INTERVAL = 15000; private static int ZOMBIE_INTERVAL_WAVE = 1000; private static int PEA_INTERVAL = 1000; private static int SUNTOKEN_INTERVAL = 10000; private LevelController levelController; private long lastZombieTime; private long lastPeaTime; private long lastSuntokenTime; public RegularAction(LevelController levelController) { this.levelController = levelController; this.lastZombieTime = 0L; this.lastPeaTime = 0L; this.lastSuntokenTime = 0L; } public void levelCompleted() { levelController.getLevel().setRunning(false); levelController.getLevel().levelCompleted(); Platform.runLater(() -> { levelController.getScene().lookup("#gameWinnerMenu").setVisible(true); levelController.getScene().lookup("#gameWinnerMenu").setDisable(false); }); } @Override public void run() { int Current_Zombie_Interval = ZOMBIE_INTERVAL; boolean waveOn = true; try { while (levelController.getLevel().isRunning()) { while (levelController.isPause() & levelController.getLevel().isRunning()) {} if (levelController.getLevel().getZombies().size()==0 && levelController.getLevel().getMaxZombies()==levelController.getLevel().getCurrentNumberOfZombies()){ throw new GameWinnerException(); } if (levelController.getLevel().isFinalWaveReady() & waveOn){ waveOn = false; Platform.runLater(() -> { levelController.getScene().lookup("#finalWaveText").setVisible(true); }); try { Thread.sleep(3000); } catch (InterruptedException e) {} Platform.runLater(() -> { levelController.getScene().lookup("#finalWaveText").setVisible(false); }); Current_Zombie_Interval = ZOMBIE_INTERVAL_WAVE; } if(System.currentTimeMillis() - lastZombieTime >= Current_Zombie_Interval) { GenerateZombie generateZombie = new GenerateZombie(levelController); Platform.runLater(generateZombie); lastZombieTime = System.currentTimeMillis(); } if(System.currentTimeMillis() - lastSuntokenTime >= SUNTOKEN_INTERVAL) { GenerateSun generateSun = new GenerateSun(levelController); Platform.runLater(generateSun); lastSuntokenTime = System.currentTimeMillis(); } if(System.currentTimeMillis() - lastPeaTime >= PEA_INTERVAL) { ShootPeas shootPeas = new ShootPeas(levelController); Platform.runLater(shootPeas); lastPeaTime = System.currentTimeMillis(); } try { Thread.sleep(1000); } catch (InterruptedException e) {} } } catch (GameWinnerException e) { levelCompleted(); } } }
true
116643b0cce079e2c59292df1266bb8b6a6e6ff9
Java
VijayEluri/DisplayableCreator
/src/java/net/niconomicon/tile/source/app/tools/DisplayableSourceBase.java
UTF-8
3,136
2.421875
2
[]
no_license
package net.niconomicon.tile.source.app.tools; import java.awt.Dimension; import java.awt.image.BufferedImage; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import net.niconomicon.tile.source.app.Ref; import net.niconomicon.tile.source.app.viewer.actions.SingleTileLoader; import net.niconomicon.tile.source.app.viewer.structs.TileCoord; import net.niconomicon.tile.source.app.viewer.structs.ZoomLevel; public class DisplayableSourceBase { Connection mapDB; String title; String description; public static final String getTilesInRange = "select * from tiles_0_0 where x >= ? and x <= ? and y >=? and y <=? and z=?"; int type = -1; Dimension tileSize = null; List<ZoomLevel> levels; String currentTileCoord; BufferedImage currentTile; public DisplayableSourceBase(String tileSourcePath){ loadInfos(tileSourcePath); } public void loadInfos(String tileSourcePath) { levels = new ArrayList<ZoomLevel>(); try { System.out.println("trying to open the map : " + tileSourcePath); mapDB = DriverManager.getConnection("jdbc:sqlite:" + tileSourcePath); mapDB.setReadOnly(true); type = SingleTileLoader.getPossibleType(mapDB); tileSize = SingleTileLoader.getTileSize(mapDB); Statement statement = mapDB.createStatement(); // zoom = 0; ResultSet rs = statement.executeQuery("select * from " + Ref.layers_infos_table_name); int totalTiles = 0; while (rs.next()) { ZoomLevel zl = new ZoomLevel(); zl.width = rs.getLong("width"); zl.height = rs.getLong("height"); zl.tiles_x = rs.getLong("tiles_x"); zl.tiles_y = rs.getLong("tiles_y"); zl.z = rs.getInt("zoom"); // System.out.println("Tiles for level " + zl.z + " : " + // zl.tiles_x * zl.tiles_y); totalTiles += zl.tiles_x * zl.tiles_y; levels.add(zl.z, zl); } ZoomLevel currentLevel = levels.get(levels.size() - 1); // System.out.println("Setting current level to " + currentLevel.z + // " total tiles : " + totalTiles); rs = statement.executeQuery("select * from infos"); while (rs.next()) { title = rs.getString("title"); description = rs.getString("description"); } // System.out.println("fully cached !"); } catch (Exception ex) { System.err.println("ex for map : " + tileSourcePath); ex.printStackTrace(); } } public boolean hasImage(TileCoord coord) { return false; } public void setImage(long x, long y, long z, BufferedImage im) { currentTileCoord = Ref.getKey(x, y, z); currentTile = im; } public BufferedImage getImage(int x, int y, int z) { String k = Ref.getKey(x, y, z); TileCoord c = new TileCoord(x, y, z); SingleTileLoader loader = new SingleTileLoader(mapDB, c, this, type); loader.run(); return currentTile; } public String getTitle() { return title; } public String getDescription() { return description; } public List<ZoomLevel> getILevelInfos() { return levels; } public int getMaxZ() { return levels.size(); } public ZoomLevel getMaxInfo() { return levels.get(0); } }
true
5ca0c68af2f9e35aab6fa606a2bb5253ed3da521
Java
gori8/KP
/userAndPaymentInfo/src/main/java/com/example/userandpaymentinfo/model/RedUrl.java
UTF-8
743
2.109375
2
[]
no_license
package com.example.userandpaymentinfo.model; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import org.hibernate.annotations.Type; import javax.persistence.*; import java.util.ArrayList; import java.util.List; import java.util.UUID; @Getter @Setter @AllArgsConstructor @NoArgsConstructor @Entity public class RedUrl { @Id @Column(name = "id") @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String url; @ManyToOne(fetch = FetchType.EAGER) private Item item; @Column(name = "uuid", unique = true, nullable = false) @Type(type="org.hibernate.type.UUIDCharType") private UUID uuid = UUID.randomUUID(); }
true
922d71d3fdc5d7e56a1d421b148239835bc400ea
Java
StanislavAntunovich/NetworkChat
/src/ru/geekbrains/chat/server/Server.java
UTF-8
5,005
2.640625
3
[]
no_license
package ru.geekbrains.chat.server; import ru.geekbrains.chat.AuthException; import ru.geekbrains.chat.server.persistance.UserRepository; import ru.geekbrains.chat.server.persistance.UserRepositoryImpl; import ru.geekbrains.chat.server.service.auth.AuthJDBCServiceImpl; import ru.geekbrains.chat.server.service.auth.AuthService; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.sql.Connection; import java.util.Collections; import java.util.HashMap; import java.util.Map; import static ru.geekbrains.chat.MessagesPatterns.*; public class Server { public Server(Connection connection) { UserRepository<User, String> repository = new UserRepositoryImpl(connection); this.authService = new AuthJDBCServiceImpl(repository); } private boolean isOnline; private AuthService authService; private Map<String, ClientHandler> clientHandlers = Collections.synchronizedMap(new HashMap<>()); //TODO: refactor public void sendAddressedMessage(String from, String to, String message) { ClientHandler toCli = clientHandlers.getOrDefault(to, null); ClientHandler fromCli = clientHandlers.get(from); if (toCli != null) { toCli.sendMessage(String.format(MESSAGE_PATTERN, from, message)); } else { fromCli.sendMessage(String.format(USER_OFFLINE_PATTERN, to)); } } public void sendBroadcastMessage(String message) { for (ClientHandler cl : clientHandlers.values()) cl.sendMessage(message); } public void subscribe(String login, ClientHandler clientHandler) { userCameOnline(login); clientHandlers.put(login, clientHandler); } public void unSubscribe(String login) { clientHandlers.remove(login); userCameOffline(login); } public void startServer(int port) { isOnline = true; try (ServerSocket serverSocket = new ServerSocket(port)) { while (isOnline) { Socket candidateSocket = serverSocket.accept(); DataOutputStream out = new DataOutputStream(candidateSocket.getOutputStream()); DataInputStream in = new DataInputStream(candidateSocket.getInputStream()); String authMessage = in.readUTF(); try { User user = handshake(authMessage); out.writeUTF("/succeeded"); this.subscribe(user.getLogin(), new ClientHandlerImpl(user.getLogin(), candidateSocket, this)); } catch (AuthException e) { e.printStackTrace(); out.writeUTF("/error " + e.getMessage()); out.flush(); } } } catch (IOException e) { e.printStackTrace(); } } //TODO перемудрил - разгрести private User handshake(String message) throws AuthException { final String[] preparedMsg = message.split(" "); if (preparedMsg.length != 3) { throw new AuthException("Wrong message"); //TODO объединить } if (preparedMsg[0].equals("/auth")) { return checkAuthentication(preparedMsg); } else if (preparedMsg[0].equals("/registration")) { return registration(preparedMsg); } else { throw new AuthException("Wrong message"); } } private User registration(String[] message) throws AuthException { User user = new User(message[1], message[2]); if (!authService.addNewUser(user)) { throw new AuthException("Login busy"); } return user; } private User checkAuthentication(String[] authMessage) throws AuthException { User user = new User(authMessage[1], authMessage[2]); if (!authService.isAuthorized(user)) { throw new AuthException("Wrong login or password"); } if (clientHandlers.containsKey(user.getLogin())) { throw new AuthException("User already logged in"); } return user; } public void sendUsersList(String userLogin) { ClientHandler cl = clientHandlers.get(userLogin); if (!clientHandlers.isEmpty()) { StringBuilder sb = new StringBuilder(); for (String login : clientHandlers.keySet()) { if (!login.equals(userLogin)) { sb.append(login); sb.append(" "); } } cl.sendMessage(String.format(USERS_LIST_PATTERN, sb.toString().trim())); } } private void userCameOnline(String userLogin) { sendBroadcastMessage(String.format(USER_CAME_ONLINE_PATTERN, userLogin)); } private void userCameOffline(String userLogin) { sendBroadcastMessage(String.format(USER_CAME_OFLINE_PATTERN, userLogin)); } }
true
12cd38cb193cace22e37f3426147ff753c7276ac
Java
alishangtian/x-pipe
/redis/redis-console/src/test/java/com/ctrip/xpipe/redis/console/alert/AlertManagerTest.java
UTF-8
1,647
2.140625
2
[ "Apache-2.0" ]
permissive
package com.ctrip.xpipe.redis.console.alert; import com.ctrip.xpipe.redis.console.config.ConsoleConfig; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import java.util.Date; import java.util.Map; import static org.mockito.Mockito.when; /** * @author chen.zhu * <p> * Dec 04, 2017 */ public class AlertManagerTest { @Mock private ConsoleConfig consoleConfig; @InjectMocks AlertManager alertManager = new AlertManager(); @Before public void beforeAlertManagerTest() { MockitoAnnotations.initMocks(this); } @Test public void testGenerateAlertMessage() throws Exception { String cluster = null, shard = "", message = "test message"; ALERT_TYPE type = ALERT_TYPE.ALERT_SYSTEM_OFF; String result = alertManager.generateAlertMessage(cluster, "jq", shard, type, message); String expected = "jq," + type.simpleDesc() + "," + message; Assert.assertEquals(expected, result); } @Test public void testShouldAlert() { when(consoleConfig.getNoAlarmMinutesForNewCluster()).thenReturn(15); Map<String, Date> map = Maps.newHashMapWithExpectedSize(1); map.put("cluster", new Date()); alertManager.setClusterCreateTime(map); alertManager.setAlertClusterWhiteList(Sets.newHashSet()); Assert.assertFalse(alertManager.shouldAlert("cluster")); Assert.assertTrue(alertManager.shouldAlert("test")); } }
true
431ec1e1baa9ef5a37506e4fca120dd64522c1ed
Java
daojunL/BigDataManagement
/project3/problem2/ReportNeighborsDensityAndIds.java
UTF-8
9,624
2.484375
2
[]
no_license
import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.Reducer; import org.apache.hadoop.mapreduce.lib.input.MultipleInputs; import org.apache.hadoop.mapreduce.lib.input.TextInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; public class ReportNeighborsDensityAndIds { public static class firstMapper extends Mapper<Object, Text, Text, Text>{ public void map(Object key, Text value, Context context) throws IOException, InterruptedException { context.write(new Text(1+""), new Text("cells," + value)); } } public static class secondMapper extends Mapper<Object, Text, Text, Text>{ public void map(Object key, Text value, Context context) throws IOException, InterruptedException { String id = value.toString().split(",")[0]; context.write(new Text(1+""), new Text("Top50,"+id)); } } public static class MyReducer extends Reducer<Text, Text, Text, Text> { public void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException { HashMap<String, String> indexandSum = new HashMap<String, String>(); ArrayList<String> lst = new ArrayList<String>(); int xCount = 0; int topId = 0; double avg = 0.00; double relativeDensity = 0.00; double[] density = new double[250000]; String neighborsIDs = ""; String neighborsDensity = ""; for(Text v:values){ String[] lines = v.toString().split(","); if(lines[0].equals("cells")){ indexandSum.put(lines[1], lines[2]); // 250000 * (Key: ID + Value: SUM) } if(lines[0].equals("Top50")){ lst.add(lines[1]); } } for(int i = 1; i <= 250000; i++){ xCount = Integer.parseInt(indexandSum.get(String.valueOf(i))); if(i == 1){ avg = (Integer.parseInt(indexandSum.get(String.valueOf(i+1))) + Integer.parseInt(indexandSum.get(String.valueOf(i+500))) + Integer.parseInt(indexandSum.get(String.valueOf(i+501))))/ 3.0; } else if(i == 500){ avg = (Integer.parseInt(indexandSum.get(String.valueOf(i-1))) + Integer.parseInt(indexandSum.get(String.valueOf(i+499))) + Integer.parseInt(indexandSum.get(String.valueOf(i+500))))/ 3.0; } else if(i == 250000-499){ avg = (Integer.parseInt(indexandSum.get(String.valueOf(i-500))) + Integer.parseInt(indexandSum.get(String.valueOf(i-499))) + Integer.parseInt(indexandSum.get(String.valueOf(i+1))))/ 3.0; } else if(i == 250000){ avg = (Integer.parseInt(indexandSum.get(String.valueOf(i-1))) + Integer.parseInt(indexandSum.get(String.valueOf(i-500))) + Integer.parseInt(indexandSum.get(String.valueOf(i-501))))/ 3.0; } else if(i>=2 && i<= 499){ avg = (Integer.parseInt(indexandSum.get(String.valueOf(i-1))) + Integer.parseInt(indexandSum.get(String.valueOf(i+1))) + Integer.parseInt(indexandSum.get(String.valueOf(i+500))) + Integer.parseInt(indexandSum.get(String.valueOf(i+499))) + Integer.parseInt(indexandSum.get(String.valueOf(i+501)))) / 5.0; } else if(i >= 250000-498 && i<=250000-1){ avg = (Integer.parseInt(indexandSum.get(String.valueOf(i-1))) + Integer.parseInt(indexandSum.get(String.valueOf(i+1))) + Integer.parseInt(indexandSum.get(String.valueOf(i-500))) + Integer.parseInt(indexandSum.get(String.valueOf(i-501))) + Integer.parseInt(indexandSum.get(String.valueOf(i-499)))) / 5.0; } else if(i % 500 == 1){ avg = (Integer.parseInt(indexandSum.get(String.valueOf(i-500))) + Integer.parseInt(indexandSum.get(String.valueOf(i+500))) + Integer.parseInt(indexandSum.get(String.valueOf(i+1))) + Integer.parseInt(indexandSum.get(String.valueOf(i-499))) + Integer.parseInt(indexandSum.get(String.valueOf(i+501)))) / 5.0; } else if(i % 500 == 0){ avg = (Integer.parseInt(indexandSum.get(String.valueOf(i-500))) + Integer.parseInt(indexandSum.get(String.valueOf(i+500))) + Integer.parseInt(indexandSum.get(String.valueOf(i-1))) + Integer.parseInt(indexandSum.get(String.valueOf(i-501))) + Integer.parseInt(indexandSum.get(String.valueOf(i+499)))) / 5.0; } else{ avg = (Integer.parseInt(indexandSum.get(String.valueOf(i-1))) + Integer.parseInt(indexandSum.get(String.valueOf(i+1))) + Integer.parseInt(indexandSum.get(String.valueOf(i-500))) + Integer.parseInt(indexandSum.get(String.valueOf(i+500))) + Integer.parseInt(indexandSum.get(String.valueOf(i-501))) + Integer.parseInt(indexandSum.get(String.valueOf(i-499))) + Integer.parseInt(indexandSum.get(String.valueOf(i+499))) + Integer.parseInt(indexandSum.get(String.valueOf(i+501)))) / 8.0; } relativeDensity = xCount / avg; density[i-1] = relativeDensity; } for(int i = 0; i < 50; i++){ topId = Integer.parseInt(lst.get(i)); if(topId == 1){ neighborsIDs = (topId+1) + "," + (topId+500) + "," + (topId+501); neighborsDensity = density[topId+1-1] + "," + density[topId+500-1] + "," + density[topId+501-1]; } else if(topId == 500){ neighborsIDs = (topId-1) + "," + (topId+499) + "," + (topId+500); neighborsDensity = density[topId-1-1] + "," + density[topId+499-1] + "," + density[topId+500-1]; } else if(topId == 250000-499){ neighborsIDs = (topId-500) + "," + (topId-499) + "," + (topId+1); neighborsDensity = density[topId-500-1] + "," + density[topId-499-1] + "," + density[topId+1-1]; } else if(topId == 250000){ neighborsIDs = (topId-1) + "," + (topId-500) + "," + (topId-501); neighborsDensity = density[topId-1-1] + "," + density[topId-500-1] + "," + density[topId-501-1]; } else if(topId>=2 && topId<= 499){ neighborsIDs = (topId-1) + "," + (topId+1) + "," + (topId+500) + "," + (topId+499) + "," + (topId+501); neighborsDensity = density[topId-1-1] + "," + density[topId+1-1] + "," + density[topId+500-1] + "," + density[topId+499-1] + "," + density[topId+501-1]; } else if(topId >= 250000-498 && topId<=250000-1){ neighborsIDs = (topId-1) + "," + (topId+1) + "," + (topId-500) + "," + (topId-501) + "," + (topId-499); neighborsDensity = density[topId-1-1] + "," + density[topId+1-1] + "," + density[topId-500-1] + "," + density[topId-501-1] + "," + density[topId-499-1]; } else if(topId % 500 == 1){ neighborsIDs = (topId-500) + "," + (topId+500) + "," + (topId+1) + "," + (topId-499) + "," + (topId+501); neighborsDensity = density[topId-500-1] + "," + density[topId+500-1] + "," + density[topId+1-1] + "," + density[topId-499-1] + "," + density[topId+501-1]; } else if(topId % 500 == 0){ neighborsIDs = (topId-500) + "," + (topId+500) + "," + (topId-1) + "," + (topId-501) + "," + (topId+499); neighborsDensity = density[topId-500-1] + "," + density[topId+500-1] + "," + density[topId-1-1] + "," + density[topId-501-1] + "," + density[topId+499-1]; } else{ neighborsIDs = (topId-1) + "," + (topId+1) + "," + (topId-500) + "," + (topId+500) + "," + (topId-501) + "," + (topId-499) + "," + (topId+499) + "," + (topId+501); neighborsDensity = density[topId-1-1] + "," + density[topId+1-1] + "," + density[topId-500-1] + "," + density[topId+500-1] + "," + density[topId-501-1] + "," + density[topId-499-1] + "," + density[topId+499-1] + "," +density[topId+501-1]; } context.write(new Text(neighborsIDs), new Text(neighborsDensity)); } } } public static void main(String[] args) throws IllegalArgumentException, IOException, ClassNotFoundException, InterruptedException { Configuration conf = new Configuration(); Job job = Job.getInstance(conf, "ReportNeighborsDensityAndIds"); job.setJarByClass(ReportNeighborsDensityAndIds.class); job.setReducerClass(MyReducer.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(Text.class); MultipleInputs.addInputPath(job,new Path("/Users/daojun/Desktop/mapreduce/output_ReportID/part-r-00000"), TextInputFormat.class, firstMapper.class); MultipleInputs.addInputPath(job,new Path("/Users/daojun/Desktop/mapreduce/output_Report50ID/part-r-00000"), TextInputFormat.class, secondMapper.class); FileOutputFormat.setOutputPath(job, new Path(args[0])); System.exit(job.waitForCompletion(true) ? 0 : 1); } }
true
8bc7dadaabc31c0945856e25433883af99e77380
Java
musaozdemir-capco/Gilded
/src/test/java/utils/CommonMethods.java
UTF-8
934
2.40625
2
[]
no_license
package utils; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import sun.jvm.hotspot.debugger.Page; import testBase.PageInitializer; public class CommonMethods extends PageInitializer { /** * Method that send text to any given elements * @param element * @param text */ public static void sendText(WebElement element, String text){ element.clear(); element.sendKeys(text); } public static void click(WebElement element){ waitForClickability(element); element.click(); } public static WebDriverWait getWaitObject(){ return new WebDriverWait(driver, Constants.EXPLICIT_WAIT_TIME); } public static void waitForClickability(WebElement element){ getWaitObject().until(ExpectedConditions.elementToBeClickable(element)); } }
true
39401f0284d895b7352add21b2127df874158c35
Java
ApurvaMithal/DatabaseEngine
/java_files/Utility.java
UTF-8
9,231
2.765625
3
[]
no_license
import java.io.IOException; import java.io.RandomAccessFile; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.text.SimpleDateFormat; public class Utility { public static int pgSize = PageSizeConstant.pageSize; public static String[] fetchPL(RandomAccessFile file, long off) { String[] pl = new String[0]; try{ file.seek(off); file.readShort(); int id = file.readInt(); int numOfCol = file.readByte(); byte[] colSize = new byte[numOfCol]; file.read(colSize); pl = new String[numOfCol+1]; pl[0] = Integer.toString(id); for(int col=1; col <= numOfCol; col++){ switch(colSize[col-1]){ case 0x00: file.readByte(); pl[col] = "null"; break; case 0x01: file.readShort(); pl[col] = "null"; break; case 0x02: file.readInt(); pl[col] = "null"; break; case 0x03: file.readLong(); pl[col] = "null"; break; case 0x04: pl[col] = Integer.toString(file.readByte()); break; case 0x05: pl[col] = Integer.toString(file.readShort()); break; case 0x06: pl[col] = Integer.toString(file.readInt()); break; case 0x07: pl[col] = Long.toString(file.readLong()); break; case 0x08: pl[col] = String.valueOf(file.readFloat()); break; case 0x09: pl[col] = String.valueOf(file.readDouble()); break; case 0x0A: pl[col] = new SimpleDateFormat ("yyyy-MM-dd_HH:mm:ss").format(new Date(file.readLong())); break; case 0x0B: pl[col] = new SimpleDateFormat ("yyyy-MM-dd_HH:mm:ss").format(new Date(file.readLong())).substring(0,10); break; default: int k = new Integer(colSize[col-1]-0x0C); byte[] array = new byte[k]; for(int j = 0; j < k; j++) array[j] = file.readByte(); pl[col] = new String(array); break; } } } catch(Exception e) { System.out.println("Error while fetching payload data:\n"+ e); } return pl; } public static int computePlSz(String name, String[] data, byte[] arr) { String[] dt = fetchDt(name); int sz = dt.length; for(int iter = 1; iter < dt.length; iter++){ byte b = serialTypeCode(data[iter], dt[iter]); arr[iter - 1] = b; sz = sz + colSize(b); } return sz; } public static byte serialTypeCode(String str, String dt) { if(str.equals("null")) { if(dt.equals("TINYINT")) return 0x00; else if(dt.equals("SMALLINT")) return 0x01; else if(dt.equals("INT")) return 0x02; else if(dt.equals("BIGINT")) return 0x03; else if(dt.equals("REAL")) return 0x02; else if(dt.equals("DOUBLE")) return 0x03; else if(dt.equals("DATETIME")) return 0x03; else if(dt.equals("DATE")) return 0x03; else if(dt.equals("TEXT")) return 0x03; else return 0x00; } else { if(dt.equals("TINYINT")) return 0x04; else if(dt.equals("SMALLINT")) return 0x05; else if(dt.equals("INT")) return 0x06; else if(dt.equals("BIGINT")) return 0x07; else if(dt.equals("REAL")) return 0x08; else if(dt.equals("DOUBLE")) return 0x09; else if(dt.equals("DATETIME")) return 0x0A; else if(dt.equals("DATE")) return 0x0B; else if(dt.equals("TEXT")) return (byte)(str.length()+0x0C); else return 0x00; } } public static short colSize(byte b) { switch(b) { case 0x00: return 1; case 0x01: return 2; case 0x02: return 4; case 0x03: return 8; case 0x04: return 1; case 0x05: return 2; case 0x06: return 4; case 0x07: return 8; case 0x08: return 4; case 0x09: return 8; case 0x0A: return 8; case 0x0B: return 8; default: return (short)(b - 0x0C); } } public static int findId(RandomAccessFile file, int id) { try{ int count = countPages(file); for(int pg = 1; pg <= count; pg++){ file.seek((pg - 1)*pgSize); byte b = file.readByte(); if(b == 0x0D){ int[] id_array = BplusTree.fetchKeys(file, pg); if(id_array.length == 0) return 0; int right = BplusTree.fetchLastRight(file, pg); if((right == 0 && id_array[id_array.length - 1] < id)||(id_array[0] <= id && id <= id_array[id_array.length - 1])){ return pg; } } } } catch(Exception exception) { System.out.println("Error while searching key: "+exception); } return 1; } public static String[] fetchDt(String name) { RandomAccessFile file = null; String[] dt = new String[0]; Storage st = new Storage(); ArrayList<String> list = new ArrayList<String>(); try{ file = new RandomAccessFile("data\\catalog\\davisbase_columns.tbl", "rw"); String[] cols = {"rowid", "table_name", "column_name", "data_type", "ordinal_position", "is_nullable"}; if(!name.equals("davisbase_tables") && !name.equals("davisbase_columns")) name = DavisBasePrompt.curDatabase+"."+name; String[] arr = {"table_name","=",name}; DatabaseOperations.filter(file, arr, cols, st); HashMap<Integer, String[]> data = st.data; for(String[] iter : data.values()){ list.add(iter[3]); } dt = list.toArray(new String[list.size()]); return dt; } catch(Exception e) { System.out.println("Error in getting the data type"); System.out.println(e); } finally{ if(file!=null) try { file.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return dt; } public static String[] fetchFieldNm(String tableName) { String[] col_array = new String[0]; RandomAccessFile file = null; try{ file = new RandomAccessFile("data\\catalog\\davisbase_columns.tbl", "rw"); Storage bf = new Storage(); String[] columnName = {"rowid", "table_name", "column_name", "data_type", "ordinal_position", "is_nullable"}; if(!tableName.equals("davisbase_tables") && !tableName.equals("davisbase_columns")) tableName = DavisBasePrompt.curDatabase+"."+tableName; String[] arr = {"table_name","=",tableName}; DatabaseOperations.filter(file, arr, columnName, bf); ArrayList<String> array = new ArrayList<String>(); for(String[] d : bf.data.values()){ array.add(d[2]); } col_array = array.toArray(new String[array.size()]); return col_array; } catch(Exception exc) { System.out.println("Error while fetching the column name:\n"+exc); } finally{ if(file!=null) try { file.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return col_array; } public static String[] isColNullable(String table) { RandomAccessFile file = null; String[] isNull_array = new String[0]; Storage bf = new Storage(); try{ file = new RandomAccessFile("data\\catalog\\davisbase_columns.tbl", "rw"); String[] fieldNm = {"rowid", "table_name", "column_name", "data_type", "ordinal_position", "is_nullable"}; if(!table.equals("davisbase_tables") && !table.equals("davisbase_columns")) table = DavisBasePrompt.curDatabase+"."+table; String[] arr = {"table_name","=",table}; DatabaseOperations.filter(file, arr, fieldNm, bf); ArrayList<String> list = new ArrayList<String>(); for(String[] d : bf.data.values()) { list.add(d[5]); } isNull_array = list.toArray(new String[list.size()]); return isNull_array; }catch(Exception excep){ System.out.println("Error in isColNullable:\n"+excep); } finally{ if(file!=null) try { file.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return isNull_array; } public static int countPages(RandomAccessFile file) { int count = 0; try { count = (int)(file.length()/(new Long(pgSize))); } catch(Exception e) { System.out.println("Error while counting pages"); } return count; } public static boolean opCheck(String[] payL, int key, String[] arr, String[] fields) { boolean flag = false; if(arr.length == 0) { flag = true; } else{ int loc = 1; for(int j = 0; j < fields.length; j++){ if(fields[j].equals(arr[0])){ loc = j + 1; break; } } String operator = arr[1]; String str = arr[2]; if(loc == 1) { if(operator.equals("=")){ if(Integer.parseInt(str) == key) flag = true; else flag = false; } if(operator.equals(">")){ if(Integer.parseInt(str) < key) flag = true; else flag = false; } if(operator.equals("<")){ if(Integer.parseInt(str) > key) flag = true; else flag = false; } if(operator.equals(">=")){ if(Integer.parseInt(str) <= key) flag = true; else flag = false; } if(operator.equals("<=")){ if(Integer.parseInt(str) >= key) flag = true; else flag = false; } if(operator.equals("<>")){ if(key != Integer.parseInt(str)) flag = true; else flag = false; } }else{ if(str.equals(payL[loc-1])) flag = true; else flag = false; } } return flag; } }
true
9d507f879ca7d6656683b955063c1f05fc483528
Java
LabyMod/labymod-server-api
/labymod-api/src/main/java/net/labymod/serverapi/api/serverinteraction/actionmenu/MenuEntry.java
UTF-8
1,323
2.875
3
[ "MIT" ]
permissive
package net.labymod.serverapi.api.serverinteraction.actionmenu; import com.google.gson.JsonObject; /** Represents a menu entry. */ public interface MenuEntry { /** * Retrieves the display name of the menu entry. * * @return The display name of the entry. */ String getDisplayName(); /** * Retrieves the value of the menu entry. * * <p><b>Note:</b> * * <p>`{name}` will be replaced with the players name. * * @return The value of the menu entry. */ String getValue(); /** * Retrieves the action type of the menu entry. * * @return The action type of the entry. */ ActionType getActionType(); /** * Retrieves the menu entry as a {@link JsonObject}. * * @return The menu entry as a json object. */ JsonObject asJsonObject(); /** A factory for creating {@link MenuEntry}'s. */ interface Factory { /** * Creates a new {@link MenuEntry} with the given {@code displayName}, {@code value} and the * {@code actionType}. * * @param displayName The display name of the menu entry. * @param value The value for the menu entry. * @param actionType The action type for the menu entry. * @return A created menu entry. */ MenuEntry create(String displayName, String value, ActionType actionType); } }
true
269b51831ef36ded5297a5f653c34a12dddcc79c
Java
TatyanaAlex/tfukova
/chapter_collectionsPro/src/main/java/ru/job4j/tree/Tree.java
UTF-8
3,191
3.484375
3
[ "Apache-2.0" ]
permissive
package ru.job4j.tree; import java.util.*; /** * Class Tree. * * @author Tatyana Fukova * @version $I$ */ public class Tree<E extends Comparable<E>> implements SimpleTree<E> { public Node<E> root; private int modCount = 0; /** * Constructor. * * @param value value. */ public Tree(E value) { this.root = new Node(value); modCount++; } @Override public Optional<Node<E>> findBy(E value) { Optional<Node<E>> rsl = Optional.empty(); Queue<Node<E>> data = new LinkedList<>(); data.offer(this.root); while (!data.isEmpty()) { Node<E> el = data.poll(); if (el.eqValue(value)) { rsl = Optional.of(el); break; } for (Node<E> child : el.leaves()) { data.offer(child); } } return rsl; } /** * method to add the child el to parent el-t. * * @return result. */ @Override public boolean add(E parent, E child) { boolean result = false; if (this.findBy(child).equals(Optional.empty())) { Optional<Node<E>> prnt = this.findBy(parent); if (!prnt.equals(Optional.empty())) { prnt.get().add(new Node<>(child)); result = true; modCount++; } } return result; } public boolean isBinary() { boolean result = true; Queue<Node<E>> data = new LinkedList<>(); data.offer(this.root); while (!data.isEmpty()) { Node<E> el = data.poll(); if (el.leaves().size() > 2) { result = false; break; } for (Node<E> child : el.leaves()) { data.offer(child); } } return result; } @Override public Iterator<E> iterator() { LinkedList<Node<E>> data = new LinkedList<>(); Queue<Node<E>> tempQueue = new LinkedList<>(); tempQueue.offer(root); data.offer(root); while (!tempQueue.isEmpty()) { Node<E> el = tempQueue.poll(); for (Node<E> child : el.leaves()) { data.offer(child); tempQueue.offer(child); } } return new Iterator<E>() { private int iteratorCount = 0; private int expectedModCount = modCount; @Override public boolean hasNext() { boolean result = false; if (modCount != expectedModCount) { throw new ConcurrentModificationException(); } if (this.iteratorCount < modCount) { result = true; } return result; } @Override public E next() { if (!this.hasNext()) { throw new NoSuchElementException(); } E element = data.get(iteratorCount).getValue(); iteratorCount++; return element; } }; } }
true
d4a4542a28788f3c04f56f3ae00d09faec4d85c3
Java
vooolkan/JavaInClass
/src/com/class13/Task1.java
UTF-8
770
3.265625
3
[]
no_license
package com.class13; import java.util.Scanner; public class Task1 { public static void main(String[] args) { Scanner scan=new Scanner(System. in); System.out.println("Enter your class day: "); String day=scan.nextLine(); if(day.trim().toLowerCase().equals("saturday")) { System.out.println("Saturday is your Java Class "); }else if(day.equalsIgnoreCase("sunday")) { System.out.println("Sunday is your Git Class"); }else if(day.trim().toUpperCase().equals("TUESDAY")) { System.out.println("Tuesday is your SDLC calass"); }else if(day.trim().toLowerCase().equals("Thursday")) { System.out.println("Thursday is your Manual Testing Class"); }else { System.err.println("Invalid day"); } scan.close(); } }
true
4b6254e7571b190e5e4721c112084c041b8f4412
Java
coldserenity/tij4-exercises
/03-controlling-execution/src/test/java/edu/coldserenity/tij/ch02/ex09/FibonacciTest.java
UTF-8
911
2.859375
3
[ "MIT" ]
permissive
package edu.coldserenity.tij.ch02.ex09; import com.tngtech.java.junit.dataprovider.DataProvider; import com.tngtech.java.junit.dataprovider.DataProviderRunner; import com.tngtech.java.junit.dataprovider.UseDataProvider; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.assertArrayEquals; @RunWith(DataProviderRunner.class) public class FibonacciTest { @DataProvider public static Object[][] testDataSet() { return new Object[][]{ {0, new Integer[]{}}, {1, new Integer[]{1}}, {5, new Integer[]{1, 1, 2, 3, 5}}, {9, new Integer[]{1, 1, 2, 3, 5, 8, 13, 21, 34}}, }; } @Test @UseDataProvider("testDataSet") public void testGetNumbers(int count, Integer[] expected) throws Exception { assertArrayEquals(expected, Fibonacci.getNumbers(count).toArray()); } }
true
6a88f0c62dcab4ce0f281b505118bcb9ca557f6f
Java
GiovanniPucariello/TeevraCore
/Development3.0/TeevraServer/platform/businessobject/src/main/java/com/headstrong/fusion/bo/java/generated/fixml_5_0/SecurityTypeRequestMessageTBeanAccessor.java
UTF-8
3,124
1.851563
2
[]
no_license
package com.headstrong.fusion.bo.java.generated.fixml_5_0; import javax.annotation.Generated; import com.headstrong.fusion.bo.java.BeanAccessor; import org.fixprotocol.fixml_5_0.SecurityTypeRequestMessageT; import java.math.BigInteger; import org.fixprotocol.fixml_5_0.SecurityTypeEnumT; import org.fixprotocol.fixml_5_0.MessageHeaderT; import com.headstrong.fusion.bo.impl.exception.AttributeNotFoundException; import com.headstrong.fusion.bo.java.JavaBusinessObject; //This file was generated on Wed Jan 20 15:18:34 IST 2010 @Generated(value = { "bo-accessor-generator" }, date="Wed Jan 20 15:18:34 IST 2010") public class SecurityTypeRequestMessageTBeanAccessor implements BeanAccessor<SecurityTypeRequestMessageT> { private SecurityTypeRequestMessageT bean; @Override public Object get(String accessPath) throws AttributeNotFoundException { if("subTyp".equalsIgnoreCase(accessPath)){ return this.bean.getSubTyp(); } else if("encTxtLen".equalsIgnoreCase(accessPath)){ return this.bean.getEncTxtLen(); } else if("hdr".equalsIgnoreCase(accessPath)){ return this.bean.getHdr(); } else if("sesID".equalsIgnoreCase(accessPath)){ return this.bean.getSesID(); } else if("encTxt".equalsIgnoreCase(accessPath)){ return this.bean.getEncTxt(); } else if("reqID".equalsIgnoreCase(accessPath)){ return this.bean.getReqID(); } else if("secTyp".equalsIgnoreCase(accessPath)){ return this.bean.getSecTyp(); } else if("sesSub".equalsIgnoreCase(accessPath)){ return this.bean.getSesSub(); } else if("txt".equalsIgnoreCase(accessPath)){ return this.bean.getTxt(); } else if("prod".equalsIgnoreCase(accessPath)){ return this.bean.getProd(); } throw new AttributeNotFoundException(accessPath, new JavaBusinessObject(bean)); } @Override public void set(String accessPath, Object obj)throws AttributeNotFoundException { if("subTyp".equalsIgnoreCase(accessPath)){ this.bean.setSubTyp((String) obj); return; } else if("encTxtLen".equalsIgnoreCase(accessPath)){ this.bean.setEncTxtLen((BigInteger) obj); return; } else if("hdr".equalsIgnoreCase(accessPath)){ this.bean.setHdr((MessageHeaderT) obj); return; } else if("encTxt".equalsIgnoreCase(accessPath)){ this.bean.setEncTxt((String) obj); return; } else if("sesID".equalsIgnoreCase(accessPath)){ this.bean.setSesID((String) obj); return; } else if("reqID".equalsIgnoreCase(accessPath)){ this.bean.setReqID((String) obj); return; } else if("secTyp".equalsIgnoreCase(accessPath)){ this.bean.setSecTyp(SecurityTypeEnumT.valueOf(obj.toString())); return; } else if("sesSub".equalsIgnoreCase(accessPath)){ this.bean.setSesSub((String) obj); return; } else if("txt".equalsIgnoreCase(accessPath)){ this.bean.setTxt((String) obj); return; } else if("prod".equalsIgnoreCase(accessPath)){ this.bean.setProd((Integer) obj); return; } throw new AttributeNotFoundException(accessPath, new JavaBusinessObject(bean)); } @Override public void setTarget(SecurityTypeRequestMessageT obj) { this.bean = obj; } }
true
ee669bab40411ad70d3e6084f1872771bd70a151
Java
iuvei/LotteryDemo
/app/src/main/java/com/qujing/leeyong/klchwsc/SsqActivity.java
UTF-8
828
1.859375
2
[]
no_license
package com.qujing.leeyong.klchwsc; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.ImageView; /** * Created by Administrator on 2018/5/15. */ public class SsqActivity extends AppCompatActivity { private ImageView mBtBack; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.shuangsheqiu); initView(); } private void initView() { mBtBack = (ImageView) findViewById(R.id.bt_back); mBtBack.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); } }
true
f822d83a536e97dbbf855d10f45b76f7e8bfc879
Java
Prozorova/StarGame
/core/src/com/gb/stargame/base/utils/ActionListener.java
UTF-8
111
1.585938
2
[]
no_license
package com.gb.stargame.base.utils; public interface ActionListener { void actionPerformed(Object src); }
true
337a7c1fef0c3cd8de3030c43330fab836abc515
Java
henry2357/jigsaw
/src/main/java/com/henry/jigsaw/spring/HelloSpring.java
UTF-8
675
2.59375
3
[]
no_license
package com.henry.jigsaw.spring; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class HelloSpring { private String userName; public void setUserName(String userName) { this.userName = userName; } public void hello() { System.out.println("hello:" + userName); } public static void main(String[] args) { ApplicationContext ctx = new ClassPathXmlApplicationContext("spring/ApplicationContext.xml"); HelloSpring helloWorld = (HelloSpring) ctx.getBean("helloWorld"); helloWorld.hello(); // 输出 hello:spring } }
true
4f6997fa932f9ab03ea2584a41eb77ef9827eddd
Java
andresnew00/Andres_Inciarte_JavaS1
/20190826/CarInventory/src/main/java/CarReader.java
UTF-8
1,368
3.9375
4
[]
no_license
import java.util.*; import java.util.stream.Collectors; public class CarReader { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // first read of the file this should be able to read the current cars created CarMethods.read(); boolean continueCode = true; int userInput; while (continueCode) { System.out.println("Please select what you would like to do: " + "\n 1 - add \n 2 - delete " + "\n 3 - search \n 4 - display \n 0 - Exit"); userInput = Integer.parseInt(scanner.next()); // add new car if (userInput == 1) { CarMethods.addCar(); //remove car } else if (userInput == 2) { CarMethods.removeCar(); // search } else if (userInput == 3) { CarMethods.searchBy(); //display } else if (userInput == 4) { CarMethods.display(); //not a valid number } else if (userInput == 0) { continueCode = false; } else { System.out.println("Please enter a valid number."); } } System.out.println("Thank you come back soon!"); } }
true
03ff8bc835a7969beb64cee61c0c7ad5581c8511
Java
s99889989/CustomDisplay
/src/main/java/com/daxton/customdisplay/manager/ListenerManager.java
UTF-8
315
2.140625
2
[ "MIT" ]
permissive
package com.daxton.customdisplay.manager; import java.util.HashMap; import java.util.Map; import java.util.UUID; public class ListenerManager { private static Map<String,Boolean> Cast_On_Stop = new HashMap<>(); public static Map<String, Boolean> getCast_On_Stop() { return Cast_On_Stop; } }
true
f1db32dcc9a34ab2ea5f1f16419571199989adf0
Java
heduiandroid/HDLinLiC
/java/com/linli/consumer/adapter/PayingOrderAdapter.java
UTF-8
4,189
1.992188
2
[]
no_license
package com.linli.consumer.adapter; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.LinearLayout; import android.widget.TextView; import com.facebook.drawee.view.SimpleDraweeView; import com.linli.consumer.R; import com.linli.consumer.base.UIHelper; import com.linli.consumer.domain.Order; import com.linli.consumer.ui.main.YaoYiYaoActivity; import java.util.List; /** * Created by hasee on 2017/2/9. */ public class PayingOrderAdapter extends BaseAdapter { private List<Order> list; private Context context; public PayingOrderAdapter(List<Order> list, Context context) { this.list = list; this.context = context; } @Override public int getCount() { return list.size(); } @Override public Object getItem(int i) { return list.get(i); } @Override public long getItemId(int i) { return i; } @Override public View getView(final int position, View convertView, ViewGroup viewGroup) { HolderView holder = null; if (convertView == null){ holder = new HolderView(); convertView = LayoutInflater.from(context).inflate(R.layout.paying_orders_item,null); holder.tv_shop_name = (TextView) convertView.findViewById(R.id.tv_shop_name); holder.tv_order_status = (TextView) convertView.findViewById(R.id.tv_order_status); holder.tv_payFee = (TextView) convertView.findViewById(R.id.tv_payFee); holder.btn_toPayOrReceived = (Button) convertView.findViewById(R.id.btn_toPayOrReceived); holder.tv_pro_count = (TextView) convertView.findViewById(R.id.tv_pro_count); holder.ll_pro_pictures = (LinearLayout) convertView.findViewById(R.id.ll_pro_pictures); convertView.setTag(holder); }else { holder = (HolderView) convertView.getTag(); } holder.tv_shop_name.setText(list.get(position).getShopName()); holder.tv_payFee.setText("¥"+list.get(position).getPayPrice().toString()); holder.tv_pro_count.setText(list.get(position).getProList().size()+""); holder.ll_pro_pictures.removeAllViews(); for (int i = 0;i < list.get(position).getProList().size();i++){ View v_prod = LayoutInflater.from(context).inflate(R.layout.paying_orders_item_cell,null); SimpleDraweeView rciv_propic = (SimpleDraweeView) v_prod.findViewById(R.id.rciv_propic); TextView tv_pro_name = (TextView) v_prod.findViewById(R.id.tv_pro_name); TextView tv_prod_num = (TextView) v_prod.findViewById(R.id.tv_prod_num); LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); layoutParams.setMargins(5, 0, 0, 0); String path = list.get(position).getProList().get(i).getPicPath(); rciv_propic.setImageURI(path); tv_pro_name.setText(list.get(position).getProList().get(i).getName()); tv_prod_num.setText("×"+list.get(position).getProList().get(i).getCountInOrder()); holder.ll_pro_pictures.addView(v_prod,layoutParams); } holder.tv_order_status.setText("待付款"); holder.btn_toPayOrReceived.setText("付款"); holder.btn_toPayOrReceived.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { YaoYiYaoActivity.orderId = list.get(position).getId(); UIHelper.togoOnLinePayActivity(context, Long.valueOf(list.get(position).getOrderNum()),list.get(position).getPayPrice(),list.get(position).getOrderNum().toString(),list.get(position).getId()); } }); return convertView; } public class HolderView{ LinearLayout ll_pro_pictures; TextView tv_shop_name; TextView tv_order_status; TextView tv_payFee; Button btn_toPayOrReceived; TextView tv_pro_count; } }
true
0a229d0fcd2b99d9303bc9177f4de57ba66cf4f2
Java
GrapeLemon/Think-In-Java
/src/_19_enum/_01_basic/Spiciness.java
UTF-8
138
1.984375
2
[]
no_license
package _19_enum._01_basic; /** * @author lwx * @date 2019/9/8-22:02 */ public enum Spiciness { NOT, MILD, MEDIUM, HOT, FLAMING }
true
aa10c0f5059ced7cb10157a9afea0a7e4a9117d1
Java
wanghaihui/tuding
/VZhi/src/com/xiaobukuaipao/vzhi/RecruitServiceActivity.java
UTF-8
9,282
1.664063
2
[]
no_license
package com.xiaobukuaipao.vzhi; import android.annotation.SuppressLint; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Message; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnTouchListener; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.LinearLayout; import android.widget.RelativeLayout; import com.alibaba.fastjson.JSONObject; import com.umeng.analytics.MobclickAgent; import com.xiaobukuaipao.vzhi.event.InfoResult; import com.xiaobukuaipao.vzhi.register.HRInfoActivity; import com.xiaobukuaipao.vzhi.util.GlobalConstants; import com.xiaobukuaipao.vzhi.util.VToast; import com.xiaobukuaipao.vzhi.view.CheckBox; import com.xiaobukuaipao.vzhi.view.CheckBox.OnCheckListener; import com.xiaobukuaipao.vzhi.wrap.RecruitWrapActivity; /** * 招聘服务 * * @author xiaobu * */ public class RecruitServiceActivity extends RecruitWrapActivity implements OnClickListener, OnCheckListener{ private CheckBox mCbox; private Complete status; private RelativeLayout mSettingLayout; private RelativeLayout mPublishLayout; private RelativeLayout mPublishedLayout; private LinearLayout mLayout; private boolean isLoaded = false; @SuppressLint("ClickableViewAccessibility") @Override public void initUIAndData() { setContentView(R.layout.activity_recruit_service); setHeaderMenuByLeft(this); setHeaderMenuByCenterTitle(R.string.recruit_service); mSettingLayout = (RelativeLayout) findViewById(R.id.recruit_service_setting_layout); mSettingLayout.setOnClickListener(this); mPublishLayout = (RelativeLayout) findViewById(R.id.recruit_service_publish_layout); mPublishLayout.setOnClickListener(this); mPublishedLayout = (RelativeLayout) findViewById(R.id.recruit_service_my_published_layout); mPublishedLayout.setOnClickListener(this); mLayout = (LinearLayout) findViewById(R.id.layout); mLayout.setVisibility(View.GONE); mCbox = (CheckBox) findViewById(R.id.recruit_service_cbox); mCbox.setOncheckListener(this); mCbox.setOutsideChecked(true); mCbox.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_UP){ if ((event.getX() <= mCbox.getWidth() && event.getX() >= 0) && (event.getY() <= mCbox.getHeight() && event.getY() >= 0)) { switchRecruitService(); } } return mCbox.onTouchEvent(event); } }); } @Override public void onEventMainThread(Message msg) { if(msg.obj instanceof InfoResult){ InfoResult infoResult = (InfoResult) msg.obj; switch (msg.what) { case R.id.hr_setting_get_recruit_status: JSONObject jsonObj = (JSONObject) JSONObject.parse(infoResult.getResult()); if(jsonObj != null){ JSONObject jsonObject = jsonObj.getJSONObject(GlobalConstants.JSON_COMPLETE); this.status = new Complete(jsonObject); if(status != null){ if(status.basic == 0 || status.hr == 0){ mCbox.setChecked(false); mSettingLayout.setEnabled(false); mPublishLayout.setEnabled(false); mPublishedLayout.setEnabled(false); findViewById(R.id.recruit_service_setting_tv).setVisibility(View.VISIBLE); findViewById(R.id.recruit_service_publish_tv).setVisibility(View.VISIBLE); findViewById(R.id.recruit_service_my_published_tv).setVisibility(View.VISIBLE); findViewById(R.id.recruit_service_open_icon).setEnabled(false); findViewById(R.id.recruit_service_setting_icon).setEnabled(false); findViewById(R.id.recruit_service_publish_icon).setEnabled(false); findViewById(R.id.recruit_service_my_published_icon).setEnabled(false); findViewById(R.id.recruit_service_open).setEnabled(false); findViewById(R.id.recruit_service_setting).setEnabled(false); findViewById(R.id.recruit_service_publish).setEnabled(false); findViewById(R.id.recruit_service_my_published).setEnabled(false); }else{ mCbox.setChecked(true); mSettingLayout.setEnabled(true); mPublishLayout.setEnabled(true); mPublishedLayout.setEnabled(true); if(status.certify == 0 || status.corp == 0){ findViewById(R.id.recruit_service_setting_tv).setVisibility(View.VISIBLE); findViewById(R.id.recruit_service_publish_tv).setVisibility(View.VISIBLE); findViewById(R.id.recruit_service_my_published_tv).setVisibility(View.VISIBLE); findViewById(R.id.recruit_service_publish).setEnabled(false); findViewById(R.id.recruit_service_my_published).setEnabled(false); findViewById(R.id.recruit_service_publish_icon).setEnabled(false); findViewById(R.id.recruit_service_my_published_icon).setEnabled(false); mPublishLayout.setEnabled(false); mPublishedLayout.setEnabled(false); }else{ findViewById(R.id.recruit_service_setting_tv).setVisibility(View.INVISIBLE); findViewById(R.id.recruit_service_publish_tv).setVisibility(View.INVISIBLE); findViewById(R.id.recruit_service_my_published_tv).setVisibility(View.INVISIBLE); findViewById(R.id.recruit_service_publish).setEnabled(true); findViewById(R.id.recruit_service_my_published).setEnabled(true); findViewById(R.id.recruit_service_publish_icon).setEnabled(true); findViewById(R.id.recruit_service_my_published_icon).setEnabled(true); mPublishLayout.setEnabled(true); mPublishedLayout.setEnabled(true); } findViewById(R.id.recruit_service_open_icon).setEnabled(true); findViewById(R.id.recruit_service_setting_icon).setEnabled(true); findViewById(R.id.recruit_service_open).setEnabled(true); findViewById(R.id.recruit_service_setting).setEnabled(true); } if(mLayout.getVisibility() != View.VISIBLE){ Animation loadAnimation = AnimationUtils.loadAnimation(this,R.anim.anim_fide_in_for_recruit); mLayout.startAnimation(loadAnimation); mLayout.setVisibility(View.VISIBLE); isLoaded = true; } } } break; case R.id.hr_setting_set_recruit_status: if(infoResult.getMessage().getStatus() == 0){ mProfileEventLogic.getRecruitServiceStatus(); } VToast.show(this, infoResult.getMessage().getMsg()); break; default: break; } } } @Override protected void onResume() { mProfileEventLogic.getRecruitServiceStatus(); super.onResume(); } @Override public void onClick(View v) { Intent intent = null; switch (v.getId()) { case R.id.recruit_service_setting_layout: intent = new Intent(this,RecruitServiceSettingActivity.class); break; case R.id.recruit_service_publish_layout: intent = new Intent(this, PublishPositionCheckActivity.class); break; case R.id.recruit_service_my_published_layout: intent = new Intent(this, PublishedPositionsActivity.class); break; default: break; } if(intent != null){ intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); } } private void switchRecruitService() { MobclickAgent.onEvent(RecruitServiceActivity.this,"ktzpfw"); final int state = mCbox.isChecked() ? 0 : 1; if(state == 0){ AlertDialog alertDialog = new AlertDialog.Builder(this).setTitle(R.string.general_tips).setMessage(R.string.recruit_service_tips4).setPositiveButton(R.string.btn_confirm, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { mProfileEventLogic.cancel(R.id.hr_setting_set_recruit_status); mProfileEventLogic.setRecruitServiceStatus(state); } }).setNegativeButton(R.string.btn_cancel, null).create(); alertDialog.show(); }else{ AlertDialog alertDialog = new AlertDialog.Builder(this).setTitle(R.string.general_tips).setMessage(R.string.recruit_service_tips3).setPositiveButton(R.string.recruit_service_tips2, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Intent intent = new Intent(); intent.setClass(RecruitServiceActivity.this, HRInfoActivity.class); intent.putExtra(GlobalConstants.RECRUIT_SETTING, true); startActivity(intent); } }).setNegativeButton(R.string.btn_cancel, null).create(); alertDialog.show(); } } @Override public void onCheck(boolean isChecked) { if(isLoaded){ } } class Complete{ public Complete(JSONObject jsonObject){ if(jsonObject != null){ if(jsonObject.getInteger(GlobalConstants.JSON_BASIC) != null){ basic = jsonObject.getInteger(GlobalConstants.JSON_BASIC); } if(jsonObject.getInteger(GlobalConstants.JSON_HR) != null){ hr = jsonObject.getInteger(GlobalConstants.JSON_HR); } if(jsonObject.getInteger(GlobalConstants.JSON_CERTIFY) != null){ certify = jsonObject.getInteger(GlobalConstants.JSON_CERTIFY); } if(jsonObject.getInteger(GlobalConstants.JSON_CORP) != null){ corp = jsonObject.getInteger(GlobalConstants.JSON_CORP); } } } int basic; int hr; int certify; int corp; } }
true
2aa23ac0c46e475a97cbf9788fd85c5a90990f99
Java
Denstden/db
/common-db/src/main/java/ua/kiev/unicyb/tcct/domain/record/Record.java
UTF-8
1,645
2.125
2
[]
no_license
package ua.kiev.unicyb.tcct.domain.record; import org.springframework.stereotype.Component; import java.io.Serializable; import java.util.HashMap; import java.util.Map; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElementWrapper; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import ua.kiev.unicyb.tcct.domain.column.Column; import ua.kiev.unicyb.tcct.domain.field.Field; /** * @Author Denys Storozhenko. */ @Component @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = {"fields"}) @XmlRootElement(name = "record") public class Record implements Serializable { private static final Long serialVersionUID = -691274196371259512L; @XmlElementWrapper(name = "fields", namespace = "ua.kiev.unicyb.tcct", required = true) @XmlElement(name = "field", namespace = "ua.kiev.unicyb.tcct") private Map<Column, Field> fields = new HashMap<>(); public Record() { } public Map<Column, Field> getFields() { return fields; } public void setFields(Map<Column, Field> fields) { this.fields = fields; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Record record = (Record) o; return fields != null ? fields.equals(record.fields) : record.fields == null; } @Override public int hashCode() { return fields != null ? fields.hashCode() : 0; } @Override public String toString() { return "Record{" + "fields=" + fields + '}'; } }
true
2ca9d8e556200eb782365141a0e58249f7d711f9
Java
saravanan661987/seleniumframework
/CucumberProject-master/src/main/java/utility/Base.java
UTF-8
6,589
1.859375
2
[]
no_license
package utility; import java.awt.AWTException; import java.awt.Robot; import java.awt.Toolkit; import java.awt.datatransfer.StringSelection; import java.awt.event.KeyEvent; import java.io.File; import java.io.FileInputStream; import java.io.FileReader; import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.concurrent.TimeUnit; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.openqa.selenium.OutputType; import org.openqa.selenium.TakesScreenshot; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.ie.InternetExplorerDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import com.relevantcodes.extentreports.ExtentReports; import com.relevantcodes.extentreports.ExtentTest; import com.relevantcodes.extentreports.LogStatus; //import com.relevantcodes.extentreports.ExtentReports; //import com.relevantcodes.extentreports.ExtentTest; //import com.relevantcodes.extentreports.LogStatus; import org.apache.commons.io.FileUtils; //import org.apache.poi.ss.usermodel.Cell; //import org.apache.poi.ss.usermodel.Row; //import org.apache.poi.ss.usermodel.Sheet; //import org.apache.poi.ss.usermodel.Workbook; //import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; public class Base { public static WebDriver driver; static WebDriverWait wait; static File f1 = new File("./JSON/Configuration.json"); static String objfile = "./objRepo/AEM.xml"; // static ExtentTest Logger = extent.startTest("passTest"); public static WebDriver getDriver() { JSONObject jsonObject = JSONReadFromFile(); String browser = (String) jsonObject.get("browser"); File f = new File("./driver"); if (browser.equals("chrome")) { System.setProperty("webdriver.chrome.driver", f.getAbsolutePath() + "/chromedriver.exe"); driver = new ChromeDriver(); } else if (browser.equals("firefox")) { System.setProperty("webdriver.gecko.driver", f.getAbsolutePath() + "/geckodriver.exe"); driver = new FirefoxDriver(); } else if (browser.equals("ie")) { System.setProperty("webdriver.ie.driver", f.getAbsolutePath() + "/IEDriverServer.exe"); driver = new InternetExplorerDriver(); } driver.manage().window().maximize(); driver.get((String) jsonObject.get("url")); return driver; } public static boolean elementToBeVisible(WebDriver driver, int time, WebElement element) { boolean flag = false; try { wait = new WebDriverWait(driver, time); wait.until(ExpectedConditions.visibilityOf(element)); flag = true; } catch (Exception e) { e.printStackTrace(); } return flag; } public static boolean alertIsPresent(WebDriver driver, int time) { boolean flag = false; try { wait = new WebDriverWait(driver, time); wait.until(ExpectedConditions.alertIsPresent()); flag = true; } catch (Exception e) { e.printStackTrace(); } return flag; } public static boolean elementToBeClickable(WebDriver driver, int time, WebElement element) { boolean flag = false; try { wait = new WebDriverWait(driver, time); wait.until(ExpectedConditions.elementToBeClickable(element)); flag = true; } catch (Exception e) { e.printStackTrace(); } return flag; } public static boolean elementFound(WebDriver driver, int time, WebElement element) { boolean res = false; driver.manage().timeouts().implicitlyWait(time, TimeUnit.SECONDS); try { res = element.isDisplayed(); } catch (Exception e) { e.printStackTrace(); } return res; } public static boolean elementFound(WebElement element) { boolean res = false; try { res = element.isDisplayed(); } catch (Exception e) { e.printStackTrace(); } return res; } public static void setText(WebElement element, String name) { if (name != null && elementFound(element)) { element.clear(); element.sendKeys(name); } } public static String getText(WebElement element) { String name = null; if (elementFound(element)) { name = element.getAttribute("value"); } return name; } public static void clickElement(WebElement element, ExtentTest logger) { try { if (elementFound(element)) { String Eletext = element.getText(); element.click(); logger.log(LogStatus.PASS, "Element Click", Eletext + " link is clicked successfully"); } else { logger.log(LogStatus.FAIL, "Element Click", "link is not clicked"); } }catch(Exception e) { e.printStackTrace(); } } public static JSONObject JSONReadFromFile() { JSONParser parser = new JSONParser(); JSONObject jsonObject = null; try { Object obj = parser.parse(new FileReader(f1.getAbsoluteFile())); jsonObject = (JSONObject) obj; } catch (Exception e) { e.printStackTrace(); } return jsonObject; } public static String ObjIdentifier(String objname) { String ObjIdentifier = null; try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(new File(objfile)); Element rootElement = doc.getDocumentElement(); NodeList list = rootElement.getElementsByTagName(objname); for (int i = 0; i < list.getLength(); i++) { Node childNode = list.item(i); System.out.println("Object xpath : " + childNode.getTextContent()); ObjIdentifier = childNode.getTextContent(); return ObjIdentifier; } } catch (Exception e) { e.printStackTrace(); } return ObjIdentifier; } public static void getScreenShot(String screenShotFileName) { File screenShotLocation = new File("./screenshot/" + screenShotFileName + ".png"); TakesScreenshot screenshot = (TakesScreenshot) driver; File file = screenshot.getScreenshotAs(OutputType.FILE); try { FileUtils.copyFile(file, screenShotLocation); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
true
5f18315d116d19e846cefdcf01d3ffb1fd681cab
Java
boekj03/plantbeheerMetAngular
/boksebeld-angular-rest/src/main/java/nl/boksebeld/resources/PlantLijstContainer.java
UTF-8
311
1.96875
2
[]
no_license
package nl.boksebeld.resources; import java.util.ArrayList; import java.util.List; import nl.boksebeld.domein.plant.Plant; public class PlantLijstContainer { private List<Plant> plantLijst= new ArrayList<Plant>(); public List<Plant> getPlantLijst() { return plantLijst; } }
true
2e97e9f0dc7c5417c234216536ac82b6ca91e30a
Java
pvessel/hands-on-spring
/src/test/java/com/handsonspring/service/grid/GridColumnsServiceTest.java
UTF-8
1,576
2.3125
2
[ "MIT", "CC-BY-4.0", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
package com.handsonspring.service.grid; import com.handsonspring.model.Identifiable; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import java.util.UUID; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; class GridColumnsServiceTest { private GridColumnsService<Identifiable> gridColumnService; private Identifiable newEntity; private Identifiable existingEntity; private UUID id; @BeforeEach void initUseCase() { gridColumnService = Mockito.mock( GridColumnsService.class, Mockito.CALLS_REAL_METHODS); newEntity = mock(Identifiable.class); when(gridColumnService.getNewEntity()).thenReturn(newEntity); id = UUID.randomUUID(); existingEntity = mock(Identifiable.class); when(gridColumnService.findEntityById(id)).thenReturn(existingEntity); } @Test void getEntity_whenIdNoProvided_thenReturnNewEntity() { // given // init use case // when Identifiable entity = gridColumnService.getEntity(null); // then assertEquals(newEntity, entity); } @Test void getEntity_whenIdProvided_thenReturnFoundEntity() { // given // init use case String idAsString = id.toString(); // when Identifiable entity = gridColumnService.getEntity(idAsString); // then assertEquals(existingEntity, entity); } }
true
4d1b11e44047b77b654d52d39a616d0b9335e8d2
Java
FictionDk/parrot
/src/main/java/com/fictio/parrot/thinking/thread/ToastOMatic.java
UTF-8
5,166
3.265625
3
[]
no_license
package com.fictio.parrot.thinking.thread; import java.util.Random; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import org.junit.Test; import lombok.extern.slf4j.Slf4j; class Toast { public enum Status { DRY, BUTTERED, PEANUT, JAMMED } private Status status = Status.DRY; private final int id; public Toast(int id) {this.id = id;} public void butter() { status = Status.BUTTERED; } public void peaNut() { status = Status.PEANUT; } public void jam() { status = Status.JAMMED; } public Status getStatus() { return this.status;} public int getId() { return this.id;} public String toString() { return "Toast: "+id+": "+status; } } @SuppressWarnings("serial") class ToastQueue extends LinkedBlockingQueue<Toast> {} @Slf4j class Toaster implements Runnable { private ToastQueue queue; private int count = 0; private Random rand = new Random(50); public Toaster(ToastQueue queue) { this.queue = queue; } @Override public void run() { try { while(!Thread.interrupted()) { TimeUnit.MILLISECONDS.sleep(100+rand.nextInt(500)); Toast t = new Toast(count++); log.info("T: {}",t); /** * Inserts the specified element at the tail of this queue, waiting if * necessary for space to become available. */ queue.put(t); /** * Inserts the specified element into this queue if it is possible to do so * immediately without violating capacity restrictions, returning * <tt>true</tt> upon success and throwing an <tt>IllegalStateException</tt> * if no space is currently available. * * <p>This implementation returns <tt>true</tt> if <tt>offer</tt> succeeds, * else throws an <tt>IllegalStateException</tt>. */ //queue.add(t); } } catch(Exception e) { log.error("Toaster interrupted ,{}",e.toString()); } log.info("Toaster off"); } } @Slf4j class Butter implements Runnable { private ToastQueue dryQueue, butterQueue; public Butter(ToastQueue dry,ToastQueue buttered) { dryQueue = dry; butterQueue = buttered; } @Override public void run() { try { while(!Thread.interrupted()) { Toast t = dryQueue.take(); t.butter(); log.info("T: {}",t); butterQueue.put(t); } } catch (Exception e) { log.error("butter interrupted ,{}",e.toString()); } log.info("butter off"); } } @Slf4j class PeaNut implements Runnable { private ToastQueue dryQueue,peaNutQueue; public PeaNut(ToastQueue dryQueue,ToastQueue peaNutQueue) { this.dryQueue = dryQueue; this.peaNutQueue = peaNutQueue; } @Override public void run() { try { while(!Thread.interrupted()) { Toast t = dryQueue.take(); t.peaNut(); log.info("T: {}",t); peaNutQueue.add(t); } } catch (Exception e) { log.error("peaNut interrupted"); } log.info("peaNut off"); } } @Slf4j class Jammer implements Runnable { private ToastQueue butterQueue, peaNutQueue, finishQueue; public Jammer(ToastQueue buttered, ToastQueue peaNuted, ToastQueue finished) { this.butterQueue = buttered; this.finishQueue = finished; this.peaNutQueue = peaNuted; } @Override public void run() { try { while(!Thread.interrupted()) { Toast t = butterQueue.take(); t.jam(); log.info("T: {}",t); finishQueue.put(t); t = peaNutQueue.take(); t.jam(); log.info("T: {}",t); finishQueue.put(t); } } catch (Exception e) { log.error("jamer interrupted ,{}",e.toString()); } log.info("Jamer off"); } } /** * <p> 结果校验类 * */ @Slf4j class Eater implements Runnable { private ToastQueue finishQueue; private int counter = 0; public Eater(ToastQueue finished) { this.finishQueue = finished; } @Override public void run() { try { while(!Thread.interrupted()) { Toast t = finishQueue.take(); if(t.getId() != counter++ || t.getStatus()!=Toast.Status.JAMMED) { log.info("check failed, >>> {}",t); System.exit(1); }else { log.info("chomp! {}",t); // 声明切换线程,可以让他多吃点 Thread.yield(); } } } catch (Exception e) { log.error("Eater interrupted"); } log.info("Eater off"); } } /** * <p>使用BlockingQueue,示例线程协作 * * @author dk * */ public class ToastOMatic { @Test public void test() { ToastQueue dryQueue = new ToastQueue(), butterQueue = new ToastQueue(), finishQueue = new ToastQueue(), peaNutQueue = new ToastQueue(); ExecutorService exec = Executors.newCachedThreadPool(); exec.execute(new Toaster(dryQueue)); exec.execute(new Butter(dryQueue, butterQueue)); exec.execute(new PeaNut(dryQueue, peaNutQueue)); exec.execute(new Jammer(butterQueue,peaNutQueue,finishQueue)); // OrnamentalGarden.sleep(2000); exec.execute(new Eater(finishQueue)); OrnamentalGarden.sleep(4000); exec.shutdownNow(); } }
true
474de4a37aa38fee0c5d2be93a1872e88f0ad582
Java
satyam323545/Core_Java
/Day_2/src/satyam/mandal/primes_addition.java
UTF-8
531
3.265625
3
[]
no_license
//Name: Satyam Mandal. //W.A.P to add a set of prime numbers. ============================================================================== package satyam.mandal; public class primes_addition { /** * @param args */ public static void main(String[] args) { int i=0,sum=0; for(i=3;i<30;i++){ sum=sum+check_prime(i); } System.out.println(sum); } private static int check_prime(int i) { for(int n=2;n<i;n++){ if(i%n==0){ return 0; } } return i; } }
true
b9dee57c6c7df4b55c32f8ebfe5d451c9fa2aa52
Java
nataliaortizvi/PARCIAL-FINAL-DCA
/PARCIAL FINAL DCA/src/Model/Persona.java
UTF-8
2,457
2.78125
3
[]
no_license
package Model; import processing.core.PApplet; public abstract class Persona implements Runnable, Comparable<Persona>{ int px, py, tam, r, g, b, vel, dir, tipo; PApplet app; String nombre; int pxTexto; int contador; public Persona(PApplet app) { this.px = (int) app.random(5, 590); this.py = (int) app.random(5, 590); this.app = app; this.tam = 7; this.vel = 3; this.dir = (int) app.random(1,5); } public int compareTo(Persona o) { return this.contador - o.getContador(); } public void run() { mover(); } public void pintar() { } public void mover() { if (this.dir == 1) { this.px += this.vel; this.py += this.vel; } if (this.dir == 2) { this.px -= this.vel; this.py -= this.vel; } if (this.dir == 3) { this.px -= this.vel; this.py += this.vel; } if (this.dir == 4) { this.px += this.vel; this.py -= this.vel; } if (this.px <= 0 || this.px >= 600 || this.py <= 0 || this.py >= 600) { this.vel *= -1; } } public int getPx() { return px; } public int getPy() { return py; } public int getTam() { return tam; } public int getR() { return r; } public int getG() { return g; } public int getB() { return b; } public int getVel() { return vel; } public int getDir() { return dir; } public int getTipo() { return tipo; } public PApplet getApp() { return app; } public void setPx(int px) { this.px = px; } public void setPy(int py) { this.py = py; } public void setTam(int tam) { this.tam = tam; } public void setR(int r) { this.r = r; } public void setG(int g) { this.g = g; } public void setB(int b) { this.b = b; } public void setVel(int vel) { this.vel = vel; } public void setDir(int dir) { this.dir = dir; } public void setTipo(int tipo) { this.tipo = tipo; } public void setApp(PApplet app) { this.app = app; } public String getNombre() { return nombre; } public int getPxTexto() { return pxTexto; } public int getContador() { return contador; } public void setNombre(String nombre) { this.nombre = nombre; } public void setPxTexto(int pxTexto) { this.pxTexto = pxTexto; } public void setContador(int contador) { this.contador = contador; } }
true
9260912b89847b6847d5480a42162314433b7a1b
Java
qingshuidada/Jin01
/src/main/java/com/mdoa/admin/model/CarRepair.java
UTF-8
2,011
2.171875
2
[]
no_license
package com.mdoa.admin.model; import java.math.BigDecimal; import java.util.Date; import com.mdoa.base.model.BaseModel; import com.mdoa.util.DateUtil; public class CarRepair extends BaseModel{ private String repairId; private String carId; private String reason; private String executant; private String notes; private String repairType; private BigDecimal fee; private String aliveFlag; private String carNo; private Date repairDate; private String repairDateStr; public String getCarNo() { return carNo; } public void setCarNo(String carNo) { this.carNo = carNo; } public String getRepairId() { return repairId; } public void setRepairId(String repairId) { this.repairId = repairId; } public String getCarId() { return carId; } public void setCarId(String carId) { this.carId = carId; } public String getReason() { return reason; } public void setReason(String reason) { this.reason = reason; } public String getExecutant() { return executant; } public void setExecutant(String executant) { this.executant = executant; } public String getNotes() { return notes; } public void setNotes(String notes) { this.notes = notes; } public String getRepairType() { return repairType; } public void setRepairType(String repairType) { this.repairType = repairType; } public BigDecimal getFee() { return fee; } public void setFee(BigDecimal fee) { this.fee = fee; } public String getAliveFlag() { return aliveFlag; } public void setAliveFlag(String aliveFlag) { this.aliveFlag = aliveFlag; } public Date getRepairDate() { return repairDate; } public void setRepairDate(Date repairDate) { this.repairDate = repairDate; this.repairDateStr = DateUtil.dateToStr(repairDate,"yyyy-MM-dd"); } public String getRepairDateStr() { return repairDateStr; } public void setRepairDateStr(String repairDateStr) { this.repairDateStr = repairDateStr; this.repairDate = DateUtil.strToDate(repairDateStr,"yyyy-MM-dd"); } }
true
0575d1051c856ee47f35ef08092d5d4cb943f8ef
Java
costasboulis/Infolytics
/model/src/test/java/com/cleargist/model/SemanticModelTest.java
UTF-8
4,829
2.046875
2
[]
no_license
package com.cleargist.model; import static org.junit.Assert.assertTrue; import java.util.LinkedList; import java.util.List; import org.junit.After; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import com.amazonaws.auth.PropertiesCredentials; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.AmazonS3Client; import com.amazonaws.services.s3.model.S3ObjectSummary; import com.amazonaws.services.simpledb.AmazonSimpleDB; import com.amazonaws.services.simpledb.AmazonSimpleDBClient; import com.amazonaws.services.simpledb.model.DeleteDomainRequest; import com.cleargist.catalog.dao.CatalogDAO; import com.cleargist.catalog.dao.CatalogDAOImpl; import com.cleargist.catalog.entity.jaxb.Catalog; public class SemanticModelTest { private static final String AWS_CREDENTIALS = "/AwsCredentials.properties"; /* @Before public void loadCatalog() throws Exception { // createXMLCatalog(); CatalogDAO catalog = new CatalogDAOImpl(); // catalog.insertCatalog("cleargist", "recipesTextsSample.xml", "", "test"); catalog.insertCatalog("cleargist", "103.xml", "", "test"); } */ /* public void createXMLCatalog() throws Exception { AmazonS3 s3 = new AmazonS3Client(new PropertiesCredentials( SemanticModelTest.class.getResourceAsStream(AWS_CREDENTIALS))); // S3Object rawProfilesFile = s3.getObject("sintagespareas", "recipesTexts.txt"); S3Object rawProfilesFile = s3.getObject("cleargist", "recipesTextsSample.txt"); BufferedReader reader = new BufferedReader(new InputStreamReader(rawProfilesFile.getObjectContent())); String line = null; CatalogDAO catalogWriter = new CatalogDAOImpl(); Catalog catalog = new Catalog(); catalog.setProducts(new Catalog.Products()); Catalog.Products products = catalog.getProducts(); List<Catalog.Products.Product> productList = products.getProduct(); while ((line = reader.readLine()) != null) { String[] topFields = line.split("\";\""); if (topFields.length != 2) { logger.warn("Skipping line " + line); continue; } topFields[0] = topFields[0].replaceAll("\"", ""); topFields[1] = topFields[1].replaceAll("\"", ""); Catalog.Products.Product product = new Catalog.Products.Product(); product.setUid(topFields[0]); product.setName(topFields[0]); product.setLink(topFields[0]); product.setImage(topFields[0]); product.setPrice(new BigDecimal(0.0f)); product.setCategory("FOOD"); String choppedDescription = topFields[1].length() > 200 ? topFields[1].substring(0, 200) : topFields[1]; product.setDescription(choppedDescription); productList.add(product); } reader.close(); catalogWriter.marshallCatalog(catalog, "cleargist", "catalog.xsd", "cleargist", "recipesTextsSample.xml", "test"); } */ public void cleanUp() throws Exception { AmazonSimpleDB sdb = new AmazonSimpleDBClient(new PropertiesCredentials( SemanticModelTest.class.getResourceAsStream(AWS_CREDENTIALS))); sdb.deleteDomain(new DeleteDomainRequest("MODEL_SEMANTIC_test_A")); sdb.deleteDomain(new DeleteDomainRequest("MODEL_SEMANTIC_test_B")); sdb.deleteDomain(new DeleteDomainRequest("MODEL_SEMANTIC_test")); sdb.deleteDomain(new DeleteDomainRequest("CATALOG_test")); AmazonS3 s3 = new AmazonS3Client(new PropertiesCredentials( SemanticModelTest.class.getResourceAsStream(AWS_CREDENTIALS))); String bucketName = "profilessemanticmodeltest"; if (s3.doesBucketExist(bucketName)) { List<S3ObjectSummary> objSummaries = s3.listObjects(bucketName).getObjectSummaries(); int i = 0; while (i < objSummaries.size()) { s3.deleteObject(bucketName, objSummaries.get(i).getKey()); i ++; } s3.deleteBucket(bucketName); } bucketName = "tmpstatssemantictest"; if (s3.doesBucketExist(bucketName)) { List<S3ObjectSummary> objSummaries = s3.listObjects(bucketName).getObjectSummaries(); int i = 0; while (i < objSummaries.size()) { s3.deleteObject(bucketName, objSummaries.get(i).getKey()); i ++; } s3.deleteBucket(bucketName); } } @Test public void train() throws Exception { SemanticModel model = new SemanticModel(); model.setTopCorrelations(30); model.createModel("104"); // model.estimateModelParameters("104"); // model.swapModelDomainNames("MODEL_SEMANTIC_", "104"); } @Ignore @Test public void testRecommendations() { SemanticModel model = new SemanticModel(); StandardFilter filter = new StandardFilter(); List<String> productIDs = new LinkedList<String>(); productIDs.add("11811"); try { List<Catalog.Products.Product> recommendedProducts = model.getRecommendedProductsInternal(productIDs, "104", filter); assertTrue(recommendedProducts.size() > 0); } catch (Exception ex) { assertTrue(false); } } }
true
aa52b0669e18502753a776878aeb302c3f3f8525
Java
ecollado92/TransitDataFeeder
/src/main/org/ideaproject/model/Address.java
UTF-8
3,397
2.28125
2
[ "Apache-2.0" ]
permissive
/** * Copyright 2010 SingleMind Consulting, Inc. (http://singlemindconsulting.com) * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.ideaproject.model; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import org.hibernate.validator.Length; import org.hibernate.validator.NotNull; /** * @author dirk * */ @Entity @Table(name = "address") public class Address { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "address_id", nullable = false, unique = true) private int addressId; @Column(name = "street_line_1", nullable = false, length = 64) @NotNull @Length(max = 64) private String streetLine1; @Column(name = "street_line_2", length = 64) @Length(max = 64) private String streetLine2; @Column(name = "city", nullable = false, length = 64) @NotNull @Length(max = 64) private String city; @Column(name = "state_province_code", nullable = false, length = 3) @NotNull @Length(max = 3) private String stateCode; @Column(name = "postal_code", nullable = false, length = 10) @Length(max = 10) private String postalCode; @Column(name = "country", length = 64) @Length(max = 64) private String country; /** * @return the addressId */ public int getAddressId() { return addressId; } /** * @param addressId the addressId to set */ public void setAddressId(int addressId) { this.addressId = addressId; } /** * @return the streetLine1 */ public String getStreetLine1() { return streetLine1; } /** * @param streetLine1 the streetLine1 to set */ public void setStreetLine1(String streetLine1) { this.streetLine1 = streetLine1; } /** * @return the streetLine2 */ public String getStreetLine2() { return streetLine2; } /** * @param streetLine2 the streetLine2 to set */ public void setStreetLine2(String streetLine2) { this.streetLine2 = streetLine2; } /** * @return the city */ public String getCity() { return city; } /** * @param city the city to set */ public void setCity(String city) { this.city = city; } /** * @return the stateCode */ public String getStateCode() { return stateCode; } /** * @param stateCode the stateCode to set */ public void setStateCode(String stateCode) { this.stateCode = stateCode; } /** * @return the postalCode */ public String getPostalCode() { return postalCode; } /** * @param postalCode the postalCode to set */ public void setPostalCode(String postalCode) { this.postalCode = postalCode; } /** * @return the country */ public String getCountry() { return country; } /** * @param country the country to set */ public void setCountry(String country) { this.country = country; } }
true
5b700bb4750a9631ccf623b975d1dc9c26509f19
Java
prowide/prowide-iso20022
/model-cain-types/src/generated/java/com/prowidesoftware/swift/model/mx/dic/AcceptorRejection4.java
UTF-8
3,458
1.90625
2
[ "Apache-2.0" ]
permissive
package com.prowidesoftware.swift.model.mx.dic; 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; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; /** * Reject of an exchange. * * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "AcceptorRejection4", propOrder = { "rjctRsn", "errRptg", "msgInErr" }) public class AcceptorRejection4 { @XmlElement(name = "RjctRsn", required = true) @XmlSchemaType(name = "string") protected RejectReason1Code rjctRsn; @XmlElement(name = "ErrRptg") protected List<ErrorReporting1> errRptg; @XmlElement(name = "MsgInErr") protected byte[] msgInErr; /** * Gets the value of the rjctRsn property. * * @return * possible object is * {@link RejectReason1Code } * */ public RejectReason1Code getRjctRsn() { return rjctRsn; } /** * Sets the value of the rjctRsn property. * * @param value * allowed object is * {@link RejectReason1Code } * */ public AcceptorRejection4 setRjctRsn(RejectReason1Code value) { this.rjctRsn = value; return this; } /** * Gets the value of the errRptg 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 errRptg property. * * <p> * For example, to add a new item, do as follows: * <pre> * getErrRptg().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link ErrorReporting1 } * * */ public List<ErrorReporting1> getErrRptg() { if (errRptg == null) { errRptg = new ArrayList<ErrorReporting1>(); } return this.errRptg; } /** * Gets the value of the msgInErr property. * * @return * possible object is * byte[] */ public byte[] getMsgInErr() { return msgInErr; } /** * Sets the value of the msgInErr property. * * @param value * allowed object is * byte[] */ public AcceptorRejection4 setMsgInErr(byte[] value) { this.msgInErr = value; return this; } @Override public String toString() { return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE); } @Override public boolean equals(Object that) { return EqualsBuilder.reflectionEquals(this, that); } @Override public int hashCode() { return HashCodeBuilder.reflectionHashCode(this); } /** * Adds a new item to the errRptg list. * @see #getErrRptg() * */ public AcceptorRejection4 addErrRptg(ErrorReporting1 errRptg) { getErrRptg().add(errRptg); return this; } }
true
bc11cb3b2a9e80eafebd12717230884897f94afb
Java
inkarnasion/OOP-Advanced
/Enumeration and Annotation/Lab/03. Coffee Machine/CoffeeMachine.java
UTF-8
1,058
3.0625
3
[]
no_license
package enumeratoin_and_anotation_lab.cofee_machine; import enumeratoin_and_anotation_lab.cofee_machine.enums.Coffee; import enumeratoin_and_anotation_lab.cofee_machine.enums.CoffeeSize; import enumeratoin_and_anotation_lab.cofee_machine.enums.CoffeeType; import enumeratoin_and_anotation_lab.cofee_machine.enums.Coin; import java.util.ArrayList; import java.util.List; public class CoffeeMachine { private List<Coffee> coffeeList; private int money; public CoffeeMachine() { coffeeList =new ArrayList<>(); } public void buyCoffee(String size, String type){ Coffee coffee = new Coffee(Enum.valueOf(CoffeeSize.class,size.toUpperCase()) ,Enum.valueOf(CoffeeType.class,type.toUpperCase())); if (coffee.getPrice()<= this.money){ this.coffeeList.add(coffee); this.money=0; } } public void insertCoin(String coin){ this.money += Enum.valueOf(Coin.class,coin.toUpperCase()).getValue(); } public Iterable<Coffee> coffeesSold(){ return this.coffeeList; } }
true
2faefdd7e6290174c18d1790a5b82355b359785b
Java
andreguedes/IGTI
/Design Patterns - GoF/src/br/com/igti/gof/estruturais/A.java
UTF-8
271
2.09375
2
[]
no_license
package br.com.igti.gof.estruturais; public class A { public Lista disponibilizarLista() { Lista lista = new Lista(); lista.adiciona(1); lista.adiciona(2); lista.adiciona(3); lista.adiciona(4); return new ListaNaoAlteravel(lista); } }
true
7169acee9b0357982022a9da329df652ce94d73a
Java
marcocrxu/leetcode
/src/main/java/huawei/huaweitest_2.java
UTF-8
769
2.6875
3
[]
no_license
package huawei; import java.util.*; public class huaweitest_2 { public static void IO(){ Scanner scanner =new Scanner(System.in); while(scanner.hasNextInt()){ int n=scanner.nextInt(); List<Integer> list=new ArrayList<>(); Map<Integer, Boolean> map=new HashMap<>(); for(int i=0;i<n;i++){ int x=scanner.nextInt(); if(!map.containsKey(x)){ map.put(x,true); list.add(x); } } Collections.sort(list); for(int i=0;i<list.size();i++){ System.out.println(list.get(i)); } } } public static void main(String[] args) { IO(); } }
true
c3a1bd5d3a805d3e5811526155d2d5762ef8c197
Java
zykjsunhaibo88/cjkj
/src/com/br/tvlicai/firstchinanet/weixin/controller/weixin/ws/WeixinWS.java
UTF-8
1,056
1.804688
2
[]
no_license
/* * ================================================== * 系统开发地 : 中国辽宁沈阳 * 系统名称: 超级组讯平台(SS) * 文件名: WeixinWS.java * ================================================== * 开发环境: JDK1.7+ * ================================================== * -变更履历 作者 YYYY/MM/DD REV. 备注 * -制作 李鑫 2016年4月11日 1.00 新建文件 * ================================================== * (C) Copyright Shenyang BR Tech. 2016 All Rights Reserved. */ package com.br.tvlicai.firstchinanet.weixin.controller.weixin.ws; import java.io.IOException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.ModelAndView; public interface WeixinWS { /** * 核心处理3:用户授权访问,后重定向 * * @param req * @param res * @throws Exception */ public void oauth2(HttpServletRequest req, HttpServletResponse res) throws Exception; }
true
68a572d6442858af515e53a3201144e41bedde5b
Java
fan-js/cpwater
/src/main/java/cn/ritac/cpwater/mybatis/model/Check.java
UTF-8
1,087
2.15625
2
[]
no_license
package cn.ritac.cpwater.mybatis.model; import javax.persistence.*; import java.io.Serializable; import java.util.Date; /** * @Author:FanJS * @Date:2019-9-5 18:14 */ @Table(name = "cpwater_check") public class Check implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY, generator = "SELECT LAST_INSERT_ID()") private Integer id; private String phone; private String type; @Column(name = "date_time") private String dateTime; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getDateTime() { return dateTime; } public void setDateTime(String dateTime) { this.dateTime = dateTime; } }
true
82a46e8f96848d464f88edf1a70ae34e3e3bf6bd
Java
canyapan/spring-webflux-sample
/src/main/java/com/canyapan/sample/reactivespring/service/EchoService.java
UTF-8
270
1.984375
2
[]
no_license
package com.canyapan.sample.reactivespring.service; import org.springframework.stereotype.Service; import reactor.core.publisher.Mono; @Service public class EchoService { public Mono<String> echo(final String message) { return Mono.just(message); } }
true
691b8a31288db01c5f035c04238a9e56fffde9d2
Java
compmstr/Crazy8
/src/com/undi/crazy8/CardAnimation.java
UTF-8
1,450
3.3125
3
[]
no_license
package com.undi.crazy8; import android.graphics.Point; public class CardAnimation { private final Point from, to; private final long timeStart, durationMs; private final CardRef card; private final Runnable callback; /** * A card animation * @param card - the CardRef to draw * @param from - point to start the animation * @param to - point to end the animation * @param durationMs * @param callback - Callback to run on the end of the animation */ public CardAnimation(CardRef card, Point from, Point to, long durationMs){ this(card, from, to, durationMs, null); } public CardAnimation(CardRef card, Point from, Point to, long durationMs, Runnable callback){ this.card = card; this.from = from; this.to = to; this.durationMs = durationMs; this.timeStart = System.currentTimeMillis(); this.callback = callback; } /** * Returns the current interpolated point for this animation * Returns null if we're past the end of the animation * @param frameTime * @return */ public Point getCurPoint(long frameTime){ double interpPoint = (frameTime - timeStart) / (double) durationMs; if(interpPoint <= 1.0){ Point ret = new Point(); ret.x = (int) (from.x + ((to.x - from.x) * interpPoint)); ret.y = (int) (from.y + ((to.y - from.y) * interpPoint)); return ret; }else{ return null; } } public CardRef getCard(){ return card; } public Runnable getCallback(){ return callback; } }
true
467f993d461b8978541e54e88362b7ed36aac48a
Java
donChelsea/Weather-app-from-scratch-2
/app/src/main/java/com/example/weatherappfromscratch/controller/WeatherAdapter.java
UTF-8
1,396
2.40625
2
[]
no_license
package com.example.weatherappfromscratch.controller; import android.content.Context; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.example.weatherappfromscratch.R; import com.example.weatherappfromscratch.model.Weather; import com.example.weatherappfromscratch.view.WeatherViewHolder; import java.text.ParseException; import java.util.List; public class WeatherAdapter extends RecyclerView.Adapter<WeatherViewHolder> { List<Weather> weatherList; Context context; public WeatherAdapter(Context context, List<Weather> weatherList) { this.context = context; this.weatherList = weatherList; } @NonNull @Override public WeatherViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) { View view = LayoutInflater.from(context).inflate(R.layout.weather_item_view, viewGroup, false); return new WeatherViewHolder(view); } @Override public void onBindViewHolder(@NonNull WeatherViewHolder weatherViewHolder, int i) { try { weatherViewHolder.onBind(weatherList.get(i)); } catch (ParseException e) { e.printStackTrace(); } } @Override public int getItemCount() { return weatherList.size(); } }
true
3adffed6b894f332bf1a74baaa9d758ec1078f18
Java
mini222333/mini
/workspace_08_13/jdbc/src/service/UsersService.java
UTF-8
339
1.757813
2
[]
no_license
package service; import java.util.List; import vo.UserVo; public interface UsersService { public List<UserVo> usersList(); public List<UserVo> usersList(int page, int n); public List<UserVo> login(UserVo vo); public int addUsers(UserVo vo); public int deleteUsers(String id); public int updateUsers(UserVo vo); }
true
28b2371c31c4bd325d736a5cb06c22222d857fd5
Java
Abhinav-vats/Project-Finance-Java
/Project-Gladiator-Abhinav/src/main/java/com/lti/service/exception/OtpServiceException.java
UTF-8
711
1.890625
2
[]
no_license
package com.lti.service.exception; public class OtpServiceException extends RuntimeException { public OtpServiceException() { super(); // TODO Auto-generated constructor stub } public OtpServiceException(String arg0, Throwable arg1, boolean arg2, boolean arg3) { super(arg0, arg1, arg2, arg3); // TODO Auto-generated constructor stub } public OtpServiceException(String message, Throwable cause) { super(message, cause); // TODO Auto-generated constructor stub } public OtpServiceException(String message) { super(message); // TODO Auto-generated constructor stub } public OtpServiceException(Throwable cause) { super(cause); // TODO Auto-generated constructor stub } }
true
f6dcc047472d71c0e71828e50ec5e3897ba9eb5f
Java
CaoXiangHong/untitled_one
/src/cn/hb/mr/Fu.java
UTF-8
124
1.984375
2
[]
no_license
package cn.hb.mr; public class Fu { public int numV = 20; public void metFu(){ System.out.println(numV); } }
true
dd9092b877bacc7f6bb00c04e1004c60c964c84d
Java
Gigigo-Android-Devs/gigigo-multipleGridRecyclerView-library-android
/app/src/main/java/com/gigigo/multiplegridrecyclerview_demo/recyclerview/CellImageWidget.java
UTF-8
215
1.710938
2
[ "Apache-2.0" ]
permissive
package com.gigigo.multiplegridrecyclerview_demo.recyclerview; import com.gigigo.multiplegridrecyclerview.entities.Cell; public class CellImageWidget extends Cell<ImageWidget> { public CellImageWidget() { } }
true
9d7e8eb1bf8fc6ca7f7d8e345414afee4c1402a7
Java
cckmit/pkpm-desktop-cloud
/desktop-cloud-shutdown/src/main/java/com/pkpmcloud/model/Record.java
UTF-8
695
1.65625
2
[]
no_license
/** * Copyright 2018 bejson.com */ package com.pkpmcloud.model; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.pkpmcloud.constants.ApiConst; import lombok.Data; import org.springframework.format.annotation.DateTimeFormat; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; /** * * @author xuhe */ @JsonIgnoreProperties(ignoreUnknown = true) @Data public class Record { private String user_name; private String connection_start_time; private String connection_setup_time; private String connection_end_time; }
true
ccf2afa922aeacec8de290bee5b8acaa37381391
Java
stebyrne04/SparkleGamesTest
/app/src/main/java/com/goldminelabs/sparklegamestest/task2emements/Scene.java
UTF-8
3,946
2.53125
3
[]
no_license
package com.goldminelabs.sparklegamestest.task2emements; import android.app.Activity; import android.content.Context; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.util.DisplayMetrics; import android.view.MotionEvent; import android.view.SurfaceHolder; import android.view.SurfaceView; import com.goldminelabs.sparklegamestest.Task2; import com.goldminelabs.sparklegamestest.R; import java.util.HashMap; import java.util.Random; /** * Created by stephen on 09/08/15. */ public class Scene extends SurfaceView implements SurfaceHolder.Callback{ private MainThread thread; private MainImage mainImage; private Cutter cutter; private HashMap<String, Pieces> pieces = new HashMap<String, Pieces>(); private String lastTouched; private int pieceCount = 0; int min = 65; int max = 80; DisplayMetrics metrics; Random r = new Random(); private int oldState; public Scene(Context context) { super(context); getHolder().addCallback(this); metrics = new DisplayMetrics(); Task2.instance.getWindowManager().getDefaultDisplay().getMetrics(metrics); mainImage = new MainImage(BitmapFactory.decodeResource(getResources(), R.drawable.mainimage), 10, 10, metrics); cutter = new Cutter(BitmapFactory.decodeResource(getResources(),R.drawable.cutter), 20, 20, BitmapFactory.decodeResource(getResources(), R.drawable.mask)); thread = new MainThread(getHolder(), this); setFocusable(true); } @Override public void surfaceCreated(SurfaceHolder holder) { thread.setRunning(true); thread.start(); } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { } @Override public void surfaceDestroyed(SurfaceHolder holder) { boolean retry = true; while (retry){ try{ thread.join(); retry = false; } catch (InterruptedException e){} } } @Override public boolean onTouchEvent(MotionEvent event) { if(event.getAction() == MotionEvent.ACTION_DOWN) { if(event.getY() > getHeight()-50){ thread.setRunning(false); ((Activity)getContext()).finish(); } else { } if((int)event.getX() > mainImage.getX()+(cutter.getBitmap().getWidth()/3-3) && (int)event.getY() > mainImage.getY()+(cutter.getBitmap().getHeight()/3-3) && (int)event.getX() < mainImage.getBitmap().getWidth()- (cutter.getBitmap().getWidth()/3+3) && (int)event.getY() < mainImage.getBitmap().getHeight()- (cutter.getBitmap().getHeight()/3+3)){ cutter.setX((int)event.getX() - cutter.getBitmap().getWidth()/2); cutter.setY((int)event.getY()- cutter.getBitmap().getHeight()/2); cutter.setTouched(true); } if(cutter.isTouched()){ int x = r.nextInt(metrics.widthPixels - (mainImage.getY()+ mainImage.getWidth() + 100) + 1) + (mainImage.getY()+ mainImage.getWidth() + 100); int y = r.nextInt((metrics.heightPixels-100) - 100 + 1) + 100; Pieces newPiece = new Pieces(mainImage.getBitmap(), x, y , cutter.getX() ,cutter.getY() ,cutter.getMask()); pieces.put("piece" + pieceCount++, newPiece); cutter.setTouched(false); } } return super.onTouchEvent(event); } @Override public void onDraw(Canvas canvas){ canvas.drawColor(Color.BLUE); mainImage.draw(canvas); cutter.draw(canvas); for (Pieces value : pieces.values()) { value.draw(canvas); } } public void stopThread(){ thread.setRunning(false); } }
true
08fa31cbbdf85202a89774595f57f155c6560db9
Java
NataliaPravitel/JavaRushGitRepository
/4.Collections/task3913/LogParser.java
UTF-8
19,460
2.59375
3
[]
no_license
package com.javarush.task.task39.task3913; import com.javarush.task.task39.task3913.query.*; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.nio.file.DirectoryStream; import java.nio.file.Files; import java.nio.file.Path; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; import java.util.stream.Stream; public class LogParser implements IPQuery, UserQuery, DateQuery, EventQuery, QLQuery { private Path logDir; private List<EventRecord> eventRecords = new ArrayList<>(); public LogParser(Path logDir) { this.logDir = logDir; parseEvent(); } @Override public Set<Object> execute(String query) { Pattern pattern = Pattern.compile("get (ip|user|date|event|status)" + "( for (ip|user|date|event|status) = \"(.*?)\")?" + "( and date between \"(.*?)\" and \"(.*?)\")?"); Matcher matcher = pattern.matcher(query); matcher.find(); String field1 = matcher.group(1); String field2 = null; String value1 = null; Date after = null; Date before = null; if (matcher.group(2) != null) { field2 = matcher.group(3); value1 = matcher.group(4); if (matcher.group(5) != null) { after = readDate(matcher.group(6)); before = readDate(matcher.group(7)); } } Set<Object> objects; Stream<EventRecord> filterRecordStream; if (field2 != null && value1 != null) { filterRecordStream = getRecordStreamFilterForValue(field2, value1); if (after != null && before != null) { Date finalAfter = after; Date finalBefore = before; filterRecordStream = filterRecordStream.filter(eventRecord -> isDateBetweenDates(eventRecord.dateLogEvent, finalAfter, finalBefore)); } objects = getValuesForField(field1, filterRecordStream); } else { objects = getValuesForField(field1, null); } return objects; } private Set<Object> getValuesForField(String field1, Stream<EventRecord> filterRecordStream) { Set<Object> objects = new HashSet<>(); filterRecordStream = filterRecordStream != null ? filterRecordStream : eventRecords.stream(); switch (field1) { case "ip": objects = filterRecordStream.map(eventRecord -> eventRecord.ip).collect(Collectors.toSet()); break; case "user": objects = filterRecordStream.map(eventRecord -> eventRecord.userName) .collect(Collectors.toSet()); break; case "date": objects = filterRecordStream.map(eventRecord -> eventRecord.dateLogEvent) .collect(Collectors.toSet()); break; case "event": objects = filterRecordStream.map(eventRecord -> eventRecord.event) .collect(Collectors.toSet()); break; case "status": objects = filterRecordStream.map(eventRecord -> eventRecord.status) .collect(Collectors.toSet()); break; } return objects; } private Stream<EventRecord> getRecordStreamFilterForValue(String field2, String value1) { Stream<EventRecord> recordStream = null; switch (field2) { case "ip": recordStream = filterLogsByParams(null, null, value1, null, null, 0, null); break; case "user": recordStream = filterLogsByParams(null, null, null, value1, null, 0, null); break; case "date": recordStream = eventRecords.stream().filter(eventRecord -> eventRecord.dateLogEvent.getTime() == readDate(value1).getTime()); break; case "event": recordStream = filterLogsByParams(null, null, null, null, readEvent(value1), 0, null); break; case "status": recordStream = filterLogsByParams(null, null, null, null, null, 0, readStatus(value1)); break; } return recordStream; } @Override public int getNumberOfUniqueIPs(Date after, Date before) { return getUniqueIPs(after, before).size(); } @Override public Set<String> getUniqueIPs(Date after, Date before) { return filterLogsByParams(after, before, null, null, null, 0, null) .map(eventRecord -> eventRecord.ip).collect(Collectors.toSet()); } @Override public Set<String> getIPsForUser(String user, Date after, Date before) { return filterLogsByParams(after, before, null, user, null, 0, null) .map(eventRecord -> eventRecord.ip).collect(Collectors.toSet()); } @Override public Set<String> getIPsForEvent(Event event, Date after, Date before) { return filterLogsByParams(after, before, null, null, event, 0, null) .map(eventRecord -> eventRecord.ip).collect(Collectors.toSet()); } @Override public Set<String> getIPsForStatus(Status status, Date after, Date before) { return filterLogsByParams(after, before, null, null, null, 0, status) .map(eventRecord -> eventRecord.ip).collect(Collectors.toSet()); } @Override public Set<String> getAllUsers() { return eventRecords.stream().map(eventRecord -> eventRecord.userName) .collect(Collectors.toSet()); } @Override public int getNumberOfUsers(Date after, Date before) { return filterLogsByParams(after, before, null, null, null, 0, null) .map(eventRecord -> eventRecord.userName).collect(Collectors.toSet()).size(); } @Override public int getNumberOfUserEvents(String user, Date after, Date before) { return filterLogsByParams(after, before, null, user, null, 0, null) .map(eventRecord -> eventRecord.event).collect(Collectors.toSet()).size(); } @Override public Set<String> getUsersForIP(String ip, Date after, Date before) { return filterLogsByParams(after, before, ip, null, null, 0, null) .map(eventRecord -> eventRecord.userName).collect(Collectors.toSet()); } @Override public Set<String> getLoggedUsers(Date after, Date before) { return filterLogsByParams(after, before, null, null, Event.LOGIN, 0, null) .map(eventRecord -> eventRecord.userName).collect(Collectors.toSet()); } @Override public Set<String> getDownloadedPluginUsers(Date after, Date before) { return filterLogsByParams(after, before, null, null, Event.DOWNLOAD_PLUGIN, 0, null) .map(eventRecord -> eventRecord.userName).collect(Collectors.toSet()); } @Override public Set<String> getWroteMessageUsers(Date after, Date before) { return filterLogsByParams(after, before, null, null, Event.WRITE_MESSAGE, 0, null) .map(eventRecord -> eventRecord.userName).collect(Collectors.toSet()); } @Override public Set<String> getSolvedTaskUsers(Date after, Date before) { return filterLogsByParams(after, before, null, null, Event.SOLVE_TASK, 0, null) .map(eventRecord -> eventRecord.userName).collect(Collectors.toSet()); } @Override public Set<String> getSolvedTaskUsers(Date after, Date before, int task) { return filterLogsByParams(after, before, null, null, Event.SOLVE_TASK, task, null) .map(eventRecord -> eventRecord.userName).collect(Collectors.toSet()); } @Override public Set<String> getDoneTaskUsers(Date after, Date before) { return filterLogsByParams(after, before, null, null, Event.DONE_TASK, 0, null) .map(eventRecord -> eventRecord.userName).collect(Collectors.toSet()); } @Override public Set<String> getDoneTaskUsers(Date after, Date before, int task) { return filterLogsByParams(after, before, null, null, Event.DONE_TASK, task, null) .map(eventRecord -> eventRecord.userName).collect(Collectors.toSet()); } @Override public Set<Date> getDatesForUserAndEvent(String user, Event event, Date after, Date before) { return filterLogsByParams(after, before, null, user, event, 0, null) .map(eventRecord -> eventRecord.dateLogEvent).collect(Collectors.toSet()); } @Override public Set<Date> getDatesWhenSomethingFailed(Date after, Date before) { return filterLogsByParams(after, before, null, null, null, 0, Status.FAILED) .map(eventRecord -> eventRecord.dateLogEvent).collect(Collectors.toSet()); } @Override public Set<Date> getDatesWhenErrorHappened(Date after, Date before) { return filterLogsByParams(after, before, null, null, null, 0, Status.ERROR) .map(eventRecord -> eventRecord.dateLogEvent).collect(Collectors.toSet()); } @Override public Date getDateWhenUserLoggedFirstTime(String user, Date after, Date before) { List<Date> dates = filterLogsByParams(after, before, null, user, Event.LOGIN, 0, null) .map(eventRecord -> eventRecord.dateLogEvent).sorted().collect(Collectors.toList()); return dates.isEmpty() ? null : dates.get(0); } @Override public Date getDateWhenUserSolvedTask(String user, int task, Date after, Date before) { List<Date> dates = filterLogsByParams(after, before, null, user, Event.SOLVE_TASK, task, null) .map(eventRecord -> eventRecord.dateLogEvent).sorted().collect(Collectors.toList()); return dates.isEmpty() ? null : dates.get(0); } @Override public Date getDateWhenUserDoneTask(String user, int task, Date after, Date before) { List<Date> dates = filterLogsByParams(after, before, null, user, Event.DONE_TASK, task, null) .map(eventRecord -> eventRecord.dateLogEvent).sorted().collect(Collectors.toList()); return dates.isEmpty() ? null : dates.get(0); } @Override public Set<Date> getDatesWhenUserWroteMessage(String user, Date after, Date before) { return filterLogsByParams(after, before, null, user, Event.WRITE_MESSAGE, 0, null) .map(eventRecord -> eventRecord.dateLogEvent).collect(Collectors.toSet()); } @Override public int getNumberOfAllEvents(Date after, Date before) { return getAllEvents(after, before).size(); } @Override public Set<Event> getAllEvents(Date after, Date before) { return filterLogsByParams(after, before, null, null, null, 0, null) .map(eventRecord -> eventRecord.event).collect(Collectors.toSet()); } @Override public Set<Event> getEventsForIP(String ip, Date after, Date before) { return filterLogsByParams(after, before, ip, null, null, 0, null) .map(eventRecord -> eventRecord.event).collect(Collectors.toSet()); } @Override public Set<Event> getEventsForUser(String user, Date after, Date before) { return filterLogsByParams(after, before, null, user, null, 0, null) .map(eventRecord -> eventRecord.event).collect(Collectors.toSet()); } @Override public Set<Event> getFailedEvents(Date after, Date before) { return filterLogsByParams(after, before, null, null, null, 0, Status.FAILED) .map(eventRecord -> eventRecord.event).collect(Collectors.toSet()); } @Override public Set<Event> getErrorEvents(Date after, Date before) { return filterLogsByParams(after, before, null, null, null, 0, Status.ERROR) .map(eventRecord -> eventRecord.event).collect(Collectors.toSet()); } @Override public int getNumberOfAttemptToSolveTask(int task, Date after, Date before) { return filterLogsByParams(after, before, null, null, Event.SOLVE_TASK, task, null) .map(eventRecord -> eventRecord.event).collect(Collectors.toList()).size(); } @Override public int getNumberOfSuccessfulAttemptToSolveTask(int task, Date after, Date before) { return filterLogsByParams(after, before, null, null, Event.DONE_TASK, task, null) .map(eventRecord -> eventRecord.event).collect(Collectors.toList()).size(); } @Override public Map<Integer, Integer> getAllSolvedTasksAndTheirNumber(Date after, Date before) { List<EventRecord> events = filterLogsByParams(after, before, null, null, Event.SOLVE_TASK, 0, null).collect(Collectors.toList()); Map<Integer, Integer> taskAndTheirNumber = new HashMap<>(); events.forEach(eventRecord -> taskAndTheirNumber.put(eventRecord.task, getNumberOfAttemptToSolveTask(eventRecord.task, after, before))); return taskAndTheirNumber; } @Override public Map<Integer, Integer> getAllDoneTasksAndTheirNumber(Date after, Date before) { List<EventRecord> events = filterLogsByParams(after, before, null, null, Event.DONE_TASK, 0, null).collect(Collectors.toList()); Map<Integer, Integer> taskAndTheirNumber = new HashMap<>(); events.forEach(eventRecord -> taskAndTheirNumber.put(eventRecord.task, getNumberOfSuccessfulAttemptToSolveTask(eventRecord.task, after, before))); return taskAndTheirNumber; } @Override public Set<Date> getDatesWhenUserDownloadedPlugin(String user, Date after, Date before) { return filterLogsByParams(after, before, null, user, Event.DOWNLOAD_PLUGIN, 0, null) .map(eventRecord -> eventRecord.dateLogEvent).collect(Collectors.toSet()); } private Stream<EventRecord> filterLogsByParams(Date after, Date before, String ip, String user, Event event, int task, Status status) { Stream<EventRecord> recordStream = eventRecords.stream() .filter(eventRecord -> isDateBetweenDates(eventRecord.dateLogEvent, after, before)); if (ip != null) { recordStream = recordStream.filter(eventRecord -> eventRecord.ip.equals(ip)); } else if (user != null) { recordStream = recordStream .filter(eventRecord -> eventRecord.userName.equalsIgnoreCase(user)); if (event != null) { recordStream = recordStream.filter(eventRecord -> eventRecord.event.equals(event)); if (task != 0) { recordStream = recordStream.filter(eventRecord -> eventRecord.task == task); } } } else if (event != null) { recordStream = recordStream.filter(eventRecord -> eventRecord.event.equals(event)); if (task != 0) { recordStream = recordStream.filter(eventRecord -> eventRecord.task == task); } } else if (status != null) { recordStream = recordStream.filter(eventRecord -> eventRecord.status.equals(status)); } return recordStream; } private void parseEvent() { // мой изначальный код List<File> logFiles = searchLogFiles(); List<String> events = readLogFile(logFiles); for (String event : events) { List<String> parseEvents = new ArrayList<>(Arrays.asList(event.split("\t"))); String ip = parseEvents.get(0); String userName = parseEvents.get(1); Date date = readDate(parseEvents.get(2)); Event logEvent = readEvent(parseEvents.get(3)); int eventAdditionalParameter = readEventAdditionalParameter(parseEvents.get(3)); Status status = readStatus(parseEvents.get(4)); eventRecords.add(new EventRecord(ip, userName, date, logEvent, eventAdditionalParameter, status)); } //код, который пропустил javarush // try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(logDir)) { // for (Path file : directoryStream) { // if (file.toString().toLowerCase().endsWith(".log")) { // try (BufferedReader reader = new BufferedReader(new FileReader(file.toFile()))) { // String line = null; // while ((line = reader.readLine()) != null) { // List<String> parseEvents = new ArrayList<>(Arrays.asList(line.split("\t"))); // if (parseEvents.size() != 5) { // continue; // } // // String ip = parseEvents.get(0); // String userName = parseEvents.get(1); // Date date = readDate(parseEvents.get(2)); // Event logEvent = readEvent(parseEvents.get(3)); // int eventAdditionalParameter = readEventAdditionalParameter(parseEvents.get(3)); // Status status = readStatus(parseEvents.get(4)); // eventRecords.add(new EventRecord(ip, userName, date, logEvent, eventAdditionalParameter, status)); // } // } // } // } // } catch (IOException e) { // e.printStackTrace(); // } } private List<File> searchLogFiles() { return Arrays.stream(logDir.toFile().listFiles()) .filter(file -> file.getName().toLowerCase().endsWith(".log")) .collect(Collectors.toList()); } private List<String> readLogFile(List<File> logFiles) { List<String> events = null; for (File log : logFiles) { try { events = Files.readAllLines(log.toPath()); } catch (IOException e) { e.printStackTrace(); } } return events; } private Date readDate(String time) { Date date = null; try { date = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss").parse(time); } catch (ParseException e) { e.printStackTrace(); } return date; } private Event readEvent(String inputParam) { Event event = null; for (int i = 0; i < Event.values().length; i++) { if (inputParam.startsWith(Event.values()[i].name())) { event = Event.values()[i]; } } return event; } private int readEventAdditionalParameter(String inputParam) { int result = -1; if (inputParam.contains(Event.DONE_TASK.name()) || inputParam.contains(Event.SOLVE_TASK.name())) { String s = inputParam.replaceAll(" ", "") .replaceAll("\\p{Alpha}", "") .replaceAll("\\p{Punct}", ""); result = Integer.parseInt(s); } return result; } private Status readStatus(String inputParam) { Status status = null; for (int i = 0; i < Status.values().length; i++) { if (Status.values()[i].name().equals(inputParam)) { status = Status.values()[i]; } } return status; } private boolean isDateBetweenDates(Date date, Date after, Date before) { if (after == null && before == null) { return true; } else { if (after == null) { return date.before(before); } else if (before == null) { return date.after(after); } else { return date.after(after) && date.before(before); } } } class EventRecord { private String ip; private String userName; private Date dateLogEvent; private Event event; private int task; private Status status; public EventRecord(String ip, String userName, Date dateLogEvent, Event event, int eventAdditionalParameter, Status status) { this.ip = ip; this.userName = userName; this.dateLogEvent = dateLogEvent; this.event = event; this.task = eventAdditionalParameter; this.status = status; } @Override public String toString() { return "EventRecord{" + "userName='" + userName + '\'' + ", ip='" + ip + '\'' + ", dateLogEvent=" + dateLogEvent + ", event=" + event + ", eventAdditionalParameter=" + task + ", status=" + status + '}'; } } }
true
5622985cf144d4257d27bbeb6502f9df378098d2
Java
Stormantonio/Departments-Employees
/src/main/java/com/chernenko/controller/factories/department/impl/CreateDepartment.java
UTF-8
806
2.203125
2
[]
no_license
package com.chernenko.controller.factories.department.impl; import com.chernenko.controller.MainController; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.sql.SQLException; /** * Created by Anton on 07.04.2017. */ public class CreateDepartment implements MainController { @Override public void doAction(HttpServletRequest request, HttpServletResponse response) throws SQLException { RequestDispatcher rd = request.getRequestDispatcher("DepartmentForm.jsp"); try { rd.forward(request, response); } catch (ServletException | IOException e) { e.printStackTrace(); } } }
true
a921e299aedeb3cba247c2b2e42314c15ea23b6b
Java
khaledboussaba/my_workspaces_al34
/intro/demo-heritage/src/main/java/fr/afcepf/al34/App.java
UTF-8
794
3.140625
3
[]
no_license
package fr.afcepf.al34; public class App { public static void main(String[] args) { Vehicle v; //v = new Vehicle(); pas possible vu que la classe Vehicle est abstract v = new Car(); v.moveForward(); System.out.println(v.getSpeed()); System.out.println(v.isTerrestrial()); System.out.println(v.toString()); v = new Baot(); v.moveForward(); System.out.println(v.getSpeed()); System.out.println(v.isTerrestrial()); IFlyable f = new Plane(); f.fly(); System.out.println(f); f = new Bird(); f.fly(); // Bird b1 = new Bird("titi"); // Bird b2 = new Bird("titi"); // System.out.println(b1.equals(b2)); // System.out.println(b1.name.equals(b2.name)); // System.out.println(b1 == b2); // System.out.println(b1.name == b2.name); } }
true
95df3db68c8246335953b1090261ffc354f738a5
Java
praskris83/click_predict_av
/src/hack/mine.java
UTF-8
332
2.515625
3
[]
no_license
package hack; /** * @author Prasad * */ public class mine { public static void main(String[] args) { pint(16); } private static void pint(int i) { System.out.println(i++); System.out.println(i++); System.out.println(i++); System.out.println(i++); System.out.println(i++); } }
true
2598180ea887030f2d9e5af451eacca0b0c5aba6
Java
skrser/CtCI
/ctci3.6/src/main/java/ru/skrser/ctci3dot6/Solution.java
UTF-8
2,203
3.671875
4
[ "MIT" ]
permissive
package ru.skrser.ctci3dot6; import java.util.ArrayDeque; import java.util.Deque; import java.util.HashSet; import java.util.Set; public class Solution { /** * Sort stack in ascending order using stacks * Computation complexity = O(N^2) * Memory consumption = O(N), no data copy, but in worst case N stacks is needed * * @param stack to sort */ public static void sort(Deque<Integer> stack) { Set<Deque<Integer>> setOfStacks = decompose(stack); compose(stack, setOfStacks); } private static Set<Deque<Integer>> decompose(Deque<Integer> stack) { Set<Deque<Integer>> setOfStacks = new HashSet<Deque<Integer>>(); while (!stack.isEmpty()) { int value = stack.pop(); Deque<Integer> suitableStack = findSuitableStack(setOfStacks, value); if (suitableStack == null) { suitableStack = new ArrayDeque<Integer>(); setOfStacks.add(suitableStack); } suitableStack.push(value); } return setOfStacks; } private static Deque<Integer> findSuitableStack(Set<Deque<Integer>> setOfStacks, int value) { for (Deque<Integer> stack : setOfStacks) { if (stack.peek() >= value) return stack; } return null; } private static void compose(Deque<Integer> stack, Set<Deque<Integer>> setOfStacks) { while (!setOfStacks.isEmpty()) { Deque<Integer> minValueStack = findMinValueStack(setOfStacks); stack.push(minValueStack.pop()); while (!minValueStack.isEmpty() && minValueStack.peek().equals(stack.peek())) { stack.push(minValueStack.pop()); } if (minValueStack.isEmpty()) setOfStacks.remove(minValueStack); } } private static Deque<Integer> findMinValueStack(Set<Deque<Integer>> setOfStacks) { Deque<Integer> minValueStack = null; for (Deque<Integer> stack : setOfStacks) { if (minValueStack == null || minValueStack.peek() > stack.peek()) minValueStack = stack; } return minValueStack; } }
true
eac3c8fae68cc67813a216e0e0c2eb090c8be60c
Java
Bigshen/RealTime-1
/src/com/foxlink/realtime/DAO/LineMappingDAO.java
UTF-8
7,700
2.125
2
[]
no_license
package com.foxlink.realtime.DAO; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; import org.springframework.jdbc.core.PreparedStatementSetter; import org.springframework.jdbc.core.RowMapper; import org.springframework.transaction.support.DefaultTransactionDefinition; import com.foxlink.realtime.model.LineMapping; import com.foxlink.realtime.model.Page; import com.foxlink.realtime.model.objectMapper.LineMappingMapper; public class LineMappingDAO extends DAO<LineMapping> { private static Logger logger = Logger.getLogger(LineMappingDAO.class); @Override public boolean AddNewRecord(LineMapping newRecord) { // TODO Auto-generated method stub return false; } @Override public boolean UpdateRecord(LineMapping updateRecord) { // TODO Auto-generated method stub return false; } @Override public boolean DeleteRecord(String recordID, String updateUser) { // TODO Auto-generated method stub return false; } @Override public List<LineMapping> FindAllRecords() { // TODO Auto-generated method stub return null; } @Override public List<LineMapping> FindAllRecords(int currentPage, int totalRecord, String queryCritirea, String queryParam) { // TODO Auto-generated method stub List<LineMapping> lineMapping = null; // TODO Auto-generated method stub String sSQL = "select t.org_name,t.mes_pdline_id,t.mes_pdline_name,t.mes_pdline_desc,t.rt_lineno,t.std_man_power FROM SWIPE.MES_RT_LINE_MAPPING t " + "where t.enabled = '1' "; try { List <Object> queryList=new ArrayList<Object>(); if(queryCritirea.equals("RTLINE")){ sSQL += " and t.rt_lineno = ? "; } Page page = new Page(currentPage, totalRecord); int endIndex=page.getStartIndex() + page.getPageSize(); sSQL += " order by t.rt_lineno " ; if (!queryCritirea.equals("")){ queryList.add(queryParam); } lineMapping = jdbcTemplate.query(sSQL,queryList.toArray() ,new LineMappingMapper()); } catch (Exception ex) { logger.error("Find LineMapping TotalRecord are failed ",ex); ex.printStackTrace(); } return lineMapping; } @Override public List<LineMapping> FindRecord(String userDataCostId, int currentPage, int totalRecord, LineMapping t) { // TODO Auto-generated method stub return null; } @Override public List<LineMapping> FindRecords(LineMapping t) { // TODO Auto-generated method stub return null; } @Override public int getTotalRecord(String queryCritirea, String queryParam) { // TODO Auto-generated method stub int totalRecord=-1; String sSQL = "select count(*) from MES_RT_LINE_MAPPING t where t.enabled = '1' "; try { List <Object> queryList=new ArrayList<Object>(); if(queryCritirea.equals("RTLINE")){ sSQL += " and t.rt_lineno = ? "; } if(!queryCritirea.equals("")){ queryList.add(queryParam); } totalRecord = jdbcTemplate.queryForObject(sSQL, queryList.toArray(), Integer.class); } catch (Exception ex) { logger.error("Find LineMapping TotalRecord are failed ",ex); ex.printStackTrace(); } return totalRecord; } @Override public int getTotalRecords(String userDataCostId, LineMapping t) { // TODO Auto-generated method stub return 0; } public boolean UpdateRecord(LineMapping lineMapping, String updateUser) { // TODO Auto-generated method stub int updateRow = -1; txDef = new DefaultTransactionDefinition(); txStatus = transactionManager.getTransaction(txDef); String sql = "update MES_RT_LINE_MAPPING t set t.org_name = ?,t.mes_pdline_id = ?,t.mes_pdline_name = ?,t.mes_pdline_desc = ?,t.std_man_power= ?" + ",t.update_time = sysdate,t.update_user = ? where t.enabled = '1' and t.rt_lineno = ?"; try{ if(lineMapping!=null){ System.out.println(updateRow+"updateRow"); updateRow=jdbcTemplate.update(sql,new PreparedStatementSetter(){ @Override public void setValues(PreparedStatement ps) throws SQLException { // TODO Auto-generated method stub ps.setString(1, lineMapping.getORG_NAME()); ps.setInt(2, lineMapping.getMES_PDLINE_ID()); ps.setString(3, lineMapping.getMES_PDLINE_NAME()); ps.setString(4, lineMapping.getMES_PDLINE_DESC()); ps.setInt(5, lineMapping.getSTD_MAN_POWER()); ps.setString(6, updateUser); ps.setString(7, lineMapping.getRT_LINENO()); } }); transactionManager.commit(txStatus); } }catch(Exception e){ logger.error("Update LineMapping is failed",e); transactionManager.rollback(txStatus); } System.out.println(updateRow+"updateRow"); if(updateRow > 0) return true; else return false; } public List<String> getRTLine() { // TODO Auto-generated method stub List<String> list = null; String sSQL = "select t.Lineno from LINENO t where t.lineno is not null and t.lineno not in(select a.rt_lineno from MES_RT_LINE_MAPPING a) order by t.lineno asc"; try { list = jdbcTemplate.query(sSQL, new RowMapper<String>(){ @Override public String mapRow(ResultSet rs, int rowNum) throws SQLException { // TODO Auto-generated method stub return rs.getString(1); } }); } catch (Exception ex) { logger.error("Find LineMapping TotalRecord are failed ",ex); ex.printStackTrace(); } return list; } public boolean checkRTLine(String rt_LINENO) { // TODO Auto-generated method stub List<LineMapping> lineMapping = null; boolean checkReault = false; // TODO Auto-generated method stub String sSQL = "select t.org_name,t.mes_pdline_id,t.mes_pdline_name,t.mes_pdline_desc,t.rt_lineno,t.std_man_power " + "FROM SWIPE.MES_RT_LINE_MAPPING t where t.enabled = '1' and t.rt_lineno = ?"; try { List <Object> queryList=new ArrayList<Object>(); queryList.add(rt_LINENO); lineMapping = jdbcTemplate.query(sSQL,queryList.toArray() ,new LineMappingMapper()); } catch (Exception ex) { logger.error("Find LineMapping TotalRecord are failed ",ex); ex.printStackTrace(); } if(lineMapping.size()>0){ checkReault = true; } return checkReault; } public boolean AddNewRecord(LineMapping lineMapping, String insertUser) { // TODO Auto-generated method stub boolean insertReault = false; txDef = new DefaultTransactionDefinition(); txStatus = transactionManager.getTransaction(txDef); int insertRow = -1; String sql = "insert into SWIPE.MES_RT_LINE_MAPPING(ORG_NAME,MES_PDLINE_ID,MES_PDLINE_NAME,MES_PDLINE_DESC,RT_LINENO,STD_MAN_POWER,UPDATE_TIME,UPDATE_USER,ENABLED) " + "VALUES(?,?,?,?,?,?,sysdate,?,?)"; try{ if(lineMapping!=null){ insertRow = jdbcTemplate.update(sql, new PreparedStatementSetter() { @Override public void setValues(PreparedStatement ps) throws SQLException { // TODO Auto-generated method stub ps.setString(1, lineMapping.getORG_NAME()); ps.setInt(2, lineMapping.getMES_PDLINE_ID()); ps.setString(3, lineMapping.getMES_PDLINE_NAME()); ps.setString(4, lineMapping.getMES_PDLINE_DESC()); ps.setString(5, lineMapping.getRT_LINENO()); ps.setInt(6, lineMapping.getSTD_MAN_POWER()); ps.setString(7, insertUser); ps.setInt(8, 1); } }); transactionManager.commit(txStatus); } }catch(Exception ex){ logger.error("Find InsertLineMapping TotalRecord are failed ",ex); transactionManager.rollback(txStatus); } if(insertRow>0){ insertReault = true; }else{ insertReault = false; } return insertReault; } }
true
1503b8cc3168dbd47c3cfe570b588310f8c3aa8a
Java
georgecaotung/twiter-web-app
/nhandinh-twitter-app-master/app/vn/picore/playtwitter/model/HashTag.java
UTF-8
2,219
2.265625
2
[ "Apache-2.0" ]
permissive
package vn.picore.playtwitter.model; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.UUID; import java.util.regex.Pattern; import org.jongo.MongoCollection; import org.jongo.MongoCursor; import uk.co.panaxiom.playjongo.PlayJongo; public class HashTag { private UUID _id; private UUID messageid; private String tag; private UUID userid; private Date createddate; public HashTag() { this._id = UUID.randomUUID(); } public static MongoCollection hashtags() { return PlayJongo.getCollection("hashtags"); } public UUID getId() { return _id; } public UUID getUserid() { return userid; } public void setUserid(UUID userid) { this.userid = userid; } public void setId(UUID id) { this._id = id; } public UUID getMessageId() { return messageid; } public void setMessage(UUID message) { this.messageid = message; } public String getTag() { return tag; } public void setTag(String tag) { this.tag = tag; } public Date getCreateddate() { return createddate; } public void setCreateddate(Date createddate) { this.createddate = createddate; } public static void create(HashTag tag) { HashTag.hashtags().save(tag); } public static void save(HashTag tag) { HashTag.hashtags().save(tag); } public static MongoCursor<HashTag> search(String query) { MongoCursor<HashTag> cursor = HashTag.hashtags().find("{tag: #}", query).as(HashTag.class); return cursor; } public static MongoCursor<HashTag> getByTagName(String tagname, Integer from, Integer perpage, Long timestamp) { if (timestamp != null) { Date date = new Date(timestamp + 1000); return HashTag.hashtags().find("{createddate: {$gt: #}, tag: #}", date, tagname).sort("{createddate: -1}") .skip(from).limit(perpage).as(HashTag.class); } else { return HashTag.hashtags().find("{tag: #}", tagname).sort("{createddate: -1}").skip(from).limit(perpage) .as(HashTag.class); } } public static MongoCursor<HashTag> findByTagName(String tagname, Integer from, Integer perpage) { return HashTag.hashtags().find("{tag: #}", Pattern.compile(tagname)).sort("{createddate: -1}").skip(from) .limit(perpage).as(HashTag.class); } }
true
3ede2a056cd57001796872e579a2d00dc510e810
Java
DirkMahler/graphql-maven-plugin-project
/graphql-java-runtime/src/test/java/com/graphql_java_generator/client/domain/forum/CustomScalarDeserializerDate.java
UTF-8
517
1.90625
2
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
/** * */ package com.graphql_java_generator.client.domain.forum; import com.graphql_java_generator.client.response.AbstractCustomScalarDeserializer; import com.graphql_java_generator.customscalars.GraphQLScalarTypeDate; /** * @author EtienneSF */ public class CustomScalarDeserializerDate extends AbstractCustomScalarDeserializer<java.util.Date> { private static final long serialVersionUID = 1L; protected CustomScalarDeserializerDate() { super(java.util.Date.class, new GraphQLScalarTypeDate()); } }
true
09ab260b4de29f142e1b9e2da15a755a4a7eb495
Java
calystamerina/weedu
/app/src/main/java/com/telkom/weedu/view/login/LoginPresenter.java
UTF-8
1,771
2.046875
2
[]
no_license
package com.telkom.weedu.view.login; import com.telkom.weedu.base.BasePresenter; import com.telkom.weedu.data.DataManager; import com.telkom.weedu.data.api.ApiCallback; import com.telkom.weedu.data.api.model.Profile; import com.telkom.weedu.data.api.model.request.LoginRequest; import com.telkom.weedu.data.api.model.response.LoginResponse; import javax.inject.Inject; import io.smooch.core.User; /** * Created by sidiqpermana on 3/29/17. */ public class LoginPresenter<V extends LoginView> extends BasePresenter<V> implements ILoginPresenter<V> , ApiCallback.OnLoginRequestCallback { @Inject public LoginPresenter(DataManager dataManager) { super(dataManager); } @Override public void openMainActivity() { getView().toMainActivity(); } @Override public void openRegisterActivity() { getView().toRegisterActivity(); } @Override public void onLoginRequestSuccess(LoginResponse loginResponse) { getView().hideLoading(); getDataManager().saveUserPreference(loginResponse.getResult()); setSmoochUser(loginResponse.getResult().getProfile()); getView().toMainActivity(); } @Override public void onLoginRequestFailed(String errorMessage) { getView().hideLoading(); getView().showToast(errorMessage); } @Override public void postLoginRequest(LoginRequest loginRequest) { getDataManager().login(loginRequest, this); getView().showLoading(); } private void setSmoochUser(Profile profile) { User.getCurrentUser().setFirstName(profile.getFirstName()); User.getCurrentUser().setLastName(profile.getLastName()); User.getCurrentUser().setEmail(profile.getEdumail()); } }
true
c453096d96290bf92948222dd387ad736073831d
Java
zeroLJ/GraduationDesign
/WebProject/VoiceNote/src/database/query/NoteQuery.java
WINDOWS-1252
2,149
2.40625
2
[]
no_license
package database.query; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import datasourse.BaseEntity; import datasourse.BaseQuery; import database.entity.Note; import datasourse.queryField.StringFieldQuery; import datasourse.queryField.DateTimeFieldQuery; import datasourse.queryField.NumberFieldQuery; import datasourse.type.FieldType; /** * @author ljl * note ѯ * 2018-07-26 02:18 */ public class NoteQuery extends BaseQuery { private final static List<String> NAMELIST = Collections.unmodifiableList(Arrays.asList(new String[]{"name","title","message","addTime","editTime","audioPath","asd"})); private final static List<FieldType> TYPELIST = Collections.unmodifiableList(Arrays.asList(new FieldType[]{FieldType.STRING,FieldType.STRING,FieldType.STRING,FieldType.DATETIME,FieldType.DATETIME,FieldType.STRING,FieldType.NUMBER})); private final static Map<String,Integer> FIELDPOSITION; private final static String tablename = "note"; static{ Map<String,Integer> m = new HashMap<String,Integer>(); for(int i=0;i<NAMELIST.size();i++){ m.put(NAMELIST.get(i), i); } FIELDPOSITION = Collections.unmodifiableMap(m); } @Override public Class<? extends BaseEntity> getEntityClass(){ return Note.class; } @Override public String getTableName() { return tablename; } @Override public List<String> getFieldNames() { return NAMELIST; } @Override public List<FieldType> getFieldTypes() { return TYPELIST; } @Override public Map<String, Integer> getFieldPositionMap() { return FIELDPOSITION; } public StringFieldQuery Field_Name() { return getStringField(0); } public StringFieldQuery Field_Title() { return getStringField(1); } public StringFieldQuery Field_Message() { return getStringField(2); } public DateTimeFieldQuery Field_AddTime() { return getDateTimeField(3); } public DateTimeFieldQuery Field_EditTime() { return getDateTimeField(4); } public StringFieldQuery Field_AudioPath() { return getStringField(5); } public NumberFieldQuery Field_Asd() { return getNumberField(6); } }
true
7b1b917ca919835ab03c434469a5ed5a246af983
Java
FatemaMahmoud/SecureYourFiles
/Encryption_Decryption/src/encryption_decryption/GenerateKeys.java
UTF-8
1,740
3.125
3
[]
no_license
package encryption_decryption; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.PublicKey; import java.util.logging.Level; import java.util.logging.Logger; public class GenerateKeys { private KeyPairGenerator keyGen; private KeyPair pair; private PrivateKey privateKey; private PublicKey publicKey; public GenerateKeys() { try { this.keyGen = KeyPairGenerator.getInstance("RSA"); this.keyGen.initialize(2048); } catch (NoSuchAlgorithmException ex) { Logger.getLogger(GenerateKeys.class.getName()).log(Level.SEVERE, null, ex); } } public void createKeys() { this.pair = this.keyGen.generateKeyPair(); this.privateKey = pair.getPrivate(); this.publicKey = pair.getPublic(); this.writeToFile("myPublicKey", this.publicKey.getEncoded()); this.writeToFile("myPrivateKey", this.privateKey.getEncoded()); } public PrivateKey getPrivateKey() { return this.privateKey; } public PublicKey getPublicKey() { return this.publicKey; } private void writeToFile(String path, byte[] key){ try { File f = new File(path); FileOutputStream fos = new FileOutputStream(f); fos.write(key); fos.flush(); fos.close(); } catch (IOException ex) { Logger.getLogger(GenerateKeys.class.getName()).log(Level.SEVERE, null, ex); } } }
true
abfd0fcf9cc5c6580cd5feac5cc3c242db0eb9a7
Java
centic9/commons-collections
/src/test/java/org/apache/commons/collections4/iterators/IteratorIterableTest.java
UTF-8
2,550
2.40625
2
[ "Apache-2.0", "LicenseRef-scancode-generic-cla" ]
permissive
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with this * work for additional information regarding copyright ownership. The ASF * licenses this file to You under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law * or agreed to in writing, software distributed under the License is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the specific language * governing permissions and limitations under the License. */ package org.apache.commons.collections4.iterators; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import junit.framework.Test; import org.apache.commons.collections4.BulkTest; /** * Tests for IteratorIterable. * */ public class IteratorIterableTest extends BulkTest { public static Test suite() { return BulkTest.makeSuite(IteratorIterableTest.class); } public IteratorIterableTest(final String name) { super(name); } private Iterator<Integer> createIterator() { final List<Integer> list = new ArrayList<>(); list.add(Integer.valueOf(0)); list.add(Integer.valueOf(1)); list.add(Integer.valueOf(2)); final Iterator<Integer> iter = list.iterator(); return iter; } @SuppressWarnings("unused") public void testIterator() { final Iterator<Integer> iter = createIterator(); final Iterable<Number> iterable = new IteratorIterable<>(iter); // first use verifyIteration(iterable); // second use for (final Number actual : iterable) { fail("should not be able to iterate twice"); } } public void testMultipleUserIterator() { final Iterator<Integer> iter = createIterator(); final Iterable<Number> iterable = new IteratorIterable<>(iter, true); // first use verifyIteration(iterable); // second use verifyIteration(iterable); } private void verifyIteration(final Iterable<Number> iterable) { int expected = 0; for (final Number actual : iterable) { assertEquals(expected, actual.intValue()); ++expected; } assertTrue(expected > 0); } }
true
54c9111fdcec10b024a163b8f4d181fddacd1b68
Java
chokkoyamada/teachyourselfjava
/src/com/kirishikistudios/Exam4/Exam4_4.java
UTF-8
676
2.859375
3
[]
no_license
package com.kirishikistudios.Exam4; /** * User: yamadanaoyuki * Date: 2013/04/21 * Time: 19:28 */ public class Exam4_4 { public static void main(String args[]) { fibonnacchi(); replacefor(); } private static void replacefor() { int i = 0; while(i<10){ System.out.println(i); i = i+2; } } private static void fibonnacchi() { int prev = 0; int succ = 1; int count = 0; do { int next = prev + succ; prev = succ; succ = next; System.out.println(next); count++; }while(count < 15); } }
true
03e36ea40b108115c331211c7f19bd0a9a5cb54e
Java
gauBep/bc2016-gene
/src/core/genj/option/MultipleChoiceOption.java
UTF-8
3,551
2.453125
2
[]
no_license
/** * GenJ - GenealogyJ * * Copyright (C) 1997 - 2002 Nils Meier <nils@meiers.net> * * This piece of code is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of the * License, or (at your option) any later version. * * This code is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package genj.option; import genj.util.Registry; import javax.swing.DefaultComboBoxModel; import javax.swing.JComboBox; import javax.swing.JComponent; /** * A multiple choice Option */ public abstract class MultipleChoiceOption extends PropertyOption { /** wrapped option */ private PropertyOption option; /** constructor */ protected MultipleChoiceOption(PropertyOption option) { super(option.instance, option.getProperty()); this.option = option; } /** restore */ public void restore(Registry r) { option.restore(r); } public void restore() { option.restore(); } /** persist */ public void persist(Registry r) { option.persist(r); } public void persist() { option.persist(); } /** name */ public String getName() { return option.getName(); } /** name */ public void setName(String set) { option.setName(set); } /** tool tip */ public String getToolTip() { return option.getToolTip(); } /** tool tip */ public void setToolTip(String set) { option.setToolTip(set); } /** value */ public Object getValue() { return option.getValue(); } /** value */ public void setValue(Object set) { option.setValue(set); } /** ui access */ public OptionUI getUI(OptionsWidget widget) { return new UI(); } /** getter for index */ protected int getIndex() { return ((Integer)option.getValue()).intValue(); } /** setter for index */ protected void setIndex(int i) { option.setValue(new Integer(i)); } /** getter for choice */ protected Object getChoice() { Object[] choices = getChoices(); int i = getIndex(); return i<0||i>choices.length-1 ? null : choices[i]; } /** accessor choices */ public final Object[] getChoices() { try { return getChoicesImpl(); } catch (Throwable t) { return new Object[0]; } } /** accessor impl */ protected abstract Object[] getChoicesImpl() throws Throwable; /** * our UI */ public class UI extends JComboBox implements OptionUI { /** constructor */ private UI() { Object[] choices = getChoices(); setModel(new DefaultComboBoxModel(choices)); int index = getIndex(); if (index<0||index>choices.length-1) index = -1; setSelectedIndex(index); } /** component representation */ public JComponent getComponentRepresentation() { return this; } /** text representation */ public String getTextRepresentation() { Object result = getChoice(); return result!=null ? result.toString() : ""; } /** commit */ public void endRepresentation() { setIndex(getSelectedIndex()); } } //UI } //MultipleChoiceOption
true
b968ac3015a41e0254972fa60a8659da740ee396
Java
olenagerasimova/sm-pcount
/src/main/java/com/olenagerasimova/pcount/GsmValidator.java
UTF-8
5,462
2.03125
2
[ "MIT" ]
permissive
/* * MIT License * * Copyright (c) 2020 olenagerasimova * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.olenagerasimova.pcount; import java.nio.charset.Charset; /** * Group Special Mobile class can determine whether message is gsm or not. * @since 1.0 */ final class GsmValidator { /** * GsmValidator to unicode table. * @checkstyle ConstantNameCheck * @checkstyle RegexpMultilineCheck */ @SuppressWarnings("PMD.FieldNamingConventions") private static final int[] GSM_2_UNICODE = { // At Pd DO Ye e! e' u! i! // o! C, LF O/ o/ CR AA aa 0x0040, 0x00A3, 0x0024, 0x00A5, 0x00E8, 0x00E9, 0x00F9, 0x00EC, 0x00F2, 0x00C7, 0x000A, 0x00D8, 0x00F8, 0x000D, 0x00C5, 0x00E5, // D* _ F* G* L* W* P* Q* // S* H* C* EC AE ae ss E' 0x0394, 0x005F, 0x03A6, 0x0393, 0x039B, 0x03A9, 0x03A0, 0x03A8, 0x03A3, 0x0398, 0x039E, 0x001B, 0x00C6, 0x00E6, 0x00DF, 0x00C9, // SP ! " NS Cu % & ' // ( ) * + , - . / 0x0020, 0x0021, 0x0022, 0x0023, 0x00A4, 0x0025, 0x0026, 0x0027, 0x0028, 0x0029, 0x002A, 0x002B, 0x002C, 0x002D, 0x002E, 0x002F, // 0 1 2 3 4 5 6 7 // 8 9 : ; < = > ? 0x0030, 0x0031, 0x0032, 0x0033, 0x0034, 0x0035, 0x0036, 0x0037, 0x0038, 0x0039, 0x003A, 0x003B, 0x003C, 0x003D, 0x003E, 0x003F, // !I A B C D E F G // H I J K L M N O 0x00A1, 0x0041, 0x0042, 0x0043, 0x0044, 0x0045, 0x0046, 0x0047, 0x0048, 0x0049, 0x004A, 0x004B, 0x004C, 0x004D, 0x004E, 0x004F, // P Q R S T U V W // X Y Z A: O: N? U: SE 0x0050, 0x0051, 0x0052, 0x0053, 0x0054, 0x0055, 0x0056, 0x0057, 0x0058, 0x0059, 0x005A, 0x00C4, 0x00D6, 0x00D1, 0x00DC, 0x00A7, // ?I a b c d e f g // h i j k l m n o 0x00BF, 0x0061, 0x0062, 0x0063, 0x0064, 0x0065, 0x0066, 0x0067, 0x0068, 0x0069, 0x006A, 0x006B, 0x006C, 0x006D, 0x006E, 0x006F, // p q r s t u v w // x y z a: o: n? u: a! 0x0070, 0x0071, 0x0072, 0x0073, 0x0074, 0x0075, 0x0076, 0x0077, 0x0078, 0x0079, 0x007A, 0x00E4, 0x00F6, 0x00F1, 0x00FC, 0x00E0, }; /** * GSM extension for utf16. */ private static final int[] GSM_EXT_UTF16 = { 0x005E, 0x007B, 0x007D, 0x005C, 0x005B, 0x007E, 0x005D, 0x007C, 0x20AC, }; /** * GSM extension. */ private static final int[] GSM_EXT_GSM = { 0x14, 0x28, 0x29, 0x2F, 0x3C, 0x3D, 0x3E, 0x40, 0x65, }; /** * Short Message. */ private final String message; /** * Ctor. * @param message Short message */ GsmValidator(final String message) { this.message = message; } /** * Determine where message has only gsm default chars. * @return True if message contains GSM symbols only * @checkstyle IllegalTokenCheck (10 lines) * @checkstyle MagicNumberCheck (10 lines) */ boolean isGsm() { final byte[] bytes = this.message.getBytes(Charset.forName("UTF-16BE")); int idx = 0; boolean res = true; while (idx < bytes.length) { final int code = ((int) bytes[idx++] & 0xFF) << 8 | ((int) bytes[idx++] & 0xFF); if (GsmValidator.gsmCode(code) < 0 && GsmValidator.gsmExtensionCode(code) < 0) { res = false; break; } } return res; } /** * Returns GSM code for unicode. * @param unicode Unicode * @return GSM code if exists and -1 if not */ private static int gsmCode(final int unicode) { int res = -1; for (int cur = 0; cur < GsmValidator.GSM_2_UNICODE.length; cur = cur + 1) { if (unicode == GsmValidator.GSM_2_UNICODE[cur]) { res = cur; break; } } return res; } /** * Returns GSM extension code for unicode. * @param unicode Unicode * @return GSM extension code if exists and -1 if not */ private static int gsmExtensionCode(final int unicode) { int res = -1; for (int cur = 0; cur < GsmValidator.GSM_EXT_UTF16.length; cur = cur + 1) { if (GsmValidator.GSM_EXT_UTF16[cur] == unicode) { res = GsmValidator.GSM_EXT_GSM[cur]; break; } } return res; } }
true
2a3ccf61de17875b1eb42f6b840bfd7026719130
Java
jessemull/MicroFlex
/src/main/java/com/github/jessemull/microflex/util/ValUtil.java
UTF-8
22,412
2.421875
2
[ "Apache-2.0" ]
permissive
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* -------------------------- Package Declaration --------------------------- */ package com.github.jessemull.microflex.util; /* ------------------------------ Dependencies ------------------------------ */ import java.util.Collection; import com.google.common.base.Preconditions; import com.github.jessemull.microflex.bigdecimalflex.plate.PlateBigDecimal; import com.github.jessemull.microflex.bigdecimalflex.plate.WellBigDecimal; import com.github.jessemull.microflex.bigdecimalflex.plate.WellSetBigDecimal; import com.github.jessemull.microflex.bigintegerflex.plate.PlateBigInteger; import com.github.jessemull.microflex.bigintegerflex.plate.WellBigInteger; import com.github.jessemull.microflex.bigintegerflex.plate.WellSetBigInteger; import com.github.jessemull.microflex.doubleflex.plate.PlateDouble; import com.github.jessemull.microflex.doubleflex.plate.WellDouble; import com.github.jessemull.microflex.doubleflex.plate.WellSetDouble; import com.github.jessemull.microflex.integerflex.plate.PlateInteger; import com.github.jessemull.microflex.integerflex.plate.WellInteger; import com.github.jessemull.microflex.integerflex.plate.WellSetInteger; import com.github.jessemull.microflex.plate.WellIndex; import com.github.jessemull.microflex.plate.WellList; /** * This class validates well, well sets, plates and stacks by checking for null * values and wells outside a range of indices. * * @author Jesse L. Mull * @update Updated Oct 18, 2016 * @address http://www.jessemull.com * @email hello@jessemull.com */ public class ValUtil { /*------- Methods for validating double wells, well sets and plates ------*/ /** * Validates the set by checking for wells outside the valid range. * @param int the number of plate rows * @param int the number of plate columns * @param WellSetDouble the well set to validate */ public static void validateSet(int rows, int columns, WellSetDouble set) { if(set == null) { throw new NullPointerException("The well set cannot be null."); } for(WellDouble well : set) { if(well.row() > rows || well.column() > columns) { throw new IllegalArgumentException("Invalid well indices for well: " + well.toString() + " in well set: " + set.toString()); } } } /** * Validates the well by checking for invalid indices. * @param int the number of plate rows * @Param int columns the number of plate columns * @param Well the well to validate */ public static void validateWell(int rows, int columns, WellDouble well) { if(well == null) { throw new NullPointerException("The well cannot be null."); } if(well.row() > rows || well.column() > columns) { throw new IllegalArgumentException("Invalid well indices for well: " + well.toString()); } } /** * Validates the plate by checking for null values and invalid dimensions. * @param PlateDouble the first plate * @param PlateDouble the second plate */ public static void validatePlateDouble(PlateDouble plate1, PlateDouble plate2) { Preconditions.checkNotNull(plate1, "Plates cannot be null."); Preconditions.checkNotNull(plate2, "Plates cannot be null."); Preconditions.checkArgument(plate1.rows() == plate2.rows() || plate1.columns() == plate2.columns(), "Unequal plate dimensions."); } /** * Validates each plate in the collection by checking for null values and * invalid dimensions. * @param PlateDouble the plate * @param Collection<PlateDouble> the plate collection */ public static void validatePlateDouble(PlateDouble plate1, Collection<PlateDouble> collection) { for(PlateDouble plate2 : collection) { validatePlateDouble(plate1, plate2); } } /** * Validate each plate by checking for null values and invalid dimensions. * @param PlateDouble[] the plate array */ public static void validatePlateDouble(PlateDouble plate1, PlateDouble[] array) { for(PlateDouble plate2 : array) { validatePlateDouble(plate1, plate2); } } /** * Validates the plate by checking for null values and invalid dimensions. * @param int the number of rows * @param int the number of columns * @param PlateDouble the second plate */ public static void validatePlateDouble(int rows, int columns, PlateDouble plate) { Preconditions.checkNotNull(plate, "Plate cannot be null."); Preconditions.checkArgument(plate.rows() == rows || plate.columns() == columns, "Invalid plate dimensions."); } /** * Validates each plate in the collection by checking for null values and * invalid dimensions. * @param int the number of rows * @param int the number of columns * @param Collection<PlateDouble> the plate collection */ public static void validatePlateDouble(int row, int column, Collection<PlateDouble> collection) { for(PlateDouble plate : collection) { validatePlateDouble(row, column, plate); } } /** * Validates each plate by checking for null values and invalid dimensions. * @param int the number of rows * @param int the number of columns * @param PlateDouble[] the plate array */ public static void validatePlateDouble(int row, int column, PlateDouble[] array) { for(PlateDouble plate : array) { validatePlateDouble(row, column, plate); } } /*------ Methods for validating integer wells, well sets and plates ------*/ /** * Validates the set by checking for wells outside the valid range. * @param int the number of plate rows * @param int the number of plate columns * @param WellSetInteger the well set to validate */ public static void validateSet(int rows, int columns, WellSetInteger set) { if(set == null) { throw new NullPointerException("The well set cannot be null."); } for(WellInteger well : set) { if(well.row() > rows || well.column() > columns) { throw new IllegalArgumentException("Invalid well indices for well: " + well.toString() + " in well set: " + set.toString()); } } } /** * Validates the well by checking for invalid indices. * @param int the number of plate rows * @Param int columns the number of plate columns * @param Well the well to validate */ public static void validateWell(int rows, int columns, WellInteger well) { if(well == null) { throw new NullPointerException("The well cannot be null."); } if(well.row() > rows || well.column() > columns) { throw new IllegalArgumentException("Invalid well indices for well: " + well.toString()); } } /** * Validates the plate by checking for null values and invalid dimensions. * @param PlateInteger the first plate * @param PlateInteger the second plate */ public static void validatePlateInteger(PlateInteger plate1, PlateInteger plate2) { Preconditions.checkNotNull(plate1, "Plates cannot be null."); Preconditions.checkNotNull(plate2, "Plates cannot be null."); Preconditions.checkArgument(plate1.rows() == plate2.rows() || plate1.columns() == plate2.columns(), "Unequal plate dimensions."); } /** * Validates each plate in the collection by checking for null values and * invalid dimensions. * @param PlateInteger the plate * @param Collection<PlateInteger> the plate collection */ public static void validatePlateInteger(PlateInteger plate1, Collection<PlateInteger> collection) { for(PlateInteger plate2 : collection) { validatePlateInteger(plate1, plate2); } } /** * Validate each plate by checking for null values and invalid dimensions. * @param PlateInteger[] the plate array */ public static void validatePlateInteger(PlateInteger plate1, PlateInteger[] array) { for(PlateInteger plate2 : array) { validatePlateInteger(plate1, plate2); } } /** * Validates the plate by checking for null values and invalid dimensions. * @param int the number of rows * @param int the number of columns * @param PlateInteger the second plate */ public static void validatePlateInteger(int rows, int columns, PlateInteger plate) { Preconditions.checkNotNull(plate, "Plate cannot be null."); Preconditions.checkArgument(plate.rows() == rows && plate.columns() == columns, "Invalid plate dimensions."); } /** * Validates each plate in the collection by checking for null values and * invalid dimensions. * @param int the number of rows * @param int the number of columns * @param Collection<PlateInteger> the plate collection */ public static void validatePlateInteger(int row, int column, Collection<PlateInteger> collection) { for(PlateInteger plate : collection) { validatePlateInteger(row, column, plate); } } /** * Validates each plate by checking for null values and invalid dimensions. * @param int the number of rows * @param int the number of columns * @param PlateInteger[] the plate array */ public static void validatePlateInteger(int row, int column, PlateInteger[] array) { for(PlateInteger plate : array) { validatePlateInteger(row, column, plate); } } /*----- Methods for validating BigDecimal wells, well sets and plates ----*/ /** * Validates the set by checking for wells outside the valid range. * @param int the number of plate rows * @param int the number of plate columns * @param WellSetBigDecimal the well set to validate */ public static void validateSet(int rows, int columns, WellSetBigDecimal set) { if(set == null) { throw new NullPointerException("The well set cannot be null."); } for(WellBigDecimal well : set) { if(well.row() > rows || well.column() > columns) { throw new IllegalArgumentException("Invalid well indices for well: " + well.toString() + " in well set: " + set.toString()); } } } /** * Validates the well by checking for invalid indices. * @param int the number of plate rows * @Param int columns the number of plate columns * @param Well the well to validate */ public static void validateWell(int rows, int columns, WellBigDecimal well) { if(well == null) { throw new NullPointerException("The well cannot be null."); } if(well.row() > rows || well.column() > columns) { throw new IllegalArgumentException("Invalid well indices for well: " + well.toString()); } } /** * Validates the plate by checking for null values and invalid dimensions. * @param PlateBigDecimal the first plate * @param PlateBigDecimal the second plate */ public static void validatePlateBigDecimal(PlateBigDecimal plate1, PlateBigDecimal plate2) { Preconditions.checkNotNull(plate1, "Plates cannot be null."); Preconditions.checkNotNull(plate2, "Plates cannot be null."); Preconditions.checkArgument(plate1.rows() == plate2.rows() || plate1.columns() == plate2.columns(), "Unequal plate dimensions."); } /** * Validates each plate in the collection by checking for null values and * invalid dimensions. * @param PlateBigDecimal the plate * @param Collection<PlateBigDecimal> the plate collection */ public static void validatePlateBigDecimal(PlateBigDecimal plate1, Collection<PlateBigDecimal> collection) { for(PlateBigDecimal plate2 : collection) { validatePlateBigDecimal(plate1, plate2); } } /** * Validate each plate by checking for null values and invalid dimensions. * @param PlateBigDecimal[] the plate array */ public static void validatePlateBigDecimal(PlateBigDecimal plate1, PlateBigDecimal[] array) { for(PlateBigDecimal plate2 : array) { validatePlateBigDecimal(plate1, plate2); } } /** * Validates the plate by checking for null values and invalid dimensions. * @param int the number of rows * @param int the number of columns * @param PlateBigDecimal the second plate */ public static void validatePlateBigDecimal(int rows, int columns, PlateBigDecimal plate) { Preconditions.checkNotNull(plate, "Plate cannot be null."); Preconditions.checkArgument(plate.rows() == rows || plate.columns() == columns, "Invalid plate dimensions."); } /** * Validates each plate in the collection by checking for null values and * invalid dimensions. * @param int the number of rows * @param int the number of columns * @param Collection<PlateBigDecimal> the plate collection */ public static void validatePlateBigDecimal(int row, int column, Collection<PlateBigDecimal> collection) { for(PlateBigDecimal plate : collection) { validatePlateBigDecimal(row, column, plate); } } /** * Validates each plate by checking for null values and invalid dimensions. * @param int the number of rows * @param int the number of columns * @param PlateBigDecimal[] the plate array */ public static void validatePlateBigDecimal(int row, int column, PlateBigDecimal[] array) { for(PlateBigDecimal plate : array) { validatePlateBigDecimal(row, column, plate); } } /*----- Methods for validating BigInteger wells, well sets and plates ----*/ /** * Validates the set by checking for wells outside the valid range. * @param int the number of plate rows * @param int the number of plate columns * @param WellSetBigInteger the well set to validate */ public static void validateSet(int rows, int columns, WellSetBigInteger set) { if(set == null) { throw new NullPointerException("The well set cannot be null."); } for(WellBigInteger well : set) { if(well.row() > rows || well.column() > columns) { throw new IllegalArgumentException("Invalid well indices for well: " + well.toString() + " in well set: " + set.toString()); } } } /** * Validates the well by checking for invalid indices. * @param int the number of plate rows * @Param int columns the number of plate columns * @param Well the well to validate */ public static void validateWell(int rows, int columns, WellBigInteger well) { if(well == null) { throw new NullPointerException("The well cannot be null."); } if(well.row() > rows || well.column() > columns) { throw new IllegalArgumentException("Invalid well indices for well: " + well.toString()); } } /** * Validates the plate by checking for null values and invalid dimensions. * @param PlateBigInteger the first plate * @param PlateBigInteger the second plate */ public static void validatePlateBigInteger(PlateBigInteger plate1, PlateBigInteger plate2) { Preconditions.checkNotNull(plate1, "Plates cannot be null."); Preconditions.checkNotNull(plate2, "Plates cannot be null."); Preconditions.checkArgument(plate1.rows() == plate2.rows() || plate1.columns() == plate2.columns(), "Unequal plate dimensions."); } /** * Validates each plate in the collection by checking for null values and * invalid dimensions. * @param PlateBigInteger the plate * @param Collection<PlateBigInteger> the plate collection */ public static void validatePlateBigInteger(PlateBigInteger plate1, Collection<PlateBigInteger> collection) { for(PlateBigInteger plate2 : collection) { validatePlateBigInteger(plate1, plate2); } } /** * Validate each plate by checking for null values and invalid dimensions. * @param PlateBigInteger[] the plate array */ public static void validatePlateBigInteger(PlateBigInteger plate1, PlateBigInteger[] array) { for(PlateBigInteger plate2 : array) { validatePlateBigInteger(plate1, plate2); } } /** * Validates the plate by checking for null values and invalid dimensions. * @param int the number of rows * @param int the number of columns * @param PlateBigInteger the second plate */ public static void validatePlateBigInteger(int rows, int columns, PlateBigInteger plate) { Preconditions.checkNotNull(plate, "Plate cannot be null."); Preconditions.checkArgument(plate.rows() == rows || plate.columns() == columns, "Invalid plate dimensions."); } /** * Validates each plate in the collection by checking for null values and * invalid dimensions. * @param int the number of rows * @param int the number of columns * @param Collection<PlateBigInteger> the plate collection */ public static void validatePlateBigInteger(int row, int column, Collection<PlateBigInteger> collection) { for(PlateBigInteger plate : collection) { validatePlateBigInteger(row, column, plate); } } /** * Validates each plate by checking for null values and invalid dimensions. * @param int the number of rows * @param int the number of columns * @param PlateBigInteger[] the plate array */ public static void validatePlateBigInteger(int row, int column, PlateBigInteger[] array) { for(PlateBigInteger plate : array) { validatePlateBigInteger(row, column, plate); } } /** * Validates the group by checking for wells outside the valid range. * @param int the number of plate rows * @param int the number of plate columns * @param WellList the group */ public static void validateGroup(int rows, int columns, WellList list) { if(list == null) { throw new NullPointerException("The well set cannot be null."); } for(WellIndex index : list) { if(index.row() > rows || index.column() > columns) { throw new IllegalArgumentException("Invalid well indices for well: " + index.toString() + " in well group: " + list.toString()); } } } }
true
f690b498f95360ea516650bd20899bc4c353b090
Java
charles-marques/dataset-375
/projetos/RESTProvider/src/novoda/lib/rest/actor/TypedActor.java
UTF-8
784
2.125
2
[]
no_license
package novoda.lib.rest.actor; import java.io.IOException; import novoda.lib.rest.marshaller.MarshallingException; import novoda.lib.rest.marshaller.net.HttpResponseMarshaller; import org.apache.http.HttpResponse; import com.novoda.lib.httpservice.actor.Actor; public abstract class TypedActor<To, M extends HttpResponseMarshaller<To>> extends Actor { @Override public void onResponseReceived(HttpResponse httpResponse) { try { onResponseReceived(getMarshaller().marshall(httpResponse)); } catch (IOException e) { e.printStackTrace(); } catch (MarshallingException e) { e.printStackTrace(); } } protected abstract M getMarshaller(); public void onResponseReceived(To data) { } }
true
234b9b3d15c1e2deaf088b36feaa7fcf4bd65f71
Java
eri-tri89/integration_ju14
/scrumboard/src/main/java/se/ju14/scrumboard/model/status/PriorityStatus.java
UTF-8
109
1.609375
2
[]
no_license
package se.ju14.scrumboard.model.status; /*Unused!*/ public enum PriorityStatus { URGENT, NORMAL, LOW }
true
70b66540edaa0cf6f31b87a6db20092837186b05
Java
ajao123/DemoTriagem
/demoTriagem/src/main/java/com/example/demo/Controller/TriagemController.java
UTF-8
3,898
2.25
2
[]
no_license
package com.example.demo.Controller; import java.time.LocalDate; import java.util.List; import java.util.Optional; import javax.servlet.http.HttpServletResponse; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationEventPublisher; import org.springframework.dao.EmptyResultDataAccessException; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import com.example.demo.event.RecursoCriadoEvent; import com.example.demo.model.Triagem; import com.example.demo.repository.TriagemRepository; import com.example.demo.service.TriagemService; import com.example.demo.service.Impl.TriagemServiceImpl; @RestController @RequestMapping("/triagens") public class TriagemController { @Autowired private ApplicationEventPublisher publisher; @Autowired private TriagemService triagemService; @GetMapping public List<Triagem> listar(){ return triagemService.listarTriagens(); } @PostMapping @ResponseStatus(HttpStatus.CREATED) public ResponseEntity<Triagem> criar(@Valid @RequestBody Triagem triagem, HttpServletResponse response) { Triagem triagemSalva = triagemService.salvar(triagem); publisher.publishEvent(new RecursoCriadoEvent(this, response, triagemSalva.getCodigo())); return ResponseEntity.status(HttpStatus.CREATED).body(triagemSalva); } //Buscando um valor no banco de dados @GetMapping("/{codigo}") public ResponseEntity<Triagem> buscarPeloCodigo(@PathVariable Long codigo) { try { return ResponseEntity.ok(triagemService.buscarTriagemPeloCodigo(codigo)); }catch(EmptyResultDataAccessException e) { return ResponseEntity.notFound().build(); } } @DeleteMapping("/{codigo}") @ResponseStatus(HttpStatus.NO_CONTENT) public void remover(@PathVariable Long codigo){ triagemService.remove(codigo); } @PutMapping("/{codigo}") public ResponseEntity<Triagem> atualizar(@PathVariable Long codigo, @Valid @RequestBody Triagem triagem){ try { Triagem triagemSalva = triagemService.atualizarTriagem(codigo, triagem); return ResponseEntity.ok(triagemSalva); }catch(EmptyResultDataAccessException e) { return ResponseEntity.notFound().build(); } } @PutMapping("/{codigo}/sintomas") @ResponseStatus(HttpStatus.NO_CONTENT) public void atualizarPropriedadeSintomas(@PathVariable Long codigo, @RequestBody List<String> sintomas) { triagemService.atualizarPropriedadeSintomas(codigo, sintomas); } @PutMapping("/{codigo}/nome") @ResponseStatus(HttpStatus.NO_CONTENT) public void atualizarPropriedadeNome(@PathVariable Long codigo, @RequestBody String nome) { triagemService.atualizarPropriedadeNome(codigo, nome); } @PutMapping("/{codigo}/pontuacao") @ResponseStatus(HttpStatus.NO_CONTENT) public void atualizarPropriedadePontuacao(@PathVariable Long codigo, @RequestBody Integer pontuacao) { triagemService.atualizarPropriedadePontuacao(codigo, pontuacao); } @PutMapping("/{codigo}/data_triagem") @ResponseStatus(HttpStatus.NO_CONTENT) public void atualizarPropriedadeDataTriagem(@PathVariable Long codigo, @RequestBody LocalDate data_triagem) { triagemService.atualizarPropriedadeDataTriagem(codigo, data_triagem); } }
true
2a99de8c38f272fd890dffc9db41d9e983ee67cd
Java
VisionLau/Study-By-Myself
/Array-Sort-Study/Array/src/main/java/com/vision/test/TestArray.java
UTF-8
864
3.1875
3
[]
no_license
package com.vision.test; import java.util.Arrays; public class TestArray { public static void main(String[] args){ //System.out.println(Arrays.toString(getOneCount())); getOneCount(); } public static void getOneCount(){ //自定义一个数组 找到该数组中只出现一次的元素 int array[]={1,3,5,7,2,3,5,7,2,8}; //int temp[]=new int [array.length]; for (int i = 0; i < array.length; i++) { int count=0; for (int i1 = 0; i1 < array.length; i1++) { if(array[i]==array[i1]){ count+=1; } } if(count==1){ System.out.println(array[i]); // temp[i]=array[i]; // return temp; } //count=0; } //return null; } }
true
5ff06ea528ad499ba983e1cd6e2d883908f47c5a
Java
xrogzu/acheron
/src/main/java/com/dbg/cloud/acheron/plugins/oauth2/authserver/base/introspection/IntrospectionSpec.java
UTF-8
1,379
2.15625
2
[]
no_license
package com.dbg.cloud.acheron.plugins.oauth2.authserver.base.introspection; import com.dbg.cloud.acheron.plugins.oauth2.authserver.base.authentication.AuthenticationOperation; import lombok.AllArgsConstructor; import org.springframework.boot.web.client.RestTemplateBuilder; public interface IntrospectionSpec { IntrospectionOperation operationForToken(String token); @AllArgsConstructor final class Simple implements IntrospectionSpec { private final String introspectionURL; private final String bearerToken; private final RestTemplateBuilder restTemplateBuilder; @Override public IntrospectionOperation operationForToken(final String token) { return new IntrospectionOperation.Simple(introspectionURL, bearerToken, token, restTemplateBuilder); } } @AllArgsConstructor final class IntrospectionSpecWithAuth implements IntrospectionSpec { private final String introspectionURL; private final AuthenticationOperation operation; private final RestTemplateBuilder restTemplateBuilder; @Override public IntrospectionOperation operationForToken(final String token) { return new IntrospectionOperation.IntrospectionOperationWithAuthentication(introspectionURL, operation, token, restTemplateBuilder); } } }
true
43b61738fd428703916a2f986d480d3aeb96a6ab
Java
suetter/gs_j2ee
/MyStore/src/main/java/org/MyStore/bean/ClientBean.java
UTF-8
731
2.140625
2
[]
no_license
package org.MyStore.bean; import java.util.Collection; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import org.MyStore.model.Commande; import org.MyStore.model.Employe; public class ClientBean { private Collection<CommandeBean> commandes; private EmployeBean employe; public Collection<CommandeBean> getCommandes() { return commandes; } public void setCommandes(Collection<CommandeBean> commandes) { this.commandes = commandes; } public EmployeBean getEmploye() { return employe; } public void setEmploye(EmployeBean employe) { this.employe = employe; } public ClientBean() { super(); // TODO Auto-generated constructor stub } }
true
45e4daf57a45774d07481e3d3b7a5d691fc6c6e3
Java
suraj115446/DropWizardJwt
/jwtRest/src/main/java/configuration/JwtRestConfiguration.java
UTF-8
440
1.984375
2
[]
no_license
package configuration; import org.hibernate.validator.constraints.NotEmpty; import com.fasterxml.jackson.annotation.JsonProperty; import io.dropwizard.Configuration; public class JwtRestConfiguration extends Configuration { @NotEmpty private String secretKey; @JsonProperty public String getSecretKey() { return secretKey; } @JsonProperty public void setSecretKey(String secretKey) { this.secretKey = secretKey; } }
true
aba19a37993ac91432b3b86fa37d422342aa6831
Java
wanidasa/Easy-Micro
/app/src/main/java/smt/wanida/esymocro/MainActivity.java
UTF-8
5,705
2.390625
2
[]
no_license
package smt.wanida.esymocro; import android.content.Context; import android.content.Intent; import android.os.AsyncTask; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.squareup.okhttp.OkHttpClient; import com.squareup.okhttp.Request; import com.squareup.okhttp.Response; import org.json.JSONArray; import org.json.JSONObject; public class MainActivity extends AppCompatActivity { // Expllicit การประกาศตัวแปร จะต้ะองอยู่นอก class ทั้งหมด private Button signInbutton, singUpbutton; private EditText userEditText, passEditText; private String userString, passwordString; private MyConstante myConstante; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); myConstante = new MyConstante(); //bind Widget signInbutton = (Button) findViewById(R.id.button); singUpbutton = (Button) findViewById(R.id.button2); userEditText = (EditText) findViewById(R.id.editText4); passEditText = (EditText) findViewById(R.id.editText5); //singUp controller singUpbutton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(MainActivity.this,SignUpActivity.class)); } }); //signIn Create signInbutton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //get value from edit text userString = userEditText.getText().toString().trim(); passwordString = passEditText.getText().toString().trim(); //check space if (userString.equals("") || passwordString.equals("")) { //have space MyAlert myAlert = new MyAlert(MainActivity.this,R.drawable.kon48, getResources().getString(R.string.title_naveSpace) ,getResources().getString(R.string.Message_haveSpace)); myAlert.myDailog(); } else { // no space GetUser getUser = new GetUser(MainActivity.this); getUser.execute(myConstante.getUrlJson()); } } //onclick }); } // Main Method private class GetUser extends AsyncTask<String, Void, String> { private Context context; private String[] nameString, imageString; private String truePasswordString; private boolean aBoolean = true; public GetUser(Context context) { this.context = context; } @Override protected String doInBackground(String... params) { try { OkHttpClient okHttpClient = new OkHttpClient(); Request.Builder builder = new Request.Builder(); Request request = builder.url(params[0]).build(); Response response = okHttpClient.newCall(request).execute(); return response.body().string(); } catch (Exception e) { e.printStackTrace(); return null; } }//doIn @Override protected void onPostExecute(String s) { super.onPostExecute(s); Log.d("6NovV3", "Jsom ==>" + s); try { JSONArray jsonArray = new JSONArray(s); nameString = new String[jsonArray.length()]; imageString = new String[jsonArray.length()]; for (int i=0; i<jsonArray.length();i++) { JSONObject jsonObject = jsonArray.getJSONObject(i); nameString[i] = jsonObject.getString("Name"); imageString[i] = jsonObject.getString("Image"); //check log Log.d("6NovV4", "Name[" + i + "] ==> " + nameString[i]); if (userString.equals(jsonObject.getString("User"))) { aBoolean = false; truePasswordString = jsonObject.getString("Password"); } } // for if (aBoolean) { MyAlert myAlert = new MyAlert(context, R.drawable.rat48, "User False", "No " + userString + " in my Database"); } else if (passwordString.equals(truePasswordString)) { Toast.makeText(context, "Welcome", Toast.LENGTH_SHORT).show(); //Intent Intent intent = new Intent(MainActivity.this, ServiceActivity.class); intent.putExtra("Name", nameString); intent.putExtra("Image", imageString); startActivity(intent); finish(); } else { MyAlert myAlert = new MyAlert(context, R.drawable.bird48, "Password False", "Please try Again... Password False"); myAlert.myDailog(); } } catch (Exception e) { e.printStackTrace(); } }//onpost } // calss } // Main Class นี่คือคลาสหลัก
true
5a093491f388ac0a2510b2cdb28f5041b338ba63
Java
BGCX262/zsgl-svn-to-git
/zsgl/src/main/java/com/zsgl/controller/JnController.java
UTF-8
4,382
2.359375
2
[]
no_license
package com.zsgl.controller; import java.util.List; import org.apache.log4j.Logger; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import com.zsgl.domain.OverseasTour; import com.zsgl.domain.OverseasTourAddress; import com.zsgl.domain.Tour; import com.zsgl.domain.TourType; import com.zsgl.util.Page; /** * 境内外旅游模块 * @author 林超 */ @Controller @RequestMapping({"/jn", "/ajax/jn"}) public class JnController { static final Logger logger = Logger.getLogger(JnController.class); static final String JN_PATH = "jn/"; static final String JN_ADDRESS_PATH = "jn/address/"; /** * 不区分地域,默认显示第一页 * @param model */ @RequestMapping public void jn(Model model) { jn(1, model); } /** * 不去分地域,根据页码显示 * @param page * @param model */ @RequestMapping("{page}") public void jn(@PathVariable int page, Model model) { logger.info(JN_PATH + page); TourType tgn = TourType.findTourType(14L); long count = OverseasTour.countOverseasTours() + Tour.countByType(tgn); Page p = new Page((int) count, page, 10); /* 境外路线 */ List<OverseasTour> tours = OverseasTour.getSortOverseasTour( p.getFirst(), p.getMaxResult()); /* 国内线路 */ List<Tour> gnlvs = Tour.getSortTourByType(tgn, (page - 1) * 0, 8); p.calePages(3, 7); gnlvs.addAll(tours); model.addAttribute("tours", gnlvs); model.addAttribute("page", p); model.addAttribute("JN_PATH", JN_PATH); } /** * 根据地域、页码进行分页显示 * @param address * @param page * @param model */ @RequestMapping("/address/{address}/{page}") public void address(@PathVariable long address, @PathVariable int page, Model model) { String uri = JN_ADDRESS_PATH + address + "/"; logger.info(uri); OverseasTourAddress ota = OverseasTourAddress.findOverseasTourAddress(address); Page p = null; if (ota.getId() == 5) { TourType tgn = TourType.findTourType(14L); model.addAttribute("tours", Tour.getSortTourByType(tgn, (page - 1) * 0, (int)Tour.countByType(tgn))); p = new Page((int)Tour.countByType(tgn), page, (int)Tour.countByType(tgn)); } else { p = new Page((int)OverseasTour.findCount(ota, ""), page, 7); model.addAttribute("tours", OverseasTour.find(ota, "", p.getFirst(), p.getMaxResult())); } model.addAttribute("page", p); model.addAttribute("JN_PATH", uri); } /////////////////////////////////////////////////////// /** * 境内外旅游 * * @param model * @param page * @return */ //@RequestMapping("jlwlv") public String jlwlv(Model model, @RequestParam(required = false, defaultValue = "1") int page) { TourType tgn = TourType.findTourType(14L); long count = OverseasTour.countOverseasTours() + Tour.countByType(tgn); Page p = new Page((int) count, page, 17); if (p.getPage() < 1 || p.getPage() > p.getLast()) { return "redirect:jlwlv?page=1"; } /* 境外路线 */ List<OverseasTour> tours = OverseasTour.getSortOverseasTour( p.getFirst(), p.getMaxResult()); /* 国内线路 */ List<Tour> gnlvs = Tour.getSortTourByType(tgn, (page - 1) * 0, 8); p.calePages(3, 7); gnlvs.addAll(tours); model.addAttribute("tours", gnlvs); /* * model.addAttribute("tours", tours); model.addAttribute("gnlvs", * gnlvs); */ model.addAttribute("page", p); return "jlwlv"; } @RequestMapping("jlw") public String jlw(Model model, @RequestParam(required = false, defaultValue = "0") long city, @RequestParam(required = false, defaultValue = "") String content, @RequestParam(required = false, defaultValue = "1") int page) { OverseasTourAddress otc = OverseasTourAddress.findOverseasTourAddress(city); Page p = new Page((int)OverseasTour.findCount(otc, content), page, 7); model.addAttribute("page", p); model.addAttribute("tours", OverseasTour.find(otc, content, p.getFirst(), p.getMaxResult())); model.addAttribute("uri", "jlw?city=" + city + "&content=" + content + "&page=" + page + "&"); return "jlwlv"; } }
true
74d3b27ca42795591915924d3c13308e170d0c6f
Java
wlhebut/synctest
/src/main/java/com/huntech/pvs/view/services/ServRequest.java
UTF-8
1,793
1.875
2
[]
no_license
package com.huntech.pvs.view.services; import com.huntech.pvs.view.request.PageRequest; public class ServRequest extends PageRequest { private Long id; private Long baseservTypeid;//baseServ-id private Long servManid; private Long servType;//0-baseServ;1-selfServ private Byte state;//状态1 private String longitude;//经度 private String latitude;//纬度 private Integer zoom;//放大级别 private String openid; public String getOpenid() { return openid; } public void setOpenid(String openid) { this.openid = openid; } public String getLongitude() { return longitude; } public void setLongitude(String longitude) { this.longitude = longitude; } public String getLatitude() { return latitude; } public void setLatitude(String latitude) { this.latitude = latitude; } public Integer getZoom() { return zoom; } public void setZoom(Integer zoom) { this.zoom = zoom; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getBaseservTypeid() { return baseservTypeid; } public void setBaseservTypeid(Long baseservTypeid) { this.baseservTypeid = baseservTypeid; } public Long getServManid() { return servManid; } public void setServManid(Long servManid) { this.servManid = servManid; } public Long getServType() { return servType; } public void setServType(Long servType) { this.servType = servType; } public Byte getState() { return state; } public void setState(Byte state) { this.state = state; } }
true
f1de86d020bf18271030556fe67fd25b77ff0120
Java
january89/Nettiemon
/src/main/java/server/HandlersApi.java
UTF-8
360
1.5625
2
[]
no_license
package server; import com.fasterxml.jackson.databind.node.ObjectNode; import org.hibernate.service.spi.ServiceException; import server.service.RequestParamException; interface HandlersApi{ void requestParamValidation() throws RequestParamException; void service() throws ServiceException; void executeService(); ObjectNode getApiResult(); }
true
afc1b3a6bb04521f6b57a2c03fc3653ea940ea75
Java
Lacedaemon/S340_Simulator
/src/s340/software/os/ProcessState.java
UTF-8
341
1.78125
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 s340.software.os; /** * * @author rak */ //giving the process state public enum ProcessState { ready, end, waiting, running; }
true
12a5066ea7bd658e92915d60e58814e803d19f9b
Java
zgeorge2/RAD-Squared
/rad2-sb/src/main/java/com/rad2/sb/res/DeferredRequest.java
UTF-8
2,009
1.953125
2
[ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
/* * Copyright (c) 2019-2020 VMware, Inc. * SPDX-License-Identifier: BSD-2-Clause */ package com.rad2.sb.res; import com.rad2.akka.common.IDeferredRequest; import com.rad2.apps.adm.ignite.JobStatusEnum; import com.rad2.ctrl.deps.IJobRef; import org.springframework.http.ResponseEntity; import org.springframework.web.context.request.async.DeferredResult; import java.util.HashMap; import java.util.Map; /** * Provides a basic wrapper around a Spring request's args and the DeferredResult object. Result type is * String for this implementation. Only String results are supported at this time. TODO: extend for non-Strings */ public class DeferredRequest implements IDeferredRequest<String> { private final static long DEFAULT_TIMEOUT = 2000L; private final Map<String, Object> argsMap; private final DeferredResult<ResponseEntity<String>> result; private final IJobRef ijr; // set up a job ref in case of request timeout. public DeferredRequest(IJobRef ijr) { this(DEFAULT_TIMEOUT, ijr); } private DeferredRequest(long waitTimeForResult, IJobRef ijr) { argsMap = new HashMap<>(); result = new DeferredResult<>(waitTimeForResult); this.ijr = ijr; // set default timeout handling String timeoutMessage = String.format(JobStatusEnum.JOB_TIMEOUT_FORMAT, this.ijr.regId()); result.onTimeout(() -> result.setResult(ResponseEntity.ok(timeoutMessage))); } @Override public Map<String, Object> args() { return argsMap; } @Override public Object arg(String key) { return argsMap.get(key); } @Override public void putArg(String key, Object arg) { argsMap.put(key, arg); } @Override public IJobRef jobRef() { return ijr; } @Override public void setResponse(String res) { getResult().setResult(ResponseEntity.ok(res)); } public DeferredResult<ResponseEntity<String>> getResult() { return result; } }
true
94638d5c68a1acc87dff4ffae882016b43d54670
Java
myejb22/factory-design
/src/main/java/com/dao/impl/XiaoXingXing.java
UTF-8
696
2.875
3
[]
no_license
package com.dao.impl; import com.dao.Person; /** * <p></p> * * @author Andy * @date 2018/3/3. */ public class XiaoXingXing implements Person { private String sex = "女"; private String name = "小星星"; public void findByFriend() { System.out.println("我的名字叫:"+this.name+",性别:"+this.sex); System.out.println("我要找对象的条件:"); System.out.println("1、长相必须要帅;"); System.out.println("2、身高180cm,体重:70kg"); System.out.println("3、有车有房"); } public String getSex() { return this.sex; } public String getName() { return this.name; } }
true
4c69f37ed7e6ff5ab3b4f1362a35620c33e8fc9c
Java
YngJian/meeting-room-reservation
/code/model/src/main/java/com/vayne/model/model/RegisterReq.java
UTF-8
553
2.0625
2
[]
no_license
package com.vayne.model.model; import lombok.Data; import javax.validation.constraints.*; /** * @author : Yang Jian * @date : 2021/6/28 0028 22:38 */ @Data public class RegisterReq { @NotNull @Size(min = 1, max = 64) private String userName; @NotNull @Size(min = 1, max = 256) private String password; @NotNull @Pattern(regexp = "1[0-9]{10}", message = "Phone number format is incorrect!") private String phone; @NotNull @NotEmpty @Email(message = "Email format error!") private String email; }
true
8e14b219bb1919569a13fc695eaa9ac7cc55357f
Java
jcc1110/carrera-java
/Modulo01_FundamentosDeJava/AnthonyHurtado/Proyectos/Excepciones/src/excepciones/MiExcepcion.java
UTF-8
257
2.640625
3
[ "MIT" ]
permissive
package excepciones; // Extendemos de la clase Exception o RuntimeException public class MiExcepcion extends Exception { // Declaro mi constructor y llamo al constructor padre. public MiExcepcion(String _mensaje) { super(_mensaje); } }
true
90c0750038ea5231196870bea0500bfaa45517be
Java
gabrielzanin150/cadastrar
/src/cadastro/view.java
ISO-8859-1
6,190
2.75
3
[]
no_license
package cadastro; import java.awt.BorderLayout; import java.awt.Color; import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import javax.swing.text.MaskFormatter; import javax.swing.JButton; import java.awt.event.ActionListener; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.awt.event.ActionEvent; import javax.swing.JLabel; import javax.swing.JTextField; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import javax.swing.JFormattedTextField; import java.awt.SystemColor; import java.awt.Font; public class view extends JFrame { // criacao da janela principal da aplicacao private JPanel contentPane; private JTextField jTxtnome; private JFormattedTextField jTxtnascimento; private JFormattedTextField jTxtnota; /** * Launch the application. */ public static void main(String[] args) { // funcao para abrir a janela EventQueue.invokeLater(new Runnable() { public void run() { try { view frame = new view(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the frame. */ public view() { int vetor[] = new int[10]; // vetor onde armazena a quantidade de vezes que uma nota aparece no arquivo int i=0; for(i=0; i<9; i++) vetor[i]=0; setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 450, 300); contentPane = new JPanel(); contentPane.setBackground(SystemColor.activeCaption); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); JButton btnCadastrar = new JButton("Cadastrar"); // criaao do botao cadastrar btnCadastrar.setFont(new Font("Sitka Display", Font.BOLD | Font.ITALIC, 14)); btnCadastrar.setBounds(10, 147, 171, 31); btnCadastrar.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Aluno aluno = new Aluno(); // cria um novo cadastro mas ainda nao salva aluno.setNome(jTxtnome.getText()); aluno.setNascimento(jTxtnascimento.getText()); aluno.setNotafinal(jTxtnota.getText()); JOptionPane.showMessageDialog(null,aluno.salvar()); // salva os dados em um arquivo txt com todos os dados e outro apenas com as notas que iro para o vetor jTxtnome.setText(""); // apaga os campos preenchidos logo aps clicar em cadastrar jTxtnascimento.setText(""); jTxtnota.setText(""); } }); contentPane.setLayout(null); contentPane.add(btnCadastrar); JButton btnVisualizar = new JButton("Visualizar"); // criao do botao visualizar btnVisualizar.setFont(new Font("Sitka Display", Font.BOLD | Font.ITALIC, 14)); btnVisualizar.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { NotasVisualizacao notas = new NotasVisualizacao(); notas.setVisible(true); } }); btnVisualizar.setBounds(10, 189, 171, 31); contentPane.add(btnVisualizar); jTxtnome = new JTextField(); jTxtnome.addKeyListener(new KeyAdapter() { // formatao do campo nome para aceitar apenas letras @Override public void keyTyped(KeyEvent e) { char vchar = e.getKeyChar(); if(Character.isDigit(vchar) && !e.isAltDown()) { e.consume(); } } }); jTxtnome.setBounds(10, 33, 171, 20); contentPane.add(jTxtnome); jTxtnome.setColumns(10); try { MaskFormatter mascara = new MaskFormatter("##/##/####"); // formatao do campo data de nascimento jTxtnascimento = new JFormattedTextField(mascara); mascara.setPlaceholderCharacter('_'); } catch (Exception e) { e.printStackTrace(); } jTxtnascimento.setColumns(10); jTxtnascimento.setBounds(10, 77, 171, 20); contentPane.add(jTxtnascimento); jTxtnota = new JFormattedTextField(); jTxtnota.setForeground(SystemColor.windowBorder); jTxtnota.addKeyListener(new KeyAdapter() { @Override public void keyTyped(KeyEvent evt) { // formatao do campo notas char vchar = evt.getKeyChar(); if(Character.isLetter(vchar) && !evt.isAltDown()) { evt.consume(); try { MaskFormatter mask = new MaskFormatter("##.##"); jTxtnota = new JFormattedTextField(mask); } catch (Exception e) { e.printStackTrace(); } jTxtnota.setText(" "); } } }); jTxtnota.setColumns(10); jTxtnota.setBounds(10, 116, 171, 20); contentPane.add(jTxtnota); JLabel lblNome = new JLabel("Nome"); // daqui at o final do cdigo reposvel por criar os campos e nomes que aparecem na tela principal lblNome.setFont(new Font("Tahoma", Font.ITALIC, 11)); lblNome.setBounds(78, 21, 46, 14); contentPane.add(lblNome); JLabel lblNascimento = new JLabel("Nascimento"); lblNascimento.setFont(new Font("Tahoma", Font.ITALIC, 11)); lblNascimento.setBounds(68, 64, 67, 14); contentPane.add(lblNascimento); JLabel lblNota = new JLabel("Nota"); lblNota.setFont(new Font("Tahoma", Font.ITALIC, 11)); lblNota.setBounds(78, 101, 46, 14); contentPane.add(lblNota); JLabel lblCadastrador = new JLabel("Cadastrador"); lblCadastrador.setFont(new Font("Yu Gothic Medium", Font.BOLD | Font.ITALIC, 20)); lblCadastrador.setBounds(255, 33, 156, 45); lblCadastrador.setForeground(SystemColor.text); contentPane.add(lblCadastrador); JLabel lblDe = new JLabel("de"); lblDe.setFont(new Font("Yu Gothic Medium", Font.BOLD | Font.ITALIC, 20)); lblDe.setBackground(SystemColor.text); lblDe.setBounds(292, 77, 46, 14); lblDe.setForeground(SystemColor.text); contentPane.add(lblDe); JLabel lblAlunos = new JLabel("Alunos"); lblAlunos.setFont(new Font("Yu Gothic Medium", Font.BOLD | Font.ITALIC, 20)); lblAlunos.setBounds(265, 101, 109, 35); lblAlunos.setForeground(SystemColor.text); contentPane.add(lblAlunos); } }
true
ef171c60b58eb827480b48b4c159f1794ba7f9b7
Java
trungnguyenduy139/houston123
/app/src/main/java/com/trungnguyen/android/houston123/bus/DeletedUserEvent.java
UTF-8
327
2.0625
2
[]
no_license
package com.trungnguyen.android.houston123.bus; /** * Created by trungnd4 on 21/10/2018. */ public class DeletedUserEvent { private int userPosition; public DeletedUserEvent(int userPosition) { this.userPosition = userPosition; } public int getUserPosition() { return userPosition; } }
true
460a6dea34e8bce672fdec102dd6b4c8347f6013
Java
catalinadg98/proyectoJAVA
/src/Alumno.java
UTF-8
680
2.71875
3
[]
no_license
/*public abstract class Alumno extends Persona { private String matricula; private String gene; private Materia materias[]; public Alumno(){ matricula=""; gene=""; materias = new Materia[6]; } public Alumno(String nombre, String fechaNac, char genero, String matricula, String gene, int[] materias){ super(nombre, fechaNac, genero); this.matricula=matricula; this.gene=gene; this.materias = new Materia[6]; this.materias=materias; } public void setHorario(){ return Horario; } public void setMaterias(Materia[] materias){ } public Horario getHorario(){ } */
true
b1ff74b0cf048777cf7d515cb4d980b1aa7139c9
Java
nickbouldien/fizzbuzz-java
/src/main/java/fizzbuzz/FizzBuzzTest.java
UTF-8
1,972
2.953125
3
[]
no_license
package fizzbuzz; import java.util.HashMap; import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; public class FizzBuzzTest { public FizzBuzz fizzbuzz = new FizzBuzz(); @Test public void testReturnsCorrectResults1() { HashMap<String, Integer> expectedResult = new HashMap<String, Integer>(); expectedResult.put("lucky", 0); expectedResult.put("fizzbuzz", 0); expectedResult.put("fizz", 0); expectedResult.put("buzz", 0); expectedResult.put("integer", 2); HashMap<String, Integer> res = fizzbuzz.run(2, 3); assertEquals(res.get("lucky"), expectedResult.get("lucky")); assertEquals(res.get("fizzbuzz"), expectedResult.get("fizzbuzz")); assertEquals(res.get("fizz"), expectedResult.get("fizz")); assertEquals(res.get("buzz"), expectedResult.get("buzz")); assertEquals(res.get("integer"), expectedResult.get("integer")); } @Test public void testReturnsCorrectResults2() { HashMap<String, Integer> expectedResult = new HashMap<String, Integer>(); expectedResult.put("lucky", 2); expectedResult.put("fizzbuzz", 1); expectedResult.put("fizz", 4); expectedResult.put("buzz", 3); expectedResult.put("integer", 10); HashMap<String, Integer> res = fizzbuzz.run(20, 3); assertEquals(res.get("lucky"), expectedResult.get("lucky")); assertEquals(res.get("fizzbuzz"), expectedResult.get("fizzbuzz")); assertEquals(res.get("fizz"), expectedResult.get("fizz")); assertEquals(res.get("buzz"), expectedResult.get("buzz")); assertEquals(res.get("integer"), expectedResult.get("integer")); } @Test public void testHasDigit() { assertTrue(fizzbuzz.hasDigit(3, 13)); assertTrue(fizzbuzz.hasDigit(3, 23)); assertFalse(fizzbuzz.hasDigit(3, 15)); assertFalse(fizzbuzz.hasDigit(7, 192)); } }
true
5e9beeef7197aad6df5312b965036bd97105ed58
Java
jcxavier/pong-gl
/src/com/jcxavier/game/gl/player/Player.java
UTF-8
502
2.921875
3
[]
no_license
package com.jcxavier.game.gl.player; import com.jcxavier.game.gl.logic.Pad; /** * Created on 10/07/2013. * * @author João Xavier <jcxavier@jcxavier.com> */ public abstract class Player { final Pad mPad; private int mPoints; Player(Pad pad) { mPad = pad; mPoints = 0; } public abstract void play(float speed); public int getPoints() { return mPoints; } public Pad getPad() { return mPad; } public void score() { mPoints++; } }
true
3b2e7780a5c2cf7acc8576b397ea046da1775bcf
Java
jaaasonwu/playgroundideas
/app/src/main/java/com/playgroundideas/playgroundideas/di/screens/ViewModelModule.java
UTF-8
1,946
1.773438
2
[]
no_license
package com.playgroundideas.playgroundideas.di.screens; import android.arch.lifecycle.ViewModel; import android.arch.lifecycle.ViewModelProvider; import com.playgroundideas.playgroundideas.viewmodel.DesignListViewModel; import com.playgroundideas.playgroundideas.viewmodel.DesignViewModel; import com.playgroundideas.playgroundideas.viewmodel.ManualViewModel; import com.playgroundideas.playgroundideas.viewmodel.ManualsListViewModel; import com.playgroundideas.playgroundideas.viewmodel.ProjectListViewModel; import com.playgroundideas.playgroundideas.viewmodel.ProjectViewModel; import com.playgroundideas.playgroundideas.viewmodel.UserViewModel; import dagger.Binds; import dagger.Module; import dagger.multibindings.IntoMap; @Module public abstract class ViewModelModule { @Binds @IntoMap @ViewModelKey(UserViewModel.class) abstract ViewModel bindUserViewModel(UserViewModel userViewModel); @Binds @IntoMap @ViewModelKey(DesignViewModel.class) abstract ViewModel bindDesignViewModel(DesignViewModel designViewModel); @Binds @IntoMap @ViewModelKey(DesignListViewModel.class) abstract ViewModel bindDesignListViewModel(DesignListViewModel designListViewModel); @Binds @IntoMap @ViewModelKey(ManualsListViewModel.class) abstract ViewModel bindManualsListViewModel(ManualsListViewModel manualsListViewModel); @Binds @IntoMap @ViewModelKey(ManualViewModel.class) abstract ViewModel bindManualViewModel(ManualViewModel manualViewModel); @Binds @IntoMap @ViewModelKey(ProjectViewModel.class) abstract ViewModel bindProjectViewModel(ProjectViewModel projectViewModel); @Binds @IntoMap @ViewModelKey(ProjectListViewModel.class) abstract ViewModel bindProjectListViewModel(ProjectListViewModel projectListViewModel); @Binds abstract ViewModelProvider.Factory bindViewModelFactory(PlaygroundViewModelFactory factory); }
true
8c4aea364ac8a1a5b944c98ef942008ef81d0e16
Java
nnn7h/AppMonitor
/app/src/main/java/hook/xposed/XViewGroup.java
UTF-8
1,889
2.03125
2
[]
no_license
package hook.xposed; import android.view.View; import android.view.ViewGroup; import de.robv.android.xposed.XC_MethodHook; import de.robv.android.xposed.XposedHelpers; import de.robv.android.xposed.callbacks.XC_LoadPackage; import util.Logger; public class XViewGroup extends XHook { private static final String className = ViewGroup.class.getName(); private static XViewGroup xViewGroup; public static XViewGroup getInstance() { if (xViewGroup == null) { xViewGroup = new XViewGroup(); } return xViewGroup; } @Override void hook(final XC_LoadPackage.LoadPackageParam packageParam) { XposedHelpers.findAndHookMethod(className, packageParam.classLoader, "addView", View.class, Integer.TYPE, ViewGroup.LayoutParams.class, new XC_MethodHook() { @Override protected void beforeHookedMethod(MethodHookParam param) { View view = (View) param.args[0]; String viewName = view.getClass().getName(); // TODO maybe read the view api to a list could be better ... if (viewName.startsWith("android.widget.") || viewName.startsWith("android.view.") || viewName.startsWith("android.support.v7.widget.") || viewName.startsWith("android.support.v7.internal.widget.") || viewName.startsWith("com.android.internal.widget.") || viewName.startsWith("com.android.internal.view")) { return; } Logger.log("[=== ViewGroup addView ===] "); Logger.log("[=== ViewGroup addView ===] " + viewName); Logger.logCallRef("[=== ViewGroup addView ===]"); } }); } }
true
93ec51a77a58550957b0dc58d4fbc5ecd353b3c1
Java
zhongxingyu/Seer
/Diff-Raw-Data/15/15_2c037a140bf91d18292bbc3af58f533805d1f6f3/Flattenizer/15_2c037a140bf91d18292bbc3af58f533805d1f6f3_Flattenizer_s.java
UTF-8
7,673
2.5625
3
[]
no_license
package com.excitedmuch.csm.ml.poker; import java.io.File; import java.io.FileNotFoundException; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Scanner; public class Flattenizer extends Thread { private final List<PlayedHand> handHistory = new ArrayList<PlayedHand>(); private final String dir; public Flattenizer(String dir) throws Exception { this.dir = dir; } private void loadHandHistory(String directory) throws FileNotFoundException { Scanner in = new Scanner(new File(directory, "hdb")); while(in.hasNextLine()) { String line = in.nextLine(); Scanner inLine = new Scanner(line); String id = inLine.next(); String dealer = inLine.next(); String handCount = inLine.next(); String playerCount = inLine.next(); String potFlop = inLine.next().split("/")[1]; String potTurn = inLine.next().split("/")[1]; String potRiver = inLine.next().split("/")[1]; String potShowdown = inLine.next().split("/")[1]; List<Card> boardCards = new ArrayList<Card>(); while(inLine.hasNext()) { boardCards.add(new Card(inLine.next())); } inLine.close(); handHistory.add(new PlayedHand(id, new BigDecimal(potFlop), new BigDecimal(potTurn), new BigDecimal(potRiver), new BigDecimal(potShowdown), boardCards)); } in.close(); } private void loadRosterInformation(String directory) throws Exception { Scanner in = new Scanner(new File(directory, "hroster")); Iterator<PlayedHand> iter = handHistory.iterator(); while(in.hasNextLine()) { String line = in.nextLine(); Scanner inLine = new Scanner(line); String id = inLine.next(); String playerCount = inLine.next(); List<String> players = new ArrayList<String>(); while(inLine.hasNext()) { players.add(inLine.next()); } inLine.close(); PlayedHand nextHand = iter.next(); if(!id.equals(nextHand.id)) { throw new Exception("Missing hand information"); } nextHand.playersNameList.addAll(players); } in.close(); } private void loadPlayerActions(String directory) throws Exception { // Player Name -> Id -> Action map Map<String, Map<String, PlayerAction>> playerToHandMap = new HashMap<String, Map<String, PlayerAction>>(); String pdbDir = directory + "/pdb/"; File pDir = new File(pdbDir); for(String pFile : pDir.list()) { Map<String, PlayerAction> handToActionMap = new HashMap<String, PlayerAction>(); String playerName = null; Scanner in = new Scanner(new File(pdbDir, pFile)); while(in.hasNext()) { String line = in.nextLine(); Scanner inLine = new Scanner(line); playerName = inLine.next(); String id = inLine.next(); String playerNum = inLine.next(); String position = inLine.next(); String flop = inLine.next(); String turn = inLine.next(); String river = inLine.next(); String showdown = inLine.next(); String bankRoll = inLine.next(); String betAmount = inLine.next(); String winAmount = inLine.next(); List<Card> cards = new ArrayList<Card>(); while(inLine.hasNext()) { cards.add(new Card(inLine.next())); } inLine.close(); handToActionMap.put(id, new PlayerAction(position, playerNum, new BigDecimal(bankRoll), flop, turn, river, showdown, cards)); } in.close(); playerToHandMap.put(playerName, handToActionMap); } for(PlayedHand ph : handHistory) { for(String playerName : ph.playersNameList) { PlayerAction action = playerToHandMap.get(playerName).get(ph.id); if(action != null) { ph.players.add(action); Collections.sort(ph.players, new Comparator<PlayerAction>() { @Override public int compare(PlayerAction o1, PlayerAction o2) { return o1.position.compareTo(o2.position); } }); } } } } @Override public void run() { try { loadHandHistory(dir); loadRosterInformation(dir); loadPlayerActions(dir); } catch (Exception e) { e.printStackTrace(System.err); System.err.println(e); } // For each hand // Get player list // Get the players' actions, in order of position // While more actions were taken // Print row for(PlayedHand hand : handHistory) { boolean hadAction; // Flop actions hadAction = true; for(int round = 1; round == 1 || hadAction; round++) { hadAction = false; for(PlayerAction player : hand.players) { if(player.flopActions.length() >= round) { printRow(player.handCards, hand.boardCards, player.playersLeft, player.position, potNormalize(hand.potFlop, player.chipCount), player.flopActions.substring(round - 1, round)); hadAction = true; } } } // Turn actions hadAction = true; for(int round = 1; round == 1 || hadAction; round++) { hadAction = false; for(PlayerAction player : hand.players) { if(player.turnActions.length() >= round) { printRow(player.handCards, hand.boardCards, player.playersLeft, player.position, potNormalize(hand.potTurn, player.chipCount), player.turnActions.substring(round - 1, round)); hadAction = true; } } } // River actions hadAction = true; for(int round = 1; round == 1 || hadAction; round++) { hadAction = false; for(PlayerAction player : hand.players) { if(player.riverActions.length() >= round) { printRow(player.handCards, hand.boardCards, player.playersLeft, player.position, potNormalize(hand.potRiver, player.chipCount), player.riverActions.substring(round - 1, round)); hadAction = true; } } } // Showdown actions hadAction = true; for(int round = 1; round == 1 || hadAction; round++) { hadAction = false; for(PlayerAction player : hand.players) { if(player.showdownActions.length() >= round) { printRow(player.handCards, hand.boardCards, player.playersLeft, player.position, potNormalize(hand.potShowdown, player.chipCount), player.showdownActions.substring(round - 1, round)); hadAction = true; } } } } } private void printRow(List<Card> handCards, List<Card> boardCards, String playersLeft, String position, BigDecimal potNormalized, String action) { String handCard1 = handCards.size() > 1 ? handCards.get(0).toString() : "-"; String handCard2 = handCards.size() > 1 ? handCards.get(1).toString() : "-"; String poolCard1 = boardCards.size() > 0 ? boardCards.get(0).toString() : "-"; String poolCard2 = boardCards.size() > 1 ? boardCards.get(1).toString() : "-"; String poolCard3 = boardCards.size() > 2 ? boardCards.get(2).toString() : "-"; String poolCard4 = boardCards.size() > 3 ? boardCards.get(3).toString() : "-"; String poolCard5 = boardCards.size() > 4 ? boardCards.get(4).toString() : "-"; System.out.println(String.format("%s %s %s %s %s %s %s %s %s %s %s", handCard1, handCard2, poolCard1, poolCard2, poolCard3, poolCard4, poolCard5, playersLeft, position, potNormalized, action)); } private BigDecimal potNormalize(BigDecimal pot, BigDecimal value) { return value.divide(pot.add(BigDecimal.TEN), BigDecimal.ROUND_FLOOR); // Adds ten cause } }
true
f4ef72717d549da7cc854c09e945311ed53a3ffa
Java
D-a-r-e-k/Code-Smells-Detection
/Preparation/processed-dataset/data-class_1_180/header.java
UTF-8
12,170
3.28125
3
[]
no_license
void method0() { /** Little trick to allow for "aliasing", that is, renaming this class. Writing code like <p> <tt>Functions.chain(Functions.plus,Functions.sin,Functions.chain(Functions.square,Functions.cos));</tt> <p> is a bit awkward, to say the least. Using the aliasing you can instead write <p> <tt>Functions F = Functions.functions; <br> F.chain(F.plus,F.sin,F.chain(F.square,F.cos));</tt> */ public static final Functions functions = new Functions(); /***************************** * <H3>Unary functions</H3> *****************************/ /** * Function that returns <tt>Math.abs(a)</tt>. */ public static final DoubleFunction abs = new DoubleFunction() { public final double apply(double a) { return Math.abs(a); } }; /** * Function that returns <tt>Math.acos(a)</tt>. */ public static final DoubleFunction acos = new DoubleFunction() { public final double apply(double a) { return Math.acos(a); } }; /** * Function that returns <tt>com.imsl.math.Sfun.acosh(a)</tt>. */ /* public static final DoubleFunction acosh = new DoubleFunction() { public final double apply(double a) { return Sfun.acosh(a); } }; */ /** * Function that returns <tt>Math.asin(a)</tt>. */ public static final DoubleFunction asin = new DoubleFunction() { public final double apply(double a) { return Math.asin(a); } }; /** * Function that returns <tt>com.imsl.math.Sfun.asinh(a)</tt>. */ /* public static final DoubleFunction asinh = new DoubleFunction() { public final double apply(double a) { return Sfun.asinh(a); } }; */ /** * Function that returns <tt>Math.atan(a)</tt>. */ public static final DoubleFunction atan = new DoubleFunction() { public final double apply(double a) { return Math.atan(a); } }; /** * Function that returns <tt>com.imsl.math.Sfun.atanh(a)</tt>. */ /* public static final DoubleFunction atanh = new DoubleFunction() { public final double apply(double a) { return Sfun.atanh(a); } }; */ /** * Function that returns <tt>Math.ceil(a)</tt>. */ public static final DoubleFunction ceil = new DoubleFunction() { public final double apply(double a) { return Math.ceil(a); } }; /** * Function that returns <tt>Math.cos(a)</tt>. */ public static final DoubleFunction cos = new DoubleFunction() { public final double apply(double a) { return Math.cos(a); } }; /** * Function that returns <tt>com.imsl.math.Sfun.cosh(a)</tt>. */ /* public static final DoubleFunction cosh = new DoubleFunction() { public final double apply(double a) { return Sfun.cosh(a); } }; */ /** * Function that returns <tt>com.imsl.math.Sfun.cot(a)</tt>. */ /* public static final DoubleFunction cot = new DoubleFunction() { public final double apply(double a) { return Sfun.cot(a); } }; */ /** * Function that returns <tt>com.imsl.math.Sfun.erf(a)</tt>. */ /* public static final DoubleFunction erf = new DoubleFunction() { public final double apply(double a) { return Sfun.erf(a); } }; */ /** * Function that returns <tt>com.imsl.math.Sfun.erfc(a)</tt>. */ /* public static final DoubleFunction erfc = new DoubleFunction() { public final double apply(double a) { return Sfun.erfc(a); } }; */ /** * Function that returns <tt>Math.exp(a)</tt>. */ public static final DoubleFunction exp = new DoubleFunction() { public final double apply(double a) { return Math.exp(a); } }; /** * Function that returns <tt>Math.floor(a)</tt>. */ public static final DoubleFunction floor = new DoubleFunction() { public final double apply(double a) { return Math.floor(a); } }; /** * Function that returns <tt>com.imsl.math.Sfun.gamma(a)</tt>. */ /* public static final DoubleFunction gamma = new DoubleFunction() { public final double apply(double a) { return Sfun.gamma(a); } }; */ /** * Function that returns its argument. */ public static final DoubleFunction identity = new DoubleFunction() { public final double apply(double a) { return a; } }; /** * Function that returns <tt>1.0 / a</tt>. */ public static final DoubleFunction inv = new DoubleFunction() { public final double apply(double a) { return 1.0 / a; } }; /** * Function that returns <tt>Math.log(a)</tt>. */ public static final DoubleFunction log = new DoubleFunction() { public final double apply(double a) { return Math.log(a); } }; /** * Function that returns <tt>com.imsl.math.Sfun.log10(a)</tt>. */ /* public static final DoubleFunction log10 = new DoubleFunction() { public final double apply(double a) { return Sfun.log10(a); } }; */ /** * Function that returns <tt>Math.log(a) / Math.log(2)</tt>. */ public static final DoubleFunction log2 = new DoubleFunction() { // 1.0 / Math.log(2) == 1.4426950408889634 public final double apply(double a) { return Math.log(a) * 1.4426950408889634; } }; /** * Function that returns <tt>com.imsl.math.Sfun.logGamma(a)</tt>. */ /* public static final DoubleFunction logGamma = new DoubleFunction() { public final double apply(double a) { return Sfun.logGamma(a); } }; */ /** * Function that returns <tt>-a</tt>. */ public static final DoubleFunction neg = new DoubleFunction() { public final double apply(double a) { return -a; } }; /** * Function that returns <tt>Math.rint(a)</tt>. */ public static final DoubleFunction rint = new DoubleFunction() { public final double apply(double a) { return Math.rint(a); } }; /** * Function that returns <tt>a < 0 ? -1 : a > 0 ? 1 : 0</tt>. */ public static final DoubleFunction sign = new DoubleFunction() { public final double apply(double a) { return a < 0 ? -1 : a > 0 ? 1 : 0; } }; /** * Function that returns <tt>Math.sin(a)</tt>. */ public static final DoubleFunction sin = new DoubleFunction() { public final double apply(double a) { return Math.sin(a); } }; /** * Function that returns <tt>com.imsl.math.Sfun.sinh(a)</tt>. */ /* public static final DoubleFunction sinh = new DoubleFunction() { public final double apply(double a) { return Sfun.sinh(a); } }; */ /** * Function that returns <tt>Math.sqrt(a)</tt>. */ public static final DoubleFunction sqrt = new DoubleFunction() { public final double apply(double a) { return Math.sqrt(a); } }; /** * Function that returns <tt>a * a</tt>. */ public static final DoubleFunction square = new DoubleFunction() { public final double apply(double a) { return a * a; } }; /** * Function that returns <tt>Math.tan(a)</tt>. */ public static final DoubleFunction tan = new DoubleFunction() { public final double apply(double a) { return Math.tan(a); } }; /** * Function that returns <tt>com.imsl.math.Sfun.tanh(a)</tt>. */ /* public static final DoubleFunction tanh = new DoubleFunction() { public final double apply(double a) { return Sfun.tanh(a); } }; */ /** * Function that returns <tt>Math.toDegrees(a)</tt>. */ /* public static final DoubleFunction toDegrees = new DoubleFunction() { public final double apply(double a) { return Math.toDegrees(a); } }; */ /** * Function that returns <tt>Math.toRadians(a)</tt>. */ /* public static final DoubleFunction toRadians = new DoubleFunction() { public final double apply(double a) { return Math.toRadians(a); } }; */ /***************************** * <H3>Binary functions</H3> *****************************/ /** * Function that returns <tt>Math.atan2(a,b)</tt>. */ public static final DoubleDoubleFunction atan2 = new DoubleDoubleFunction() { public final double apply(double a, double b) { return Math.atan2(a, b); } }; /** * Function that returns <tt>com.imsl.math.Sfun.logBeta(a,b)</tt>. */ /* public static final DoubleDoubleFunction logBeta = new DoubleDoubleFunction() { public final double apply(double a, double b) { return Sfun.logBeta(a,b); } }; */ /** * Function that returns <tt>a < b ? -1 : a > b ? 1 : 0</tt>. */ public static final DoubleDoubleFunction compare = new DoubleDoubleFunction() { public final double apply(double a, double b) { return a < b ? -1 : a > b ? 1 : 0; } }; /** * Function that returns <tt>a / b</tt>. */ public static final DoubleDoubleFunction div = new DoubleDoubleFunction() { public final double apply(double a, double b) { return a / b; } }; /** * Function that returns <tt>a == b ? 1 : 0</tt>. */ public static final DoubleDoubleFunction equals = new DoubleDoubleFunction() { public final double apply(double a, double b) { return a == b ? 1 : 0; } }; /** * Function that returns <tt>a > b ? 1 : 0</tt>. */ public static final DoubleDoubleFunction greater = new DoubleDoubleFunction() { public final double apply(double a, double b) { return a > b ? 1 : 0; } }; /** * Function that returns <tt>Math.IEEEremainder(a,b)</tt>. */ public static final DoubleDoubleFunction IEEEremainder = new DoubleDoubleFunction() { public final double apply(double a, double b) { return Math.IEEEremainder(a, b); } }; /** * Function that returns <tt>a == b</tt>. */ public static final DoubleDoubleProcedure isEqual = new DoubleDoubleProcedure() { public final boolean apply(double a, double b) { return a == b; } }; /** * Function that returns <tt>a < b</tt>. */ public static final DoubleDoubleProcedure isLess = new DoubleDoubleProcedure() { public final boolean apply(double a, double b) { return a < b; } }; /** * Function that returns <tt>a > b</tt>. */ public static final DoubleDoubleProcedure isGreater = new DoubleDoubleProcedure() { public final boolean apply(double a, double b) { return a > b; } }; /** * Function that returns <tt>a < b ? 1 : 0</tt>. */ public static final DoubleDoubleFunction less = new DoubleDoubleFunction() { public final double apply(double a, double b) { return a < b ? 1 : 0; } }; /** * Function that returns <tt>Math.log(a) / Math.log(b)</tt>. */ public static final DoubleDoubleFunction lg = new DoubleDoubleFunction() { public final double apply(double a, double b) { return Math.log(a) / Math.log(b); } }; /** * Function that returns <tt>Math.max(a,b)</tt>. */ public static final DoubleDoubleFunction max = new DoubleDoubleFunction() { public final double apply(double a, double b) { return Math.max(a, b); } }; /** * Function that returns <tt>Math.min(a,b)</tt>. */ public static final DoubleDoubleFunction min = new DoubleDoubleFunction() { public final double apply(double a, double b) { return Math.min(a, b); } }; /** * Function that returns <tt>a - b</tt>. */ public static final DoubleDoubleFunction minus = plusMult(-1); /* new DoubleDoubleFunction() { public final double apply(double a, double b) { return a - b; } }; */ /** * Function that returns <tt>a % b</tt>. */ public static final DoubleDoubleFunction mod = new DoubleDoubleFunction() { public final double apply(double a, double b) { return a % b; } }; /** * Function that returns <tt>a * b</tt>. */ public static final DoubleDoubleFunction mult = new DoubleDoubleFunction() { public final double apply(double a, double b) { return a * b; } }; /** * Function that returns <tt>a + b</tt>. */ public static final DoubleDoubleFunction plus = plusMult(1); /* new DoubleDoubleFunction() { public final double apply(double a, double b) { return a + b; } }; */ /** * Function that returns <tt>Math.abs(a) + Math.abs(b)</tt>. */ public static final DoubleDoubleFunction plusAbs = new DoubleDoubleFunction() { public final double apply(double a, double b) { return Math.abs(a) + Math.abs(b); } }; /** * Function that returns <tt>Math.pow(a,b)</tt>. */ public static final DoubleDoubleFunction pow = new DoubleDoubleFunction() { public final double apply(double a, double b) { return Math.pow(a, b); } }; }
true
e03bcddc2a69481bcffe39dfb1c810b797203427
Java
MarcoAG-115/Cardholders
/Cardholder.java
UTF-8
7,479
3.453125
3
[]
no_license
import java.util.Arrays; import java.text.DecimalFormat; /** * This class outputs information * about a user's account. The * information deals with their * balance, category, account number, * purchases, and purchase points. * * Project 11 * Marco Gonzalez - COMP1210 - 010 * 12/05/2018 */ public abstract class Cardholder implements Comparable<Cardholder> { // Instance Variables /** The category. */ protected String category; /** The account number. */ protected String acctNumber; /** The name. */ protected String name; /** The previous balance. */ protected double prevBalance; /** The payment amount. */ protected double payment; /** An array that represents new purchases. */ protected double[] purchases; /** The interest rate. */ public static final double INTEREST_RATE = 0.01; // Constructor /** * Sets default values for the instance variables. * * @param acctNumberIn Command line arguments * @param nameIn Command line arguments */ public Cardholder(String acctNumberIn, String nameIn) { name = nameIn; acctNumber = acctNumberIn; purchases = new double[0]; } //Methods /** * Returns the account number. * * @return The account number */ public String getAcctNumber() { return acctNumber; } /** * Sets a value to the account number. * * @param acctNumberIn Command line arguments */ public void setAcctNumber(String acctNumberIn) { acctNumber = acctNumberIn; } /** * Returns a name. * * @return name */ public String getName() { return name; } /** * Sets a value to name. * * @param nameIn Command line arguments */ public void setName(String nameIn) { name = nameIn; } /** * Returns the previous balance. * * @return The previous balane */ public double getPrevBalance() { return prevBalance; } /** * Sets a value to previous balance. * * @param prevBalanceIn Command line arguments */ public void setPrevBalance(double prevBalanceIn) { prevBalance = prevBalanceIn; } /** * Returns the payment amount. * * @return The payment amount */ public double getPayment() { return payment; } /** * Sets a value to the payment amount. * * @param paymentIn Command line arguments */ public void setPayment(double paymentIn) { payment = paymentIn; } /** * Returns the array of purchases. * * @return The array of purchases */ public double[] getPurchases() { return purchases; } /** * Sets a value to the list of purchases. * * @param purchasesIn Command line arguments */ public void setPurchases(double[] purchasesIn) { purchases = purchasesIn; } /** * Accepts a variable length parameter and adds * double values to the purchases array. * * @param list Command line arguments */ public void addPurchases(double... list) { for (double x : list) { addPurchases2(x); } } /** * This method adds a purchase to the * purchase list. * * @param element Command line arguments */ private void addPurchases2(double element) { boolean check = false; if (purchases.length == 0) { check = true; } purchases = Arrays.copyOf(purchases, purchases.length + 1); for (int j = 0; j <= purchases.length; j++) { if (check) { purchases[0] = element; } else { purchases[purchases.length - 1] = element; } } } /** * This method finds the variables that matches the parameter * and deletes them from the list. * * @param list Command line arguments */ public void deletePurchases(double... list) { for (double x : list) { deletePurchases2(x); } } /** * This method removes the specified element. * * @param element Command line arguments */ private void deletePurchases2(double element) { int count = 0; int check = 0; for (int i = 0; i < purchases.length; i++) { if (purchases[i] == element) { count = 1 + count; for (int j = i; j < purchases.length - 1; j++) { purchases[j] = purchases[j + 1]; } } else { check++; } } if (check != purchases.length) { for (int z = 0; z < count; z++) { purchases = Arrays.copyOf(purchases, purchases.length - 1); } } } /** * Returns calculated interest. * * @return Interest owed */ public double interest() { return (prevBalance - payment) * INTEREST_RATE; } /** * Returns total items in purchase array. * * @return array number size */ public double totalPurchases() { double total = 0; for (double x : purchases) { total += x; } return total; } /** * Returns balance. * * @return balance */ public double balance() { return prevBalance + interest() + totalPurchases(); } /** * Returns current balance. * * @return current balance */ public double currentBalance() { return prevBalance - payment + interest() + totalPurchases(); } /** * Returns minimial payment. * * @return minimal payment */ public double minPayment() { return currentBalance() * .03; } /** * Returns output. * * @return output */ public String toString() { String strBalance = Double.toString(prevBalance); DecimalFormat newFormat1 = new DecimalFormat("$#,##0.00"); DecimalFormat newFormat2 = new DecimalFormat("#,##0"); String output = category; output += "\nAcctNo/Name: " + acctNumber + " " + name; output += "\nPrevious Balance: " + newFormat1.format(prevBalance); output += "\nPayment: (" + newFormat1.format(payment) + ")"; output += "\nInterest: " + newFormat1.format(interest()); output += "\nNew Purchases: " + newFormat1.format(totalPurchases()); output += "\nCurrent Balance: " + newFormat1.format(currentBalance()); output += "\nMinimum Payment: " + newFormat1.format(minPayment()); output += "\nPurchase Points: " + newFormat2.format(totalPurchases()); return output; } /** * Returns number of purchase points gained. * * @return purchase points */ public abstract int purchasePoints(); /** * The compareTo method compares the name * strings in the objects. * * @param obj Command line arguments * @return purchase points */ public int compareTo(Cardholder obj) { return name.compareToIgnoreCase(obj.getName()); } /** * Checks if an object is of the * Cardholder type. * * @param obj Command line arguments * @return true or false */ public boolean equals(Object obj) { if (!(obj instanceof Cardholder)) { return false; } else { Cardholder c = (Cardholder) obj; return (name.equalsIgnoreCase(c.getName())); } } /** * Allows for comparison of two Cardholder * arrays. * * @return zero */ public int hashCode() { return 0; } }
true
15e5b682a9d37f728c86fec428ec9a06fc4e9ac0
Java
wwjiang007/yugabyte-db
/managed/src/main/java/com/yugabyte/yw/forms/PlatformLoggingConfig.java
UTF-8
525
1.765625
2
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0", "OpenSSL" ]
permissive
// Copyright (c) YugaByte, Inc. package com.yugabyte.yw.forms; import javax.annotation.Nullable; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.validation.constraints.Min; import javax.validation.constraints.NotNull; import lombok.Data; import org.slf4j.event.Level; @Data public class PlatformLoggingConfig { @NotNull @Enumerated(EnumType.STRING) private Level level; @Nullable private String rolloverPattern; @Nullable @Min(value = 0) private Integer maxHistory; }
true
4d4e690107512d12896bfc517f54d1df3f86b62e
Java
YongfuHou/network-management-platform
/java web client/src/servlet/DoStrategy.java
GB18030
2,035
2.53125
3
[]
no_license
package servlet; import java.io.IOException; import java.io.PrintWriter; import strategy.*; import javax.servlet.RequestDispatcher; 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 org.apache.jasper.tagplugins.jstl.core.Out; /** * Servlet implementation class DoStrategy */ @WebServlet("/DoStrategy") public class DoStrategy extends HttpServlet { private static final long serialVersionUID = 1L; static String srategy_num = null; /** * @see HttpServlet#HttpServlet() */ public DoStrategy() { super(); // TODO Auto-generated constructor stub } public void deley(int deleytime){ //ӳٺ try { Thread.sleep(deleytime); } catch (InterruptedException e) { // TODO Զɵ catch e.printStackTrace(); } } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub response.setCharacterEncoding("utf-8"); response.setContentType("text/html; charset=utf-8"); PrintWriter out = response.getWriter(); One one = new One(); Two two = new Two(); Three three = new Three(); srategy_num=request.getParameter("strategy"); while(srategy_num!=null){ if (srategy_num.equals("1")){ one.function(); deley(80000); }else if(srategy_num.equals("2")){ two.function(); deley(80000); }else if (srategy_num.equals("3")){ three.function(); deley(8000); }else if(srategy_num.equals("stop")){ out.println("ֶֹͣAP"); break; } // srategy_num=request.getParameter("strategy"); } } }
true
a36ce3b0d8c548164108feb7c1995853b52c2c01
Java
kanison/finance
/zcb_app/finance/service/dao/src/main/java/com/zhaocb/zcb_app/finance/service/dao/FinanceDAO.java
UTF-8
918
1.796875
2
[]
no_license
package com.zhaocb.zcb_app.finance.service.dao; import com.zhaocb.zcb_app.finance.service.facade.dataobject.AdvanceTypeConfigDO; import com.zhaocb.zcb_app.finance.service.facade.dataobject.SpBizConfigDO; import com.zhaocb.zcb_app.finance.service.facade.dataobject.SpConfigDO; import com.zhaocb.zcb_app.finance.service.facade.dataobject.TradeOrderDO; import com.zhaocb.zcb_app.finance.service.facade.dataobject.UserBindDO; public interface FinanceDAO { public SpConfigDO querySpConfig(SpConfigDO spConfigDO); public SpBizConfigDO querySpBizConfig(SpBizConfigDO spBizConfigDO); public AdvanceTypeConfigDO queryAdvanceTypeConfig(AdvanceTypeConfigDO advanceTypeConfigDO); public void insertTradeOrder(TradeOrderDO tradeOrderDO); public UserBindDO queryUserBindInfo(UserBindDO userBindDO); public void insertUserBind(UserBindDO userBindDO); public void updateTradeOrder(TradeOrderDO tradeOrderDO); }
true
fea5321c9f5edfb0cb2ac9b972c6793ae8afd982
Java
marioosh-net/JSF2.0-Hello-World
/src/main/java/com/mkyong/common/HelloBean.java
UTF-8
1,449
2.171875
2
[]
no_license
package com.mkyong.common; import java.io.Serializable; import java.util.Date; import javax.annotation.PostConstruct; import javax.faces.bean.ManagedBean; import javax.faces.bean.ManagedProperty; import javax.faces.bean.ViewScoped; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; @ManagedBean @ViewScoped public class HelloBean implements Serializable { transient private Logger log = Logger.getLogger(getClass()); @Autowired private SpringBean springBean; @ManagedProperty(value="#{tokenBean}") private TokenBean tokenBean; public void setTokenBean(TokenBean tokenBean) { this.tokenBean = tokenBean; } @PostConstruct public void t() { token = tokenBean.getHash(); } private static final long serialVersionUID = 1L; private String name; private String token; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getToken() { return token; } public void setToken(String token) { this.token = token; } public Date getTime() { log.debug(springBean); return new Date(); } public String voidek() { log.debug("NAME: "+name); log.debug("TOKEN: "+token); if(tokenBean.getToken().equals(token)) { log.debug("SEND"); } else { log.error("INVALID TOKEN, AVOID SEND"); } t(); return null; } }
true
28c1b7557f4ee287e46bf10013d6d0e284f36433
Java
y897356576/nginxCase
/src/main/java/com/EhcacheUtil.java
UTF-8
402
2.140625
2
[]
no_license
package com; import net.sf.ehcache.Cache; import net.sf.ehcache.CacheManager; /** * Created by 石头 on 2017/6/25. */ public class EhcacheUtil { private static CacheManager cacheManager; public static Cache getCache(String cacheName){ if(cacheManager == null){ cacheManager = CacheManager.create(); } return cacheManager.getCache(cacheName); } }
true
c5709acf9b90a64ab25addf251ddd8643fe48894
Java
ukong/ds_demo
/ds_pindao/src/main/java/cn/dataguru/dianshang/service/RedisService.java
UTF-8
2,087
2.046875
2
[]
no_license
package cn.dataguru.dianshang.service; import cn.dataguru.dianshang.entity.ProductTotal; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import java.util.List; @FeignClient(value = "youfands-redis") public interface RedisService { /** * 设置Str缓存 * @param key * @param val * @return */ @RequestMapping(value = "redis/setStr") public String setStr(@RequestParam(value = "key") String key, @RequestParam(value = "val") String val); /** * 根据key查询Str缓存 * @param key * @return */ @RequestMapping(value = "redis/getStr") public String getStr(@RequestParam(value = "key") String key); /** * @param key * @return */ @RequestMapping(value = "redis/delStr") public String delStr(@RequestParam(value = "key") String key); /** * 设置obj缓存 * @param key * @return */ @RequestMapping(value = "redis/setObj") public String setObj(@RequestParam(value = "key") String key, @RequestBody ProductTotal productTotal); /** * 获取obj缓存 * @param key * @return */ @RequestMapping(value = "redis/getObj") public Object getObj(@RequestParam(value = "key") String key); /** * 删除obj缓存 * @param key * @return */ @RequestMapping(value = "redis/delObj") public Object delObj(@RequestParam(value = "key") String key); @RequestMapping(value = "redis/setkeybypire") public void setkeybypire(@RequestParam(value = "key")String key,@RequestParam(value = "seconds")long seconds); @RequestMapping(value = "redis/pushkeyvalue") public void pushkeyvalue(@RequestParam(value = "key")String key ,@RequestParam(value = "value")String value); @RequestMapping(value = "redis/rangekeyvalue") public List<String> rangekeyvalue(@RequestParam(value = "key") String key ); }
true