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
6e0a61c2e316f9f03ff7d294870f647e942f8ec1
Java
alisha8899/Introduction-Java
/cs46a_hw4b/InputApplication.java
UTF-8
817
3.625
4
[]
no_license
/** * Displays the users favorite dessert * * @author Alisha */ import java.util.Scanner; public class InputApplication { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.print("Enter a your favorite dessert: "); String word = in.nextLine(); System.out.println(word.charAt(word.length()-1)); System.out.print("Enter a double: "); double number1 = in.nextDouble(); System.out.print("Enter an integer: "); int number2 = in.nextInt(); System.out.print("Product: "); System.out.println(number1 * number2); System.out.print("Integer portion: "); int product= (int)(number1 * number2); System.out.println(product); } }
true
8e3fa9c532ea8c0363d5c0d0db6c313acd7c6fd8
Java
elenaanghel90/HibernateAndDBCreatedWithCars
/src/main/java/com/sda/app/masini/db/Masina.java
UTF-8
2,515
2.328125
2
[]
no_license
package com.sda.app.masini.db; import com.sda.app.utilizatori.db.Utilizator; import javax.persistence.*; import java.util.List; @Entity @Table(name = "Masini") public class Masina { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) //identity lasi baza de date sa genereze ea in fucntie de cum stie @Column(name = "id") private Integer id; @Column(name = "marca") private String marca; @Column(name = "model") private String model; @Column(name = "numar") private String numar; @ManyToMany(mappedBy = "masini") private List<Utilizator> utilizatori; public Masina(Integer id, String marca, String model, String numar) { this.id = id; this.marca = marca; this.model = model; this.numar = numar; } public Masina() { } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getMarca() { return marca; } public void setMarca(String marca) { this.marca = marca; } public String getModel() { return model; } public void setModel(String model) { this.model = model; } public String getNumar() { return numar; } public void setNumar(String numar) { this.numar = numar; } @Override public String toString() { return "Masina{" + "id=" + id + ", marca='" + marca + '\'' + ", model='" + model + '\'' + ", numar='" + numar + '\'' + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Masina masina = (Masina) o; if (id != null ? !id.equals(masina.id) : masina.id != null) return false; if (marca != null ? !marca.equals(masina.marca) : masina.marca != null) return false; if (model != null ? !model.equals(masina.model) : masina.model != null) return false; return numar != null ? numar.equals(masina.numar) : masina.numar == null; } @Override public int hashCode() { int result = id != null ? id.hashCode() : 0; result = 31 * result + (marca != null ? marca.hashCode() : 0); result = 31 * result + (model != null ? model.hashCode() : 0); result = 31 * result + (numar != null ? numar.hashCode() : 0); return result; } }
true
6304345100a90ae6de85f39cda39042d09d8e995
Java
IgnacioCisneros-dev/Api-Rest_SIC
/src/main/java/com/ignacio/persistencia/RowMapper/PuestoRowMapper.java
UTF-8
691
2.484375
2
[]
no_license
package com.ignacio.persistencia.RowMapper; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import org.springframework.jdbc.core.RowMapper; import com.ignacio.persistencia.entidad.Puesto; public class PuestoRowMapper implements RowMapper<List<Puesto>> { @Override public List<Puesto> mapRow(ResultSet rs, int rowNum) throws SQLException { List<Puesto> puestos = new ArrayList<Puesto>(); Puesto puesto = null; do { puesto = new Puesto(); puesto.setIdPosition(rs.getInt("idPosition")); puesto.setNombre(rs.getString("nombre")); puestos.add(puesto); } while (rs.next()); return puestos; } }
true
e218e542f12ad7faf7d952f2f3fb462ae241f161
Java
GalkinDenis/AppForSibers
/app/build/tmp/kapt3/stubs/release/com/denis/appForSibersTeam/network/PokeApi.java
UTF-8
1,193
1.65625
2
[]
no_license
package com.denis.appForSibersTeam.network; import java.lang.System; @kotlin.Metadata(mv = {1, 5, 1}, k = 1, d1 = {"\u0000\u0014\n\u0002\u0018\u0002\n\u0002\u0010\u0000\n\u0002\b\u0002\n\u0002\u0018\u0002\n\u0002\b\u0005\b\u00c6\u0002\u0018\u00002\u00020\u0001B\u0007\b\u0002\u00a2\u0006\u0002\u0010\u0002R\u001b\u0010\u0003\u001a\u00020\u00048FX\u0086\u0084\u0002\u00a2\u0006\f\n\u0004\b\u0007\u0010\b\u001a\u0004\b\u0005\u0010\u0006\u00a8\u0006\t"}, d2 = {"Lcom/denis/appForSibersTeam/network/PokeApi;", "", "()V", "retrofitService", "Lcom/denis/appForSibersTeam/network/GetJSON;", "getRetrofitService", "()Lcom/denis/appForSibersTeam/network/GetJSON;", "retrofitService$delegate", "Lkotlin/Lazy;", "app_release"}) public final class PokeApi { @org.jetbrains.annotations.NotNull() public static final com.denis.appForSibersTeam.network.PokeApi INSTANCE = null; @org.jetbrains.annotations.NotNull() private static final kotlin.Lazy retrofitService$delegate = null; private PokeApi() { super(); } @org.jetbrains.annotations.NotNull() public final com.denis.appForSibersTeam.network.GetJSON getRetrofitService() { return null; } }
true
2dff1cabf9851c7c3c9cb19e3e49ac692cdad89a
Java
PaddyDeng/toefl-ad-app
/app/src/main/java/io/dcloud/H58E83894/ui/make/dub/adapter/DubDeRankAdapter.java
UTF-8
2,561
2.140625
2
[]
no_license
package io.dcloud.H58E83894.ui.make.dub.adapter; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import java.util.List; import io.dcloud.H58E83894.R; import io.dcloud.H58E83894.base.adapter.BaseRecyclerViewHolder; import io.dcloud.H58E83894.base.adapter.callback.OnItemClickListener; import io.dcloud.H58E83894.data.prelesson.LessonData; import io.dcloud.H58E83894.http.RetrofitProvider; import io.dcloud.H58E83894.ui.prelesson.adapter.CardHotAdapterHelper; import io.dcloud.H58E83894.utils.GlideUtil; public class DubDeRankAdapter extends RecyclerView.Adapter<BaseRecyclerViewHolder> { private List<LessonData> lists; private OnItemClickListener mListener; private CardHotAdapterHelper mCardAdapterHelper = new CardHotAdapterHelper(); public DubDeRankAdapter(List<LessonData> lists) { this.lists = lists; } public void setItemListener(OnItemClickListener listener) { mListener = listener; } @Override public BaseRecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_dub_rank, parent, false); // mCardAdapterHelper.onCreateViewHolder(parent, itemView); return new BaseRecyclerViewHolder(parent.getContext(), itemView); } @Override public void onBindViewHolder(BaseRecyclerViewHolder holder, final int position) { mCardAdapterHelper.onBindViewHolder(holder.itemView, position, getItemCount()); Context context = holder.itemView.getContext(); LessonData data = lists.get(position); //标题 holder.getTextView(R.id.rank_sum).setText(position+"");//1234 holder.getTextView(R.id.rank_zan_sum).setText(position+"");//总共多个攒 holder.getTextView(R.id.rank_name).setText(position+"");//名字 holder.getTextView(R.id.rank_time).setText(position+"");//时间 //图片 GlideUtil.load(RetrofitProvider.TOEFLURL + data.getImage(), holder.getImageView(R.id.rank_head)); // holder.itemView.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // if (mListener != null) { // mListener.onClick(v, position); // } // } // }); } @Override public int getItemCount() { return lists == null ? 0 : lists.size(); } }
true
58c42a742a61e641feea752add918435a063dc77
Java
SoftwareEngineeringWheelMaker/Furniture-management-system
/furniture-management-system/src/com/furniture/dao/impl/OperatorDaoImpl.java
UTF-8
1,826
2.46875
2
[]
no_license
package com.furniture.dao.impl; import java.util.List; import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.handlers.BeanListHandler; import com.furniture.domain.Operator; import com.furniture.exception.OperatorDaoException; import com.furniture.utils.JdbcUtils; public class OperatorDaoImpl { public void AddOperator(Operator operator) { try { QueryRunner runner = new QueryRunner(JdbcUtils.getDataSource()); String sql = "insert into operator(oname,opassword) values(?,?)"; Object[] params = new Object[] {operator.getOname(),operator.getOpassword()}; runner.update(sql, params); } catch (Exception e) { throw new OperatorDaoException(e); } } public void DeleteOperator(Operator operator) { try { QueryRunner runner = new QueryRunner(JdbcUtils.getDataSource()); String sql = "delete from operator where oid=?"; runner.update(sql,operator.getOid()); } catch (Exception e) { throw new OperatorDaoException(e); } } public void UpdateOperator(Operator operator) { try { QueryRunner runner = new QueryRunner(JdbcUtils.getDataSource()); String sql = "update operator set oname=?,opassword=? where oid=?"; Object[] params = new Object[] {operator.getOname(),operator.getOpassword(),operator.getOid()}; runner.update(sql, params); } catch (Exception e) { throw new OperatorDaoException(e); } } public List<Operator> getOperator(Operator operator) { try { QueryRunner runner = new QueryRunner(JdbcUtils.getDataSource()); String sql = "select * from operator where oid=?"; List<Operator> operator1 = runner.query(sql, new BeanListHandler<>(Operator.class),operator.getOid()); return operator1; } catch (Exception e) { throw new OperatorDaoException(e); } } }
true
a28c78ebe3d6a19b517671c819958dc54532d34a
Java
theKorpit/StackOverCoffee
/src/main/java/com/compassouol/config/ValidationExceptionHandler.java
UTF-8
2,543
2.421875
2
[]
no_license
package com.compassouol.config; import java.util.ArrayList; import java.util.List; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestControllerAdvice; import com.compassouol.controller.dto.ErroFormDto; import com.compassouol.controller.dto.JogosEmMesmoHorarioExceptionDto; import com.compassouol.exceptions.DataInicioMaiorQueDataFimException; import com.compassouol.exceptions.JogoInvalidoException; import com.compassouol.exceptions.JogosEmMesmoHorarioException; import com.fasterxml.jackson.databind.JsonMappingException.Reference; import com.fasterxml.jackson.databind.exc.InvalidFormatException; @RestControllerAdvice public class ValidationExceptionHandler { @ResponseStatus(code = HttpStatus.BAD_REQUEST) @ExceptionHandler(InvalidFormatException.class) public List<ErroFormDto> InvalidFormatExceptionHandler(InvalidFormatException exception) { List<ErroFormDto> erros = new ArrayList<ErroFormDto>(); List<Reference> references = exception.getPath(); references.forEach(e -> { ErroFormDto erro = new ErroFormDto(e.getFieldName(), exception.getCause().getMessage()); erros.add(erro); }); return erros; } @ResponseStatus(code = HttpStatus.BAD_REQUEST) @ExceptionHandler(DataInicioMaiorQueDataFimException.class) public ErroFormDto DataInicioMaiorQueDataFimException(DataInicioMaiorQueDataFimException exception) { ErroFormDto erro = new ErroFormDto("Data", exception.getMessage()); return erro; } @ResponseStatus(code = HttpStatus.BAD_REQUEST) @ExceptionHandler(JogoInvalidoException.class) public ErroFormDto DataInicioMaiorQueDataFimException(JogoInvalidoException exception) { ErroFormDto erro = null; if(exception.getId() != null) erro = new ErroFormDto("AppID", exception.getMessage()); else erro = new ErroFormDto("Nome Jogo", exception.getMessage()); return erro; } @ResponseStatus(code = HttpStatus.CONFLICT) @ExceptionHandler(JogosEmMesmoHorarioException.class) public JogosEmMesmoHorarioExceptionDto JogosEmMesmoHorarioExceptionHandler(JogosEmMesmoHorarioException exception) { JogosEmMesmoHorarioExceptionDto erroJogosEmMesmoHorarioExceptionDto = new JogosEmMesmoHorarioExceptionDto(exception.getDataInicio(), exception.getDataFim(), exception.getDataInicioToAdd(), exception.getDataFimToAdd(),exception.getMessage()); return erroJogosEmMesmoHorarioExceptionDto; } }
true
7de78f8f2d6cd70a091b00c1dbf20cdaaeac2557
Java
hollyroberts/volcano-infiltration
/src/levelComponents/AutomaticDoor.java
UTF-8
4,570
3.28125
3
[]
no_license
package levelComponents; import java.awt.Color; import java.awt.Graphics2D; import java.util.ArrayList; import audio.SoundEffectsHandler; public class AutomaticDoor implements LevelObject { private int x; private int y; private int width; private int height; private int mode; //1 for closed when switch off //2 for open when switch off private double closeFactor; //Amount to close/open the door by private double openAmount; //Amount the door is currently open private boolean closed = true; //Is the door/wall closed or not private boolean useFloors = false; //Use floors as the object instead of walls private boolean stealthMode; //Use the same colour as walls private LevelObject doorTop; //Top part of door private LevelObject doorBottom; //Bottom part of door public AutomaticDoor(int door_x, int door_y, int door_width, int door_height, int door_mode, double door_closeF, boolean door_useFloors, boolean door_stealthMode) { //Basic data this.x = door_x; this.y = door_y; this.width = door_width; this.height = door_height; //Door open/close info this.stealthMode = door_stealthMode; this.useFloors = door_useFloors; this.mode = door_mode; this.closeFactor = door_closeF; this.openAmount = height / 2; if (mode == 2) { //Set door to open if on mode 2 openAmount = 0; closed = !closed; } int openAmount_int = (int) openAmount; //Initate door objects if (useFloors) { doorTop = new Floor(x, y, width, openAmount_int); doorBottom = new Floor(x, y + (height - openAmount_int), width, openAmount_int); LevelHandler.getFloors().add((Floor) doorTop); LevelHandler.getFloors().add((Floor) doorBottom); } else { doorTop = new Wall(x, y, width, openAmount_int); doorBottom = new Wall(x, y + (height - openAmount_int), width, openAmount_int); LevelHandler.getWalls().add((Wall) doorTop); LevelHandler.getWalls().add((Wall) doorBottom); } //Set door colour to slightly darker than the other doors if not using stealth mode if (!stealthMode) { doorTop.setColour(new Color(110, 110, 110)); doorBottom.setColour(new Color(110, 110, 110)); } } public static void init() { } public void tick() { if ((openAmount > 0 & !closed) | (openAmount < height / 2 & closed)) { //If the door is in the process of opening/closing the process that if (closed) { openAmount += closeFactor; } else { openAmount -= closeFactor; } //Play open/close sound effects if (openAmount <= 0) { openAmount = 0; SoundEffectsHandler.playSound("door close", SoundEffectsHandler.getDistanceFactor(x + width / 2, y + height / 2, 30) + 1); } if (openAmount >= height / 2) { openAmount = height / 2; SoundEffectsHandler.playSound("door close", SoundEffectsHandler.getDistanceFactor(x + width / 2, y + height / 2, 30) + 1); } //Change values doorTop.setHeight((int) openAmount); doorBottom.setY((int) ((y + height) - openAmount)); doorBottom.setHeight((int) openAmount); } //If the player is in the door whilst it's closed then remove health doorTop.collisionRemoveHealth(); doorBottom.collisionRemoveHealth(); //Tick doorTop.tick(); doorBottom.tick(); } public void render(Graphics2D g2) { doorTop.render(g2); doorBottom.render(g2); } public void changeState() { //Make the door start closing or opening closed = !closed; SoundEffectsHandler.playSound("hydraulics", SoundEffectsHandler.getDistanceFactor(x + width / 2, y + height / 2, 15) -1); } public ArrayList<Floor> getFloors() { //Return the door objects for anything that wants them ArrayList<Floor> floors = new ArrayList<Floor>(); if (useFloors) { floors.add((Floor) doorTop); floors.add((Floor) doorBottom); } return floors; } public ArrayList<Wall> getWalls() { //Return the door objects for anything that wants them ArrayList<Wall> walls = new ArrayList<Wall>(); if (!useFloors) { walls.add((Wall) doorTop); walls.add((Wall) doorBottom); } return walls; } public int getX() { return x; } public int getY() { return y; } public int getWidth() { return width; } public int getHeight() { return height; } public void setX(int x) { this.x = x; } public void setY(int y) { this.y = y; } public void setWidth(int width) { this.width = width; } public void setHeight(int height) { this.height = height; } public void setColour(Color newColour) { //Void } public void collisionRemoveHealth() { //Void } public void hit() { } }
true
0f287ff6ef73a22dc59d538805fda7dff2004cfb
Java
ARC96/Baseprogamming
/Map/src/Map/Mapclass1.java
UTF-8
853
3.078125
3
[]
no_license
package Map; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; public class Mapclass1 { public static void main(String[] args) { HashMap m=new HashMap(); m.put(1,10); m.put(2,20); m.put(3,30); m.put(4,40); m.put(5,50); m.put(6,60); m.put(7,10); m.put(8,20); System.out.println(m); Set s1=m.entrySet(); System.out.println(s1); Iterator ir=s1.iterator(); while(ir.hasNext()) { Map.Entry m1 = (Map.Entry) ir.next(); if (m1.getValue().equals(10)) { Object s2 = m1.setValue(14); System.out.println(m); } // System.out.println("after iterator"); //System.out.println(s1); } } }
true
321bc8d15dc651383332f0bb7e0f03016f6b42f6
Java
suhane/HackerEarthSolution
/src/main/java/sorting/BubbleSort.java
UTF-8
336
3.390625
3
[]
no_license
package sorting; public class BubbleSort { public static void sort(int[] A){ int s=0; int len=A.length; for(int i=0;i<len;i++){ for(int j=i+1;j<len;j++){ if(A[i]>A[j]){ int temp=A[i]; A[i]=A[j]; A[j]=temp; s+=j-i; } } } System.out.println("Number of shifts in from bubble sort= "+s); } }
true
78b37a3fcd06cf2632cdfdebd58e309e9502fcea
Java
MarkTOPI/SuperFit
/app/src/main/java/com/example/superfit/exercisesScreen/ExercisesScreen.java
UTF-8
701
1.75
2
[]
no_license
package com.example.superfit.exercisesScreen; import android.content.Intent; import android.os.Bundle; import android.view.View; import androidx.appcompat.app.AppCompatActivity; import com.example.superfit.R; import com.example.superfit.mainscreen.mainScreen; public class ExercisesScreen extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { setTheme(R.style.Theme_AppCompat_Light_NoActionBar); super.onCreate(savedInstanceState); setContentView(R.layout.activity_exercises_screen); } public void goHome(View view) { Intent intent = new Intent(this, mainScreen.class); startActivity(intent); } }
true
017dfd214f7c80d3d763bb18450a2a91b3af8f5b
Java
btamada/Java-Fundamentals
/MergeSortDriver.java
UTF-8
316
3.109375
3
[]
no_license
package mergesort; public class MergeSortDriver { public static void main(String[] args) { int[] integers = {3,2,1,4}; MergeSort ms = new MergeSort(); ms.mergesort(integers); } private static void print(int[] array) { for(int i = 0; i < array.length; i++) { System.out.println(array[i]); } } }
true
26cae5906e0c018320ba4c833dc62a06d7db5bad
Java
xinxinOh/jiemoTest
/JiemoTest/src/main/java/com/neuedu/JiemoTest/entity/Question.java
UTF-8
2,726
2.03125
2
[]
no_license
package com.neuedu.JiemoTest.entity; public class Question { private Integer questionid; private String questionskill; private String title; private String options; private String answer; private Integer questiontype; private String analysis; private Integer difficultdegree; private Integer edittime; private Integer spare1; private Integer spare2; private String spare3; private String spare4; public Integer getQuestionid() { return questionid; } public void setQuestionid(Integer questionid) { this.questionid = questionid; } public String getQuestionskill() { return questionskill; } public void setQuestionskill(String questionskill) { this.questionskill = questionskill == null ? null : questionskill.trim(); } public String getTitle() { return title; } public void setTitle(String title) { this.title = title == null ? null : title.trim(); } public String getOptions() { return options; } public void setOptions(String options) { this.options = options == null ? null : options.trim(); } public String getAnswer() { return answer; } public void setAnswer(String answer) { this.answer = answer == null ? null : answer.trim(); } public Integer getQuestiontype() { return questiontype; } public void setQuestiontype(Integer questiontype) { this.questiontype = questiontype; } public String getAnalysis() { return analysis; } public void setAnalysis(String analysis) { this.analysis = analysis == null ? null : analysis.trim(); } public Integer getDifficultdegree() { return difficultdegree; } public void setDifficultdegree(Integer difficultdegree) { this.difficultdegree = difficultdegree; } public Integer getEdittime() { return edittime; } public void setEdittime(Integer edittime) { this.edittime = edittime; } public Integer getSpare1() { return spare1; } public void setSpare1(Integer spare1) { this.spare1 = spare1; } public Integer getSpare2() { return spare2; } public void setSpare2(Integer spare2) { this.spare2 = spare2; } public String getSpare3() { return spare3; } public void setSpare3(String spare3) { this.spare3 = spare3 == null ? null : spare3.trim(); } public String getSpare4() { return spare4; } public void setSpare4(String spare4) { this.spare4 = spare4 == null ? null : spare4.trim(); } }
true
88d74ed5ff0f98e03a0fa426667066e99c070eb4
Java
H4lfE1f/trpp-second-13_2
/src/main/java/ru/mirea/trpp_second_13/controllers/CarController.java
UTF-8
1,599
2.734375
3
[]
no_license
package ru.mirea.trppsecond13.controllers; import com.opencsv.bean.CsvToBeanBuilder; import io.micronaut.http.HttpResponse; import io.micronaut.http.annotation.Controller; import io.micronaut.http.annotation.Get; import ru.mirea.trppsecond13.entity.Car; import java.io.InputStreamReader; import java.util.List; import java.util.Optional; /** Контроллер для работы с автомобилями. */ @Controller("/car") public class CarController { /** Список автомобилей. */ private final List<Car> carList; /** Конструктор. */ public CarController() { carList = new CsvToBeanBuilder<Car>(new InputStreamReader(this.getClass() .getResourceAsStream("/MOCK_DATA.csv"))).withType(Car.class).build().parse(); } /** * Получить список автомобилей. * @return список автомобилей */ @Get() public HttpResponse<List<Car>> getCars() { return HttpResponse.ok(carList); } /** * Найти автомобиль по идентификатору. * @param id идентификатор автомобиля * @return Автомобиль, если есть, иначе 404 ошибка */ @Get("/{id}") public HttpResponse<Car> findById(Long id) { Optional<Car> result = carList.stream().filter(it -> it.getId().equals(id)).findAny(); if (result.isPresent()) { return HttpResponse.ok(result.get()); } else { return HttpResponse.notFound(); } } }
true
e20b0e702e876fc50aec121b1343d823d8046d7b
Java
AppInformation/AppInformation
/src/cn/easybuy/service/UserListService.java
GB18030
459
2.03125
2
[]
no_license
package cn.easybuy.service; import cn.easybuy.entity.Page; import cn.easybuy.entity.User; public interface UserListService { /** * ҳ * @param index * @param sum * @return */ public Page Select(int index); /** * ɾû * @param id * @return */ public int delete(int id); /** * ޸û */ public int update(User user); /** * idѯû */ public User SelectId(int dd); }
true
8c225eaf24b989882c67c07df3e1a7df9dc5addd
Java
moutainhigh/Vshop
/Vshop-service/src/main/java/com/Vshop/service/module/goods/service/TranSportService.java
UTF-8
214
1.632813
2
[]
no_license
package com.Vshop.service.module.goods.service; import java.util.List; import com.Vshop.core.entity.Transport; public interface TranSportService { public List<Transport> queryStoreList(Integer storeId); }
true
b098cfac362ce5300ddb8bc8b5094260dccc4933
Java
ljcservice/autumnprogram
/src/main/java/com/hitzd/WebPage/Impl/BasePageBean.java
UTF-8
4,977
2.3125
2
[ "Apache-2.0" ]
permissive
package com.hitzd.WebPage.Impl; import java.util.LinkedHashMap; import com.hitzd.DBUtils.TCommonRecord; import com.hitzd.WebPage.PageView; import com.hitzd.WebPage.QueryResult; import com.hitzd.DBUtils.CommonMapper; import com.hitzd.persistent.Persistent4DB; /** * 分页基类 * @author Administrator * */ public class BasePageBean extends Persistent4DB { /** * 分页操作 * @param maxresult 一页显示记录数 * @param currentpage 页码 * @param queryCode 系统代码 * @param wheres 条件 * @param value 参数值 * @param orders 排序 * @param tableName 表名 * @param fields 字段名称 * @return */ @SuppressWarnings ("unchecked") public PageView<TCommonRecord> getScrollData(int maxresult, int currentpage, String queryCode ,String wheres,Object[] value ,LinkedHashMap<String, String> orders,String tableName,String fields) { setQueryCode(queryCode); /* 分页数据集合 */ QueryResult<TCommonRecord> qr = new QueryResult<TCommonRecord>(); /* 页码 */ currentpage = currentpage < 1 ? 1 : currentpage; /* 一页显示记录数 */ maxresult = maxresult < 1? 12 : maxresult; PageView<TCommonRecord> pageView = new PageView<TCommonRecord>(maxresult,currentpage); /* 数据总数 */ StringBuffer countSql = new StringBuffer(); countSql.append("select count(*) total from ").append(tableName).append(" where 1=1 ").append(wheres); /* 数据总数 */ qr.setTotalrecord(((TCommonRecord)query.queryForObject(countSql.toString(),value == null ? new Object[]{} : value,new CommonMapper())).getInt("total")); /* 当总页数小于当前页 当前页设置为 第一页 */ if(((qr.getTotalrecord() / maxresult) + ((qr.getTotalrecord() % maxresult) > 0 ? 1 : 0 )) < currentpage) { pageView.setCurrentpage(1); } Integer firstindex = (pageView.getCurrentpage()-1) * pageView.getMaxresult(); Integer lastindex = (pageView.getCurrentpage()) * pageView.getMaxresult(); /* 是否指定字段查询 */ fields = fields == null? "*": fields; /* 分页数据 */ StringBuffer pageSql = new StringBuffer("select * from (select t.* ,rownum rn from (select ").append(fields).append(" from "); pageSql.append(tableName).append(" where 1=1 ").append(wheres); pageSql.append(getOrder(orders)); pageSql.append(") t where rownum <= ").append(lastindex.toString()).append(") b where b.rn > ").append(firstindex.toString()); /* 分页数据 */ qr.setResultlist(query.query(pageSql.toString(),value == null?new Object[]{}:value, new CommonMapper())); pageView.setQueryResult(qr); return pageView; } public PageView<TCommonRecord> getScrollData(int maxresult, int currentpage, String queryCode ,String wheres,Object[] value ,LinkedHashMap<String, String> orders,String tableName) { return getScrollData( maxresult, currentpage, queryCode , wheres, value , orders, tableName ,null); } public PageView<TCommonRecord> getScrollData(int maxresult, int currentpage,String queryCode, String tableName) { return getScrollData(maxresult, currentpage, queryCode,null,null ,null, tableName,null); } public PageView<TCommonRecord> getScrollData(int maxresult, int currentpage,String queryCode,String wheres, String tableName) { return getScrollData(maxresult, currentpage, queryCode,wheres,null ,null, tableName,null); } public PageView<TCommonRecord> getScrollData(int maxresult, int currentpage,String queryCode,String wheres,LinkedHashMap<String , String> orders, String tableName) { return getScrollData(maxresult, currentpage, queryCode,wheres,null ,orders, tableName,null); } public PageView<TCommonRecord> getScrollData(int maxresult, int currentpage,String queryCode,String wheres ,Object[] value , String tableName) { return getScrollData(maxresult, currentpage, queryCode,wheres,value ,null, tableName,null); } /** * 构建排序方法 * @param orders * @return */ private String getOrder(LinkedHashMap<String, String> orders) { StringBuffer strOrder = new StringBuffer(""); if(orders!=null&&orders.size()>0) { strOrder.append(" order by "); for(String order :orders.keySet()) { strOrder.append(order).append(" ").append(orders.get(order)).append(","); } strOrder.deleteCharAt(strOrder.length()-1); } return strOrder.toString(); } }
true
d838523e3bf9a10407f686055ba063c5d88ca1ba
Java
ilover5555/cacaoeng
/kakaoeng/src/main/java/Kakao/kakaoeng/servlet/StudentScheduleServlet.java
UTF-8
6,468
2.203125
2
[]
no_license
package Kakao.kakaoeng.servlet; import java.io.IOException; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; 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.springframework.context.ApplicationContext; import Kakao.kakaoeng.Checker; import Kakao.kakaoeng.Util; import Kakao.kakaoeng.dao.ClassLogDAO; import Kakao.kakaoeng.dao.HolidayDAO; import Kakao.kakaoeng.dao.LectureDAO; import Kakao.kakaoeng.dao.OneClassDAO; import Kakao.kakaoeng.dao.StudentDAO; import Kakao.kakaoeng.dao.TeacherDAO; import Kakao.kakaoeng.domain.model.ClassLog; import Kakao.kakaoeng.domain.model.Lecture; import Kakao.kakaoeng.domain.model.OneClass; import Kakao.kakaoeng.domain.model.Student; import Kakao.kakaoeng.domain.model.StudentSchedule; import Kakao.kakaoeng.domain.model.Lecture.Status; import Kakao.kakaoeng.domain.model.StudentSchedule.StudentClassState; @SuppressWarnings("serial") @WebServlet("/m5/studentSchedule.view") public class StudentScheduleServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Calendar calendar = Calendar.getInstance(); Student student = (Student) req.getSession().getAttribute("student"); if(student == null){ resp.sendRedirect("./main/main.jsp"); return; } String yearString = req.getParameter("year"); String monthString = req.getParameter("month"); int year = calendar.get(Calendar.YEAR); int month = calendar.get(Calendar.MONTH)+1; int date = calendar.get(Calendar.DATE); int purchaseNumber = -1; boolean reloadFlag = false; try{year = Integer.parseInt(yearString);}catch(NumberFormatException e){reloadFlag=true;} try{month = Integer.parseInt(monthString);}catch(NumberFormatException e){reloadFlag=true;} try{purchaseNumber = Integer.parseInt(req.getParameter("purchaseNumber"));}catch(NumberFormatException e){} if(reloadFlag){ resp.sendRedirect("./studentSchedule.view?year="+year+"&month="+month+"&purchaseNumber="+purchaseNumber); return; } Date firstOfMonth = Util.getFirstDateOfMonth(year, month); Date lastOfMonth = Util.getLastDateOfMonth(year, month); ApplicationContext applicationContext = (ApplicationContext) req.getServletContext().getAttribute("applicationContext"); LectureDAO lectureDAO = (LectureDAO) applicationContext.getBean("lectureDAO"); ClassLogDAO classLogDAO = (ClassLogDAO) applicationContext.getBean("classLogDAO"); OneClassDAO oneClassDAO = (OneClassDAO) applicationContext.getBean("oneClassDAO"); HolidayDAO holidayDAO = (HolidayDAO) applicationContext.getBean("holidayDAO"); List<Lecture> lectureList = lectureDAO.getLectureListByStudentId(student.getId()); for(Iterator<Lecture> iter = lectureList.iterator(); iter.hasNext();){ Lecture lecture = iter.next(); if(!lecture.getStatus().equals(Status.OnGoing)) iter.remove(); } if(purchaseNumber == -1 && lectureList.size() >= 1) purchaseNumber = lectureList.get(0).getPurchaseNumber(); Lecture lecture = lectureDAO.getOnGoingLectureByPurchase(purchaseNumber); if(lectureList.size() == 0){ resp.sendRedirect("./student_empty_schedule.jsp"); return; } Map<String, ClassLog> classLogMap = new HashMap<>(); Map<OneClass, List<ClassLog>> map = new HashMap<>(); List<OneClass> oneClassList = oneClassDAO.getOneClassListGroupedByLectureIdTransaction(lecture.getId()); Checker customCalendarCodeList = new Checker(); for(OneClass oneClass : oneClassList){ List<ClassLog> classLogList = classLogDAO.getClassLogListByParent(oneClass.getParent(), firstOfMonth, lastOfMonth); oneClass.setStartDate(lecture); map.put(oneClass, classLogList); customCalendarCodeList.add(oneClass); oneClass.setDone(classLogList); for(ClassLog element : classLogList){ classLogMap.put(Util.dateFormatting(element.getClassDate()), element); } } lecture.setDone(oneClassList); lecture.setEndDate(oneClassList, classLogDAO, holidayDAO); List<Date> fullCalendar = Util.getFullMonthCalendar(year, month); List<StudentSchedule> scheduleList = new ArrayList<>(); for(Date element : fullCalendar){ if(element.before(firstOfMonth) || element.after(lastOfMonth)){ scheduleList.add(new StudentSchedule(element, null, month)); continue; } ClassLog classLog = classLogMap.get(Util.dateFormatting(element)); StudentClassState state = null; if(classLog != null){ switch (classLog.getClassState()) { case Completed: state = StudentClassState.Completed; break; case PostponeStudent: state = StudentClassState.PostponeStudent; break; case PostponeTeacher: state = StudentClassState.PostponeTeacher; break; case AbsentStudent: state = StudentClassState.AbsentStudent; break; case AbsentTeacher: state = StudentClassState.AbsentTeacher; break; case Uncompleted: case Uncompleted_0: case Uncompleted_100: case Uncompleted_30: case Uncompleted_50: state = StudentClassState.Uncompleted; break; default: break; } } boolean start = false; if(Util.dateFormatting(lecture.getStartDate()).equals(element)) start = true; scheduleList.add(new StudentSchedule(element, state, month, start)); } StudentDAO studentDAO = (StudentDAO) applicationContext.getBean("studentDAO"); TeacherDAO teacherDAO = (TeacherDAO) applicationContext.getBean("teacherDAO"); lecture.loadStudent(studentDAO); lecture.loadTeacher(teacherDAO); req.setAttribute("lecture", lecture); req.setAttribute("lectureList", lectureList); req.setAttribute("scheduleList", scheduleList); req.setAttribute("customCalendarCodeList", customCalendarCodeList); req.setAttribute("today", Util.dateFormatting(new Date())); req.setAttribute("holidayDAO", applicationContext.getBean("holidayDAO")); req.getRequestDispatcher("./student_schedule.jsp?year="+year+"&month="+month+"&purchaseNumber="+purchaseNumber).forward(req, resp); } }
true
dd62914adc6d5cf424dacf864111d7e1d58ba8cd
Java
lvbing92/chintec-ikks
/ikks-erp/src/main/java/com/chintec/ikks/erp/feign/ICredentialsService.java
UTF-8
2,793
2.0625
2
[]
no_license
package com.chintec.ikks.erp.feign; import com.chintec.ikks.common.entity.vo.CredentialsRequest; import com.chintec.ikks.common.util.ResultResponse; import io.swagger.annotations.ApiOperation; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.*; /** * <p> * 服务类 * </p> * * @author Jeff·Tang * @since 2020-08-26 */ @FeignClient(value = "ikks-auth",path = "/v1") public interface ICredentialsService { /** * 用户列表查询 * * @param pageSize 页数 * @param currentPage 当前页 * @param role 角色 * @param status 状态 * @param searchValue 查询条件 * @param sorted 排序 * @return ResultResponse */ @ApiOperation(value = "用户列表查询") @GetMapping(value = "/users") ResultResponse getUserList(@RequestParam(value = "pageSize", required = false) Integer pageSize, @RequestParam(value = "currentPage", required = true) Integer currentPage, @RequestParam(value = "role", required = false) String role, @RequestParam(value = "status", required = false) String status, @RequestParam(value = "searchValue", required = false) String searchValue, @RequestParam(value = "sorted", required = false) String sorted); /** * 新增用户 * * @param credentialsRequest 用户对象 * @return ResultResponse */ @ApiOperation(value = "用户新增") @PostMapping(value = "/user/add") ResultResponse addUser(@RequestBody CredentialsRequest credentialsRequest); /** * 通过Id查询用户 * * @param id 用户Id * @return ResultResponse */ @ApiOperation(value = "用户列表查询") @GetMapping(value = "/user/{id}") ResultResponse queryUser(@PathVariable Integer id); /** * 更新客户 * @param credentialsRequest 客户信息 * @return ResultResponse */ @ApiOperation(value = "更新客户") @PutMapping("/user/update") ResultResponse updateUser(CredentialsRequest credentialsRequest); /** * 删除用户 * * @param id 用户Id * @return ResultResponse */ @ApiOperation(value = "删除用户") @DeleteMapping(value = "/user/{id}") ResultResponse deleteUser(@PathVariable Integer id); /** * 查询当前登录人角色和菜单信息 * * @param token 当前登录人token * @return ResultResponse */ @ApiOperation(value = "获取角色和菜单信息") @PostMapping(value = "/user/roleAndMenu") ResultResponse getRoleAndMenu(@RequestParam(value = "token") String token); }
true
a550e81211cca17a69d2717d30d3a90bd5b20263
Java
lchen666/lchen
/lchen-common/lchen-common-swagger/src/main/java/com/lchen/common/swagger/dto/ApiJsonDocumentationBuilder.java
UTF-8
606
2.078125
2
[]
no_license
package com.lchen.common.swagger.dto; import java.util.List; public class ApiJsonDocumentationBuilder { private String name; private List<ApiJsonPropertySingle> properties; public ApiJsonDocumentationBuilder name(String name){ this.name = name; return this; } public ApiJsonDocumentationBuilder properties(List<ApiJsonPropertySingle> properties){ this.properties = properties; return this; } public ApiJsonDocumentation build(){ return new ApiJsonDocumentation( name, properties ); } }
true
094cf535656416473d73d2c27d24508d3a12dcaf
Java
ericchangzmm/com.jije.boh.demo
/plugins/com.jije.boh.demo.jpa/src/com/jije/boh/demo/jpa/repository/BascStoreRepository.java
UTF-8
1,804
1.875
2
[]
no_license
package com.jije.boh.demo.jpa.repository; import java.util.Collection; import java.util.Date; import java.util.List; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.repository.PagingAndSortingRepository; import org.springframework.transaction.annotation.Transactional; import com.jije.boh.demo.domain.model.BascStore; /** * Store CRUD repository * * @author Paul.Yu */ @Transactional public interface BascStoreRepository extends PagingAndSortingRepository<BascStore, String>, JpaSpecificationExecutor<BascStore> { @Transactional(readOnly = true) public BascStore findByXcompany(String xcompany); @Transactional(readOnly = true) public List<BascStore> findByXnameLike(String xname); @Transactional(readOnly = true) public List<BascStore> findByXnameIn(Collection<String> xnames); @Transactional(readOnly = true) public List<BascStore> findByXstatus(int xstatus); @Transactional(readOnly = true) public BascStore findByXrefnumber(String xrefnumber); @Transactional(readOnly = true) public List<BascStore> findByXplugininfo(String xplugininfo); @Transactional(readOnly = true) public List<BascStore> findByXstoreid(String xstoreid); @Transactional(readOnly = true) public List<BascStore> findByXcreateby(String xcreateby); @Transactional(readOnly = true) public List<BascStore> findByXinsertby(String xinsertby); @Transactional(readOnly = true) public List<BascStore> findByXcreatetime(Date xcreatetime); @Transactional(readOnly = true) public List<BascStore> findByXinserttime(Date xinserttime); @Transactional(readOnly = true) public List<BascStore> findByXlastupdatetime(Date xlastupdatetime); @Transactional(readOnly = true) public List<BascStore> findByXlastupdateby(String xlastupdateby); }
true
8da5ee5dd3d6059f93e94d0f4a776b4854865038
Java
heatork/piggy
/THIRD_LIBS/HBLTest/src/com/howbuy/frag/control/FragControlBubble.java
UTF-8
2,272
2.265625
2
[]
no_license
package com.howbuy.frag.control; import java.util.ArrayList; import android.content.Context; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.howbuy.control.RandomBubbleView; import com.howbuy.control.RandomBubbleView.BubbleClickListener; import com.howbuy.lib.adp.AbsSimpleAdp; import com.howbuy.lib.adp.AbsViewHolder; import com.howbuy.lib.frag.AbsFrag; import com.howbuy.lib.utils.LogUtils; import com.howbuy.libtest.R; public class FragControlBubble extends AbsFrag implements BubbleClickListener { private RandomBubbleView mGroup = null; @Override protected int getFragLayoutId() { return R.layout.frag_control_bubble; } @Override protected void initViewAdAction(View root, Bundle bundle) { mGroup = (RandomBubbleView)root.findViewById(R.id.lay_content); mGroup.setAdapter(new MyAdp(getSherlockActivity(),createItems(150))); mGroup.setBubbleClickListener(this); } public ArrayList<String> createItems(int n){ ArrayList<String> list=new ArrayList<String>(); for(int i=0;i<n;i++){ list.add(""+i); } return list; } class MyAdp extends AbsSimpleAdp<String> { public MyAdp(LayoutInflater lf, ArrayList<String> items) { super(lf, items); } public MyAdp(Context cx, ArrayList<String> items) { super(cx, items); } @Override protected View getViewFromXml(int type,ViewGroup p) { TextView mTv=new TextView(getSherlockActivity()); mTv.setTextSize(40); mTv.setBackgroundResource(R.drawable.xml_bt_blue); return mTv; } @Override public void recycleView(int index, View v) { TextView tv = (TextView) v; tv.setText("-1"); } @Override protected AbsViewHolder<String> getViewHolder() { return new BubbleViewHolder(); } class BubbleViewHolder extends AbsViewHolder<String>{ public TextView mTv=null; @Override protected void initView(View root, int type) { mTv=(TextView) root; } @Override protected void initData(int index, int type, String item, boolean isReuse) { mTv.setText(""+index); } } } @Override public void onBubbleClickListener(RandomBubbleView p, View v, int index) { pop("click "+index,false); } }
true
6e164325af83ca27b3f6eab4ddc9b49da7b74e5e
Java
kjwinic/communication
/ICQServer/src/ServerThread.java
GB18030
8,118
2.421875
2
[]
no_license
import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.PrintStream; import java.net.Socket; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Vector; public class ServerThread extends Thread { private Socket netClient; private Vector<Customer> userOnline; private Vector<Chat> userChat; private Vector<Chat>privateChat; private ObjectInputStream fromClient; private PrintStream toClient; private Object obj; private ServerFrame sFrame; static Connection getconn()//ݿ { String url="jdbc:mysql://localhost:3306/icq?useUnicode=true&characterEncoding=utf-8&useSSL=false"; String user="root"; String password="poiu321ert789"; try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } Connection conn = null; try { conn = DriverManager.getConnection(url,user,password); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return conn; } public ServerThread(){} @SuppressWarnings({ "rawtypes", "unchecked" }) public ServerThread(ServerFrame frame, Socket client, Vector u, Vector c,Vector pc)throws IOException { netClient = client; userOnline = u; userChat = c; privateChat=pc; sFrame = frame; try { // ˫ͨ // ͻ fromClient = new ObjectInputStream(netClient.getInputStream()); // дͻ toClient = new PrintStream(netClient.getOutputStream()); } catch (IOException e) { try { netClient.close(); } catch (IOException e1) { System.out.println("ܽ" + e1); return; } } this.start(); } public void run() { try {// objObjectĶ obj = (Object) fromClient.readObject(); System.out.println(obj); System.out.println("privateChat"); if (obj.getClass().getName().equals("Customer")) { try { serverLogin(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if (obj.getClass().getName().equals("Register_Customer")) { serverRegiste(); } if (obj.getClass().getName().equals("Chat")) { serverChat(); } if(obj.getClass().getName().equals("Message")) { this.serverMessage(); } if(obj.getClass().getName().equals("Exit")) { serverExit(); } } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e1) { System.out.println("" + e1); } finally { try { netClient.close(); } catch (IOException e) { System.out.println(e); } } if(this.sFrame.textArea.getLineCount()>50) { sFrame.textArea.setText(""); } } public void serverLogin() throws SQLException { Customer clientMessage = (Customer) obj; this.userChat.clear(); Connection c=getconn(); String sql="SELECT USER,PASSWORD FROM usertable WHERE USER=?"; PreparedStatement prepare; prepare = c.prepareStatement(sql); prepare.clearParameters(); prepare.setString(1,clientMessage.custName); ResultSet r=prepare.executeQuery(); if(r.next()) { String pass=r.getString("password").trim(); if(clientMessage.custPassword.regionMatches(0, pass, 0, pass.length())) { this.sFrame.textArea.append("¼ɹok\n"); this.userOnline.addElement(clientMessage); System.out.println("¼ɹ"); toClient.println("¼ɹ"); String setip ="update usertable set ip=? where user=?"; PreparedStatement prest =c.prepareStatement(setip); prest.clearParameters(); prest.setString(1,this.netClient.getInetAddress().getHostAddress()); prest.setString(2,clientMessage.custName); @SuppressWarnings("unused") int set=prest.executeUpdate(); String status="update usertable set status=1 where user=?"; PreparedStatement prest2=c.prepareStatement(status); prest2.clearParameters();prest2.setString(1,clientMessage.custName); @SuppressWarnings("unused") int set2=prest2.executeUpdate(); try { c.commit(); } catch(SQLException ex) { } } else { toClient.println(""); } } else { toClient.println("û"); this.sFrame.textArea.append("û\n"); } } public void serverRegiste() { Register_Customer clientMessage2 = (Register_Customer) obj; try { Connection c2=getconn(); String sql2="insert into usertable(user,password,status,ip)"+" values(?,?,0,0)"; PreparedStatement prepare2; prepare2 = c2.prepareStatement(sql2); prepare2.clearParameters(); prepare2.setString(1,clientMessage2.custName ); prepare2.setString(2, clientMessage2.custPassword); prepare2.execute(); this.sFrame.textArea.append("עɹ\n"); toClient.println("עɹ"); System.out.println("עɹ"); try { c2.commit(); } catch(SQLException ex) { } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void serverChat() { Chat cObj = new Chat(); cObj = (Chat) obj; this.sFrame.textArea.append(cObj.chatUser+""+cObj.chatToUser+"Ϣ\n"+cObj.chatMessage+"˽="+cObj.whisper+"\n"); // ϢлӵϢʸ if(cObj.whisper){ privateChat.addElement((Chat)cObj); } else { userChat.addElement((Chat) cObj); } } public void serverMessage() { try { Message mess = (Message)obj; Message tomess=new Message(); tomess.userOnLine = userOnline; tomess.name=mess.name; Vector<Chat> privateChat2=new Vector<Chat>(); tomess.chat = userChat; String txt=""; for(int i=0;i<privateChat.size();i++) { Chat chat=privateChat.elementAt(i); if(chat.chatToUser.equals(mess.name)) { txt+=chat.chatMessage; privateChat2.addElement((Chat)chat); } } System.out.println("privateChat:"+txt); //tomess.privatechat=privateChat2; tomess.privatechat=privateChat2; //privateChat2.removeAllElements(); ObjectOutputStream outputstream = new ObjectOutputStream(netClient .getOutputStream()); outputstream.writeObject((Message) tomess); System.out.println("messfromServer"); // server list // sFrame.list.setListData(new String[] { "3", "4", "5" }); netClient.close(); outputstream.close(); } catch (IOException e) { } } @SuppressWarnings("unused") public void serverExit() { Exit exit = new Exit(); exit = (Exit) obj; Connection c=getconn(); String sql="update usertable set status=0 where user=?"; PreparedStatement prepare; try { prepare = c.prepareStatement(sql); prepare.clearParameters(); prepare.setString(1,exit.exitname); int r=prepare.executeUpdate(); this.userChat.clear(); this.privateChat.clear(); removeUser(exit); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } // chenmin } /** * ûɾ˳û * * @param exit ˳û */ private void removeUser(Exit exit) { // TODO Զɷ Vector<Customer> vec = new Vector<Customer>(); Customer _cus = null; for (int j = 0; j < userOnline.size(); j++) { _cus = (Customer) userOnline.get(j); if (!exit.exitname.equals(_cus.custName)) { vec.add(_cus); } // System.out.println("list:"+_cus.custName); } userOnline.removeAllElements(); for (int j = 0; j < vec.size(); j++) { _cus = (Customer) vec.get(j); userOnline.add(_cus); } } }
true
a3580ffe98523eab722836ce7e9a0ccd75784458
Java
Monti90/RPG-Catalog-CRUD
/rpgcollection/src/main/java/wasko/collectionmanager/rpgcollection/security/ApplicationSecurityConfig.java
UTF-8
5,117
2.015625
2
[]
no_license
package wasko.collectionmanager.rpgcollection.security; import lombok.AllArgsConstructor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpMethod; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.AuthenticationProvider; import org.springframework.security.authentication.DefaultAuthenticationEventPublisher; import org.springframework.security.authentication.dao.DaoAuthenticationProvider; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.CorsConfigurationSource; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; import org.springframework.web.filter.CorsFilter; import wasko.collectionmanager.rpgcollection.services.LoginDetailsService; import javax.sql.DataSource; import java.util.Arrays; @Configuration @EnableWebSecurity @AllArgsConstructor public class ApplicationSecurityConfig extends WebSecurityConfigurerAdapter { private DataSource dataSource; private PasswordEncoder passwordEncoder; private LoginDetailsService loginDetailsService; private JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint; private JwtRequestFilter jwtRequestFilter; public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { // configure AuthenticationManager so that it knows from where to load // user for matching credentials // Use BCryptPasswordEncoder auth.userDetailsService(loginDetailsService).passwordEncoder(passwordEncoder); } @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable(); http .authorizeRequests() .antMatchers(HttpMethod.DELETE,"/**").hasRole("ADMIN") .antMatchers(HttpMethod.POST, "/game", "/user").hasRole("ADMIN") .antMatchers(HttpMethod.POST, "/authenticate") .permitAll() .anyRequest().authenticated() .and() .cors() .and() .exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint).and().sessionManagement() .sessionCreationPolicy(SessionCreationPolicy.STATELESS); // Add a filter to validate the tokens with every request http.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class); } @Bean @Override public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } @Bean public AuthenticationProvider daoAuthenticationProvider(){ final DaoAuthenticationProvider provider = new DaoAuthenticationProvider(); provider.setPasswordEncoder(passwordEncoder); provider.setUserDetailsService(loginDetailsService); return provider; } @Bean public DefaultAuthenticationEventPublisher defaultAuthenticationEventPublisher(){ return new DefaultAuthenticationEventPublisher(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.authenticationProvider(daoAuthenticationProvider()); auth.authenticationEventPublisher(defaultAuthenticationEventPublisher()); } @Bean public CorsFilter corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); CorsConfiguration config = new CorsConfiguration(); config.setAllowCredentials(true); // you USUALLY want this // likely you should limit this to specific origins config.addAllowedOrigin("http://localhost:4200"); config.addAllowedHeader("Content-Type"); config.addAllowedHeader("X-XSRF-TOKEN"); config.addAllowedHeader("x-requested-with"); config.addAllowedHeader("Authorization"); config.addAllowedHeader("X-Pagination-Total-Pages"); config.addAllowedHeader("X-Pagination-Total-Entries"); config.addAllowedHeader("X-Pagination-Current-Page"); config.addAllowedHeader("X-Pagination-Per-Page"); config.addAllowedMethod("GET"); config.addAllowedMethod("POST"); config.addAllowedMethod("PUT"); config.addAllowedMethod("DELETE"); source.registerCorsConfiguration("/**", config); return new CorsFilter(source); } }
true
5575be4221af1e3ebbd6bea5c147ef4ffeeb878e
Java
pikkolo78/esercizio-prenotazionu-sportello
/Main.java
UTF-8
2,937
3.8125
4
[]
no_license
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner input =new Scanner(System.in); //creaiamo metodo scannere per acquisire da tastiera Sportello sportello1 =new Sportello();//creaiamo oggetto sportello //creaimo menu per utente String risposta;//tramite il do while ,nel do facciamo stampare sempre il menu do { System.out.println("Menu Sportello: "); System.out.println("1. Inserisci prenotazione "); System.out.println("2. Prossima prenotazione"); System.out.println("3. Rinuncia prenotazione"); System.out.println("4. Tempo attesa"); System.out.println("5. Stampa prenotazioni"); System.out.println("6. esci"); System.out.println("");//e poi lo gestiamo tramite lo switch risposta=input.nextLine();//si associa alla variabile in stringa la scelta del menu switch(risposta)//per ogni risposta uncaso e un metodo da fare con le relative eccezioni....e le risposte acquisite da tastiera tramite i metodo next.int() o next.line() { case "1": System.out.println("Digita nome e cognome"); sportello1.prenota(input.nextLine());break; case "2": try { sportello1.estrai();break; } catch(Exception ex) { System.out.println(ex); } case "3": try { System.out.println("Digita il numero della prenotazione da annullare"); sportello1.rinuncia(input.nextInt());break; } catch(Exception ex) { System.out.println(ex); } case "4": try { System.out.println("Digita il numero della prenotazione"); int numero= Integer.parseInt(input.nextLine()) ; System.out.println("Il tempo di attesa della prenotazione "+ numero + " e' "+sportello1.tempoAttesa(numero));break; } catch(Exception ex) { System.out.println(ex); } case "5": System.out.println(sportello1);break; case "6":break; default : System.out.println("selezione errata");break; } } while(!risposta.equals("6"));//appena si digita il 6 la condizione del while viene a finire e si esce se si vuole dal programma } }
true
d2a089cf9242e449b9e440652c799e97cf8d15fa
Java
daewoong/OWL4RDB
/Janus/src/janus/database/DBBridgeFactory.java
UTF-8
368
2.53125
3
[]
no_license
package janus.database; public class DBBridgeFactory { public static DBBridge getDBBridge(DBMSTypes DBMS_TYPE, String host, String port, String id, String password, String schema) { DBBridge dbBridge = null; if(DBMS_TYPE.equals(DBMSTypes.MY_SQL)) dbBridge = MySQLBridge.getInstance(host, port, id, password, schema); return dbBridge; } }
true
e3998d8d719590ef39847d22d91db99068f0fe6f
Java
tokyorider/NetSnake
/src/events/BecomeAdminEvent.java
UTF-8
770
2.328125
2
[]
no_license
package events; import me.ippolitov.fit.snakes.SnakesProto; import java.net.InetAddress; public class BecomeAdminEvent extends Event { private int selfId; private InetAddress oldAdminIp; private SnakesProto.GameState lastGameState; public BecomeAdminEvent(int selfId, InetAddress oldAdminIp, SnakesProto.GameState lastGameState) { super(EventType.BECOME_ADMIN); this.selfId = selfId; this.oldAdminIp = oldAdminIp; this.lastGameState = lastGameState; } public int getSelfId() { return selfId; } public InetAddress getOldAdminIp() { return oldAdminIp; } public SnakesProto.GameState getLastGameState() { return lastGameState; } }
true
303fb5b30b6cb96bf95c8ca43eeec9c4ddf13aa7
Java
kanaida/LG-Esteem-Homeless-Kernel
/out/target/common/obj/JAVA_LIBRARIES/android_stubs_current_intermediates/src/org/apache/http/impl/cookie/RFC2965Spec.java
UTF-8
1,196
2.078125
2
[]
no_license
package org.apache.http.impl.cookie; public class RFC2965Spec extends org.apache.http.impl.cookie.RFC2109Spec { public RFC2965Spec() { throw new RuntimeException("Stub!"); } public RFC2965Spec(java.lang.String[] datepatterns, boolean oneHeader) { throw new RuntimeException("Stub!"); } public java.util.List<org.apache.http.cookie.Cookie> parse(org.apache.http.Header header, org.apache.http.cookie.CookieOrigin origin) throws org.apache.http.cookie.MalformedCookieException { throw new RuntimeException("Stub!"); } public void validate(org.apache.http.cookie.Cookie cookie, org.apache.http.cookie.CookieOrigin origin) throws org.apache.http.cookie.MalformedCookieException { throw new RuntimeException("Stub!"); } public boolean match(org.apache.http.cookie.Cookie cookie, org.apache.http.cookie.CookieOrigin origin) { throw new RuntimeException("Stub!"); } protected void formatCookieAsVer(org.apache.http.util.CharArrayBuffer buffer, org.apache.http.cookie.Cookie cookie, int version) { throw new RuntimeException("Stub!"); } public int getVersion() { throw new RuntimeException("Stub!"); } public org.apache.http.Header getVersionHeader() { throw new RuntimeException("Stub!"); } }
true
862c5bbc8b66e295f6942432bd6ae7056d29b955
Java
ScottMaclure/Kantban
/test/models/StoryTest.java
UTF-8
5,664
2.609375
3
[]
no_license
package models; import static org.hamcrest.Matchers.*; import static matchers.Matchers.recentDate; import java.util.Calendar; import java.util.List; import org.hamcrest.Matcher; import org.junit.After; import org.junit.Test; import services.SystemTime; public class StoryTest extends BasicModelTest { /** * Test that we can create a new story, and that this story has the right parameters. */ @Test public void newStoryTest() { String title = "Story title"; String description = "Some <a href=\"Link\">text</a> to go into this story"; Project project = getDefaultProject(); State state = project.defaultState(); Story story = state.newStory(title, getDefaultUser()); assertThat(story, notNullValue()); story.description = description; assertThat(story.getState().project, is(getDefaultProject())); story.save(); project = getDefaultProject(); assertThat(project, is(story.getState().project)); assertThat(project.defaultState().stories.size(), is(1)); List<Story> stories = Story.findAll(); assertThat(1, is(stories.size())); story = stories.get(0); assertThat(story, notNullValue()); assertThat(title, is(story.title)); assertThat(description, is(story.description)); assertThat(story.createdOn, is(recentDate())); assertThat(story.updatedOn, is(recentDate())); assertThat(getDefaultUser(), is(story.createdUser)); assertThat(getDefaultProject().states.get(0), is(story.getState())); assertFalse(story.isArchived()); } // Check a story's state private void checkState(Story story, Integer lead, Integer cycle, int block, int wait, int work) { if (lead == null) assertThat(story.getLeadTime(), nullValue()); else assertThat(story.getLeadTime(), is(lead)); if (cycle == null) assertThat(story.getCycleTime(), nullValue()); else assertThat(story.getCycleTime(), is(cycle)); assertThat(story.getBlockTime(), is(block)); assertThat(story.getWaitTime(), is(wait)); assertThat(story.getWorkTime(), is(work)); } // fast forward time private int warp(Calendar timeLine, int minutes) { timeLine.add(Calendar.MINUTE, minutes); SystemTime.setDate(timeLine.getTime()); return minutes; } /** * Test that the statistics about work states are kept correctly */ @Test public void testStatistics() { Calendar timeLine = Calendar.getInstance(); int leadTime = warp(timeLine, 0); Story story = getDefaultStory(); assertThat(story, notNullValue()); // test initial state checkState(story, null, null, 0, 0, 0); // Get some states to move the story along List<State> states = story.getState().project.states; //State sandbox = states.get(0); State analysis = states.get(1); State work = states.get(2); State archive = states.get(states.size() - 1); // after 30 minutes, move it to the analysis lane leadTime += warp(timeLine, 30); analysis.addStory(story); assertThat(story.getState(), is(analysis)); checkState(story, null, null, 0, 0, 0); // work on it for 5 minutes, then a further 15 leadTime += warp(timeLine, 5); checkState(story, null, null, 0, 0, 5 * 60); leadTime += warp(timeLine, 15); checkState(story, null, null, 0, 0, (5 + 15) * 60); // block it for 20 minutes story.setBlocked(true); leadTime += warp(timeLine, 20); checkState(story, null, null, 20 * 60, 0, (5 + 15) * 60); // unblock it for 10 minutes story.setBlocked(false); checkState(story, null, null, 20 * 60, 0, (5 + 15) * 60); leadTime += warp(timeLine, 10); checkState(story, null, null, 20 * 60, 0, (5 + 15 + 10) * 60); // block for another 5 story.setBlocked(true); leadTime += warp(timeLine, 5); checkState(story, null, null, (20 + 5) * 60, 0, (5 + 15 + 10) * 60); // mark as ready story.setReady(true); assertFalse(story.isBlocked()); checkState(story, null, null, (20 + 5) * 60, 0, (5 + 15 + 10) * 60); leadTime += warp(timeLine, 7); checkState(story, null, null, (20 + 5) * 60, 7 * 60, (5 + 15 + 10) * 60); // block again story.setBlocked(true); assertFalse(story.isReady()); checkState(story, null, null, (20 + 5) * 60, 7 * 60, (5 + 15 + 10) * 60); leadTime += warp(timeLine, 25); checkState(story, null, null, (20 + 5 + 25) * 60, 7 * 60, (5 + 15 + 10) * 60); // mark as ready again story.setReady(true); leadTime += warp(timeLine, 13); checkState(story, null, null, (20 + 5 + 25) * 60, (7 + 13) * 60, (5 + 15 + 10) * 60); // pull to next lane, and work on it for 21 minutes work.addStory(story); assertFalse(story.isReady()); checkState(story, null, null, (20 + 5 + 25) * 60, (7 + 13) * 60, (5 + 15 + 10) * 60); leadTime += warp(timeLine, 21); checkState(story, null, null, (20 + 5 + 25) * 60, (7 + 13) * 60, (5 + 15 + 10 + 21) * 60); // Now archive it archive.addStory(story); checkState(story, leadTime * 60, (leadTime - 30) * 60, (20 + 5 + 25) * 60, (7 + 13) * 60, (5 + 15 + 10 + 21) * 60); warp(timeLine, 210); checkState(story, leadTime * 60, (leadTime - 30) * 60, (20 + 5 + 25) * 60, (7 + 13) * 60, (5 + 15 + 10 + 21) * 60); } }
true
c4b05e1e3b2b1a175c7a9744fe1469384e57a39d
Java
jmepicapp/YoDono-apirest
/src/main/java/com/proyecto/integrado/yodono/service/PoblacionService.java
UTF-8
798
2.171875
2
[]
no_license
package com.proyecto.integrado.yodono.service; import com.proyecto.integrado.yodono.model.dto.PoblacionDTO; import com.proyecto.integrado.yodono.model.Poblacion; import java.util.List; import java.util.Optional; /** * Service Interface for managing {@link Poblacion}. */ public interface PoblacionService { /** * Get all the poblacions. * * @return the list of entities. */ List<PoblacionDTO> findAll(); /** * Get all the provincias by comunidad. * * @param id the provincia_id * @return the list of entities. */ List<PoblacionDTO> findAllByProvincia(Long id); /** * Get the "id" poblacion. * * @param id the id of the entity. * @return the entity. */ Optional<PoblacionDTO> findOne(Long id); }
true
5d3c78a690a46e0f7bf7399871c40976c3f05928
Java
TheShermanTanker/NMS-1.16.3
/com/mysql/jdbc/Constants.java
UTF-8
991
1.984375
2
[]
no_license
/* */ package com.mysql.jdbc; /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ public class Constants /* */ { /* 33 */ public static final byte[] EMPTY_BYTE_ARRAY = new byte[0]; /* */ /* */ /* */ /* */ /* 38 */ public static final String MILLIS_I18N = Messages.getString("Milliseconds"); /* */ /* 40 */ public static final byte[] SLASH_STAR_SPACE_AS_BYTES = new byte[] { 47, 42, 32 }; /* */ /* 42 */ public static final byte[] SPACE_STAR_SLASH_SPACE_AS_BYTES = new byte[] { 32, 42, 47, 32 }; /* */ } /* Location: C:\Users\Josep\Downloads\Decompile Minecraft\tuinity-1.16.3.jar!\com\mysql\jdbc\Constants.class * Java compiler version: 5 (49.0) * JD-Core Version: 1.1.3 */
true
465d3f982991872b05040497a2291009dd97be6a
Java
jiage2018/weather
/app/src/main/java/com/jiage/weather/gson/WeatherAqi.java
UTF-8
1,147
1.9375
2
[ "Apache-2.0" ]
permissive
package com.jiage.weather.gson; import com.google.gson.annotations.SerializedName; public class WeatherAqi { public Basic basic; public update update; public String status; @SerializedName("air_now_city") public Aqi weatheraqi; } /* { "HeWeather6":[ { "basic":{"cid":"CN101200801","location":"荆州","parent_city":"荆州","admin_area":"湖北","cnty":"中国","lat":"30.32685661","lon":"112.23812866","tz":"+8.00"}, "update":{"loc":"2019-01-16 08:05","utc":"2019-01-16 00:05"}, "status":"ok", "air_now_city":{"aqi":"87","qlty":"良","main":"PM10","pm25":"42","pm10":"123","no2":"45","so2":"14","co":"1.3","o3":"9","pub_time":"2019-01-16 08:00"}, "air_now_station":[ {"air_sta":"市图书馆","aqi":"84","asid":"CNA1844","co":"1.2","lat":"30.3175","lon":"112.2551","main":"PM10","no2":"41","o3":"12","pm10":"118","pm25":"36","pub_time":"2019-01-16 08:00","qlty":"良","so2":"16"}, {"air_sta":"市委党校","aqi":"89","asid":"CNA1845","co":"1.3","lat":"30.3515","lon":"112.2068","main":"PM10","no2":"49","o3":"5","pm10":"128","pm25":"47","pub_time":"2019-01-16 08:00","qlty":"良","so2":"12"}]}]} */
true
5f3369f50eecd6ab331ccccb0d9a57672987f404
Java
loveonwheels/ClientApplicationApp
/app/src/main/java/com/mSIHAT/client/fragments/LoginFragment.java
UTF-8
8,896
2.125
2
[]
no_license
package com.mSIHAT.client.fragments; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.mSIHAT.client.APIServices.RestUserService; import com.mSIHAT.client.MainActivity; import com.mSIHAT.client.R; import com.mSIHAT.client.models.UserP; import com.mSIHAT.client.utils.Constants; import java.util.regex.Matcher; import java.util.regex.Pattern; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; /** * A simple {@link Fragment} subclass. * Activities that contain this fragment must implement the * {@link LoginFragment.OnFragmentInteractionListener} interface * to handle interaction events. * Use the {@link LoginFragment#newInstance} factory method to * create an instance of this fragment. */ public class LoginFragment extends Fragment { // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private static final String ARG_PARAM1 = "param1"; private static final String ARG_PARAM2 = "param2"; // TODO: Rename and change types of parameters private String mParam1; private String mParam2; EditText username; EditText password; private ProgressDialog progressBar; private RestUserService restUserService; private OnFragmentInteractionListener mListener; public LoginFragment() { // Required empty public constructor } /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 Parameter 1. * @param param2 Parameter 2. * @return A new instance of fragment LoginFragment. */ // TODO: Rename and change types and number of parameters public static LoginFragment newInstance(String param1, String param2) { LoginFragment fragment = new LoginFragment(); Bundle args = new Bundle(); args.putString(ARG_PARAM1, param1); args.putString(ARG_PARAM2, param2); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { mParam1 = getArguments().getString(ARG_PARAM1); mParam2 = getArguments().getString(ARG_PARAM2); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_login, container, false); restUserService = new RestUserService(); Button login = (Button)view.findViewById(R.id.btnLogin); username = (EditText) view.findViewById(R.id.input_username); password = (EditText) view.findViewById(R.id.input_pwd); login.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String usernametxt = username.getText().toString(); String passwordtxt = password.getText().toString(); if(isValidEmail(usernametxt) && isValidPassword(passwordtxt)){ progressBar = new ProgressDialog(getActivity()); progressBar.setMessage(getString(R.string.logging_in)); progressBar.setProgressStyle(ProgressDialog.STYLE_SPINNER); progressBar.setIndeterminate(true); progressBar.show(); Call<UserP> call = restUserService.getService().validateLogin(usernametxt, passwordtxt); call.enqueue(new Callback<UserP>() { @Override public void onResponse(Call<UserP> call, Response<UserP> response) { int statusCode = response.code(); UserP userP = response.body(); String msg = null; if (statusCode == 200) { msg = getString(R.string.welcome) + userP.fullname + "!"; Intent loginIntent = new Intent(getActivity(), MainActivity.class); Bundle loginBundle = new Bundle(); loginBundle.putInt(Constants.EXTRA_USER_ID, userP.id); loginBundle.putString(Constants.EXTRA_USER_FULLNAME, userP.fullname); loginBundle.putString(Constants.EXTRA_USER_EMAIL, userP.email); loginIntent.putExtras(loginBundle); startActivity(loginIntent); } else if (statusCode == 404){ msg = getString(R.string.invalid_username_and_or_password); android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(getActivity()); builder.setMessage("Authentication failed verify username and password") .setCancelable(false) .setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { } }); android.app.AlertDialog alert = builder.create(); alert.show(); } else msg = String.valueOf(statusCode); progressBar.dismiss(); Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show(); } @Override public void onFailure(Call<UserP> call, Throwable t) { progressBar.dismiss(); Toast.makeText(getActivity(), t.getMessage(), Toast.LENGTH_SHORT).show(); } }); } else { if(!isValidEmail(usernametxt)){ username.setError(getString(R.string.invalid_username)); } if(!isValidPassword(passwordtxt)){ password.setError(getString(R.string.invalid_password)); } } } }); /* register.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(getActivity().getBaseContext(), RegistrationActivity.class); getActivity().startActivity(intent); getActivity().overridePendingTransition(R.anim.move, R.anim.moveout); } });*/ return view; } private boolean isValidEmail(String email){ String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@" + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"; Pattern pattern = Pattern.compile(EMAIL_PATTERN); Matcher matcher = pattern.matcher(email); if(email.trim().length() == 0){ return false; } else { return matcher.matches(); } } private boolean isValidPassword(String password){ if(password != null && password.length() > 0){ return true; } return false; } // TODO: Rename method, update argument and hook method into UI event public void onButtonPressed(Uri uri) { if (mListener != null) { mListener.onFragmentInteraction(uri); } } @Override public void onDetach() { super.onDetach(); mListener = null; } /** * This interface must be implemented by activities that contain this * fragment to allow an interaction in this fragment to be communicated * to the activity and potentially other fragments contained in that * activity. * <p/> * See the Android Training lesson <a href= * "http://developer.android.com/training/basics/fragments/communicating.html" * >Communicating with Other Fragments</a> for more information. */ public interface OnFragmentInteractionListener { // TODO: Update argument type and name void onFragmentInteraction(Uri uri); } }
true
b94ba26f54021ec8b6bbc6eb8bd8f3e63b13c975
Java
akashgalagali/FMS
/ForestryManagementSystem/src/main/java/com/cg/fms/dao/IOrderDao.java
UTF-8
426
1.882813
2
[]
no_license
package com.cg.fms.dao; import org.springframework.data.jpa.repository.JpaRepository; import com.cg.fms.dto.Orders; public interface IOrderDao extends JpaRepository<Orders,String>{ // public Orders getOrder(String orderNumber); // // public boolean addOrder(Orders order); // // public boolean updateOrder(Orders order); // // public boolean deleteOrder(String orderNumber); // // public List<Orders> getAllOrders(); }
true
95f5d576e21c57e1d94250e69223a989270778d0
Java
pranju123/Playground
/Matinee movie tickets/Main.java
UTF-8
260
2.40625
2
[]
no_license
#include<iostream> using namespace std; int main() { int age; float show; cin>>age>>show; if(age<=13) { if(show<=12.00) cout<<"$4.00"; else cout<<"$2.00"; } else if(age>13) { if(show<=12.00) cout<<"$8.00"; else cout<<"$5.00"; } }
true
b6863d94a85c3b77b1ba691984a28626e97d8496
Java
Egor2001/twilight-imperium
/src/main/java/player/units/GroundForce/Infantry.java
UTF-8
162
2.140625
2
[]
no_license
package player.units.GroundForce; import player.Race; public class Infantry extends GroundForce { public Infantry(Race race) { super(race); } }
true
c497f246812743bbb717f5c51756a5ac3d6766eb
Java
druidJane/Druid3.0.3
/web-server/server-common/src/main/java/com/xuanwu/mos/domain/enums/StatusCode.java
UTF-8
1,553
3
3
[]
no_license
package com.xuanwu.mos.domain.enums; import com.xuanwu.mos.domain.handler.HasIndexValue; import com.xuanwu.mos.exception.BusinessException; /** * Created by 林泽强 on 2016-8-28. UploadResult状态编码 */ public enum StatusCode implements HasIndexValue { /** * 成功 */ Success(0), /** * 失败:单个文件大小超过限制 */ FileSizeExceeded(-1), /** * 失败:请求表单类型不正确 */ InvalidContentType(-2), /** * 失败:文件类型不正确 */ InvalidFileType(-3), /** * 失败:文件内容为空 */ NoContent(-4), /** * 失败:请使用正确的分隔符 */ InvalidDelimiter(-5), /** * 文件头或文件内容为空 */ NoExistFileHead(-6), /** * 失败:其它错误 */ Other(-9); private int index; private StatusCode(int index) { this.index = index; } public String getStateDesc() { switch (index) { case 0: return "成功。"; case -1: return "文件大小超过限制!"; case -2: return "请求表单类型不正确!"; case -3: return "文件类型不正确!"; case -4: return "文件内容为空!"; case -5: return "请使用正确的分隔符!"; case -6: return "文件头或文件内容为空"; default: return "其它错误!"; } } public static StatusCode getStatus(int index) { for (StatusCode ret : StatusCode.values()) { if (ret.getIndex() == index) return ret; } throw new BusinessException("Invalid status value: " + index); } @Override public int getIndex() { return index; } }
true
fea25408bce17e7f4f8ae797e9fb25f03a3e0336
Java
felizju/java_basic_study
/src/day11/poly/car/Driver.java
UTF-8
1,155
3.625
4
[]
no_license
package day11.poly.car; public class Driver { /* void drive(Sonata s){ System.out.println("운전을 시작합니다."); s.run(); } void drive(Tusan t){ System.out.println("운전을 시작합니다."); t.run(); } void drive(Boxter b){ System.out.println("운전을 시작합니다."); b.run(); }*/ // 매개변수의 다형성 void drive(Car c){ // xx.drive(new Sonata()); System.out.println("운전을 시작합니다."); c.run(); } // 리턴 타입의 다형성 Car buyCar(String carName){ if(carName.equals("투싼")){ System.out.println("투싼을 구매합니다."); return new Tusan(); }else if(carName.equals("쏘나타")){ System.out.println("쏘나타을 구매합니다."); return new Sonata(); }else if(carName.equals("박스터")){ System.out.println("박스터을 구매합니다."); return new Boxter(); }else{ System.out.println("해당 차량은 없습니다."); return null; } } }
true
c4b26df10e5cf1c9d4509a28dc2638424dae8dfe
Java
Pharmazon/GeekUniversity
/cloud-storage/server/src/main/java/ru/cloud/storage/server/util/Assets.java
UTF-8
881
2.25
2
[]
no_license
package ru.cloud.storage.server.util; import ru.cloud.storage.server.service.AuthService; import java.nio.file.Path; public class Assets { private static final Assets ourInstance = new Assets(); public static Assets getInstance() { return ourInstance; } private AuthService authService; private Path serverPath; private int bufferSize; public AuthService getAuthService() { return authService; } public Path getServerPath() { return serverPath; } public int getBufferSize() { return bufferSize; } public void setServerPath(Path serverPath) { this.serverPath = serverPath; } public void setBufferSize(int bufferSize) { this.bufferSize = bufferSize; } private Assets() { this.authService = new AuthService(); authService.connect(); } }
true
ba262948fdd7ff7a6e48f54ba68caffe271cfcc9
Java
LeeDohyoung/project_toy
/src/main/java/com/happylopers/wakeup/controller/WakeUpController.java
UTF-8
2,584
2.1875
2
[]
no_license
package com.happylopers.wakeup.controller; import javax.inject.Inject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import com.happylopers.wakeup.domain.WakeUpVO; import com.happylopers.wakeup.service.WakeUpService; @Controller @RequestMapping("/wakeup/*") public class WakeUpController { private static final Logger logger = LoggerFactory.getLogger(WakeUpController.class); @Inject private WakeUpService service; @RequestMapping(value = "", method = RequestMethod.GET) public String root(Model model, RedirectAttributes rttr) throws Exception { return "redirect:/wakeup/list"; } @RequestMapping(value = "/list", method = RequestMethod.GET) public void list(Model model) throws Exception { logger.info("기상일지 리스트 호출 "); model.addAttribute("list",service.list()); } @RequestMapping(value="/register", method = RequestMethod.POST) public String registPOST(WakeUpVO vo, RedirectAttributes rttr) throws Exception{ logger.info("기상 데이터 등록"); logger.info(vo.toString()); service.updateWakeUp(vo); return "redirect:/wakeup/list"; } @RequestMapping(value="/register", method = RequestMethod.GET) public void registGET() throws Exception{ logger.info("등록 GET 들어옴"); } @RequestMapping(value = "/delete", method = RequestMethod.POST) public String delete(WakeUpVO vo, RedirectAttributes rttr)throws Exception{ logger.info("기상 일지 삭제 시퀀스 : "+vo.getSeq()); service.remove(vo); return "redirect:/wakeup/list"; } @RequestMapping(value = "/modify", method = RequestMethod.POST) public String modifyPOST(@RequestParam("modal_date") String modal_date, @RequestParam("modal_comment") String modal_comment, @RequestParam("modal_seq") int modal_seq, RedirectAttributes rttr) throws Exception{ logger.info("기상 일지 수정 POST"); //System.out.println("modal_date,modal_comment,modal_seq "+modal_date+" "+modal_comment+" "+modal_seq); service.modify(modal_date,modal_comment,modal_seq); return "redirect:/wakeup/list"; } }
true
b8b987bda3eb88c6135da02d22826c3e2e3b2d21
Java
VHAINNOVATIONS/Telepathology
/Source/Java/CoreValueObjects/main/src/java/gov/va/med/imaging/exchange/business/storage/ArtifactSourceInfo.java
UTF-8
1,007
2.28125
2
[ "Apache-2.0" ]
permissive
/** * */ package gov.va.med.imaging.exchange.business.storage; import gov.va.med.imaging.core.interfaces.StorageCredentials; import java.io.Serializable; /** * @author vhaiswpeterb * */ public class ArtifactSourceInfo implements Serializable, StorageCredentials { private static final long serialVersionUID = 1L; private String type = null; private String identifier = null; private String username = null; private String password = null; /** * Constructor */ public ArtifactSourceInfo(String type, String identifier, String username, String password){ this.type = type; this.identifier = identifier; this.username = username; this.password = password; } /** * @return the type */ public String getType() { return type; } /** * @return the identifier */ public String getIdentifier() { return identifier; } @Override public String getPassword() { return this.password; } @Override public String getUsername() { return this.username; } }
true
463d7143ac0e7d732634e0ec064931e3a2ae38f6
Java
bcyran/func-analyzer
/src/main/java/pl/bazylicyran/funcanalyzer/math/FunctionDiscretizer.java
UTF-8
2,696
3.53125
4
[]
no_license
package pl.bazylicyran.funcanalyzer.math; import java.util.ArrayList; import java.util.List; /** * Discretizes function in given interval and with given resolution. * * @author Bazyli Cyran */ public class FunctionDiscretizer { /** String with function to discretize. */ private String input; private FunctionExpression function; /** Start of interval in which function will be discretized. */ private double intervalStart; /** End of interval in which function will be discretized. */ private double intervalEnd; /** Discretization resolution. */ private double resolution; /** Discretized function. */ private List<CSPoint> points = new ArrayList<>(); /** Whether or not function was discretized. */ private boolean discretized = false; /** * Creates empty FunctionDiscretizer. */ public FunctionDiscretizer() { } /** * Creates FunctionDiscretizer with given values. * * @param function Function to discretize. * @param intervalStart Start of discretization interval. * @param IntervalEnd End of discretization interval. * @param resolution Discretization resolution. */ public FunctionDiscretizer(String function, double intervalStart, double intervalEnd, double resolution) { this.input = function; this.intervalStart = intervalStart; this.intervalEnd = intervalEnd; this.resolution = resolution; } /** * Sets given string as current function to discretize. * * @param function Function to discretize. */ public void setFunction(String function) { input = function; discretized = false; } /** * Sets discretizer interval to given values. * * @param intervalStart Start of interval. * @param intervalEnd End of interval. */ public void setInterval(double intervalStart, double intervalEnd) { this.intervalStart = intervalStart; this.intervalEnd = intervalEnd; } /** * Sets discretizer resolution to given value. * * @param resolution Resolution to set. */ public void setResolution(double resolution) { this.resolution = resolution; } /** * Returns list of discretized points. * * @return Discretized points. */ public List<CSPoint> getPoints() { if (discretized == false) { discretize(); } return points; } /** * Discretizes current function. */ private void discretize() { points.clear(); function = new FunctionExpression(input); Double value; for (double x = intervalStart; x <= intervalEnd; x += resolution) { function.setVar("x", x); try { value = function.getValue(); } catch (ArithmeticException e) { value = null; } CSPoint point = new CSPoint(x, value); points.add(point); } discretized = true; } }
true
36366729981eff22324708b177a2dc0e1d7bb7b4
Java
heshengyx/electric-service
/src/main/java/com/grgbanking/electric/mapper/IEventMapper.java
UTF-8
1,480
2.28125
2
[]
no_license
package com.grgbanking.electric.mapper; import java.util.List; import org.apache.ibatis.annotations.Param; import com.grgbanking.electric.entity.Event; import com.grgbanking.electric.param.EventQueryParam; public interface IEventMapper { /** * 新增 * @param event * @return */ int save(@Param("param") Event event); /** * 批量新增 * @param events * @return */ int saveBatch(@Param("list") List<Event> events); /** * 修改 * @param event */ int update(@Param("param") Event event); /** * 根据ID删除 * @param id */ int deleteById(@Param("id") String id); /** * 多条件删除 * @param event */ int delete(@Param("param") Event event); /** * 根据ID批量删除 * @param id */ int deleteByIds(@Param("ids") List<String> ids); /** * 根据ID查找 * @param id * @return */ Event getById(@Param("id") String id); /** * 多条件查找 * @param event * @return */ Event getData(@Param("param") Event event); int count(@Param("param") EventQueryParam param); List<Event> query(@Param("param") EventQueryParam param, @Param("start") int start, @Param("end") int end); /** * 查找全部 * @param param * @return */ List<Event> queryAll(@Param("param") EventQueryParam param); }
true
f7768dda038bd5f4c9a145fc37988c77a7e55741
Java
AamirB/myproject
/src/main/java/com/yourl/service/AccountServiceImpl.java
UTF-8
3,839
2.53125
3
[]
no_license
package com.yourl.service; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.Base64; import java.util.HashMap; import java.util.Map; import java.util.StringTokenizer; import java.util.concurrent.ConcurrentHashMap; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.yourl.dto.AccountCreateResponse; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; @Service public class AccountServiceImpl implements AccountService { private Map<String, String> userById = new ConcurrentHashMap<>(); @Autowired public PassWordGeneratorService passWordGeneratorService; private Map<String, String> currentSession = new HashMap<String, String>(); @Override public String findUserById(String id) { return userById.get(id); } @Override public void storeUserPwdAndId(String id, String pwd) { userById.put(id, pwd); } @Override public AccountCreateResponse createAccount(String id) { AccountCreateResponse res = new AccountCreateResponse(); if (findUserById(id) == null) { String passwrd = passWordGeneratorService.getSaltString(); storeUserPwdAndId(id, passwrd); res.setDescription( "Successfully created account with password " + passwrd); res.setSuccess(true); res.setPassword(passwrd); } else { res.setDescription("Account already exist with ID " + id); res.setSuccess(false); } return res; } @Override public boolean authenticateUser(String userId, String password) { if (userById.get(userId) == null) { return false; } else if (userById.get(userId).equals(password)) { return true; } return false; } @Override public boolean authenticateUser(String accountId, String password, HttpServletRequest request, HttpServletResponse response) { if (authenticateUser(accountId, password)) { try { String jwt = Jwts.builder().setSubject("users/TzMUocMF4p") .claim("username", accountId) .signWith(SignatureAlgorithm.HS256, "secret".getBytes("UTF-8")) .compact(); Cookie cookie = new Cookie("token", jwt); cookie.setMaxAge(60 * 60 * 24 * 365); response.setContentType("text/html"); cookie.setPath("/"); response.addCookie(cookie); setLoggedInuser(accountId); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return true; } return false; } @Override public boolean authenticate(String authCredentials) { if (null == authCredentials) return false; // header value format will be "Basic encodedstring" for Basic // authentication. Example "Basic YWRtaW46YWRtaW4=" final String encodedUserPassword = authCredentials .replaceFirst("Basic" + " ", ""); String usernameAndPassword = null; try { byte[] decodedBytes = Base64.getDecoder() .decode(encodedUserPassword); usernameAndPassword = new String(decodedBytes, "UTF-8"); } catch (IOException e) { e.printStackTrace(); } final StringTokenizer tokenizer = new StringTokenizer( usernameAndPassword, ":"); final String username = tokenizer.nextToken(); final String password = tokenizer.nextToken(); // we have fixed the userid and password as admin // call some UserService/LDAP here boolean authenticationStatus = authenticateUser(username, password); return authenticationStatus; } @Override public void setLoggedInuser(String accountId) { currentSession.put("user", accountId); } @Override public String getLoggedInuser() { return currentSession.get("user"); } @Override public void logoutUser(HttpServletRequest request, HttpServletResponse response) { currentSession.remove("user"); } }
true
8adbae925f79170b5cd3a71cf6f37692c91c7106
Java
marqusm/demo-backend
/src/main/java/com/marqusm/demobackendrestjavaspringboot/annotation/CacheAffecting.java
UTF-8
357
1.867188
2
[ "MIT" ]
permissive
package com.marqusm.demobackendrestjavaspringboot.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** @author : Marko Mišković */ @Retention(value = RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface CacheAffecting {}
true
061e33750ec48b98d00ee1f9ed7ed948e7c5a64f
Java
qiuchili/ggnn_graph_classification
/program_data/github_java_program_data/49/565.java
UTF-8
2,901
2.90625
3
[ "MIT" ]
permissive
package com.mycompany.maventest; import no.uib.cipr.matrix.DenseMatrix; import no.uib.cipr.matrix.Matrices; import no.uib.cipr.matrix.Matrix; public class LinearRegression { //# Training examples private int m; //# of features private int n; //Inputs (m*n) private Matrix X; //Outputs (m*1) private Matrix y; //Values to fit training data (n*1) private Matrix Theta; //Matrix of average X values for each feature private Matrix mu; //Matrix of standard deviations of each feature private Matrix sigma; public LinearRegression(Matrix x, Matrix y){ this.X = x; this.y = y; this.m = x.numRows(); this.n = x.numColumns(); this.Theta = MTJExt.Zeros(n, 1); } //add column of ones to X public void addBias(){ X = MTJExt.concat(MTJExt.Ones(m, 1), X, 1); n++; Theta = MTJExt.Zeros(n, 1); } //(1/2m)*(sum((X*Theta-y)^2)) public double costFunction(){ Matrix temp = MTJExt.minusExtend(X.mult(Theta, new DenseMatrix(m,1)), y); //Should be 1*1 matrix Matrix squaredSum = temp.transAmult(temp, new DenseMatrix(1,1)); return squaredSum.get(0,0)/(2*m); } //Normalize features public void featureNoramlize(){ mu = MTJExt.mean(X, 2); sigma = MTJExt.std(X, 2); X = GenFunc.featureNormalize(X, mu, sigma); } //perform gradient descent with learning rate alpha for iterns iterations, returns cost history if rec is true public Matrix gradientDescent(int iterns, double alpha, boolean rec){ double[][] costHist = new double[iterns][1]; for(int i = 0; i < iterns; i++){ Matrix temp = X.transAmult(MTJExt.minusExtend(X.mult(Theta, new DenseMatrix(m,1)),y), new DenseMatrix(n,1)); Theta = MTJExt.minusExtend(Theta,temp.scale(alpha/m)); if(rec) costHist[i][0] = costFunction(); } return new DenseMatrix(costHist); } //caluclate minumum using the normal equation public void normalEquation(){ Theta = (((X.transAmult(X, new DenseMatrix(n,n))).solve(Matrices.identity(n), new DenseMatrix(n,n))).transBmult(X, new DenseMatrix(n,m))).mult(y, new DenseMatrix(n,1)); } //predict output of a using current values of theta public double predict(Matrix a){ return a.mult(Theta,new DenseMatrix(1,1)).get(0, 0); } public Matrix getTheta(){ return Theta; } public Matrix getX(){ return X; } public Matrix getY(){ return y; } public Matrix getMu(){ return mu; } public Matrix getSigma(){ return sigma; } public int getM(){ return m; } public int getN(){ return n; } }
true
21cee75884a31db0fc1d3fbddca212203127d71c
Java
orlysemperfi/cartelerag6
/src/main/java/edu/upc/cartelerag6/cartelerag6/dao/JdbcComentarioRepository.java
UTF-8
7,400
2.390625
2
[]
no_license
package edu.upc.cartelerag6.cartelerag6.dao; import java.sql.Connection; import java.sql.Date; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import javax.sql.DataSource; import edu.upc.cartelerag6.cartelerag6.model.Comentario; import edu.upc.cartelerag6.cartelerag6.repository.ComentarioRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; @Repository public class JdbcComentarioRepository implements ComentarioRepository { @Autowired private DataSource dataSource; public Comentario registrarComentario(Integer idComentario, Integer idPelicula, String comentario, String estado, Date fechaCreacion) { Comentario c = null; String sql = "insert into T_COMENTARIO(idPelicula," + "comentario, estado, fechaRegistro) values (?, ?, ?, ?)"; Connection conn = null; PreparedStatement ps = null; try { conn = dataSource.getConnection(); ps = conn.prepareStatement(sql); ps.setInt(1, 1); ps.setString(2, comentario); ps.setString(3, estado); ps.setDate(4, fechaCreacion); ps.execute(); c = new Comentario (1, idPelicula, comentario, estado, fechaCreacion); return c; } catch (SQLException e) { throw new RuntimeException("Error al insertar un nuevo comentario.", e); } finally { if (ps != null) { try { // Close to prevent database cursor exhaustion ps.close(); } catch (SQLException ex) { } } if (conn != null) { try { // Close to prevent database connection exhaustion conn.close(); } catch (SQLException ex) { } } } } public Boolean actualizarEstado(Integer idComentario, Integer idPelicula, String estado) { Boolean actualizacionOk = false; String sql = "update T_COMENTARIO " + "Set Estado = ? " + "WHERE idComentario = ? and idPelicula = ? "; Connection conn = null; PreparedStatement ps = null; try { conn = dataSource.getConnection(); ps = conn.prepareStatement(sql); ps.setString(1, estado); ps.setInt(2, idComentario); ps.setInt(3, idPelicula); ps.executeUpdate(); actualizacionOk = true; } catch (SQLException e) { throw new RuntimeException("Error al actualizar comentario.", e); } finally { if (ps != null) { try { // Close to prevent database cursor exhaustion ps.close(); } catch (SQLException ex) { } } if (conn != null) { try { // Close to prevent database connection exhaustion conn.close(); } catch (SQLException ex) { } } } return actualizacionOk; } public ArrayList<Comentario> listarComentarios(Integer idPelicula, String estado) { String sql = "select * " + "from T_COMENTARIO " + "WHERE idPelicula = ? " + "AND estado = ? "; ArrayList<Comentario> comentarios = null; Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; try { conn = dataSource.getConnection(); ps = conn.prepareStatement(sql); ps.setInt(1, idPelicula); ps.setString(2, estado); rs = ps.executeQuery(); comentarios = mapComentarios(rs); } catch (SQLException e) { throw new RuntimeException("Error al seleccionar comentarios.", e); } finally { if (rs != null) { try { // Close to prevent database cursor exhaustion rs.close(); } catch (SQLException ex) { } } if (ps != null) { try { // Close to prevent database cursor exhaustion ps.close(); } catch (SQLException ex) { } } if (conn != null) { try { // Close to prevent database connection exhaustion conn.close(); } catch (SQLException ex) { } } } return comentarios; } public Comentario listarComentario(Integer idComentario, Integer idPelicula) { String sql = "select * " + "from T_COMENTARIO " + "WHERE idComentario = ? " + "AND idPelicula = ? "; Comentario comentario = null; Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; try { conn = dataSource.getConnection(); ps = conn.prepareStatement(sql); ps.setInt(1, idComentario); ps.setInt(2, idPelicula); rs = ps.executeQuery(); comentario = mapComentario(rs); } catch (SQLException e) { throw new RuntimeException("Error al obtener comentario.", e); } finally { if (rs != null) { try { // Close to prevent database cursor exhaustion rs.close(); } catch (SQLException ex) { } } if (ps != null) { try { // Close to prevent database cursor exhaustion ps.close(); } catch (SQLException ex) { } } if (conn != null) { try { // Close to prevent database connection exhaustion conn.close(); } catch (SQLException ex) { } } } return comentario; } public Boolean eliminarComentario(Integer idComentario, Integer idPelicula) { Boolean eliminacionOk = false; String sql = "delete from T_COMENTARIO " + "WHERE idComentario = ? and idPelicula = ? "; Connection conn = null; PreparedStatement ps = null; try { conn = dataSource.getConnection(); ps = conn.prepareStatement(sql); ps.setInt(1, idComentario); ps.setInt(2, idPelicula); ps.execute(); eliminacionOk = true; } catch (SQLException e) { throw new RuntimeException("Error al eliminar comentario.", e); } finally { if (ps != null) { try { // Close to prevent database cursor exhaustion ps.close(); } catch (SQLException ex) { } } if (conn != null) { try { // Close to prevent database connection exhaustion conn.close(); } catch (SQLException ex) { } } } return eliminacionOk; } private Comentario mapComentario(ResultSet rs) throws SQLException { Comentario comentario = null; while (rs.next()) { if (comentario == null) { Integer idComentario = rs.getInt("idComentario"); Integer idPelicula = rs.getInt("idPelicula"); String txComentario = rs.getString("comentario"); String estado = rs.getString("estado"); Date fechaRegistro = rs.getDate("fechaRegistro"); comentario = new Comentario(idComentario, idPelicula, txComentario, estado, fechaRegistro); } } if (comentario == null) { // no rows returned - throw an empty result exception //throw new EmptyResultDataAccessException(1); } return comentario; } private ArrayList<Comentario> mapComentarios(ResultSet rs) throws SQLException { Comentario comentario = null; ArrayList<Comentario> comentarios = new ArrayList<Comentario>(); while (rs.next()) { if (comentario == null) { Integer idComentario = rs.getInt("idComentario"); Integer idPelicula = rs.getInt("idPelicula"); String txComentario = rs.getString("comentario"); String estado = rs.getString("estado"); Date fechaRegistro = rs.getDate("fechaRegistro"); comentario = new Comentario(idComentario, idPelicula, txComentario, estado, fechaRegistro); if (comentario != null){ comentarios.add(comentario); comentario = null; } } } return comentarios; } }
true
d696c229cfd9c30ed7fdd506135ec821c2eb3259
Java
HQLboy/0721
/src/com/atguigu/test/Boy.java
UTF-8
608
3.25
3
[]
no_license
package com.atguigu.test; public class Boy { private String name; private int age; public Boy(String name, int age){ this.name = name; this.age = age; } public void setName(String name){ this.name = name; } public String getName(){ return name; } public void setAge(int age){ this.age = age; } public int getAge(){ return age; } public void marry(Girl girl){ System.out.println(this.name +":" +girl.getName() + "好啊,我和开心"); this.shout(); } public void shout(){ System.out.println("今晚你要嫁给我"); } }
true
3625d6e488e52e7d2817f82bfb7f52e848a74b4d
Java
thinkparadox/Android-MessegerDemo
/messagermodel/src/main/java/com/listenread/luhuanju/messagermodel/ServerService.java
UTF-8
1,615
2.453125
2
[]
no_license
package com.listenread.luhuanju.messagermodel; import android.app.Service; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.os.Message; import android.os.Messenger; import android.os.RemoteException; import android.support.annotation.Nullable; /** * Created by luhuanju on 16/5/27. * 服务器端的Service 处理客户端的链接请求 */ public class ServerService extends Service { private static final int MESSAGE = 0; private Messenger messenger = new Messenger(new MessengerHanlder()); private static class MessengerHanlder extends Handler { @Override public void handleMessage(Message msg) { switch (msg.what) { case MESSAGE: { //接收到客户端的消息 System.out.println(msg.getData().get("tag")); Message message = Message.obtain(null, 0); Bundle bundle = new Bundle(); bundle.putString("tag", "收到消息,这是回复"); message.setData(bundle); try { msg.replyTo.send(message); // msg.replyTo 返回的就是承载MESSAGE 消息的Messenger } catch (RemoteException e) { } break; } default: super.handleMessage(msg); } } } @Nullable @Override public IBinder onBind(Intent intent) { // return messenger.getBinder(); // } }
true
8883b62b351e7797e897460ca22360c9eb69af5c
Java
zgqq/flycat
/flycat-context/src/main/java/com/github/flycat/context/ContextManager.java
UTF-8
3,390
1.90625
2
[ "Apache-2.0" ]
permissive
/** * Copyright 2019 zgqq <zgqjava@gmail.com> * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.flycat.context; import com.github.flycat.log.logback.LogInterceptor; import com.github.flycat.module.Module; import com.github.flycat.module.ModuleManager; import com.github.flycat.util.CollectionUtils; import com.github.flycat.util.StringUtils; import com.github.flycat.util.date.DateFormatter; import com.github.flycat.util.io.FormatPrintStream; import com.github.flycat.context.util.ServerEnvUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.BufferedOutputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.PrintStream; import java.util.Date; import java.util.List; import java.util.ServiceLoader; public class ContextManager { private static final Logger LOGGER = LoggerFactory.getLogger(ContextManager.class); static List<ContextListener> contextListeners; static { ServiceLoader<ContextListener> loader = ServiceLoader.load(ContextListener.class); contextListeners = CollectionUtils.iteratorToList(loader.iterator()); } public static void beforeRun(RunContext runContext) { for (ContextListener contextListener : contextListeners) { contextListener.beforeRun(runContext); } Class<? extends Module>[] modules = runContext.getModules(); ModuleManager.load(modules); } private static void redirectOutputStream() { if (!ContextUtils.isLocalProfile()) { final String logDir = ServerEnvUtils.getProperty("logging.file.path"); if (StringUtils.isNotBlank(logDir)) { try { String format = DateFormatter.YYYYMMDD_HHMMSS.format(new Date()); String logPath = logDir + "console.out." + format + ".log"; System.setOut(new PrintStream(new BufferedOutputStream( new FileOutputStream(logPath)), true)); System.setErr(new PrintStream(new BufferedOutputStream( new FileOutputStream(logPath)), true)); } catch (FileNotFoundException e) { throw new RuntimeException("Unable to console file ", e); } } } System.setOut(new FormatPrintStream(System.out)); System.setErr(new FormatPrintStream(System.err)); } public static void afterRun(ApplicationContext applicationContext) { for (ContextListener contextListener : contextListeners) { contextListener.afterRun(applicationContext); } LogInterceptor.disableTrace = true; LOGGER.info("Slow log, content:{}", LogInterceptor.slowLog.get("main")); redirectOutputStream(); } }
true
f6a62b80ab6e7e28e38c4ad2d0dba8c65bcf91d9
Java
dazhaozhao/community
/src/main/java/com/alan/community/dto/TagDTO.java
UTF-8
290
1.5
2
[]
no_license
package com.alan.community.dto; import com.alan.community.cache.TagCache; import lombok.Data; import java.util.List; /** * @author alan * @date 2020/3/24 22:09 */ @Data public class TagDTO { private String categoryName; private List<String> tagCaches; }
true
c85e5186ffacdc4d61bf133f2e0e0305f9e9f4c6
Java
samhincks/RoadBrain2015
/src/NeuracleLabelingTask.java
UTF-8
1,526
3.078125
3
[]
no_license
import java.io.BufferedWriter; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.Socket; import java.net.UnknownHostException; public class NeuracleLabelingTask implements Runnable{ private static final String SERVER_IP = "127.0.0.1"; private int port = 1980; private static final int REST =1000; public String currentCondition = "junk"; public boolean NEW = true; public NeuracleLabelingTask(int port) { this.port = port; } @Override public void run(){ try( Socket socket = new Socket(SERVER_IP, port); PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true); ){ int index = 0; ///.. while there are no errors while(!out.checkError()){ if (NEW) { System.out.println("sending " + currentCondition + " to " + port); out.println(currentCondition); NEW = false; } Thread.sleep(REST); index++; } }catch(Exception e) { System.err.println("Moving on with, life... We didn't manage to connect to " + port); } } public void setCurrentCondition(String condition) { this.currentCondition = condition; NEW = true; } public static void main(String[] args) throws InterruptedException{ NeuracleLabelingTask n = new NeuracleLabelingTask(2212); new Thread(n).start(); Thread.sleep(500); n.setCurrentCondition("df"); } }
true
ff40c009d3cc0762963b06b533d09e1ee36f57d9
Java
patrWan/arquitectura_sw_kiosko
/Kiosko_app_final/src/gui/App.java
UTF-8
25,789
2.125
2
[]
no_license
package gui; import java.awt.Color; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JOptionPane; import model.Boleta; import model.Data; import model.Producto; import model.Tabla; import model.Tabla_boleta; import model.Tabla_venta; import model.Venta; public class App extends javax.swing.JFrame { private Data d; private int cantidad; private int id_producto; private int precio; private int stock; private int total_boleta; private List<Boleta> listaBoleta; private int fila; public App() { try { initComponents(); cantidad = 0; total_boleta = 0; d = new Data(); Panel2 p = new Panel2(); p.setVisible(false); cargarTabla(); listaBoleta = new ArrayList<>(); } catch (ClassNotFoundException ex) { Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex); } catch (SQLException ex) { Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex); } } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jFrame_historial_ventas = new javax.swing.JFrame(); jScrollPane3 = new javax.swing.JScrollPane(); tabla_ventas = new javax.swing.JTable(); jScrollPane4 = new javax.swing.JScrollPane(); tabla_boleta_det = new javax.swing.JTable(); calen_mes = new com.toedter.calendar.JMonthChooser(); calen_anio = new com.toedter.calendar.JYearChooser(); btn_calen_buscar = new javax.swing.JButton(); jButton1 = new javax.swing.JButton(); jScrollPane1 = new javax.swing.JScrollPane(); jtbProducto = new javax.swing.JTable(); jScrollPane2 = new javax.swing.JScrollPane(); jTable2 = new javax.swing.JTable(); btnAgregar = new javax.swing.JButton(); btn_generarVenta = new javax.swing.JButton(); txtCantidad = new javax.swing.JTextField(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); lbl_total = new javax.swing.JLabel(); txt_buscar = new javax.swing.JTextField(); btn_buscar = new javax.swing.JButton(); jLabel3 = new javax.swing.JLabel(); lbl_mensaje = new javax.swing.JLabel(); jMenuBar1 = new javax.swing.JMenuBar(); jMenu1 = new javax.swing.JMenu(); jMenuItem1 = new javax.swing.JMenuItem(); jMenuItem3 = new javax.swing.JMenuItem(); jMenuItem2 = new javax.swing.JMenuItem(); tabla_ventas.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null} }, new String [] { "Title 1", "Title 2", "Title 3", "Title 4" } )); tabla_ventas.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { tabla_ventasMouseClicked(evt); } }); jScrollPane3.setViewportView(tabla_ventas); tabla_boleta_det.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null} }, new String [] { "Title 1", "Title 2", "Title 3", "Title 4" } )); jScrollPane4.setViewportView(tabla_boleta_det); btn_calen_buscar.setText("Buscar"); btn_calen_buscar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btn_calen_buscarActionPerformed(evt); } }); jButton1.setText("Todas"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); javax.swing.GroupLayout jFrame_historial_ventasLayout = new javax.swing.GroupLayout(jFrame_historial_ventas.getContentPane()); jFrame_historial_ventas.getContentPane().setLayout(jFrame_historial_ventasLayout); jFrame_historial_ventasLayout.setHorizontalGroup( jFrame_historial_ventasLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jFrame_historial_ventasLayout.createSequentialGroup() .addGap(19, 19, 19) .addGroup(jFrame_historial_ventasLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jFrame_historial_ventasLayout.createSequentialGroup() .addComponent(calen_mes, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(calen_anio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btn_calen_buscar) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton1) .addGap(0, 0, Short.MAX_VALUE)) .addGroup(jFrame_historial_ventasLayout.createSequentialGroup() .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 429, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 68, Short.MAX_VALUE) .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 258, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap()) ); jFrame_historial_ventasLayout.setVerticalGroup( jFrame_historial_ventasLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jFrame_historial_ventasLayout.createSequentialGroup() .addContainerGap() .addGroup(jFrame_historial_ventasLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(calen_mes, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(calen_anio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(jFrame_historial_ventasLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btn_calen_buscar) .addComponent(jButton1))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jFrame_historial_ventasLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 158, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 158, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(88, Short.MAX_VALUE)) ); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jtbProducto.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null} }, new String [] { "Title 1", "Title 2", "Title 3", "Title 4" } )); jtbProducto.setName("tblProducto"); // NOI18N jtbProducto.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseReleased(java.awt.event.MouseEvent evt) { jtbProductoMouseReleased(evt); } }); jScrollPane1.setViewportView(jtbProducto); jTable2.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null} }, new String [] { "Title 1", "Title 2", "Title 3", "Title 4" } )); jScrollPane2.setViewportView(jTable2); btnAgregar.setText("Agregar"); btnAgregar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnAgregarActionPerformed(evt); } }); btn_generarVenta.setText("Generar Venta"); btn_generarVenta.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btn_generarVentaActionPerformed(evt); } }); jLabel1.setText("Cantidad:"); jLabel2.setText("Total:"); lbl_total.setText("0"); btn_buscar.setText("Buscar"); btn_buscar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btn_buscarActionPerformed(evt); } }); lbl_mensaje.setText("Estado"); jMenu1.setText("Opciones"); jMenuItem1.setText("Productos"); jMenuItem1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem1ActionPerformed(evt); } }); jMenu1.add(jMenuItem1); jMenuItem3.setText("Historial Ventas"); jMenuItem3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem3ActionPerformed(evt); } }); jMenu1.add(jMenuItem3); jMenuItem2.setText("Salir"); jMenuItem2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem2ActionPerformed(evt); } }); jMenu1.add(jMenuItem2); jMenuBar1.add(jMenu1); setJMenuBar(jMenuBar1); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(jLabel1) .addGap(18, 18, 18) .addComponent(txtCantidad, javax.swing.GroupLayout.PREFERRED_SIZE, 137, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnAgregar, javax.swing.GroupLayout.PREFERRED_SIZE, 224, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(layout.createSequentialGroup() .addComponent(txt_buscar, javax.swing.GroupLayout.PREFERRED_SIZE, 171, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(btn_buscar, javax.swing.GroupLayout.PREFERRED_SIZE, 154, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(layout.createSequentialGroup() .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 52, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(lbl_total, javax.swing.GroupLayout.PREFERRED_SIZE, 74, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 202, Short.MAX_VALUE) .addComponent(btn_generarVenta, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(lbl_mensaje, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addContainerGap(23, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(19, 19, 19) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(txt_buscar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btn_buscar))) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel3) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(lbl_mensaje))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 173, Short.MAX_VALUE) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(lbl_total)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(txtCantidad, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btnAgregar) .addComponent(jLabel1) .addComponent(btn_generarVenta)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jtbProductoMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jtbProductoMouseReleased if (evt.getClickCount() == 1) { //Cuand hace doble click.. fila = jtbProducto.getSelectedRow(); //Muestra la fila seleccionada.. System.out.println(fila); //Imprime la fila.. Tabla t = (Tabla) jtbProducto.getModel(); //Entrega el modelo y es necesario decirle a Java que es, TMFood. Producto p = t.getProducto(fila); //Estan todos los datos en Food. id_producto = p.getId(); precio = p.getPrecio(); stock = p.getStock(); System.out.println("Stock AL Click: " + stock); } }//GEN-LAST:event_jtbProductoMouseReleased private void btnAgregarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAgregarActionPerformed try { cantidad = Integer.parseInt(txtCantidad.getText()); int comStock = d.getStock(id_producto) - cantidad; System.out.println("Stock Al GREGAR: " + stock); System.out.println("CALCULO DE STOCK: " + comStock); if (comStock >= 0) { Boleta b = new Boleta(); b.setId_producto(id_producto); b.setCantidad(cantidad); int sub_tot = cantidad * precio; b.setSubtotal(sub_tot); total_boleta = total_boleta + sub_tot; listaBoleta.add(b); cargarTablaBoleta(); lbl_total.setText(String.valueOf(total_boleta)); lbl_mensaje.setText(null); } else { lbl_mensaje.setBackground(Color.red); lbl_mensaje.setText("Stock Insuficiente."); } txtCantidad.setText(null); } catch (Exception e) { } }//GEN-LAST:event_btnAgregarActionPerformed private void btn_generarVentaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_generarVentaActionPerformed try { d.generar_venta(listaBoleta, total_boleta); total_boleta = 0; lbl_total.setText(String.valueOf(total_boleta)); listaBoleta = new ArrayList<>(); cargarTablaBoleta(); cargarTabla(); } catch (SQLException ex) { Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex); } }//GEN-LAST:event_btn_generarVentaActionPerformed private void btn_buscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_buscarActionPerformed try { String text = txt_buscar.getText(); List<Producto> list = d.buscar_producto(text); Tabla t = new Tabla(list); jtbProducto.setModel(t); } catch (ClassNotFoundException ex) { Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex); } catch (SQLException ex) { Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex); } }//GEN-LAST:event_btn_buscarActionPerformed private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed try { this.setVisible(false); Panel2 panel = new Panel2(); panel.setVisible(true); } catch (ClassNotFoundException ex) { Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex); } catch (SQLException ex) { Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex); } }//GEN-LAST:event_jMenuItem1ActionPerformed private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem2ActionPerformed if (JOptionPane.showConfirmDialog(this, "¿Desea salir?", "Seguridad", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) { System.exit(0); } }//GEN-LAST:event_jMenuItem2ActionPerformed private void jMenuItem3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem3ActionPerformed cargarTablaVenta(); jFrame_historial_ventas.setVisible(true); jFrame_historial_ventas.setBounds(200, 350, 800, 300); }//GEN-LAST:event_jMenuItem3ActionPerformed private void tabla_ventasMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tabla_ventasMouseClicked fila = tabla_ventas.getSelectedRow(); //Muestra la fila seleccionada.. System.out.println(fila); //Imprime la fila.. Tabla_venta t = (Tabla_venta) tabla_ventas.getModel(); //Entrega el modelo y es necesario decirle a Java que es, TMFood. Venta v = t.getVenta(fila); cargarTablaBoleta(v.getId()); }//GEN-LAST:event_tabla_ventasMouseClicked private void btn_calen_buscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_calen_buscarActionPerformed int mes = calen_mes.getMonth()+1; int anio = calen_anio.getYear(); cargarTablaVentaFiltro(mes, anio); }//GEN-LAST:event_btn_calen_buscarActionPerformed private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed cargarTablaVenta(); }//GEN-LAST:event_jButton1ActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new App().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnAgregar; private javax.swing.JButton btn_buscar; private javax.swing.JButton btn_calen_buscar; private javax.swing.JButton btn_generarVenta; private com.toedter.calendar.JYearChooser calen_anio; private com.toedter.calendar.JMonthChooser calen_mes; private javax.swing.JButton jButton1; private javax.swing.JFrame jFrame_historial_ventas; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JMenu jMenu1; private javax.swing.JMenuBar jMenuBar1; private javax.swing.JMenuItem jMenuItem1; private javax.swing.JMenuItem jMenuItem2; private javax.swing.JMenuItem jMenuItem3; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JScrollPane jScrollPane3; private javax.swing.JScrollPane jScrollPane4; private javax.swing.JTable jTable2; private javax.swing.JTable jtbProducto; private javax.swing.JLabel lbl_mensaje; private javax.swing.JLabel lbl_total; private javax.swing.JTable tabla_boleta_det; private javax.swing.JTable tabla_ventas; private javax.swing.JTextField txtCantidad; private javax.swing.JTextField txt_buscar; // End of variables declaration//GEN-END:variables private void cargarTabla() { try { List<Producto> listaProductos = d.getListaProducto(); Tabla tipo = new Tabla(listaProductos); jtbProducto.setModel(tipo); } catch (SQLException ex) { Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex); } catch (ClassNotFoundException ex) { Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex); } } private void cargarTablaVenta() { try { List<Venta> listaVentas = d.getListaVenta(); Tabla_venta tv = new Tabla_venta(listaVentas); tabla_ventas.setModel(tv); } catch (SQLException ex) { Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex); } catch (ClassNotFoundException ex) { Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex); } } private void cargarTablaVentaFiltro(int mes,int anio) { try { List<Venta> listaVentas = d.getListaVentaPorMes(mes, anio); Tabla_venta tv = new Tabla_venta(listaVentas); tabla_ventas.setModel(tv); } catch (SQLException ex) { Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex); } catch (ClassNotFoundException ex) { Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex); } } private void cargarTablaBoleta() { try { List<Boleta> listaBoleta = this.listaBoleta; Tabla_boleta tb = new Tabla_boleta(listaBoleta); jTable2.setModel(tb); } catch (SQLException ex) { Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex); } catch (ClassNotFoundException ex) { Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex); } } private void cargarTablaBoleta(int id_venta) { try { List<Boleta> listaBoleta_v = d.getListaBoleta(id_venta); Tabla_boleta tb = new Tabla_boleta(listaBoleta_v); tabla_boleta_det.setModel(tb); } catch (SQLException ex) { Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex); } catch (ClassNotFoundException ex) { Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex); } } }
true
1834b03448a61dc0e806edb2a3ed1ce393deb22a
Java
metabrainz/search-server
/servlet/src/main/java/org/musicbrainz/search/servlet/mmd1/ArtistMmd1XmlWriter.java
UTF-8
4,212
1.875
2
[]
no_license
/* Copyright (c) 2009 Lukas Lalinsky * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the MusicBrainz project nor the names of the * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.musicbrainz.search.servlet.mmd1; import com.google.common.base.Strings; import com.jthink.brainz.mmd.*; import org.apache.commons.lang.StringUtils; import org.musicbrainz.search.MbDocument; import org.musicbrainz.search.index.ArtistIndexField; import org.musicbrainz.search.index.MMDSerializer; import org.musicbrainz.search.index.ReleaseIndexField; import org.musicbrainz.search.servlet.Result; import org.musicbrainz.search.servlet.Results; import java.io.IOException; import java.math.BigInteger; public class ArtistMmd1XmlWriter extends Mmd1XmlWriter { public Metadata write(Results results) throws IOException { ObjectFactory of = new ObjectFactory(); Metadata metadata = of.createMetadata(); ArtistList artistList = of.createArtistList(); for (Result result : results.results) { MbDocument doc = result.getDoc(); Artist artist = of.createArtist(); result.setNormalizedScore(results.getMaxScore()); artist.getOtherAttributes().put(getScore(), String.valueOf(result.getNormalizedScore())); org.musicbrainz.mmd2.Artist artistv2 = (org.musicbrainz.mmd2.Artist) MMDSerializer.unserialize(doc.get(ArtistIndexField.ARTIST_STORE), org.musicbrainz.mmd2.Artist.class); artist.setId(artistv2.getId()); artist.setType(StringUtils.capitalize(artistv2.getType())); artist.setName(artistv2.getName()); if(!Strings.isNullOrEmpty(artistv2.getSortName())) { artist.setSortName(artistv2.getSortName()); } if(!Strings.isNullOrEmpty(artistv2.getDisambiguation())) { artist.setDisambiguation(artistv2.getDisambiguation()); } if(artistv2.getLifeSpan()!=null) { String begin = artistv2.getLifeSpan().getBegin(); String end = artistv2.getLifeSpan().getEnd(); if (begin != null || end != null) { LifeSpan lifespan = of.createLifeSpan(); if (begin != null) { lifespan.setBegin(begin); } if (end != null) { lifespan.setEnd(end); } artist.setLifeSpan(lifespan); } } artistList.getArtist().add(artist); } artistList.setCount(BigInteger.valueOf(results.getTotalHits())); artistList.setOffset(BigInteger.valueOf(results.getOffset())); metadata.setArtistList(artistList); return metadata; } }
true
42095b23221555f1a3859cb832dd1e171efdf29f
Java
CarlosMo-Va/IntelliJActualProject
/app/src/main/java/com/example/carlos_moreno/intellijproject/MainActivity.java
UTF-8
9,316
3.09375
3
[]
no_license
package com.example.carlos_moreno.intellijproject; import java.util.Scanner; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ConnectFour game1 = new ConnectFour(6,6); Scanner scan = new Scanner(System.in); int computersMove; int round = 1; int move = 0; int playAgain = 0; if(round%2 == 0) System.out.println("Computer Starts"); else System.out.println("Player Starts"); BIG_LOOP: while(game1.gameOver('X') == false && game1.gameOver('O') == false && game1.checkTies() == false) { if(round%2 == 0) { computersMove = game1.randomNum(); System.out.println("Computers Turn:"); while(game1.isColumnFull(computersMove) == true) { System.out.println(" Space unavailable, Computer tries again : "); computersMove = game1.randomNum(); System.out.println(" " + game1.lastMove()); game1.isColumnFull(computersMove); if(game1.checkTies() == true) break; } game1.playMove(computersMove, 'O'); System.out.println("\nComputers Move: " + game1.lastMove() + "\n" + game1.toString()); System.out.println("Players Turn, make a move: "); move = scan.nextInt(); while(move < 1 || move > 6) { System.out.println("Column out of bounds, try again: "); move = scan.nextInt(); } while(game1.isColumnFull(move) == true) { game1.isColumnFull(move); System.out.println(" Space unavailable, Players Turn, make move : "); move = scan.nextInt(); game1.isColumnFull(move); if(game1.checkTies() == true) break; } game1.playMove(move, 'X'); System.out.println(game1.toString()); game1.gameOver('X'); game1.gameOver('O'); game1.checkTies(); } else { System.out.println("Players Turn, make move : "); move = scan.nextInt(); while(move < 1 || move > 6) { System.out.println("Column out of bounds, try again: "); move = scan.nextInt(); } while(game1.isColumnFull(move) == true) { game1.isColumnFull(move); System.out.println(" Space unavailable, Players Turn, make move : "); move = scan.nextInt(); if(game1.checkTies() == true) break; } game1.playMove(move, 'X'); System.out.println(game1.toString()); computersMove = game1.randomNum(); System.out.println("Computers Turn: "); while(game1.isColumnFull(computersMove) == true) { System.out.println(" Space unavailable, Computer tries again : "); computersMove = game1.randomNum(); System.out.println(" " + game1.lastMove()); game1.isColumnFull(computersMove); if(game1.checkTies() == true) break; } game1.playMove(computersMove, 'O'); System.out.println("\nComputers Move: " + game1.lastMove() + "\n" + game1.toString()); } } if(game1.gameOver('X')) { System.out.println("PLYER WINS!!"); System.out.println("\n\nWould you like to play again?\n\t1)yes\t2)no"); playAgain = scan.nextInt(); } if(game1.gameOver('O')) { System.out.println("COMPUTER WINS!!"); System.out.println("\n\nWould you like to play again?\n\t1) Yes\t2) No"); playAgain = scan.nextInt(); } if(game1.checkTies() == true) { System.out.println("Its a Tie, Game over "); System.out.println("\n\nWould you like to play again?\n\t1) Yes\t2) No"); playAgain = scan.nextInt(); } if(playAgain == 1) round++; while(playAgain == 1) { game1.resetBoard(); while(game1.gameOver('X') == false && game1.gameOver('O') == false && game1.checkTies() == false) { if(round%2 == 0) { computersMove = game1.randomNum(); System.out.println("Computers Turn:"); while(game1.isColumnFull(computersMove) == true) { System.out.println(" Space unavailable, Computer tries again : "); computersMove = game1.randomNum(); System.out.println(" " + game1.lastMove()); game1.isColumnFull(computersMove); if(game1.checkTies() == true) break; } game1.playMove(computersMove, 'O'); System.out.println("\nComputers Move: " + game1.lastMove() + "\n" + game1.toString()); System.out.println("Players Turn, make a move: "); move = scan.nextInt(); while(move < 1 || move > 6) { System.out.println("Column out of bounds, try again: "); move = scan.nextInt(); } while(game1.isColumnFull(move) == true) { game1.isColumnFull(move); System.out.println(" Space unavailable, Players Turn, make move : "); move = scan.nextInt(); game1.isColumnFull(move); if(game1.checkTies() == true) break; } game1.playMove(move, 'X'); System.out.println(game1.toString()); game1.gameOver('X'); game1.gameOver('O'); game1.checkTies(); } else { System.out.println("Players Turn, make move : "); move = scan.nextInt(); while(move < 1 || move > 6) { System.out.println("Column out of bounds, try again: "); move = scan.nextInt(); } while(game1.isColumnFull(move) == true) { game1.isColumnFull(move); System.out.println(" Space unavailable, Players Turn, make move : "); move = scan.nextInt(); game1.isColumnFull(move); if(game1.checkTies() == true) break; } game1.playMove(move, 'X'); System.out.println(game1.toString()); computersMove = game1.randomNum(); System.out.println("Computers Turn: "); while(game1.isColumnFull(computersMove) == true) { System.out.println(" Space unavailable, Computer tries again : "); computersMove = game1.randomNum(); System.out.println(" " + game1.lastMove()); game1.isColumnFull(computersMove); if(game1.checkTies() == true) break; } game1.playMove(computersMove, 'O'); System.out.println("\nComputers Move: " + game1.lastMove() + "\n" + game1.toString()); } } if(game1.gameOver('X')) { System.out.println("PLYER WINS!!"); System.out.println("\n\nWould you like to play again?\n\t1)yes\t2)no"); playAgain = scan.nextInt(); } if(game1.gameOver('O')) { System.out.println("COMPUTER WINS!!"); System.out.println("\n\nWould you like to play again?\n\t1) Yes\t2) No"); playAgain = scan.nextInt(); } if(game1.checkTies() == true) { System.out.println("Its a Tie, Game over "); System.out.println("\n\nWould you like to play again?\n\t1) Yes\t2) No"); playAgain = scan.nextInt(); } if(playAgain == 1) round++; } } }
true
06cd437d8d722984caa38239d9f2716997069fe6
Java
kuriye/Marsrover
/app/src/main/java/com/mustart/marspictures/NasaApiManager.java
UTF-8
3,284
2.1875
2
[ "MIT" ]
permissive
package com.mustart.marspictures; import android.content.Context; import android.util.Log; import com.android.volley.DefaultRetryPolicy; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonArrayRequest; import com.android.volley.toolbox.JsonObjectRequest; import com.android.volley.toolbox.Volley; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.Random; /** * Created by Bou's Laptop on 30/05/2018. */ public class NasaApiManager { private RequestQueue queue; private NasaApiListener listener; private ArrayList<Picture> pictures; public NasaApiManager(Context context, NasaApiListener listener) { this.queue = Volley.newRequestQueue(context); this.listener = listener; this.pictures = new ArrayList<>(); } public void getPictures(){ String url = "https://api.nasa.gov/mars-photos/api/v1/rovers/curiosity/photos?sol=1000&api_key=4WKcgHtFzcv8s7IM9zfv1rhzCwMySeUVpSrZzzS1"; JsonObjectRequest request = new JsonObjectRequest( Request.Method.GET, url, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { Log.d("nasa", response.toString()); try { JSONArray images = response.getJSONArray("photos"); for( int idx = 0; idx < images.length(); idx++) { //String id = response.getJSONObject(idx).getString("id"); int id = images.getJSONObject(idx).getInt("id"); String imageUrl = images.getJSONObject(idx).getString("img_src"); String camera = images.getJSONObject(idx).getJSONObject("camera").getString("name"); String fullName = images.getJSONObject(idx).getJSONObject("camera").getString("full_name"); Picture picture = new Picture(id, imageUrl, camera, fullName); System.out.println(picture); //pictures.add(picture); listener.onPictureAvailable(picture); Log.d("VOLLEY_TAG", picture.toString()); } // listener.onPictureAvailable(pictures); } catch (JSONException e) { Log.d("API", e.getLocalizedMessage()); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.d("nasa", error.toString()); listener.onPictureError(error.toString()); } } ); request.setRetryPolicy(new DefaultRetryPolicy(5000, 5, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT)); this.queue.add(request); } }
true
981fdfae17576d1fc906e5aa3a14aadd7baa3240
Java
zsk1313/scszhl
/scsV1.0/src/main/java/org/zhl/scs/util/PageModel.java
UTF-8
1,449
2.65625
3
[]
no_license
package org.zhl.scs.util; import org.zhl.scs.util.common.ScsConstants; /** * 分页实体 */ public class PageModel { /** 分页总数据条数 */ private int recordCount; /** 当前页面 */ private int pageIndex ; /** 每页分多少条数据 */ private int pageSize = ScsConstants.PAGE_DEFAULT_SIZE; /** 总页数 */ private int totalSize; public int getRecordCount() { this.recordCount = Math.max(this.recordCount, 0); return recordCount; } public void setRecordCount(int recordCount) { this.recordCount = recordCount; } public int getPageIndex() { this.pageIndex = this.pageIndex <= 0?1:this.pageIndex; /** 判断当前页面是否超过了总页数:如果超过了默认给最后一页作为当前页 */ this.pageIndex = Math.min(this.pageIndex, this.getTotalSize()); return pageIndex; } public void setPageIndex(int pageIndex) { this.pageIndex = pageIndex; } public int getPageSize() { this.pageSize = Math.max(this.pageSize, ScsConstants.PAGE_DEFAULT_SIZE); return pageSize; } public void setPageSize(int pageSize) { this.pageSize = pageSize; } public int getTotalSize() { if(this.getRecordCount() <=0){ totalSize = 0 ; }else{ totalSize = (this.getRecordCount() -1)/this.getPageSize() + 1; } return totalSize; } public int getFirstLimitParam(){ if (getPageIndex() <= 0) { return 0; } return (this.getPageIndex()-1)*this.getPageSize() ; } }
true
87a128f2ebe4a1d87293f281fe7c13f29afb1bcd
Java
gabriela-han/I.P.
/L3/L3_13.java
UTF-8
278
2.84375
3
[ "MIT" ]
permissive
class L3_13{ public static void main(String[] args){ int Valor = 1; comprimento (Valor); } static void comprimento(int comp){ for (int valor = 1; valor <=5; valor++){ System.out.println("**********"); } } }
true
413e59050d27ca0f666c869304fa48b8a42cf85e
Java
isaacmg/kafka_flink
/src/main/java/StreamKafka.java
UTF-8
4,601
2.5
2
[]
no_license
import facebook.avro.FacebookPost; import org.apache.flink.api.common.functions.FilterFunction; import org.apache.flink.api.common.functions.FlatMapFunction; import org.apache.flink.api.common.functions.MapFunction; import org.apache.flink.api.java.tuple.Tuple2; import org.apache.flink.streaming.api.datastream.DataStream; import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment; import org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer08; import org.apache.flink.util.Collector; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Properties; import edu.stanford.nlp.coref.CorefCoreAnnotations; import edu.stanford.nlp.coref.data.CorefChain; import edu.stanford.nlp.io.*; import edu.stanford.nlp.ling.*; import edu.stanford.nlp.pipeline.*; import edu.stanford.nlp.semgraph.SemanticGraph; import edu.stanford.nlp.semgraph.SemanticGraphCoreAnnotations; import edu.stanford.nlp.sentiment.SentimentCoreAnnotations; import edu.stanford.nlp.trees.*; import edu.stanford.nlp.util.*; /** * Created by isaac on 4/2/17. */ public class StreamKafka { // Function to return Kafka properties private static Properties getProperties(){ Properties properties = new Properties(); properties.setProperty("bootstrap.servers", "localhost:9092"); properties.setProperty("zookeeper.connect", "localhost:2181"); properties.setProperty("group.id", "fb"); return properties; } public static void main(String[] args){ StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); Properties properties = getProperties(); //Initialize the deserialization schema AvroDeserializationSchema<FacebookPost> aPost = new AvroDeserializationSchema<>(FacebookPost.class); DataStream<FacebookPost> stream = env .addSource(new FlinkKafkaConsumer08<>("fb", aPost, properties)); DataStream<String> s = stream.map(new StatusMessage()); s.map(new NLP()).print(); DataStream<Tuple2<String,Integer>> finalCount = s.flatMap(new TokenizeTerms()).filter(new RelevantTerms("somefile.txt")); finalCount.keyBy(0).sum(1).print(); try{ env.execute("StreamKafka"); } catch (Exception e){ System.out.println(e.getMessage()); } } } class RelevantTerms implements FilterFunction< Tuple2<String,Integer>> { private ArrayList<String> relevantTerms; RelevantTerms(String path){ relevantTerms = new ArrayList<>(); addTermsFromFile(path); //I'm adding terms manually for now relevantTerms.add("tellico"); relevantTerms.add("ocoee"); relevantTerms.add("clearwater"); relevantTerms.add("Video"); } public boolean filter(Tuple2<String,Integer> theTerm){ String s = theTerm.getField(0) ; return relevantTerms.contains(s); } private void addTermsFromFile(String filePath){ //TODO IMPLEMENT } } class TokenizeTerms implements FlatMapFunction<String, Tuple2 <String, Integer>> { public void flatMap(String s, Collector<Tuple2<String,Integer>> out){ String words[] = s.split("\\s+"); for(String word: words){ Tuple2<String,Integer> theT = new Tuple2<String,Integer>(word,1); out.collect(theT); } } } class StatusMessage implements MapFunction<FacebookPost,String>{ public String map(FacebookPost thePost){ String s = thePost.getStatusMessage().toString(); return tokenize(s); } private String tokenize(String sentence) { StringBuffer s = new StringBuffer(); for (int i = 0; i < sentence.length(); i++) { char c = sentence.charAt(i); if (Character.isLetterOrDigit(c)) { s.append(c); } else if (c == ' ' || c == '\t' || c == '\r') { s.append(' '); } else { //s.append(" " + c + " ");// pad symbol with space } } return s.toString().toLowerCase(); } } class NLP implements MapFunction<String, String>{ public String map( String message){ Annotation a = new Annotation(message); List<CoreMap> sentences = a.get(CoreAnnotations.SentencesAnnotation.class); if(sentences !=null && !sentences.isEmpty()){ return " the string is " + sentences.get(0).get(SentimentCoreAnnotations.SentimentClass.class); } return "stupid thing found nothing " ; } }
true
01c558b775035c2f8cb550e419e51250e86432a8
Java
exactpro/clearth
/clearth-modules/clearth-json/src/main/java/com/exactprosystems/clearth/automation/actions/json/SendJsonMessage.java
UTF-8
2,428
1.734375
2
[ "Apache-2.0" ]
permissive
/****************************************************************************** * Copyright 2009-2023 Exactpro Systems Limited * https://www.exactpro.com * Build Software to Test Software * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.exactprosystems.clearth.automation.actions.json; import com.exactprosystems.clearth.automation.GlobalContext; import com.exactprosystems.clearth.automation.MatrixContext; import com.exactprosystems.clearth.automation.StepContext; import com.exactprosystems.clearth.automation.actions.SendMessageAction; import com.exactprosystems.clearth.automation.exceptions.ResultException; import com.exactprosystems.clearth.connectivity.json.ClearThJsonMessage; import com.exactprosystems.clearth.connectivity.json.ClearThJsonMessageBuilder; import com.exactprosystems.clearth.connectivity.json.JsonCodec; import com.exactprosystems.clearth.messages.MessageBuilder; import com.exactprosystems.clearth.utils.inputparams.InputParamsUtils; import org.apache.commons.lang.StringUtils; import java.util.Set; public class SendJsonMessage extends SendMessageAction<ClearThJsonMessage> { public static final String IGNORE_VALIDATION = "IgnoreValidation"; @Override public MessageBuilder<ClearThJsonMessage> getMessageBuilder(Set<String> serviceParameters, Set<String> metaFields) { return new ClearThJsonMessageBuilder(serviceParameters, metaFields); } @Override protected void beforeSend(ClearThJsonMessage msg, StepContext stepContext, MatrixContext matrixContext, GlobalContext globalContext) throws ResultException { if (InputParamsUtils.YES.contains(StringUtils.lowerCase(msg.getField(IGNORE_VALIDATION)))) msg.setValidate(false); msg.removeField(IGNORE_VALIDATION); } @Override protected String getDefaultCodecName() { return JsonCodec.DEFAULT_CODEC_NAME; } }
true
f9c66af223734540604c82c4686818ee0acedbe1
Java
cheke42/SGA-FINAL
/src/com/desarrollo/modelo/Informe.java
UTF-8
1,029
2.265625
2
[]
no_license
package com.desarrollo.modelo; import java.util.Date; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "INFORME") public class Informe { private int idInforme; private String tipoInforme; private Date fechaGeneracionInforme; private String descripcion; @Id @GeneratedValue public int getIdInforme() { return idInforme; } public void setIdInforme(int idInforme) { this.idInforme = idInforme; } public String getTipoInforme() { return tipoInforme; } public void setTipoInforme(String tipoInforme) { this.tipoInforme = tipoInforme; } public Date getFechaGeneracionInforme() { return fechaGeneracionInforme; } public void setFechaGeneracionInforme(Date fechaGeneracionInforme) { this.fechaGeneracionInforme = fechaGeneracionInforme; } public String getDescripcion() { return descripcion; } public void setDescripcion(String descripcion) { this.descripcion = descripcion; } }
true
2fe3a603f2ebe06de40a7f06f424b5ff2cb62371
Java
TKimura416/ThatIsAndrioid
/app/src/main/java/com/thatsit/android/Utility.java
UTF-8
34,562
1.523438
2
[]
no_license
package com.thatsit.android; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Timer; import java.util.TimerTask; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.net.io.Util; import org.jivesoftware.smack.AccountManager; import org.jivesoftware.smack.XMPPConnection; import org.jivesoftware.smack.XMPPException; import org.jivesoftware.smack.packet.IQ; import org.jivesoftware.smack.packet.Presence; import org.jivesoftware.smack.packet.Presence.Type; import org.jivesoftware.smack.packet.RosterPacket; import org.jivesoftware.smackx.packet.VCard; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.ActivityInfo; import android.content.res.Configuration; import android.database.Cursor; import android.database.DatabaseUtils; import android.graphics.Bitmap; import android.os.Handler; import android.preference.PreferenceManager; import android.provider.Settings; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.view.WindowManager.LayoutParams; import android.view.inputmethod.InputMethodManager; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.seasia.myquick.asyncTasks.UserPauseStateAsync; import com.seasia.myquick.asyncTasks.ValidateUserLoginStatusAsync; import com.seasia.myquick.model.AuthenticateUserServiceTemplate; import com.seasia.myquick.model.ValidateUserLoginStatus; import com.thatsit.android.activities.BlurredActivity; import com.thatsit.android.activities.ContactActivity; import com.thatsit.android.activities.InviteContactsToRoster; import com.thatsit.android.activities.SplashActivity; import com.thatsit.android.activities.WelcomeActivity; import com.thatsit.android.adapter.ImageAdapter; import com.thatsit.android.adapter.PresenceAdapter; import com.thatsit.android.application.ThatItApplication; import com.thatsit.android.db.DbOpenHelper; import com.thatsit.android.db.One2OneChatDb; import com.thatsit.android.encryption.helper.EncryptionManager; import com.thatsit.android.fragement.FragmentChatHistoryScreen; import com.thatsit.android.fragement.FragmentChatScreen; import com.thatsit.android.fragement.FragmentContact; import com.thatsit.android.fragement.FragmentInvitationReceive; import com.thatsit.android.fragement.FragmentInvitationSent; import com.thatsit.android.interfaces.ValidateUserLoginInterface; import com.thatsit.android.interfaces.ValidateUserPauseStateInterface; import com.thatsit.android.invites.PresenceType; import com.thatsit.android.xmpputils.XmppManager; import com.myquick.socket.ClientChatThread; import com.myquick.socket.Constants; import com.myquick.socket.ServerThread; import com.myquickapp.receivers.NetworkAvailabilityReceiver; import com.seasia.myquick.model.AppSinglton; /** * @author psingh5 * This class includes static methods which are declared here once and used all * over the app to avoid redundancy such as show toast, show dialogs, show connection * error alerts etc. * */ public class Utility { public static FragmentInvitationReceive fragmentInvitationReceive = null; public static FragmentInvitationSent fragmentInvitationsent = null; public static FragmentChatHistoryScreen fragmentChatHistoryScreen = null; public static FragmentChatScreen fragmentChatScreen = null; public static FragmentContact fragmentContact = null; public static boolean allowAuthenticationDialog,isShowing = false; private static DbOpenHelper dbOpenHelper; private static SharedPreferences settings,prefSaveThatsItId; public static boolean VcardLoadedOnce = false; public static boolean RegsiterDataFetchedOnce = false; public static boolean FragmentContactDataFetchedOnce = false; public static boolean FragmentHistoryDataFetchedOnce = false; static Handler handler = new Handler(); public static InviteContactsToRoster inviteContactsToRoster=null; public static String email_id; static Dialog dialog = null; public static ContactActivity contactActivity = null; public static boolean isAuthenticationWindowOpened,enteredFragmentOnce = false; static ProgressDialog progressDialog ; public static boolean isAppStarted = false; public static SplashActivity splashActivity; public static WelcomeActivity welcomeActivity; public static boolean disconnected = false; public static boolean connectionClosedCalled = false; public static boolean reloginCalled = false; public static boolean loginCalledOnce = false; public static boolean smileyScreenOpened = false; public static boolean serviceBinded = false; public static EncryptionManager encryptionManager = new EncryptionManager(); public static boolean groupNotificationClicked = false; public static boolean fragPaymentSettingsOpen = false; public static boolean hasPincode = false; public static boolean fragChatIsOpen = false; public static VCard card =new VCard(); public static String action; public static boolean fragChatHistoryOpened = false; public static boolean disAllowSubscription = false; public static Timer mTimer; public static int radioBtnValue; public static boolean isBusy = false,isDialogOpened = false; public static boolean mBinded = false; public static boolean googleServicesUnavailable,noNetwork; /** * @param getRosterHistoryList * Delete chat history of the unsubscribed person */ public void deleteUnsubscribedUserChatHistory( ArrayList<String> getRosterHistoryList, ArrayList<Integer> rosterHistoryToBeDeleted, String rosterWhoseHistoryDeleted, MainService mService) { try { getRosterHistoryList = new ArrayList<String>(); rosterHistoryToBeDeleted = new ArrayList<Integer>(); ThatItApplication myApplication = ThatItApplication.getApplication(); myApplication.openDatabase(); Cursor cursor = One2OneChatDb.getAllMessagesOfParticipant(rosterWhoseHistoryDeleted); DatabaseUtils.dumpCursor(cursor); if (cursor.moveToFirst()) { int position = 0; do { getRosterHistoryList.add(cursor.getString(cursor.getColumnIndex(DbOpenHelper.COLUMN_ID))); rosterHistoryToBeDeleted.add(Integer.parseInt(getRosterHistoryList.get(position))); position = position + 1; } while (cursor.moveToNext()); } cursor.close(); } catch (IllegalArgumentException e) { e.printStackTrace(); } try { One2OneChatDb chatDb = new One2OneChatDb(mService); for (int i = 0; i < rosterHistoryToBeDeleted.size(); i++) { chatDb.deleteMessage(rosterHistoryToBeDeleted.get(i)); } } catch (Exception e) { e.printStackTrace(); } } /** * @param email * Check whether the email entered is valid. */ public boolean isEmailValid(String email) { boolean isValid = false; String expression = "^[\\w\\.-]+@([\\w\\-]+\\.)+[A-Z]{2,4}$"; CharSequence inputStr = email; Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE); Matcher matcher = pattern.matcher(inputStr); if (matcher.matches()) { isValid = true; } return isValid; } /** * @param IdToBeRemoved * @param sendPresence * Unsubscribe Roster and set presence unavailable */ public static void removeFriendXMPP(final Context activity , final String IdToBeRemoved , final XMPPConnection connection , boolean sendPresence){ try{ ThatItApplication.getApplication().getIncomingRequestHash().remove(IdToBeRemoved); Presence p = new Presence(Type.unsubscribed); p.setTo(IdToBeRemoved); if(sendPresence) sendPresence(p,IdToBeRemoved,connection); RosterPacket packet = new RosterPacket(); packet.setType(IQ.Type.SET); RosterPacket.Item item = new RosterPacket.Item(IdToBeRemoved, null); item.setItemType(RosterPacket.ItemType.remove); packet.addRosterItem(item); connection.sendPacket(packet); } catch (Exception e1) { e1.printStackTrace(); } } public static void sendPresence(Presence p, String deniedID, XMPPConnection connection ) { try { PresenceAdapter preAdapt = new PresenceAdapter(p); Presence presence2 = new Presence(PresenceType.getPresenceTypeFrom(preAdapt.getType())); presence2.setTo(p.getTo()); deniedID = p.getTo(); if (connection != null) { presence2.setFrom(connection.getUser()); connection.sendPacket(presence2); } } catch (Exception e) { e.printStackTrace(); } } /** * Insert Emojicons. * @param message * @return */ public static String processSmileyCodes(String message){ try{ for(int index=0;index<ImageAdapter.mThumbIdsForDispatch.length;index++){ message = message.replaceAll(ImageAdapter.mThumbIdsForDispatch[index], ImageAdapter.mThumbIds[index]); } }catch(Exception e){ return message; } return message; } public static void showMessage(final String message) { handler.post(new Runnable() { @Override public void run() { Toast.makeText(ThatItApplication.getApplication(), message, Toast.LENGTH_SHORT).show(); } }); } /** * Set default values for sending files via socket. */ public static void resetSocket() { Constants.isDownloading=false; ClientChatThread.connected=false; ServerThread.currentInt=-1; ServerThread.currentInt=-1; } /** * That's It 11-digit pincode. * @return */ public static String getUserName() { SharedPreferences mSettings = PreferenceManager.getDefaultSharedPreferences(ThatItApplication.getApplication()); return mSettings.getString(ThatItApplication.ACCOUNT_USERNAME_KEY, ""); } public static String getPassword() { SharedPreferences mSettings = PreferenceManager.getDefaultSharedPreferences(ThatItApplication.getApplication()); return mSettings.getString(ThatItApplication.ACCOUNT_PASSWORD_KEY, ""); } public static String getChatPassword() { SharedPreferences mSettings = PreferenceManager.getDefaultSharedPreferences(ThatItApplication.getApplication()); return mSettings.getString(ThatItApplication.ACCOUNT_CHAT_PASSWORD_KEY, ""); } public static String getEmail() { SharedPreferences mSettings = PreferenceManager.getDefaultSharedPreferences(ThatItApplication.getApplication()); return mSettings.getString(ThatItApplication.ACCOUNT_EMAIL_ID, ""); } /** * Login Dialog * @param activity */ public static void showLoginPromtScreen(final Activity activity ) { try { if(dialog!=null && dialog.isShowing()){ dialog.dismiss(); } } catch (Exception e1) { e1.printStackTrace(); } dialog=null; if(dialog==null ){ dialog = new Dialog(activity); dialog.setContentView(R.layout.login_promt); dialog.setTitle("Enter Login Password 1"); isAuthenticationWindowOpened = true; Utility.isShowing = true; try{ Button btnAccept = (Button)dialog.findViewById(R.id.btn_accept); Button btnDecline = (Button)dialog.findViewById(R.id.btn_decline); EditText etUsername = (EditText)dialog.findViewById(R.id.etUsername); TextView signInDifferentUser = (TextView)dialog.findViewById(R.id.signInDifferentUser); etUsername.setEnabled(false); etUsername.setVisibility(View.GONE); final EditText etPassword = (EditText)dialog.findViewById(R.id.etPassword); InputMethodManager imm = (InputMethodManager)activity .getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(etPassword.getWindowToken(), 0); etUsername.setText(Utility.email_id); signInDifferentUser.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { openExitDialog(activity); } }); btnAccept.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { try { try { InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(etPassword.getWindowToken(), 0); } catch (Exception e) { e.printStackTrace(); } if (NetworkAvailabilityReceiver.isInternetAvailable(ThatItApplication.getApplication())) { if (etPassword.getText().toString().trim().toCharArray().length == 0) { Utility.showMessage("Enter login password"); } else { String login_password = encryptionManager.encryptPayload(etPassword.getText().toString()); login_password = URLEncoder.encode(login_password, "UTF-8"); if (login_password.contains("%")) { login_password = login_password.replace("%", "2"); } if (login_password.equals(Utility.getPassword())) { Utility.allowAuthenticationDialog = false; isAuthenticationWindowOpened = false; dialog.dismiss(); dialog = null; if(noNetwork == true) { Intent intent = new Intent(activity, ContactActivity.class); activity.startActivity(intent); } activity.finish(); } else { stopDialog(); Utility.showMessage("Incorrect Password"); } } }else{ Utility.showMessage("No Network Available"); } } catch (Exception e) { e.printStackTrace(); } } }); btnDecline.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); dialog=null; Intent intent = new Intent(Intent.ACTION_MAIN); intent.addCategory(Intent.CATEGORY_HOME); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); activity .startActivity(intent); activity.finish(); } }); }catch(Exception e){ e.printStackTrace(); } dialog.setCancelable(false); dialog.setCanceledOnTouchOutside(false); } dialog.show(); } /** * Open dialog after the app is resumed after stop. * @param * - activity */ public static void taskPromtOnResume(Activity activity){ if(Utility.allowAuthenticationDialog == true){ Utility.showLoginPromtScreen(activity); } } /** * Set Prompt dialog true i.e. allowed to be opened on resume. * @param isAllowed * @param activity */ public static void taskPromtOnStop(boolean isAllowed, Activity activity){ try { allowAuthenticationDialog = true; /*if(allowAuthenticationDialog){ View v = activity.getWindow().getDecorView(); v.setDrawingCacheEnabled(true); v.buildDrawingCache(); catchedBitmap = Bitmap.createBitmap(v.getDrawingCache()); }*/ } catch (OutOfMemoryError e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } /** * Set activity blurred in the background when lock dialog is opened. */ public static void showLock(final Activity activity){ try { if(Utility.allowAuthenticationDialog == true){ Intent intent = new Intent(activity, BlurredActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION); activity.startActivity(intent); } } catch (Exception e) { e.printStackTrace(); } } private static void clearAppSingletonData() { AppSinglton.userId = ""; AppSinglton.thatsItPincode = ""; } /** * Clear all shared preference data of the app */ public static void clearAllSharedPreferences() { settings = PreferenceManager.getDefaultSharedPreferences(ThatItApplication.getApplication()); settings.edit().clear().commit(); SharedPreferences clearVibrateData = ThatItApplication.getApplication().getSharedPreferences("mSharedPreferencesVibrateValue",Context.MODE_PRIVATE); clearVibrateData.edit().clear().commit(); SharedPreferences clearUserID = ThatItApplication.getApplication().getSharedPreferences("USERID",Context.MODE_PRIVATE); clearUserID.edit().clear().commit(); SharedPreferences THATSITID = ThatItApplication.getApplication().getSharedPreferences("THATSITID",Context.MODE_PRIVATE); THATSITID.edit().clear().commit(); SharedPreferences clearAvlData = ThatItApplication.getApplication().getSharedPreferences("mSharedPreferencesAvlValue",Context.MODE_PRIVATE); clearAvlData.edit().clear().commit(); SharedPreferences clearSetNotificationTone = ThatItApplication.getApplication().getSharedPreferences("AudioPreference",Context.MODE_PRIVATE); clearSetNotificationTone.edit().clear().commit(); SharedPreferences clearRegisterData = ThatItApplication.getApplication().getSharedPreferences("register_data",Context.MODE_PRIVATE); clearRegisterData.edit().clear().commit(); } /** * Destroy database tables and clear all data */ private static void clearDatabase() { dbOpenHelper = new DbOpenHelper(ThatItApplication.getApplication()); boolean isDatabaseDeleted = dbOpenHelper.deleteDatabase(); System.out.println("Database deletion status :" + isDatabaseDeleted); } /** * Dialog prompt befor exiting the application. * @param activity */ static void openExitDialog(final Activity activity) { try { final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(activity); // set title alertDialogBuilder.setTitle("Do You Want to Exit"); alertDialogBuilder.setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { } }) .setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { } }); final AlertDialog dialog = alertDialogBuilder.create(); dialog.show(); dialog.setCancelable(false); dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { try { dialog.dismiss(); if (!NetworkAvailabilityReceiver.isInternetAvailable(ThatItApplication.getApplication())) { performSignOutTask(activity); } else { progressDialog = new ProgressDialog(activity); progressDialog.setMessage("Please Wait"); progressDialog.setCancelable(false); progressDialog.show(); UserLoginStatus(activity, Utility.getEmail(), "False", "", "", mValidateUserLoginInterface); } } catch (Exception e) { e.printStackTrace(); } } }); dialog.getButton(AlertDialog.BUTTON_NEGATIVE).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { try { dialog.dismiss(); } catch (Exception e) { e.printStackTrace(); } } }); } catch (Exception e) { e.printStackTrace(); } } public static void startDialog(final Activity context){ try { context.runOnUiThread(new Runnable() { @Override public void run() { if (progressDialog != null && progressDialog.isShowing()) { stopDialog(); } } }); if(progressDialog!=null) progressDialog=null; progressDialog = new ProgressDialog(context); progressDialog.setMessage("Please Wait"); progressDialog.setCancelable(false); try { context.runOnUiThread(new Runnable() { @Override public void run() { // if(!context.isFinishing() && !context.isDestroyed() ) progressDialog.show(); } }); } catch (Exception e) { e.printStackTrace(); } } catch (Exception e) { e.printStackTrace(); } } public static void startDialog(Activity context, String message){ try { if(progressDialog !=null && progressDialog.isShowing()){ return; } if(progressDialog!=null) progressDialog=null; progressDialog = new ProgressDialog(context); progressDialog.setMessage(message); progressDialog.setCancelable(false); context.runOnUiThread(new Runnable() { @Override public void run() { progressDialog.show(); } }); } catch (Exception e) { e.printStackTrace(); } } public static void stopDialog(Activity activity){ try { if(progressDialog!=null && progressDialog.isShowing()){ activity.runOnUiThread(new Runnable() { @Override public void run() { try { progressDialog.dismiss(); } catch (Exception e) { e.printStackTrace(); } } }); } if(progressDialog!=null){ progressDialog=null; } } catch (Exception e) { e.printStackTrace(); } } public static void stopDialog(){ try { if(progressDialog!=null && progressDialog.isShowing()){ progressDialog.dismiss(); } if(progressDialog!=null){ progressDialog=null; } } catch (Exception e) { e.printStackTrace(); } } /** * Load details of the subscribed friend using Vcard. * @param friend_jid */ public static void onFriendAdded(String friend_jid){ //ProviderManager.getInstance().addIQProvider("vCard", "vcard-temp:x:update", new VCardProvider()); try { card.load(XmppManager.getInstance().getXMPPConnection(), friend_jid); } catch (Exception e) { e.printStackTrace(); } (new One2OneChatDb(ThatItApplication.getApplication())).saveRoster(friend_jid, card.getFirstName(), card.getLastName(), card.getField("profile_picture_url")); } public static void removeFriendIfExists(String friend_jid){ if(friend_jid.contains("@")){ friend_jid = friend_jid.substring(0, friend_jid.indexOf("@")); } new One2OneChatDb(ThatItApplication.getApplication()).removeFriendDataIfExists(friend_jid); } public static boolean isFriendExists(String sender) { return new One2OneChatDb(ThatItApplication.getApplication()).isFriendExists(sender); } /** * CONNECTION ERROR WHILE USING APPLICATION */ /*public static void showConnectionErrorAlert(final String action,final Activity activity){ try { if(dialogConnectionErrorAlert!=null && dialogConnectionErrorAlert.isShowing()){ dialogConnectionErrorAlert.dismiss(); } } catch (Exception e1) { e1.printStackTrace(); } dialogConnectionErrorAlert=null; if(dialogConnectionErrorAlert==null ){ dialogConnectionErrorAlert = new Dialog(activity); dialogConnectionErrorAlert.setContentView(R.layout.connection_error_alert_dialog); dialogConnectionErrorAlert.setTitle("That's It"); Utility.isShowing = true; try{ Button btnAccept = (Button)dialogConnectionErrorAlert.findViewById(R.id.btn_accept_error_dialog); Button btnDecline = (Button)dialogConnectionErrorAlert.findViewById(R.id.btn_decline_error_dialog); btnAccept.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if(NetworkAvailabilityReceiver.isInternetAvailable(ThatItApplication.getApplication())){ dialogConnectionErrorAlert.dismiss(); if(action.equalsIgnoreCase("WelcomeActivityError")){ if(!MainService.mService.connection.isConnected() || !MainService.mService.connection.isAuthenticated()){ try { Utility.startDialog(activity); MainService.mService.connectAsync(); } catch (Exception e) { e.printStackTrace(); } } } else if(action.equalsIgnoreCase("ContactActivityError")){ if(!MainService.mService.connection.isConnected() || !MainService.mService.connection.isAuthenticated()){ try { MainService.mService.connection.connect(); } catch(XMPPException e){ e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } } }else{ Toast.makeText(activity,"No Network Available",Toast.LENGTH_SHORT).show(); } } }); btnDecline.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { try { dialogConnectionErrorAlert.dismiss(); } catch (Exception e) { e.printStackTrace(); } } }); }catch(Exception e){ e.printStackTrace(); } dialogConnectionErrorAlert.setCancelable(false); dialogConnectionErrorAlert.setCanceledOnTouchOutside(false); } dialogConnectionErrorAlert.show(); }*/ public static void saveThatsItPincode(Activity activity,String ThatsItId){ prefSaveThatsItId = activity.getSharedPreferences("THATSITID", 0); prefSaveThatsItId.edit().putString("THATSITID",ThatsItId).commit(); } public static void openAlertDialogIfInappFail(Context context) { AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context); alertDialogBuilder.setTitle("That's It"); alertDialogBuilder .setMessage("Please change your email registered with the play store to purchase That's It ID."); alertDialogBuilder.setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface arg0, int arg1) { } }); AlertDialog alertDialog = alertDialogBuilder.create(); alertDialog.show(); } public static AlertDialog alertDialogSplash; public static void openAlertSplash(final Context context,final String string, final String Message) { handler.post(new Runnable() { @Override public void run() { try { if (alertDialogSplash == null) { AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context); alertDialogBuilder.setTitle("That's It"); alertDialogBuilder.setMessage(Message); alertDialogBuilder.setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface arg0, int arg1) { alertDialogSplash.dismiss(); alertDialogSplash = null; performSignOutTask(context); } }); alertDialogSplash = alertDialogBuilder.create(); alertDialogSplash.show(); alertDialogSplash.setCancelable(false); } } catch (Exception e) { alertDialogSplash = null; e.printStackTrace(); } } }); } public static AlertDialog alertDialog; public static void openAlert(final Context context,final String string, final String Message) { handler.post(new Runnable() { @Override public void run() { try { if (alertDialog == null) { AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context); alertDialogBuilder.setTitle("That's It"); alertDialogBuilder.setMessage(Message); alertDialogBuilder.setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface arg0, int arg1) { alertDialog.dismiss(); alertDialog = null; // Clear Gcm Shared Preference if exists if(string.equalsIgnoreCase("AccountDisabled") || string.equalsIgnoreCase("AccountPaused")){ SharedPreferences mSharedPreferences_Gcm = ThatItApplication.getApplication().getSharedPreferences("GcmPreference",Context.MODE_PRIVATE); mSharedPreferences_Gcm.edit().clear().commit(); } if (string.equalsIgnoreCase("RenewalError") || string.equalsIgnoreCase("AccountDisabled") || string.equalsIgnoreCase("AccountPaused")) { if(!NetworkAvailabilityReceiver.isInternetAvailable(ThatItApplication.getApplication())){ performSignOutTask(context); }else{ progressDialog = new ProgressDialog(context); progressDialog.setMessage("Please Wait"); progressDialog.setCancelable(false); progressDialog.show(); if(string.equalsIgnoreCase("AccountDisabled")){ // Remove user from XMPP Server try { if(MainService.mService.connection.isConnected() && MainService.mService.connection.isAuthenticated()){ AccountManager accountManager = MainService.mService.connection.getAccountManager(); accountManager.deleteAccount(); performSignOutTask(context); } } catch (XMPPException e) { e.printStackTrace(); } } else{ UserLoginStatus(context, Utility.getEmail(), "False","","", mValidateUserLoginInterface); } } } else if (string.equalsIgnoreCase("InternetUnstable")) { //settings = PreferenceManager.getDefaultSharedPreferences(ThatItApplication.getApplication()); //settings.edit().clear().commit(); } } }); alertDialog = alertDialogBuilder.create(); alertDialog.show(); alertDialog.setCancelable(false); } } catch (Exception e) { alertDialog = null; e.printStackTrace(); } } }); } private static void performSignOutTask(Context context) { clearAppSingletonData(); clearAllSharedPreferences(); clearDatabase(); Utility.isAppStarted = false; Utility.disconnected = true; if(MainService.mService != null) { MainService.mService.connection.disconnect(); MainService.mService.disconnect(); if (progressDialog != null) { progressDialog.dismiss(); } context.stopService(new Intent(context, MainService.class)); } Intent startMain = new Intent(context, WelcomeActivity.class); startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); context.startActivity(startMain); android.os.Process.killProcess(android.os.Process.myPid()); } public static boolean LoginStarted = false; /** * Timer to update user presence */ public static void startLoginTimer(final Context context,final int value) { try { Log.d("LOGIN_TIMER_STARTED", "LOGIN_TIMER_STARTED"); if(mTimer != null){ mTimer.cancel(); } mTimer= new Timer(); mTimer.schedule(new TimerTask() { @Override public void run() { Log.e("","TIMER STOPPED"); if(LoginStarted == true){ Utility.stopDialog(); mTimer.cancel(); mTimer = null; if(value == 1){ //settings = PreferenceManager.getDefaultSharedPreferences(ThatItApplication.getApplication()); //settings.edit().clear().commit(); } openAlert(context,"InternetUnstable","Your internet connection seems to be unstable"); } } },50000,50000); } catch (Exception e) { e.printStackTrace(); } } public static void setDeviceTypeAndSecureFlag(Activity activity){ activity.getWindow().setFlags(LayoutParams.FLAG_SECURE, LayoutParams.FLAG_SECURE); checkTabletSize(activity); } public static void checkTabletSize(Activity activity) { boolean tabletSize = activity.getResources().getBoolean(R.bool.isTablet); if (!tabletSize) { // is smartphone activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); } } /** * Send User Login Status * @param context * @param email * @param status */ public static void UserLoginStatus(final Context context,final String email, final String status, final String registrationId, final String statusID, final ValidateUserLoginInterface mValidateUserLoginInterface) { new ValidateUserLoginStatusAsync(context,email,status,registrationId,statusID,mValidateUserLoginInterface).execute(); } /** * Send Login status to server */ static ValidateUserLoginInterface mValidateUserLoginInterface = new ValidateUserLoginInterface() { @Override public void validateUserLogin(Context context,ValidateUserLoginStatus mValidateUserLoginStatus) { if (mValidateUserLoginStatus != null) { performSignOutTask(context); } } }; public static void UserPauseStatus(final Context context) { if(NetworkAvailabilityReceiver.isInternetAvailable(ThatItApplication.getApplication()) && Utility.googleServicesUnavailable == true) { new UserPauseStateAsync(context, Utility.getEmail(), Utility.getPassword(), mValidateUserPauseStateInterface).execute(); } } /** * Validate User Pause State */ public static ValidateUserPauseStateInterface mValidateUserPauseStateInterface = new ValidateUserPauseStateInterface() { @Override public void validateUserPauseState(Context context,AuthenticateUserServiceTemplate mAuthenticateUserServiceTemplate) { Utility.stopDialog(); if(mAuthenticateUserServiceTemplate != null){ String userId = mAuthenticateUserServiceTemplate.getmAuthenticateUserServiceResult().getmAuthenticateUserServiceParams()[0].getRetVal(); if (userId.equals("2")) { Utility.openAlert(context,"AccountDisabled", "Your account has been suspended by Admin. Kindly Sign in with different account."); } } } }; public static void lockScreenRotation(Activity activity,int SCREEN_ORIENTATION) { if (activity.getResources().getBoolean(R.bool.isTablet)) { if (SCREEN_ORIENTATION == 0) { // PORTRAIT activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); } /*else if (SCREEN_ORIENTATION == 1) { // REVERSE PORTRAIT activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT); }*/ else if (SCREEN_ORIENTATION == 2) { // LANDSCAPE activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); }/* else if (SCREEN_ORIENTATION == 3) { // REVERSE LANDSCAPE activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE); }*/ } } public static void unlockScreenRotation(Activity activity) { if (activity.getResources().getBoolean(R.bool.isTablet)) { activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR); } } }
true
878973ad90cc4c04494eb94431c9933f3b65bbe6
Java
HimanshuBhardwaj/HelloToPractice
/src/main/java/com/himanshu/practice/y2018/nov/nov08/LiebigsBarrels.java
UTF-8
2,084
3.3125
3
[]
no_license
package com.himanshu.practice.y2018.nov.nov08; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collections; /** * Created by himanshubhardwaj on 08/11/18. * 5:06--5:51 * Statement: https://codeforces.com/contest/985/problem/C * Algo: Sorting. This problem was specially designed to recall that insertionSort function of arrays in java uses quic insertionSort. while of collection uses merge insertionSort. * Submission: https://codeforces.com/contest/985/submission/45443584 */ public class LiebigsBarrels { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String[] str = br.readLine().split(" "); int n = Integer.parseInt(str[0]); int k = Integer.parseInt(str[1]); int l = Integer.parseInt(str[2]); ArrayList<Integer> arr = new ArrayList<>(n * k); str = br.readLine().split(" "); for (int i = 0; i < str.length; i++) { arr.add(Integer.parseInt(str[i])); } Collections.sort(arr); int start = arr.get(0); int pos = 1; while (pos < arr.size() && (arr.get(pos) - start) <= l) { pos++; } long sum = 0; if (pos >= n) { pos--; int collected = 0; boolean flag = false; for (int i = 0; (collected < n) && (i <= pos); ) { sum += arr.get(i); collected++; if (!flag) { int nextExpectedPosition = i + k; int remaining = pos - nextExpectedPosition + 1; if (collected + remaining >= n) { i = nextExpectedPosition; } else { i = pos; flag = true; } } else { i--; } } } System.out.print(sum); } }
true
bb157c0aa8ea4df90d6504afce539d025c592741
Java
youngcodding/MyGithub
/Reflection/src/com/yn/reflection/others/OthersTest.java
UTF-8
984
2.828125
3
[]
no_license
package com.yn.reflection.others; import com.yn.reflection.constructor.Emp; /** * @author yn * @class MyGithub * @describe * @date 2020/12/8-11:05 */ public class OthersTest { public static void main(String[] args) { //获取反射对象 Class<Emp> empClass = Emp.class; //反射获取类加载器 /* ClassLoader classLoader = empClass.getClassLoader(); ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader(); System.out.println(classLoader); System.out.println(systemClassLoader);*/ /* Class<?>[] interfaces = empClass.getInterfaces(); for (Class<?> anInterface : interfaces) { //获取全路径名称 System.out.println(anInterface.getName()); //获取简单类名 System.out.println(anInterface.getSimpleName()); }*/ Class<? super Emp> superclass = empClass.getSuperclass(); System.out.println(superclass); } }
true
b443ca7411ebbd0755dda15abf42783b962430ce
Java
lenaavramenko/ProductsSystem
/src/main/java/com/javaguru/products/service/validation/ProductValidationService.java
UTF-8
528
2.34375
2
[]
no_license
package com.javaguru.products.service.validation; import com.javaguru.products.domain.Product; import java.math.BigDecimal; import java.util.HashSet; import java.util.Set; public class ProductValidationService { private final Set<ProductValidationRule> validationRules; public ProductValidationService(Set<ProductValidationRule> validationRules) { this.validationRules = validationRules; } public void validate(Product product) { validationRules.forEach(s -> s.validate(product)); } }
true
3f470c464869d2db7a0ad219d4c88be1e86855c2
Java
hoangytm/TCPS
/UDPClient/src/vn/viettuts/client/UDPClient.java
UTF-8
4,562
2.96875
3
[]
no_license
package vn.viettuts.client; import java.io.BufferedInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.ObjectOutputStream; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketException; import java.net.UnknownHostException; import vn.viettuts.common.FileInfo; public class UDPClient { private static final int PIECES_OF_FILE_SIZE = 1024 * 32; private DatagramSocket clientSocket; private int serverPort = 6677; private String serverHost = "localhost"; /** * run program * * @author viettuts.vn * @param args */ public static void main(String[] args) { String sourcePath = "E:\\trash\\file source\\dev.sql"; String destinationDir = "E:\\trash\\file destination\\"; UDPClient udpClient = new UDPClient(); udpClient.connectServer(); udpClient.sendFile(sourcePath, destinationDir); } /** * connect server * * @author viettuts.vn */ private void connectServer() { try { clientSocket = new DatagramSocket(); } catch (SocketException e) { e.printStackTrace(); } } /** * send file to server * * @param sourcePath * @param destinationDir */ private void sendFile(String sourcePath, String destinationDir) { InetAddress inetAddress; DatagramPacket sendPacket; try { File fileSend = new File(sourcePath); InputStream inputStream = new FileInputStream(fileSend); BufferedInputStream bis = new BufferedInputStream(inputStream); inetAddress = InetAddress.getByName(serverHost); byte[] bytePart = new byte[PIECES_OF_FILE_SIZE]; // get file size long fileLength = fileSend.length(); int piecesOfFile = (int) (fileLength / PIECES_OF_FILE_SIZE); int lastByteLength = (int) (fileLength % PIECES_OF_FILE_SIZE); // check last bytes of file if (lastByteLength > 0) { piecesOfFile++; } // split file into pieces and assign to fileBytess byte[][] fileBytess = new byte[piecesOfFile][PIECES_OF_FILE_SIZE]; int count = 0; while (bis.read(bytePart, 0, PIECES_OF_FILE_SIZE) > 0) { fileBytess[count++] = bytePart; bytePart = new byte[PIECES_OF_FILE_SIZE]; } // read file info FileInfo fileInfo = new FileInfo(); fileInfo.setFilename(fileSend.getName()); fileInfo.setFileSize(fileSend.length()); fileInfo.setPiecesOfFile(piecesOfFile); fileInfo.setLastByteLength(lastByteLength); fileInfo.setDestinationDirectory(destinationDir); // send file info ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(fileInfo); sendPacket = new DatagramPacket(baos.toByteArray(), baos.toByteArray().length, inetAddress, serverPort); clientSocket.send(sendPacket); // send file content System.out.println("Sending file..."); // send pieces of file for (int i = 0; i < (count - 1); i++) { sendPacket = new DatagramPacket(fileBytess[i], PIECES_OF_FILE_SIZE, inetAddress, serverPort); clientSocket.send(sendPacket); waitMillisecond(40); } // send last bytes of file sendPacket = new DatagramPacket(fileBytess[count - 1], PIECES_OF_FILE_SIZE, inetAddress, serverPort); clientSocket.send(sendPacket); waitMillisecond(40); // close stream bis.close(); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } System.out.println("Sent."); } /** * sleep program in millisecond * * @param millisecond */ public void waitMillisecond(long millisecond) { try { Thread.sleep(millisecond); } catch (InterruptedException e) { e.printStackTrace(); } } }
true
5717c1a9fcb19be97b612a4274ff7e50a309ad45
Java
jotaerre123/proyectoFinal
/ProyectoFinalJaimeJimenez/ProyectoFinalJaimeJimenez/src/main/java/com/salesianostriana/dam/proyectofinaljaimejimenez/ProyectoFinalJaimeJimenezApplication.java
UTF-8
381
1.664063
2
[]
no_license
package com.salesianostriana.dam.proyectofinaljaimejimenez; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class ProyectoFinalJaimeJimenezApplication { public static void main(String[] args) { SpringApplication.run(ProyectoFinalJaimeJimenezApplication.class, args); } }
true
9ab5cd49c9d731b0e408ef8cb3b83af778830648
Java
YevgenRiaboshtan/eContact
/eContactData/src/main/java/org/econtact/data/filter/visitor/LessVisitor.java
UTF-8
509
2.1875
2
[]
no_license
package org.econtact.data.filter.visitor; import org.econtact.data.filter.impl.LessFilter; public class LessVisitor extends AbstractVisitor<LessFilter> { protected LessVisitor(VisitorContext visitorContext) { super(visitorContext); } @Override public void processFilter(LessFilter filter) { predicate = visitorContext.getCriteriaBuilder().lessThan( getPath(filter.getFieldName()), visitorContext.createFindParam(filter.getValue())); } }
true
fd935f33fe8732669bc3333e90258122749248fe
Java
ivaylogeorgiev1/DominosPizza
/src/dominos/OOP/Menu.java
UTF-8
871
2.71875
3
[]
no_license
package dominos.OOP; import java.util.ArrayList; public class Menu implements Iconstants{ private ArrayList<Product> orderablesList; private ArrayList<Restaurant> restaurantsList; private static Menu menuEdinstveno = null; private Menu() { orderablesList = new ArrayList<>(); restaurantsList = new ArrayList<>(); } public static Menu createMenu() { if (menuEdinstveno == null) { menuEdinstveno = new Menu(); } return menuEdinstveno; } public void addOrderable(Product orderable) { if(orderable != null) { orderablesList.add(orderable); } } public void addRestaurant(Restaurant restaurant) { if(restaurant != null) { restaurantsList.add(restaurant); } } public ArrayList<Product> getOrderablesList() { return orderablesList; } public ArrayList<Restaurant> getRestaurantsList() { return restaurantsList; } }
true
bfb27b615c654e2ea0e335001b3774af711e03dc
Java
Asuka-Nana/Automation-Access-Control-System
/SpringBoot/src/main/java/com/example/tryagain/controller/CommentController.java
UTF-8
4,950
2.078125
2
[]
no_license
package com.example.tryagain.controller; import com.example.tryagain.dto.*; import com.example.tryagain.mapper.CommentMapper; import com.example.tryagain.mapper.NoticeMapper; import com.example.tryagain.mapper.UserMapper; import com.example.tryagain.pojo.User; import com.example.tryagain.pojo.notice; import com.example.tryagain.util.parsingtoken; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Base64; import java.util.LinkedList; import java.util.List; @RestController public class CommentController { @Autowired NoticeMapper noticeMapper; @Autowired CommentMapper commentMapper; @Autowired UserMapper userMapper; @RequestMapping("/getcomment") @RequiresPermissions("0") public CommentRes getComment (@RequestHeader("Authorization") String token , @RequestBody getcommentp id){ String user = parsingtoken.Parsing(token); Integer nid = id.getNid(); User userDeatail = userMapper.findpwdbyname(user); Integer department = userDeatail.getDepartment(); Integer role = userDeatail.getState(); Integer ndep = noticeMapper.getdepbyid(nid); if(ndep == null){ return new CommentRes(null,null,-3); } if(role != 2 && (ndep != department ) && (ndep != 10)){ return new CommentRes(null,null,-1); } notice noticeex = noticeMapper.getnoticebyid(nid); InputStream inputStream = null; byte[] buffer = null; String path = "D:\\data\\"+noticeex.getUsername()+".jpg"; File file = new File(path); if(!file.exists()){ path = "D:\\data\\def.jpg"; } //读取图片字节数组 try { inputStream = new FileInputStream(path); int count = 0; while (count == 0) { count = inputStream.available(); } buffer = new byte[count]; inputStream.read(buffer); } catch (IOException e) { e.printStackTrace(); } finally { if (inputStream != null) { try { // 关闭inputStream流 inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } String src = Base64.getEncoder().encodeToString(buffer); NoticeRes noticeRes = new NoticeRes(noticeex.getId(),noticeex.getUsername(),noticeex.getTime(),noticeex.getContent(),src); CommentDetail[] commentDetails = commentMapper.getcomment(nid); if(commentDetails.length == 0){ return new CommentRes(noticeRes,null,-2); } List<Comment> comments = new LinkedList<>() ; for (Integer i = 0 ; i< commentDetails.length; i++){ InputStream inputStream1 = null; byte[] buffer1 = null; String path1 = "D:\\data\\"+commentDetails[i].getUsername()+".jpg"; File file1 = new File(path); if(!file1.exists()){ path1 = "D:\\data\\def.jpg"; } //读取图片字节数组 try { inputStream1 = new FileInputStream(path1); int count1 = 0; while (count1 == 0) { count1 = inputStream1.available(); } buffer1 = new byte[count1]; inputStream1.read(buffer1); } catch (IOException e) { e.printStackTrace(); } finally { if (inputStream1 != null) { try { // 关闭inputStream流 inputStream1.close(); } catch (IOException e) { e.printStackTrace(); } } } String src1 = Base64.getEncoder().encodeToString(buffer1); comments.add(new Comment(commentDetails[i].getCid(),commentDetails[i].getUsername(),commentDetails[i].getTime(),commentDetails[i].getContent(),src1)); } return new CommentRes(noticeRes,comments,1); } @RequestMapping("/addcomment") @RequiresPermissions("0") public Integer addComment(@RequestHeader("Authorization") String token, @RequestBody addCommentpara comments){ String user = parsingtoken.Parsing(token); commentMapper.addcomment(user,comments.getTime(),comments.getComment(),comments.getId()); return 1; } }
true
daaca64d9629306a5d7b29e7ee670d11ba757f34
Java
smallSand/CodeInterView
/src/com/lsl/code/ZipZag.java
UTF-8
442
2.71875
3
[]
no_license
package com.lsl.code; public class ZipZag { public static void main(String[] args) { } public String getZipTag(String str,int rows){ StringBuilder result=new StringBuilder(); if(str.length()<=rows||rows==1){ return str; } int num=2*rows-2; for(int i=0;i<rows;i++){ for(int j=0;j<str.length();j+=num){ result.append(str.charAt(j)); } } return result.toString(); } }
true
cdc23bf39aed983839fe58bcdcb5371ac871b8a0
Java
PitikTrondol/JumpingGame
/core/src/com/afriandi/project/enums/ScreenEnums.java
UTF-8
1,369
2.3125
2
[]
no_license
package com.afriandi.project.enums; import com.badlogic.gdx.Screen; import com.afriandi.project.screens.Credits; import com.afriandi.project.screens.Gameplay; import com.afriandi.project.screens.MainMenu; import com.afriandi.project.screens.Paused; import com.afriandi.project.screens.Result; import com.afriandi.project.screens.Splash; public enum ScreenEnums { SPLASH { @Override public com.badlogic.gdx.Screen getScreenInstance() { return new Splash(); } }, MAIN_MENU { @Override public com.badlogic.gdx.Screen getScreenInstance() { return new MainMenu(); } }, GAMEPLAY { @Override public com.badlogic.gdx.Screen getScreenInstance() { return new Gameplay(); } }, PAUSED { @Override public com.badlogic.gdx.Screen getScreenInstance() { return new Paused(); } }, RESULT { @Override public com.badlogic.gdx.Screen getScreenInstance() { return new Result(); } }, CREDITS { @Override public com.badlogic.gdx.Screen getScreenInstance() { return new Credits(); } }; public abstract Screen getScreenInstance(); }
true
a21eebc482ee665c86e4a730d5245457b54f89db
Java
AY2021S2-CS2103T-W15-3/JJIMY
/src/main/java/seedu/address/model/ReadOnlyBook.java
UTF-8
160
1.695313
2
[ "MIT" ]
permissive
package seedu.address.model; import javafx.collections.ObservableList; public interface ReadOnlyBook<T extends Item> { ObservableList<T> getItemList(); }
true
03367da2c52cec3617bc33700a40240b6e0e1c55
Java
codeArtPesure/leetcode
/src/com/dengzhili/leetcode/Demo482.java
UTF-8
2,006
3.59375
4
[]
no_license
package com.dengzhili.leetcode; /** * 给定一个密钥字符串S,只包含字母,数字以及 '-'(破折号)。N 个 '-' 将字符串分成了 N+1 组。 * 给定一个数字 K,重新格式化字符串,除了第一个分组以外,每个分组要包含 K 个字符, * 第一个分组至少要包含 1 个字符。两个分组之间用 '-'(破折号)隔开,并且将所有的小写字母转换为大写字母。 * * 给定非空字符串 S 和数字 K,按照上面描述的规则进行格式化。 * * 示例 1: * * 输入:S = "5F3Z-2e-9-w", K = 4 * * 输出:"5F3Z-2E9W" * * 解释:字符串 S 被分成了两个部分,每部分 4 个字符; * 注意,两个额外的破折号需要删掉。 * 示例 2: * * 输入:S = "2-5g-3-J", K = 2 * * 输出:"2-5G-3J" * * 解释:字符串 S 被分成了 3 个部分,按照前面的规则描述,第一部分的字符可以少于给定的数量,其余部分皆为 2 个字符。 */ public class Demo482 { public String licenseKeyFormatting(String S, int K) { if(S==null || S.length()==0){ return null; } char[] arr=new char[S.length()+S.length()/K]; char[] strArr=S.toCharArray(); int j=0; int letterCount=0; for (int i = strArr.length-1; i >= 0; i--) { if(!('-'==strArr[i])){ if(strArr[i]<='z'&&strArr[i]>='a'){ arr[j]=(char)(strArr[i]-32); }else { arr[j]=strArr[i]; } j++; letterCount++; if(letterCount%K==0){ arr[j]='-'; j++; } } } char[] tarArr=new char[j]; for (int i=j-1;i>=0;i--){ tarArr[j-i-1]=arr[i]; } if(tarArr[0]=='-') return new String(tarArr,1,tarArr.length-1); else return new String(tarArr); } }
true
86793dac39eea2e4c31c4699aeb5ffc6b20454d4
Java
dtanh275/spring-boot
/spring-boot-cache/src/main/java/com/donkey/springboot/springbootcache/keygenerator/Witcher.java
UTF-8
409
2.28125
2
[]
no_license
package com.donkey.springboot.springbootcache.keygenerator; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; @Data @AllArgsConstructor @NoArgsConstructor @Builder public class Witcher { private long id; private String name; @Override public String toString() { return String.format("[id=%d, name=%s]", id, name); } }
true
b3a54618c032107f1edd6984b0cb90142d6948df
Java
hellengithubtest/chess2
/src/main/java/com/company/app/Player.java
UTF-8
1,550
3.078125
3
[]
no_license
package com.company.app; import com.company.app.factory.CreatePieces; import com.company.app.factory.FactoryBlack; import com.company.app.factory.FactoryPiece; import com.company.app.factory.FactoryWhite; import com.company.app.models.*; import java.util.ArrayList; import java.util.List; import java.util.Random; public class Player implements Observer{ private final PlayerColor color; private List<Piece> pieces = new ArrayList<Piece>(); public Player(PlayerColor color) { this.color = color; initializePieces(); } public List<Piece> getPieces() { return pieces; } public PlayerColor getColor() { return this.color; } public void initializePieces() { FactoryPiece factory; CreatePieces createPieces; if (this.color == PlayerColor.WHITE) { factory = new FactoryWhite(); createPieces = new CreatePieces(factory); pieces = createPieces.getListPieces(); } else { factory = new FactoryBlack(); createPieces = new CreatePieces(factory); pieces = createPieces.getListPieces(); } } public Piece getRandomPiece() { Random random = new Random(); return pieces.get(random.nextInt(pieces.size())); } @Override public void update(List<Piece> deletedPieces) { for (int i = 0; i < pieces.size(); i++) { if (deletedPieces.contains(pieces.get(i))) { pieces.remove(i); } } } }
true
adfe0384651cf0ed5999b3fd8917c3684976398a
Java
carter-ya/ToDoList_android
/app/src/main/java/com/ifengxue/android/todolist/response/TaskResponse.java
UTF-8
354
1.523438
2
[]
no_license
package com.ifengxue.android.todolist.response; import lombok.Data; @Data public class TaskResponse { private Long createdAt; private Long endedAt; private Boolean empty; private Long id; private Long parentId; private Integer priority; private Long projectId; private Long startedAt; private String title; private String state; }
true
20a6783728d63a79c38577b5117c875add479988
Java
WINTERFELLS/codingoffer
/codingoffer/src/codingoffer/Solution64.java
GB18030
1,802
3.671875
4
[]
no_license
package codingoffer; /* һmкnеķһ˴0,0ĸӿʼƶÿһֻңϣĸƶһ Dzܽλ֮ʹkĸӡ 磬kΪ18ʱܹ뷽35,37Ϊ3+5+3+7 = 18 ǣܽ뷽35,38Ϊ3+5+3+8 = 19ʸûܹﵽٸӣ */ public class Solution64 { public int movingCount(int threshold, int rows, int cols){ int res = 0; if(threshold == 0){ return res; } int[][] num = new int[rows][cols]; dfs(0,0,num,rows,cols,threshold); for(int i = 0; i < rows; i++){ for(int j = 0; j < cols; j++){ if(num[i][j] == 1){ res++; } } } return res; } public void dfs(int temprow, int tempcol, int[][] num, int rows, int cols, int threshold){ if(temprow < 0 || tempcol < 0 || temprow >= rows || tempcol >= cols) return; if(num[temprow][tempcol] == 1) return; if(sum(temprow,tempcol)>threshold) return; num[temprow][tempcol] = 1; dfs(temprow+1,tempcol,num,rows,cols,threshold); dfs(temprow-1,tempcol,num,rows,cols,threshold); dfs(temprow,tempcol+1,num,rows,cols,threshold); dfs(temprow,tempcol-1,num,rows,cols,threshold); } public int sum(int a, int b){ int num1 = cal(a); int num2 = cal(b); return num1+num2; } public int cal(int num){ int res = 0; while(num > 0){ res += num%10; num /= 10; } return res; } }
true
e3e310036250d9f5d74d859ad7d1cc322236d100
Java
shadowridgedev/dkpro-jwpl
/de.tudarmstadt.ukp.wikipedia.revisionmachine/src/main/java/de/tudarmstadt/ukp/wikipedia/revisionmachine/difftool/config/gui/dialogs/InputDialog.java
UTF-8
6,904
2.140625
2
[ "Apache-2.0" ]
permissive
/* * Licensed to the Technische Universität Darmstadt under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The Technische Universität Darmstadt * 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. * * 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 de.tudarmstadt.ukp.wikipedia.revisionmachine.difftool.config.gui.dialogs; import java.awt.Dimension; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JDialog; import javax.swing.JFileChooser; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import de.tudarmstadt.ukp.wikipedia.revisionmachine.difftool.config.gui.control.ConfigController; import de.tudarmstadt.ukp.wikipedia.revisionmachine.difftool.config.gui.control.ConfigSettings; import de.tudarmstadt.ukp.wikipedia.revisionmachine.difftool.config.gui.control.ConfigVerification; import de.tudarmstadt.ukp.wikipedia.revisionmachine.difftool.config.gui.panels.AbstractPanel; import de.tudarmstadt.ukp.wikipedia.revisionmachine.difftool.data.archive.ArchiveDescription; import de.tudarmstadt.ukp.wikipedia.revisionmachine.difftool.data.archive.InputType; /** * InputDialog - Dialog to specify input archives. * * * */ @SuppressWarnings("serial") public class InputDialog extends JDialog { /** * Panel of the InputDialog * * * */ private class InputDialogPanel extends AbstractPanel { /** * (Constructor) Creates the InputDialogPanel. * * @param controller * Reference to the controller */ public InputDialogPanel(final ConfigController controller) { super(controller); createPathSettings(); createTypeChooser(); createButtons(); createStartLabel(); } private JLabel pathLabel; private JTextField pathField; private JButton searchButton; private JLabel typeLabel; private JComboBox typeChooser; private JLabel startLabel; private JTextField startPosition; private JButton addButton; private JButton cancelButton; /** * Creates the path input components. */ private void createPathSettings() { pathLabel = new JLabel("Please enter the path: "); pathLabel.setBounds(10, 10, 150, 25); this.add(pathLabel); pathField = new JTextField(); pathField.setBounds(10, 40, 250, 25); this.add(pathField); searchButton = new JButton("Search"); searchButton.setBounds(180, 10, 80, 25); searchButton.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { JFileChooser fc = new JFileChooser(); if (fc.showOpenDialog(new JPanel()) == JFileChooser.APPROVE_OPTION) { pathField.setText(fc.getSelectedFile().getPath()); } } }); this.add(searchButton); } /** * Creates the start input components. */ private void createStartLabel() { startLabel = new JLabel("Ignore all bytes before:"); startLabel.setBounds(10, 120, 130, 25); this.add(startLabel); startPosition = new JTextField(); startPosition.setBounds(150, 120, 110, 25); this.add(startPosition); } /** * Creates the input type chooser. */ private void createTypeChooser() { typeLabel = new JLabel("Input type: "); typeLabel.setBounds(10, 80, 130, 25); this.add(typeLabel); typeChooser = new JComboBox(); typeChooser.setBounds(150, 80, 110, 25); typeChooser.addItem(InputType.XML); if (this.controller.is7ZipEnabled()) { typeChooser.addItem(InputType.SEVENZIP); } typeChooser.addItem(InputType.BZIP2); this.add(typeChooser); } /** * Creates the buttons of the dialog panel. */ private void createButtons() { addButton = new JButton("Add"); addButton.setBounds(10, 170, 120, 25); addButton.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { String path = pathField.getText(); if (path.length() == 0) { return; } InputType type = (InputType) typeChooser.getSelectedItem(); controller.addArchive(new ArchiveDescription(type, path)); controller.repaint(); close(); } }); this.add(addButton); cancelButton = new JButton("Cancel"); cancelButton.setBounds(140, 170, 120, 25); cancelButton.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { close(); } }); this.add(cancelButton); } /** * empty method */ @Override public void validate() { } /** * A call of this method should validate the positions of the panels * components. */ @Override public void relocate() { int w = 250, h = 185; int x = (this.getWidth() - w) / 2, y = (this.getHeight() - h) / 2; pathLabel.setLocation(x, y); pathField.setLocation(x, y + 30); searchButton.setLocation(x + 170, y); typeLabel.setLocation(x, y + 70); typeChooser.setLocation(x + 140, y + 70); startLabel.setLocation(x, y + 110); startPosition.setLocation(x + 140, y + 110); addButton.setLocation(x, y + 160); cancelButton.setLocation(x + 130, y + 160); } /** * empty method * * @deprecated * @throws UnsupportedOperationException */ @Deprecated @Override public void toXML(final StringBuilder builder, final ConfigVerification errors) { throw new UnsupportedOperationException(); } /** * empty method * * @deprecated * @throws UnsupportedOperationException */ @Deprecated @Override public void applyConfig(final ConfigSettings config) { throw new UnsupportedOperationException(); } } /** * (Constructor) Creates a new InputDialog. * * @param controller * Reference to the controller */ public InputDialog(final ConfigController controller) { super(controller.getRegistry().getGUI(), true); this.setTitle("Add an input file"); setSize(300, 250); setResizable(false); Dimension d = Toolkit.getDefaultToolkit().getScreenSize(); setLocation((d.width - getSize().width) / 2, (d.height - getSize().height) / 2); this.setContentPane(new InputDialogPanel(controller)); } /** * Closes the dialog. */ public void close() { this.setVisible(true); this.dispose(); } }
true
7f0f71073bced24b9db4251da37efd94447ab606
Java
lumanmann/DecoratorPatternPractice
/app/src/main/java/com/lumanman/decoratorpatternpractice/StringText.java
UTF-8
230
2.546875
3
[]
no_license
package com.lumanman.decoratorpatternpractice; public class StringText extends AbstractString { public StringText(String str){ super(str); } public String getString() { return this.string; } }
true
692ff958189aed75b9f252e88772f2a63745e562
Java
score-server/movie-score
/src/main/java/ch/wetwer/moviedbapi/data/groupinvite/GroupDao.java
UTF-8
996
2.1875
2
[ "MIT", "LicenseRef-scancode-other-permissive" ]
permissive
package ch.wetwer.moviedbapi.data.groupinvite; import ch.wetwer.moviedbapi.data.DaoInterface; import org.springframework.stereotype.Service; import java.util.List; /** * @author Wetwer * @project movie-score */ @Service public class GroupDao implements DaoInterface<GroupInvite> { private GroupRepository groupRepository; public GroupDao(GroupRepository groupRepository) { this.groupRepository = groupRepository; } @Override public GroupInvite getById(Long id) { return groupRepository.getOne(id); } @Override public List<GroupInvite> getAll() { return groupRepository.findAll(); } @Override public void save(GroupInvite groupInvite) { groupRepository.save(groupInvite); } public void delete(Long groupId) { groupRepository.delete(groupRepository.getOne(groupId)); } public GroupInvite getByName(String groupKey) { return groupRepository.findByNameEquals(groupKey); } }
true
8e2b1219fff325f8d44bbccbdc9c812d5f777baf
Java
maximignashov/mignashov
/chapter_001/src/main/java/ru/job4j/condition/Triangle.java
UTF-8
1,314
3.875
4
[ "Apache-2.0" ]
permissive
package ru.job4j.condition; /** * Класс, Point описывает точку в системе координат. * @author mignashov * @since 27.03.2017 * @version 2 */ public class Triangle { /** * Объявление переменной a типа Point. */ private Point a; /** * Объявление переменной b типа Point. */ private Point b; /** * Объявление переменной c типа Point. */ private Point c; /** * Конструктор. Задает стороны треугольника. * @param a pointA. * @param b pointB. * @param c pointC. */ public Triangle(Point a, Point b, Point c) { this.a = a; this.b = b; this.c = c; } /** * Рассчет площади треугольника. * @return -1 если треугольник не существует. */ public double area() { double spacingAB = a.spacingTo(b); double spacingBC = b.spacingTo(c); double spacingAC = a.spacingTo(c); boolean isTriangle = ((spacingAB + spacingBC > spacingAC) & (spacingBC + spacingAC > spacingAB) & (spacingAB + spacingAC > spacingBC)); if (isTriangle) { double p = (spacingAB + spacingBC + spacingAC) / 2; return Math.sqrt(p * (p - spacingAB) * (p - spacingBC) * (p - spacingAC)); } else { return -1; } } }
true
128bb91b5963c49e751cd9d8242f3d2904ae46fe
Java
lorenzokyne/Metodi-Avanzati-di-Programmazione---Caso-di-studio-2017-2018
/Codice Sorgente/KmeansServer/src/data/DiscreteAttribute.java
UTF-8
2,823
3.5625
4
[]
no_license
package data; import java.util.Iterator; import java.util.Set; import java.util.TreeSet; /** * Classe che estende la classe Attribute e rappresenta un attributo discreto * (categorico). * * @author Fernando * * @param <T> * prametro generico che rappresenta il tipo di un attributo * categorico */ public class DiscreteAttribute<T> extends Attribute implements Iterable<String> { /** * TreeSet di oggetti String uno per ciascun valore del dominio discreto * memorizzati in modo ordinato. */ private TreeSet<String> values; /** * Metodo che invoca il costruttore della classe madre e inizializza il membro * values con il parametro in input. * * @param name * valore da passare come parametro a super per assegnarlo alla * variabile di classe name della classe Attribute. * @param index * valore da passare come parametro a super per assegnarlo alla * variabile di classe index della classe Attribute. * @param values * valore da assegnare alla variabile di classe values. */ public DiscreteAttribute(String name, int index, TreeSet<String> values) { super(name, index); this.values = values; } /** * Metodo che restituisce la dimensione di values. * * @return intero che rappresenta la grandezza di values. */ public int GetNumberOfDistinctValues() { return values.size(); } /** * Metodo che restituisce l'iteratore di values. */ public Iterator<String> iterator() { Iterator<String> a = values.iterator(); return a; } /** * Metodo che controlla se l' v appartiene al TreeSet values. * * @param v * stringa su cui effettuare il controllo di appartenenza. * @return true se v appartiene a values false altrimenti. */ public boolean appartiene(String v) { if (values.contains(v)) return true; return false; } /** * Metodo che determina il numero di volte che il valore v compare in * corrispondenza dell'attributo corrente (indice di colonna) negli esempi * memorizzati in data e indicizzate (per riga) da idList. * * @param data * riferimento ad un oggetto Data, * @param idList * riferimento ad un oggetto ArraySet (che mantiene l'insieme degli * indici di riga di alcune tuple memorizzate in data). * @param v * valore discreto sul quale effettuare il controllo di frequenza. * @return numero di occorrenze del valore discreto (intero). */ public int frequency(Data data, Set<Integer> idList, String v) { int cont = 0; Object temp[] = idList.toArray(); if (appartiene(v)) { for (int i = 0; i < temp.length; i++) { if (((String) (data.getAttributeValue((int) temp[i], getIndex()))).equals(v)) { cont++; } } } return cont; } }
true
8e893720555b68f6aedbae26907110e14735142c
Java
SeniorAdvisor/spring-data-cloudant
/src/main/java/org/springframework/data/cloudant/core/repository/CloudantRepositoryFactoryBean.java
UTF-8
1,509
1.882813
2
[ "Apache-2.0" ]
permissive
package org.springframework.data.cloudant.core.repository; import com.google.gson.GsonBuilder; import org.springframework.data.mapping.context.MappingContext; import org.springframework.data.repository.Repository; import org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport; import org.springframework.data.repository.core.support.RepositoryFactorySupport; import java.io.Serializable; /** * Created by kevin on 6/18/15. */ public class CloudantRepositoryFactoryBean<T extends Repository<S, ID>, S, ID extends Serializable> extends RepositoryFactoryBeanSupport<T, S, ID> { private String username; private String password; private String account; private int maxConnections; private int connectionTimeout; private GsonBuilder gsonBuilder; public void setUsername(String username) { this.username = username; } public void setPassword(String password) { this.password = password; } public void setAccount(String account) { this.account = account; } public void setMaxConnections(int maxConnections) { this.maxConnections = maxConnections; } public void setConnectionTimeout(int connectionTimeout) { this.connectionTimeout = connectionTimeout; } public void setGsonBuilder(GsonBuilder gsonBuilder) { this.gsonBuilder = gsonBuilder; } @Override protected RepositoryFactorySupport createRepositoryFactory() { return null; } }
true
f9b713c18d380c1b27e7bfec5daa5382d009e39b
Java
wttech/aet
/test-executor/src/main/java/com/cognifide/aet/executor/model/TestRun.java
UTF-8
3,342
2.3125
2
[ "Apache-2.0", "MIT", "JSON" ]
permissive
/** * AET * * Copyright (C) 2013 Cognifide Limited * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.cognifide.aet.executor.model; import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; /** * Represents single test in test suite. Consists of sequence of steps: 1) Collection 2) Comparison * And set of urls on which tests will be performed. */ public class TestRun implements Serializable { private static final long serialVersionUID = 1453942700093647211L; private final List<CollectorStep> collectorSteps; private final Map<String, List<ComparatorStep>> comparatorSteps; private final List<ExtendedUrl> urls; private final String name; private final String useProxy; private final String browser; /** * @param collectorSteps - list of collector steps. * @param comparatorSteps - set of comparison steps. * @param urls - list of urls. * @param name - unique name of test. * @param useProxy - says what kind of proxy should be used, backward compatibility: set 'true' to * use 'rest' proxy, set 'false' to use none. * @param browser - id of preferred browser or null if the default one should be used */ public TestRun(List<CollectorStep> collectorSteps, Set<ComparatorStep> comparatorSteps, List<ExtendedUrl> urls, String name, String useProxy, String browser) { this.collectorSteps = collectorSteps; this.comparatorSteps = getMap(comparatorSteps); this.urls = urls; this.name = name; this.useProxy = useProxy; this.browser = browser; } private Map<String, List<ComparatorStep>> getMap(Set<ComparatorStep> comparatorSteps) { Map<String, List<ComparatorStep>> result = new HashMap<>(); for (ComparatorStep comparatorStep : comparatorSteps) { List<ComparatorStep> list = result.get(comparatorStep.getType()); if (list == null) { list = new ArrayList<>(); result.put(comparatorStep.getType(), list); } list.add(comparatorStep); } return result; } /** * @return list of collector steps in this test. */ public List<CollectorStep> getCollectorSteps() { return collectorSteps; } /** * @return list of comparison steps in this test. */ public Map<String, List<ComparatorStep>> getComparatorSteps() { return comparatorSteps; } /** * @return list of urls. */ public List<ExtendedUrl> getUrls() { return urls; } /** * @return unique name of test. */ public String getName() { return name; } /** * @return name of kind of proxy that will be used. */ public String getUseProxy() { return useProxy; } /** * @return id of preferred browser. */ public String getBrowser() { return browser; } }
true
d97366949b9b8584f29322f25be30a98174f1e1b
Java
khalakuzamanrony/Chatting_App
/app/src/main/java/com/android/personalchat/Adapter/RequestAdapter.java
UTF-8
3,727
2.171875
2
[]
no_license
package com.android.personalchat.Adapter; import android.content.Context; import android.content.Intent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.android.personalchat.Models.RequestModel; import com.android.personalchat.R; import com.android.personalchat.UserDetailsActivity; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import com.squareup.picasso.Picasso; import java.util.ArrayList; import de.hdodenhof.circleimageview.CircleImageView; public class RequestAdapter extends RecyclerView.Adapter<RequestAdapter.ViewHolder> { private ArrayList<RequestModel> arrayList; private DatabaseReference databaseReference; private Context context; private String hisid, myid; public RequestAdapter(ArrayList<RequestModel> arrayList, Context context) { this.arrayList = arrayList; this.context = context; } @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.friends_layout, parent, false); return new ViewHolder(view); } @Override public void onBindViewHolder(@NonNull final ViewHolder holder, int position) { RequestModel requestModel = arrayList.get(position); hisid = requestModel.getHe(); myid = requestModel.getMe(); databaseReference = FirebaseDatabase.getInstance().getReference(); databaseReference.keepSynced(true); databaseReference.child("Users").child(hisid).addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { if (dataSnapshot.hasChildren()) { String x = dataSnapshot.child("name").getValue().toString(); String thumb=dataSnapshot.child("thumb_image").getValue().toString(); holder.name.setText(x); Picasso.get().load(thumb).placeholder(R.drawable.ic_launcher_background).into(holder.circleImageView); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); //---------ON Click ----------// holder.relativeLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { context.startActivity(new Intent(context, UserDetailsActivity.class) .putExtra("id",hisid)); } }); } @Override public int getItemCount() { return arrayList.size(); } public class ViewHolder extends RecyclerView.ViewHolder { private RelativeLayout relativeLayout; private TextView name; private ImageView online_status; private CircleImageView circleImageView; public ViewHolder(@NonNull View itemView) { super(itemView); relativeLayout = itemView.findViewById(R.id.friend_full_layout); name = itemView.findViewById(R.id.friend_name); circleImageView = itemView.findViewById(R.id.friend_image); online_status = itemView.findViewById(R.id.friend_online_status); } } }
true
03bfe010cbb6036e62acfe91fdff8bb9d8183451
Java
sr0004/GUI2.0DynamicButtons
/src/main/SceneFrame.java
UTF-8
18,415
2.359375
2
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package main; import scene.Scene; import javax.swing.JButton; import main.EngineGame; import scene.SceneTable; import java.util.ArrayList; /** * SceneFrame extends the class JFrame and adds on extra features needed for * Dungeon Escape. * @author sra0004 */ public class SceneFrame extends javax.swing.JFrame { private ArrayList<Scene> sceneList; private int[] buttonVis; int currentIdx; int nextIdx; private SceneTable scenetable; Scene currentScene; /** * Creates new form SceneFrame */ public SceneFrame() { sceneList = new ArrayList<Scene>(); buttonVis = null; initComponents(); nextIdx= -1; scenetable = new SceneTable(); scenetable.initTable(); currentIdx = 0; } /** * addScene adds an instance of Scene to SceneManager * @param aScene * @param idx */ public void addScene(Scene aScene, int idx){ sceneList.add(idx, aScene); if(idx == 0) { SceneManager.add(aScene, idx); } } /** * displayScene adds the current scene to be displayed to an ArrayList of * scenes used to organize them. * @param idx */ public void displayScene(int idx){ if (idx != -1) { currentScene = sceneList.get(idx); currentScene.displayEvents(); SceneManager.getComponent(0).setVisible(false); SceneManager.remove(0); //currentScene = (Scene)SceneManager.getComponent(idx); SceneManager.add(currentScene); SceneManager.getComponent(0).setVisible(true); //SceneManager.getComponent(currentIdx).setVisible(false); currentScene.displayEvents(); currentIdx = idx; } } //public void displayScene(Scene) /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { SceneManager1 = new scene.ScenePanel(); SceneManager = new scene.ScenePanel(); frameTorchButton = new javax.swing.JButton(); frameKeyButton = new javax.swing.JButton(); jScrollPane1 = new javax.swing.JScrollPane(); jTextArea1 = new javax.swing.JTextArea(); ForwardButton = new javax.swing.JButton(); LeftButton = new javax.swing.JButton(); RightButton = new javax.swing.JButton(); BackButton = new javax.swing.JButton(); frameSwordButton = new javax.swing.JButton(); javax.swing.GroupLayout SceneManager1Layout = new javax.swing.GroupLayout(SceneManager1); SceneManager1.setLayout(SceneManager1Layout); SceneManager1Layout.setHorizontalGroup( SceneManager1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 400, Short.MAX_VALUE) ); SceneManager1Layout.setVerticalGroup( SceneManager1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 300, Short.MAX_VALUE) ); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Adventure Game"); setAlwaysOnTop(true); setBackground(new java.awt.Color(255, 0, 255)); setForeground(new java.awt.Color(255, 51, 51)); SceneManager.setBorder(new javax.swing.border.MatteBorder(null)); javax.swing.GroupLayout SceneManagerLayout = new javax.swing.GroupLayout(SceneManager); SceneManager.setLayout(SceneManagerLayout); SceneManagerLayout.setHorizontalGroup( SceneManagerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 398, Short.MAX_VALUE) ); SceneManagerLayout.setVerticalGroup( SceneManagerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 298, Short.MAX_VALUE) ); frameTorchButton.setBackground(new java.awt.Color(51, 51, 51)); frameTorchButton.setForeground(new java.awt.Color(102, 102, 102)); frameTorchButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/torch2.png"))); // NOI18N frameTorchButton.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); frameTorchButton.setEnabled(false); frameTorchButton.setFocusable(false); frameTorchButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { frameTorchButtonActionPerformed(evt); } }); frameKeyButton.setBackground(new java.awt.Color(51, 51, 51)); frameKeyButton.setForeground(new java.awt.Color(102, 102, 102)); frameKeyButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/key.png"))); // NOI18N frameKeyButton.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); frameKeyButton.setEnabled(false); frameKeyButton.setFocusable(false); frameKeyButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { frameKeyButtonActionPerformed(evt); } }); jTextArea1.setEditable(false); jTextArea1.setColumns(20); jTextArea1.setRows(5); jTextArea1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); jScrollPane1.setViewportView(jTextArea1); ForwardButton.setText("Forward"); ForwardButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ForwardButtonActionPerformed(evt); } }); LeftButton.setText("Left"); LeftButton.setPreferredSize(new java.awt.Dimension(73, 23)); LeftButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { LeftButtonActionPerformed(evt); } }); RightButton.setText("Right"); RightButton.setMaximumSize(new java.awt.Dimension(73, 23)); RightButton.setPreferredSize(new java.awt.Dimension(73, 23)); RightButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { RightButtonActionPerformed(evt); } }); BackButton.setText("Back"); BackButton.setPreferredSize(new java.awt.Dimension(73, 23)); BackButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { BackButtonActionPerformed(evt); } }); frameSwordButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/Steel_sword_icon.png"))); // NOI18N frameSwordButton.setEnabled(false); frameSwordButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { frameSwordButtonActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(21, 21, 21) .addComponent(SceneManager, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(frameTorchButton, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(frameKeyButton, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(2, 2, 2)) .addComponent(frameSwordButton, javax.swing.GroupLayout.DEFAULT_SIZE, 165, Short.MAX_VALUE))) .addGroup(layout.createSequentialGroup() .addGap(55, 55, 55) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 304, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(68, 68, 68) .addComponent(ForwardButton) .addGap(0, 0, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(69, 69, 69) .addComponent(BackButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addGap(18, 18, 18) .addComponent(LeftButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(27, 27, 27) .addComponent(RightButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap()))) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(19, 19, 19) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(SceneManager, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createSequentialGroup() .addGap(26, 26, 26) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(frameTorchButton, javax.swing.GroupLayout.PREFERRED_SIZE, 126, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(frameKeyButton, javax.swing.GroupLayout.PREFERRED_SIZE, 126, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addComponent(frameSwordButton, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(18, 18, 18) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 138, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addGap(46, 46, 46) .addComponent(ForwardButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(LeftButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(RightButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(BackButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void frameTorchButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_frameTorchButtonActionPerformed currentScene=sceneList.get(currentIdx); currentScene.isDark=false; currentScene.updateButtons(); this.displayScene(currentIdx); currentScene.updateDirectionButtons(); currentScene.updateSceneText(); }//GEN-LAST:event_frameTorchButtonActionPerformed /** * frameKeybutton calls the functions needed to use the key to unlock doors. * @param evt */ private void frameKeyButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_frameKeyButtonActionPerformed currentScene=sceneList.get(currentIdx); currentScene.isClosed=false; this.displayScene(currentIdx); currentScene.updateDirectionButtons(); currentScene.updateSceneText(); }//GEN-LAST:event_frameKeyButtonActionPerformed /** * ForwardButton calls all of the necessary functions to travel forward * within the dungeon. * @param evt */ private void ForwardButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ForwardButtonActionPerformed nextIdx = scenetable.changeScene(currentIdx, 0); this.displayScene(nextIdx); currentScene.updateDirectionButtons(); currentScene.updateSceneText(); }//GEN-LAST:event_ForwardButtonActionPerformed /** * LeftButton calls all of the necessary functions to travel to the right * within the dungeon. * @param evt */ private void LeftButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_LeftButtonActionPerformed nextIdx = scenetable.changeScene(currentIdx, 3); this.displayScene(nextIdx); currentScene.updateDirectionButtons(); currentScene.updateSceneText(); }//GEN-LAST:event_LeftButtonActionPerformed /** * RightButton calls all of the necessary functions to travel to the right * within the dungeon. * @param evt */ private void RightButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_RightButtonActionPerformed nextIdx = scenetable.changeScene(currentIdx, 2); this.displayScene(nextIdx); currentScene.updateDirectionButtons(); currentScene.updateSceneText(); }//GEN-LAST:event_RightButtonActionPerformed /** * BackButton calls all the necessary functions to travel backwards within * the dungeon. * @param evt */ private void BackButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BackButtonActionPerformed nextIdx = scenetable.changeScene(currentIdx, 1); this.displayScene(nextIdx); currentScene.updateDirectionButtons(); currentScene.updateSceneText(); }//GEN-LAST:event_BackButtonActionPerformed /** * frameSwordButton is the button denoted by a sword icon on main jFrame. * @param evt */ private void frameSwordButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_frameSwordButtonActionPerformed currentScene=sceneList.get(currentIdx); currentScene.isAlive=false; this.displayScene(currentIdx); currentScene.updateDirectionButtons(); currentScene.updateSceneText(); }//GEN-LAST:event_frameSwordButtonActionPerformed /** * setTextArea is called in the constructor of each scene to set the textbox * for each scene. * @param TA */ public void setTextArea(String TA){ jTextArea1.setText(TA); } /** * repaintScene() is called to repaint a scene after a choice that alters a * scene is made. */ public void repaintScene(){ this.displayScene(currentIdx); } /** * updateDirections enables and disables buttons based on the directions you * can travel in each scene. * @param forward * @param back * @param left * @param right */ public void updateDirections(boolean forward, boolean back, boolean left, boolean right){ ForwardButton.setEnabled(forward); BackButton.setEnabled(back); LeftButton.setEnabled(left); RightButton.setEnabled(right); } /** * updateSceneText will get the text to be displayed in each scene * describing what is happening and pointing out any important features. * @param text */ public void updateSceneText(String text){ jTextArea1.setText(text); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton BackButton; private javax.swing.JButton ForwardButton; private javax.swing.JButton LeftButton; private javax.swing.JButton RightButton; private javax.swing.JPanel SceneManager; private javax.swing.JPanel SceneManager1; public javax.swing.JButton frameKeyButton; public javax.swing.JButton frameSwordButton; public javax.swing.JButton frameTorchButton; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTextArea jTextArea1; // End of variables declaration//GEN-END:variables }
true
9642b73a0b2f065cc50710cfd4b44d6596cdfbd4
Java
ajanaliz/Pacman
/src/uk/alij/mainengine/GameCanvas.java
UTF-8
1,383
2.78125
3
[]
no_license
package uk.alij.mainengine; import javax.swing.*; import java.awt.*; import java.awt.event.ComponentEvent; import java.awt.event.ComponentListener; /** * Created by Ali J on 3/7/2015. */ public class GameCanvas extends JComponent implements ComponentListener { private Game game; public GameCanvas() { } public GameCanvas(Game game) { this.game = game; addKeyListener(game); addMouseListener(game); addMouseMotionListener(game); addMouseWheelListener(game); requestFocus(); addComponentListener(this); } public void setGame(Game game) { this.game = game; addKeyListener(game); addMouseListener(game); addMouseMotionListener(game); requestFocus(); addComponentListener(this); } @Override public void paintComponent(Graphics g) { game.draw((Graphics2D)g); } @Override public void componentResized(ComponentEvent ce) { game.resize(ce.getComponent().getWidth(), ce.getComponent().getHeight()); } @Override public void componentMoved(ComponentEvent ce) { } @Override public void componentShown(ComponentEvent ce) { // game.resize(ce.getComponent().getWidth(), ce.getComponent().getHeight()); } @Override public void componentHidden(ComponentEvent ce) { } }
true
ee28f1e13165e15340c0a9331396953997a8a788
Java
czy920/DCOPSolverInfrastructure
/src/edu/cqu/core/FinishedListener.java
UTF-8
168
1.703125
2
[]
no_license
package edu.cqu.core; import edu.cqu.result.Result; /** * Created by dyc on 2017/6/20. */ public interface FinishedListener { void onFinished(Result result); }
true
ff0859080dc210e3d92f182974c9cb6377268595
Java
liuchengts/bassis
/bassis-data/src/main/java/com/bassis/data/common/Declaration.java
UTF-8
221
1.945313
2
[]
no_license
package com.bassis.data.common; /** * 常量声明 */ public interface Declaration { /** * 最小连接数 */ int min_count = 10; /** * 最大连接数 */ int max_count = 20; }
true
6f4521986b81c88c1582ebfd3542aad8e3bbca28
Java
QAInsights/kraken
/backend/commons/analysis/analysis-client-properties/src/main/java/com/kraken/analysis/client/properties/AnalysisClientPropertiesConfiguration.java
UTF-8
723
1.929688
2
[ "LGPL-2.0-or-later", "Apache-2.0", "LicenseRef-scancode-proprietary-license" ]
permissive
package com.kraken.analysis.client.properties; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Slf4j @Configuration public class AnalysisClientPropertiesConfiguration { @Autowired @Bean AnalysisClientProperties analysisClientProperties(@Value("${kraken.analysis.url:#{environment.KRAKEN_ANALYSIS_URL}}") final String analysisUrl) { log.info("Analysis URL is set to " + analysisUrl); return AnalysisClientProperties.builder() .analysisUrl(analysisUrl) .build(); } }
true
8340e2f691284b032942a05522b13ad8f8087cb1
Java
vipncc02153/biz-study
/src/main/java/com/everhomes/learning/demos/cache/zxm/DataUtils/DataCache.java
UTF-8
557
2.359375
2
[]
no_license
package com.everhomes.learning.demos.cache.zxm.DataUtils; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * @author feiyue * @className DataCache * @description * @date 2018/7/21 **/ public class DataCache { /** * 定义一个 ConcurrentHashMap 用来存放缓存 */ private static Map<String, Object> map = new ConcurrentHashMap<>(); public static Map<String, Object> getMap() { return map; } public static void setMap(Map<String, Object> map) { DataCache.map = map; } }
true
be310431a016f000665cf70a63a21cc34be53931
Java
xhselina/framework
/framework-test/src/main/java/org/china/framework/spring/pattern/factory/factorys/impl/MailSenderImpl.java
UTF-8
352
2.1875
2
[]
no_license
package org.china.framework.spring.pattern.factory.factorys.impl; import org.china.framework.spring.pattern.factory.Sender; /** * @version Ver 1.0 * @Author <a href="mailto:jeffreyji@yeah.net">jeffrey</a> * @Date 2016/8/23 17:31. */ public class MailSenderImpl implements Sender{ @Override public String send() { return "发邮件"; } }
true
a27cefc1236e033996a9ff51017f16504b29ddcc
Java
AlyMoanes2018/Android
/app/src/main/java/com/android/agzakhanty/sprints/two/adapters/HomeAdsAdapter.java
UTF-8
3,598
2.046875
2
[]
no_license
package com.android.agzakhanty.sprints.two.adapters; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.drawable.BitmapDrawable; import android.support.v7.widget.RecyclerView; import android.util.Base64; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.RatingBar; import android.widget.TextView; import com.android.agzakhanty.R; import com.android.agzakhanty.general.application.Constants; import com.android.agzakhanty.sprints.two.models.Ad; import com.android.agzakhanty.sprints.two.models.UserRatings; import com.android.agzakhanty.sprints.two.models.api_responses.AdResponseModel; import com.android.agzakhanty.sprints.two.views.AdDetails; import com.bumptech.glide.Glide; import java.util.ArrayList; /** * Created by a.moanes on 24/05/2018. */ public class HomeAdsAdapter extends RecyclerView.Adapter<MyViewHolder2> { private ArrayList<AdResponseModel> list; Context context; public HomeAdsAdapter(ArrayList<AdResponseModel> Data, Context ctx) { list = Data; context = ctx; } @Override public MyViewHolder2 onCreateViewHolder(ViewGroup parent, int viewType) { // create a new view View view = LayoutInflater.from(parent.getContext()) .inflate(R.layout.horizontal_ads_list_item, parent, false); MyViewHolder2 holder = new MyViewHolder2(view); return holder; } @Override public void onBindViewHolder(final MyViewHolder2 holder, int position) { if (list.get(position).getPcyImage() != null && !list.get(position).getPcyImage().equalsIgnoreCase("null") && !list.get(position).getPcyImage().isEmpty()) { Glide .with(context) .load(Constants.BASE_URL + list.get(position).getPcyImage()) .centerCrop() .into(holder.pharmacyPhoto); } else { Glide .with(context) .load(Constants.NO_IMG_FOUND_URL) .centerCrop() .into(holder.pharmacyPhoto); } if (list.get(position).getAdvImage() != null && !list.get(position).getAdvImage().equalsIgnoreCase("null") && !list.get(position).getAdvImage().isEmpty()) { Glide .with(context) .load(Constants.BASE_URL + list.get(position).getAdvImage()) .centerCrop() .into(holder.adPhoto); } else { Glide .with(context) .load(Constants.NO_IMG_FOUND_URL) .centerCrop() .into(holder.adPhoto); } holder.adDescription.setText(list.get(position).getAdvSubject()); holder.adPCY.setText(list.get(position).getPcyName()); } @Override public int getItemCount() { return list.size(); } } class MyViewHolder2 extends RecyclerView.ViewHolder { public ImageView pharmacyPhoto; public ImageView adPhoto; public TextView adDescription; public TextView adPCY; public MyViewHolder2(View v) { super(v); pharmacyPhoto = (ImageView) v.findViewById(R.id.pharmacyLogoIV); adPhoto = (ImageView) v.findViewById(R.id.adImg); adDescription = (TextView) v.findViewById(R.id.adDescription); adPCY = (TextView) v.findViewById(R.id.adPCY); } }
true
4dfcdf6b1f90c4439bd0bd6f491875356104ab50
Java
mhnavid/Ration-Distribution
/app/src/main/java/com/headblocks/rationdistribution/api/ApiInterface.java
UTF-8
706
2.03125
2
[]
no_license
package com.headblocks.rationdistribution.api; import okhttp3.MultipartBody; import okhttp3.RequestBody; import okhttp3.ResponseBody; import retrofit2.Call; import retrofit2.http.Field; import retrofit2.http.FormUrlEncoded; import retrofit2.http.Multipart; import retrofit2.http.POST; import retrofit2.http.Part; public interface ApiInterface { @Multipart @POST("search-face") Call<ResponseBody> sendFaceImage(@Part MultipartBody.Part image, @Part("name") RequestBody name); @FormUrlEncoded @POST("api/v1/date-update") Call<ResponseBody> sendStatus(@Field("id") String id, @Field("status") String status); }
true
2febacbf16d13854620633e4a07a9f15731977c6
Java
melonw123/xzproject
/teahouse-core/src/main/java/cn/com/shopec/core/equipment/dao/EquipmentBrandDao.java
UTF-8
462
2.078125
2
[]
no_license
package cn.com.shopec.core.equipment.dao; import java.util.List; import cn.com.shopec.core.common.BaseDao; import cn.com.shopec.core.equipment.model.EquipmentBrand; /** * 设备品牌表 数据库处理类 */ public interface EquipmentBrandDao extends BaseDao<EquipmentBrand,String> { /** * 编辑验证设备品牌名称不唯一 * 查询除过当前不属于该设备编号的数据 */ List<EquipmentBrand> queryUniqueBrandList(String brandNo); }
true
b8601da1defd0adac52dee968bc015d4a28475d1
Java
luocunhao/rest-demo
/src/main/java/xlink/rest/demo/rest/exception/Rest404StatusException.java
UTF-8
446
2.140625
2
[]
no_license
package xlink.rest.demo.rest.exception; import io.netty.handler.codec.http.HttpResponseStatus; public final class Rest404StatusException extends RestStatusException { /** * */ private static final long serialVersionUID = 4733869007263094763L; public Rest404StatusException(int errorcode, String msg) { super(errorcode, msg); } @Override public HttpResponseStatus getHttpStatus() { return HttpResponseStatus.NOT_FOUND; } }
true
1d4ddd0e447f6e5bf9bd1c9062d24c56543e23e5
Java
cengover/IDAMS
/src/iDAMS/ACO.java
UTF-8
3,167
2.71875
3
[]
no_license
package iDAMS; import java.util.Iterator; import java.util.LinkedList; import repast.simphony.engine.environment.RunEnvironment; import repast.simphony.parameter.Parameters; public class ACO { int id; public LinkedList<PCP> pcpList; public LinkedList<Bill> outstandingBills; // Interventions public double offline_rate; // E-mail, FB public double online_rate; // Tele-monitoring public double onsite_rate; // Education by community workers public double offline_cost; // Cost of offline messaging public double online_cost; // Cost of tele-monitoring public double onsite_cost;// Cost of education by community workers public double visit_cost; // Cost of care to patient public ACO(int id){ Parameters p = RunEnvironment.getInstance().getParameters(); this.id = id; this.pcpList = new LinkedList<PCP>(); this.outstandingBills= new LinkedList<Bill>(); this.offline_rate = (Double)p.getDouble("offline_rate"); this.online_rate = (Double)p.getDouble("online_rate"); this.onsite_rate = (Double)p.getDouble("onsite_rate"); this.offline_cost = (Double)p.getDouble("offline_cost"); this.online_cost = (Double)p.getDouble("online_cost"); this.onsite_cost = (Double)p.getDouble("onsite_cost"); this.visit_cost = (Double)p.getDouble("visit_cost"); } public class Bill { public PCP pcp; public Bene bene; public double cost; public BillType costType; public Bill(Bene patient,PCP provider, double cost, BillType cType) { this.pcp = provider; this.cost = cost; this.costType = cType; this.bene = patient; } } public enum BillType { offline, online, onsite, visit } public void bill(Bene patient, PCP provider, double cost, BillType costType) { outstandingBills.add(new Bill(patient,provider, cost, costType)); } public double getCost(){ double cost = 0; for (Iterator<Bill> iterator = this.outstandingBills.iterator(); iterator.hasNext();) { Bill b = iterator.next(); if (b.costType!=BillType.visit){ cost = cost + b.cost; } } return cost; } public double getOfflineCost(){ double cost = 0; for (Iterator<Bill> iterator = this.outstandingBills.iterator(); iterator.hasNext();) { Bill b = iterator.next(); if (b.costType==BillType.offline){ cost = cost + b.cost; } } return cost; } public double getOnlineCost(){ double cost = 0; for (Iterator<Bill> iterator = this.outstandingBills.iterator(); iterator.hasNext();) { Bill b = iterator.next(); if (b.costType==BillType.online){ cost = cost + b.cost; } } return cost; } public double getOnsiteCost(){ double cost = 0; for (Iterator<Bill> iterator = this.outstandingBills.iterator(); iterator.hasNext();) { Bill b = iterator.next(); if (b.costType==BillType.onsite){ cost = cost + b.cost; } } return cost; } public double getVisitCost(){ double cost = 0; for (Iterator<Bill> iterator = this.outstandingBills.iterator(); iterator.hasNext();) { Bill b = iterator.next(); if (b.costType==BillType.visit){ cost = cost + b.cost; } } return cost; } }
true
9c048d04b2a4a14ee84e2b49f6b061ae6f41ce78
Java
GodLike4814/1904-hygl
/hygl-zhh/src/main/java/com/fh/utils/CookieUtil.java
UTF-8
1,149
2.9375
3
[]
no_license
package com.fh.utils; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class CookieUtil { /** * 写cookie */ public static void writeCookie(String name, String value, String domain, int maxage, HttpServletResponse response){ /*创建cookie*/ Cookie cookie = new Cookie(name,value); /*配置参数*/ /*域名*/ cookie.setDomain(domain); /*过期时间 以秒为单位*/ if (maxage>0){ cookie.setMaxAge(maxage); } /*网站的根路径*/ cookie.setPath("/"); /*服务端响应信息*/ response.addCookie(cookie); } /** * 读取客户端cookie */ public static String readCookie(HttpServletRequest request, String name){ Cookie[] cookies = request.getCookies(); if(cookies == null){ return ""; } for (Cookie cookie : cookies) { if (cookie.getName().equals(name)){ return cookie.getValue(); } } return ""; } }
true
540d0321ae9fdb6ec7adb69914ab49cecfe3a670
Java
Noizept/apitweetspring
/src/main/java/com/sergio/restapi/Repository/Animenews/IAnimeNewsRepo.java
UTF-8
411
1.9375
2
[]
no_license
package com.sergio.restapi.Repository.Animenews; import com.sergio.restapi.Entity.AnimeNew; import java.util.List; public interface IAnimeNewsRepo { List<AnimeNew> getAll(); AnimeNew getById(Integer Id); void save(AnimeNew entity); void saveAll(List<AnimeNew> Entities); Integer count(); void truncate(); List<AnimeNew> getLatest(Integer total); AnimeNew getLastTweet(); }
true